diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Agent.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Agent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5ef93eca1d0f0324044283347f65fd44e4b4096 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Agent.cpp @@ -0,0 +1,426 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Agent.cpp +// +// Source file containing code for the agent creation APIs. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +namespace Concurrency +{ + +// A Filter function for a filter_block to check if the Agent has completed +bool _IsDone(agent_status const &status) +{ + return status == agent_done || status == agent_canceled; +} + +// A Filter function for a filter_block to check if the Agent has started (or completed) +bool _IsStarted(agent_status const &status) +{ + return _IsDone(status) || status == agent_started; +} + +/// +/// Creates an agent within the default scheduler, and places it any schedule +/// group of the scheduler's choosing. +/// +agent::agent() : + _M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(NULL), _M_pScheduleGroup(NULL) +{ + _Trace_agents(AGENTS_EVENT_CREATE, + details::_Trace_agents_get_id(this), + details::_Trace_agents_get_id(this)); + + send (_M_status, agent_created); +} + +/// +/// Create an agent within the specified scheduler, in a schedule group of the +/// scheduler's choosing. +/// +agent::agent(Scheduler& pScheduler) : + _M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(&pScheduler), _M_pScheduleGroup(NULL) +{ + _Trace_agents(AGENTS_EVENT_CREATE, + details::_Trace_agents_get_id(this), + details::_Trace_agents_get_id(this)); + + send (_M_status, agent_created); +} + +/// +/// Create an agent within the specified schedule group. The scheduler is implied +/// by the schedule group. +/// +agent::agent(ScheduleGroup& pGroup) : + _M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(NULL), _M_pScheduleGroup(&pGroup) +{ + _Trace_agents(AGENTS_EVENT_CREATE, + details::_Trace_agents_get_id(this), + details::_Trace_agents_get_id(this)); + + send (_M_status, agent_created); +} + +/// +/// Cleans up any resources that may have been created by the Agent. +/// +agent::~agent() +{ + _Trace_agents(AGENTS_EVENT_DESTROY, details::_Trace_agents_get_id(this)); +} + +/// +/// Returns a message source that can pass messages about the current state of the agent +/// +ISource * agent::status_port() +{ + return &_M_status; +} + +/// +/// Returns the current state of the agent. Note that this returned state could change +/// immediately after being returned. +/// +agent_status agent::status() +{ + return receive(_M_status); +} + +/// +/// Moves an Agent from the agent_created state to the agent_runnable state, and schedules it for execution. +/// +/// +/// true if the agent started correctly, false otherwise +/// +bool agent::start() +{ + if(_M_status.value() != agent_created) + { + return false; + } + + // + // Check if the agent is Startable. If the agent had already called start() or + // this variable was set to FALSE in cancel(), return false. + // + if(InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) == FALSE) + { + return false; + } + + _Trace_agents(AGENTS_EVENT_SCHEDULE, details::_Trace_agents_get_id(this)); + send (_M_status, agent_runnable); + + TaskProc proc = &Concurrency::agent::_Agent_task_wrapper; + if(_M_pScheduleGroup != NULL) + { + _M_pScheduleGroup->ScheduleTask(proc, this); + } + else if(_M_pScheduler != NULL) + { + _M_pScheduler->ScheduleTask(proc, this); + } + else + { + CurrentScheduler::ScheduleTask(proc, this); + } + + return true; +} + +/// +/// Moves an agent into the done state, indicating the completion of the agent +/// +/// +/// true if the agent is moved to the agent_done state, false otherwise +/// +bool agent::done() +{ + // + // current status + // + agent_status currentStatus = this->status(); + + // + // Indicate that the agent can no longer be started. + // + if (InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) != TRUE) + { + // + // agent is either canceled, started or completed run. + // + currentStatus = receive(_M_status, _IsStarted); + } + + // + // Agent is not cancelable anymore. + // + InterlockedExchange(&_M_fCancelable, FALSE); + + // + // Transition to agent_done state if it not already in one of + // the terminal states. + // + if ((currentStatus != agent_canceled) && (currentStatus != agent_done)) + { + send (_M_status, agent_done); + + return true; + } + + return false; +} + +/// +/// Moves an agent from the agent_created or agent_runnable to the agent_canceled state. +/// +/// +/// true if the agent was canceled correctly, false otherwise +/// +bool agent::cancel() +{ + // + // In case this agent has been canceled before it was even started + // mark it as no longer Startable and send a agent_canceled message to the + // status port + // + if(InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) == TRUE) + { + send (_M_status, agent_canceled); + } + + // + // Check to see if the agent is still Cancelable. Agents are initialized + // m_fCancelable == TRUE, and set to false either here in cancel(), so + // cancel() will not be called twice, or in the LWT, once the execution + // of the Agent task has begun. + // + if(InterlockedCompareExchange(&_M_fCancelable, FALSE, TRUE) == TRUE) + { + // Wait for the agent to reach a canceled state state + receive(_M_status, _IsDone); + + // The above InterlockedCompareExchange marked this agent for cancellation + // When the LWT that has been spun up tries to execute the task, it will + // find it has been canceled and will propagate out the canceled state to + // the state buffer. + return true; + } + + return false; +} + + +// Private helper class to order an input array of agents. This is used by +// wait_for_all and wait_for_one to create an array of appropriate order nodes. +// The template _OrderNode specifies an _Order_node_base that accepts agent_status. +// For example, _Reserving_node +template +class _OrderBlock +{ +public: + + // Constructs an orderBlock which has an array of ordernodes connected to the agents. + // The ordernodes are given a filter method to filter out non-terminal agent states + _OrderBlock(size_t _Count, agent ** _PAgents, ITarget * _PTarget) : _M_count(_Count) + { + // Create an array of order nodes + _M_ppNodes = _concrt_new _OrderNode*[_M_count]; + for (size_t i = 0; i < _M_count; i++) + { + _M_ppNodes[i] = _concrt_new _OrderNode(_PAgents[i]->status_port(), i, _PTarget, _IsDone); + } + } + + // Destroys the block + ~_OrderBlock() + { + for (size_t i = 0; i < _M_count; i++) + { + delete _M_ppNodes[i]; + } + + delete [] _M_ppNodes; + } + + // Retrieve the agent status for the agent at the given index + agent_status _Status(size_t _Index) + { + _CONCRT_ASSERT(_M_ppNodes[_Index]->has_value()); + + return _M_ppNodes[_Index]->value(); + } + +private: + + // Number of order nodes + size_t _M_count; + + // Array of order nodes + _OrderNode ** _M_ppNodes; +}; + + +/// +/// Wait for an agent to complete its task. A task is completed when it enters the agent_canceled, +/// or agent_done states. +/// +agent_status agent::wait(_Inout_ agent * pAgent, unsigned int timeout) +{ + if(pAgent == NULL) + { + throw std::invalid_argument("pAgent"); + } + + return receive(pAgent->status_port(), _IsDone, timeout); +} + +/// +/// Wait for all agents in a given Agent array to complete their tasks. A task is completed +/// when it enters the agent_canceled or agent_done states. +/// +void agent::wait_for_all(size_t count, _In_reads_(count) agent ** pAgents, _Out_writes_opt_(count) agent_status * pStatus, unsigned int timeout) +{ + if ( pAgents == NULL ) + { + throw std::invalid_argument("pAgents"); + } + + for (size_t i = 0; i < count; i++) + { + if ( pAgents[i] == NULL ) + { + throw std::invalid_argument("pAgents"); + } + } + + // Create the following network + // + // agent - orderNode - + // \ + // agent - orderNode - --call ~~~ single_assignment + // / + // agent - orderNode - + + single_assignment _Sa; + volatile size_t _CompletedAgents = 0; + call _Call([&](size_t const&) + { + // Safe to access without synchronization since call blocks + // guarantee that the function is not called for multiple + // messages at the same time. + _CONCRT_ASSERT(_CompletedAgents < count); + size_t value = _CompletedAgents; + _CompletedAgents = ++value; + if (_CompletedAgents == count) + { + // All the agents have completed. Indicate the same by sending a message + // (initialize) to the single assignment. + send(_Sa, 1); + } + }); + + _OrderBlock<_Greedy_node> _OrderedAgents(count, pAgents, &_Call); + + receive(&_Sa, timeout); + + // single_assignment has a message => all agents completed + // Retrieve their status messages. + if(pStatus != NULL) + { + for (size_t i = 0; i < count; i++) + { + pStatus[i] = _OrderedAgents._Status(i); + } + } +} + +/// +/// Wait for any one of the agents in a given AgentTask array to complete its task. A task is completed +/// when it enters the agent_canceled or agent_done states. +/// +void agent::wait_for_one(size_t count, _In_reads_(count) agent ** pAgents, agent_status &status, size_t& index, unsigned int timeout) +{ + if ( pAgents == NULL ) + { + throw std::invalid_argument("pAgents"); + } + + for (size_t i = 0; i < count; i++) + { + if ( pAgents[i] == NULL ) + { + throw std::invalid_argument("pAgents"); + } + } + + // Create the following network + // + // agent - orderNode - + // \ + // agent - orderNode - --single_assignment + // / + // agent - orderNode - + + single_assignment _Sa; + _OrderBlock<_Greedy_node> _OrderedAgents(count, pAgents, &_Sa); + + index = receive(&_Sa, timeout); + + // We were able to receive the index. Get the message (agent_status) + status = _OrderedAgents._Status(index); +} + +// A static wrapper function that calls the Run() method. Used for scheduling of the task +void agent::_Agent_task_wrapper(void* data) +{ + agent *pAgent = (agent *) data; + + if(InterlockedCompareExchange(&pAgent->_M_fCancelable, FALSE, TRUE) == TRUE) + { + send (pAgent->_M_status, agent_started); + + // Invoke the run() function of the agent. + _Trace_agents(AGENTS_EVENT_START, details::_Trace_agents_get_id(pAgent)); + pAgent->run(); + _Trace_agents(AGENTS_EVENT_END, details::_Trace_agents_get_id(pAgent), 0); + } + else + { + // This else path can be entered only if an agent was canceled before it + // ran. Send a agent_canceled message to the status. + send (pAgent->_M_status, agent_canceled); + } +} + +// Implementation of agent APIs that should not be publicly exposed + +namespace details +{ + static volatile runtime_object_identity s_RuntimeObjectIdentity = 0; + + _CONCRTIMP _Runtime_object::_Runtime_object() + { + // Increment the id by 2. This is done because certain blocks (like join) need to have + // a special message id to indicate a NULL id. In this case, we use -1. Incrementing by 2 + // will avoid any wrap-around issues causing us to hit -1. + runtime_object_identity id = InterlockedExchangeAdd((volatile long *) &s_RuntimeObjectIdentity, 2); + _CONCRT_ASSERT(id != -1); + _M_id = id; + } + + _CONCRTIMP _Runtime_object::_Runtime_object(runtime_object_identity _Id) : _M_id(_Id) + { + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90f48b0601d6324383e38069451db7d3382e7fa7 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.cpp @@ -0,0 +1,99 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// CacheLocalScheduleGroup.cpp +// +// Implementation file for CacheLocalScheduleGroup. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Puts a runnable context into the runnables collection in the schedule group. + /// + void CacheLocalScheduleGroupSegment::AddToRunnablesCollection(InternalContextBase* pContext) + { + m_runnableContexts.Enqueue(pContext); + } + + /// + /// Places a chore in the mailbox associated with this schedule group segment. + /// + /// + /// The chore to mail. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + Mailbox<_UnrealizedChore>::Slot CacheLocalScheduleGroupSegment::MailChore(_UnrealizedChore *pChore) + { + // + // There are two possible segments to which pChore can be accounted. One is the segment where it will appear on the WSQ -- the other is + // the segment where it will appear on the mailbox. Both are in the same group and hence we do not at present have reference counting + // issues. It will be attributed to the group it was picked up from which will further honor that affinity if the task blocks, etc... + // + ASSERT(!m_affinity._Is_system()); + Mailbox<_UnrealizedChore>::Slot affinitySlot = m_mailedTasks.Enqueue(pChore); + + ASSERT(!affinitySlot.IsEmpty()); + return affinitySlot; + } + + /// + /// Notifies virtual processors that work affinitized to them has become available in the schedule group segment. + /// + void CacheLocalScheduleGroupSegment::NotifyAffinitizedWork() + { + SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler(); + pScheduler->PostAffinityMessage(m_affinitySet); + + // + // If this item qualifies for the quick cache, stash it. + // + if (m_affinity._GetType() == location::_ExecutionResource) + { + pScheduler->SetQuickCacheSlot(m_maskIdIf, this); + } + } + + /// + /// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified + /// location. + /// + /// + /// The chore to mail. + /// + /// + /// A pointer to a location where the chore will be mailed. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + Mailbox<_UnrealizedChore>::Slot CacheLocalScheduleGroup::MailChore(_UnrealizedChore * pChore, + location * pPlacement, + ScheduleGroupSegmentBase ** ppDestinationSegment) + { + CacheLocalScheduleGroupSegment * pCacheLocalSegment = static_cast(LocateSegment(pPlacement, true)); + *ppDestinationSegment = pCacheLocalSegment; + return pCacheLocalSegment->MailChore(pChore); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.h new file mode 100644 index 0000000000000000000000000000000000000000..694bd96eda91c4b2073cb0aab8385c3395305c6f --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.h @@ -0,0 +1,159 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// CacheLocalScheduleGroup.h +// +// Header file containing CacheLocalScheduleGroup related declarations. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + + class CacheLocalScheduleGroup; + + class CacheLocalScheduleGroupSegment : public ScheduleGroupSegmentBase + { + + public: + + // + // Public Methods + // + + /// + /// Constructs a cache local schedule group segment + /// + CacheLocalScheduleGroupSegment(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) : + ScheduleGroupSegmentBase(pOwningGroup, pOwningRing, pSegmentAffinity) + { + } + + /// + /// Places a chore in the mailbox associated with this schedule group segment. + /// + /// + /// The chore to mail. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore *pChore); + + /// + /// Notifies virtual processors that work affinitized to them has become available in the schedule group segment. + /// + virtual void NotifyAffinitizedWork(); + + protected: + + + private: + friend class SchedulerBase; + friend class CacheLocalScheduleGroup; + friend class ContextBase; + friend class ExternalContextBase; + friend class InternalContextBase; + friend class ThreadInternalContext; + friend class SchedulingNode; + friend class SchedulingRing; + friend class VirtualProcessor; + + // + // Private data + // + + // Each schedule group has three stores of work. It has a collection of runnable contexts, + // a FIFO queue of realized chores and a list of workqueues that hold unrealized chores. + + // A collection of Runnable contexts. + SafeSQueue m_runnableContexts; + + // + // Private methods + // + + /// + /// Puts a runnable context into the runnables collection in the schedule group. + /// + void AddToRunnablesCollection(InternalContextBase *pContext); + + InternalContextBase *GetRunnableContext() + { + if (m_runnableContexts.Empty()) + return NULL; + + InternalContextBase *pContext = m_runnableContexts.Dequeue(); +#if defined(_DEBUG) + SetContextDebugBits(pContext, CTX_DEBUGBIT_REMOVEDFROMRUNNABLES); +#endif // _DEBUG + return pContext; + } + }; + + class CacheLocalScheduleGroup : public ScheduleGroupBase + { + public: + + /// + /// Constructs a new cache local schedule group. + /// + CacheLocalScheduleGroup(SchedulerBase *pScheduler, location* pGroupPlacement) : + ScheduleGroupBase(pScheduler, pGroupPlacement) + { + m_kind = CacheLocalScheduling; + } + + /// + /// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified + /// location. + /// + /// + /// The chore to mail. + /// + /// + /// A pointer to a location where the chore will be mailed. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore, + location * pPlacement, + ScheduleGroupSegmentBase ** ppDestinationSegment); + protected: + + /// + /// Allocates a new cache local schedule group segment within the specified group and ring with the specified affinity. + /// + /// + /// The affinity for the segment. + /// + /// + /// The scheduling ring to which the newly allocated segment will belong. + /// + /// + /// A new cache local schedule group within the specified group and ring with the specified affinity. + /// + virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity) + { + return _concrt_new CacheLocalScheduleGroupSegment(this, pOwningRing, pSegmentAffinity); + } + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Chores.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Chores.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35df72e313f1966ac86940969b2a52d1aa607eea --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Chores.cpp @@ -0,0 +1,376 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Chores.cpp +// +// Miscellaneous implementations of things related to individuals chores +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Sets the attachment state of the chore at the time of stealing. + /// + void _UnrealizedChore::_SetDetached(bool _FDetached) + { + _M_fDetached = _FDetached; + } + + /// + /// To free memory allocated with _InternalAlloc. + /// + void _UnrealizedChore::_InternalFree(_UnrealizedChore * _PChore) + { + ASSERT(_PChore->_M_fRuntimeOwnsLifetime); + delete _PChore; + } + + /// + /// Place associated task collection in a safe state. + /// + void _UnrealizedChore::_CheckTaskCollection() + { + // + // If _M_pTaskCollection is non-NULL, the chore is still scheduled to a task collection. This is only happening + // from a handle destructor and we have blown back through a stack based handle while it's still scheduled. We must + // wait. The semantic we choose is that this means cancellation too. + // + Concurrency::details::_TaskCollectionBase *pBase = _M_pTaskCollection; + if (pBase != NULL) + { + bool fThrow = false; + + if (_M_pChoreFunction == &_UnrealizedChore::_StructuredChoreWrapper) + { + _StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *>(pBase); + fThrow = !pTaskCollection->_TaskCleanup(); + } + else + { + _TaskCollection *pTaskCollection = static_cast<_TaskCollection *>(pBase); + fThrow = !pTaskCollection->_TaskCleanup(true); + } + + if (fThrow) + throw missing_wait(); + } + } + + /// + /// Prepares for execution as a stolen chore. + /// + void _UnrealizedChore::_PrepareSteal(ContextBase *pContext) + { + if (_M_pChoreFunction == &_UnrealizedChore::_StructuredChoreWrapper) + { + _PrepareStealStructured(pContext); + } + else + { + _PrepareStealUnstructured(pContext); + } + } + + /// + /// Called when a stolen chore from a given cancellation token is canceled. + /// + void _UnrealizedChore::_CancelViaToken(ContextBase *pContext) + { + pContext->CancelEntireContext(); + pContext->CancelStealers(NULL); + } + + /// + /// Prepares for execution as a stolen chore. + /// + void _UnrealizedChore::_PrepareStealStructured(ContextBase *pBaseContext) + { + InternalContextBase *pContext = static_cast (pBaseContext); + + if (pContext->GetRootCollection() == NULL) + { + _StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *> (_M_pTaskCollection); + ContextBase *pOriginContext = reinterpret_cast (pTaskCollection->_M_pOwningContext); + + pContext->SetRootCollection(pTaskCollection); + + pOriginContext->AddStealer(pContext, false); + } + } + + /// + /// Wrapper around execution of a structured chore that performs appropriate notification + /// and exception handling semantics. + /// + __declspec(noinline) + void __cdecl _UnrealizedChore::_StructuredChoreWrapper(_UnrealizedChore * pChore) + { + InternalContextBase *pContext = static_cast (SchedulerBase::FastCurrentContext()); + // The context could be canceled if it was already prepared for steal (this happens during a block unblock race) + ASSERT(pContext != NULL && (!pContext->HasInlineCancellation() || pContext->GetRootCollection() != NULL)); + + _StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *> (pChore->_M_pTaskCollection); + ContextBase *pOriginContext = reinterpret_cast (pTaskCollection->_M_pOwningContext); + + pChore->_PrepareStealStructured(pContext); + + // + // This allows cancellation of stolen chores based on a cancellation token between the declaration of a stg and its inlining. + // + _CancellationTokenState *pTokenState = pTaskCollection->_GetTokenState(); + _CancellationTokenRegistration *pRegistration = NULL; + + if (_CancellationTokenState::_IsValid(pTokenState)) + { + pRegistration = pTokenState->_RegisterCallback(reinterpret_cast(&_UnrealizedChore::_CancelViaToken), (ContextBase *)pContext); + } + + try + { + // + // We need to consider this a possible interruption point. It's entirely possible that we stole and raced with a + // cancellation thread. The collection was canceled after we stole(e.g.: removed from the WSQ) but before we added ourselves + // to the stealing chain list above. In this case, the entire context will wait until completion (bad). Immediately + // after we go on the list (a memory barrier) we need to check the collection cancellation flag. If the collection is going away, + // we need to get out *NOW* otherwise the entire subtree executes. + // + if (pTaskCollection->_IsAbnormalExit()) + throw _Interruption_exception(); + + pChore->m_pFunction(pChore); + } + catch(const _Interruption_exception &) + { + // + // If someone manually threw the _Interruption_exception exception, we will have a cancel count but not a canceled context. This + // means we need to apply the cancel one level up. Normally, the act of throwing would do that via being caught in the + // wait, but this is special "marshaling" for _Interruption_exception. + // + if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled()) + pTaskCollection->_Cancel(); + } + catch(...) + { + // + // Track the exception that was thrown here. _RaisedException makes the decision on what + // exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow. + // + pTaskCollection->_RaisedException(); + pTaskCollection->_Cancel(); + } + + pOriginContext->RemoveStealer(pContext); + ASSERT(pContext->GetGoverningTokenState() == NULL); + + // + // This allows cancellation of stolen chores based on a cancellation token between the declaration of a stg and its inlining. + // + if (pRegistration != NULL) + { + ASSERT(pTokenState != NULL); + pTokenState->_DeregisterCallback(pRegistration); + pRegistration->_Release(); + } + + pContext->ClearCancel(); + pContext->SetRootCollection(NULL); + pChore->_M_pTaskCollection = NULL; + pTaskCollection->_CountUp(); + } + + /// + /// Prepares for execution as a stolen chore. + /// + void _UnrealizedChore::_PrepareStealUnstructured(ContextBase *pBaseContext) + { + InternalContextBase *pContext = static_cast (pBaseContext); + + if (pContext->GetRootCollection() == NULL) + { + _TaskCollection* pTaskCollection = static_cast<_TaskCollection *> (_M_pTaskCollection); + ContextBase *pOriginContext = reinterpret_cast (pTaskCollection->_M_pOwningContext); + + pContext->SetRootCollection(pTaskCollection); + + // + // pOriginContext is only safe to touch if the act of stealing from a non-detached context put a hold on that context + // to block deletion until we are chained for cancellation. + // + SafeRWList *pList = reinterpret_cast *> (pTaskCollection->_M_stealTracker); + ASSERT(sizeof(pTaskCollection->_M_stealTracker) >= sizeof(*pList)); + + if (_M_fDetached) + { + // + // We cannot touch the owning context -- it was detached as of the steal. The chain goes onto the task collection. + // + pContext->NotifyTaskCollectionChainedStealer(); + pList->AddTail(&(pContext->m_stealChain)); + } + else + { + pList->AcquireWrite(); + pTaskCollection->_M_activeStealersForCancellation++; + pList->ReleaseWrite(); + pOriginContext->AddStealer(pContext, true); + } + } + } + + /// + /// Wrapper around execution of an unstructured chore that performs appropriate notification + /// and exception handling semantics. + /// + __declspec(noinline) + void __cdecl _UnrealizedChore::_UnstructuredChoreWrapper(_UnrealizedChore * pChore) + { + InternalContextBase *pContext = static_cast (SchedulerBase::FastCurrentContext()); + // The context could be canceled if it was already prepared for steal (this happens during a block unblock race) + ASSERT(pContext != NULL && (!pContext->HasInlineCancellation() || pContext->GetRootCollection() != NULL)); + + _TaskCollection* pTaskCollection = static_cast<_TaskCollection *> (pChore->_M_pTaskCollection); + + // + // pOriginContext is only safe to touch if the act of stealing from a non-detached context put a hold on that context + // to block deletion until we are chained for cancellation. + // + ContextBase *pOriginContext = reinterpret_cast (pTaskCollection->_M_pOwningContext); + SafeRWList *pList = reinterpret_cast *> (pTaskCollection->_M_stealTracker); + + pChore->_PrepareStealUnstructured(pContext); + + _CancellationTokenState *pTokenState = pTaskCollection->_GetTokenState(); + _CancellationTokenRegistration *pRegistration = NULL; + if (_CancellationTokenState::_IsValid(pTokenState)) + { + pRegistration = pTokenState->_RegisterCallback(reinterpret_cast(&_UnrealizedChore::_CancelViaToken), (ContextBase *)pContext); + } + + // + // Waiting on the indirect alias may throw (e.g.: the entire context may have been canceled). If it + // throws, we need to deal with appropriate marshaling. + // + try + { + // + // Set up an indirect alias for this task collection. Any usage of the original task collection + // within this stolen chore will automatically redirect through the indirect alias. This allows + // preservation of single-threaded semantics within the task collection while allowing it to be "accessed" + // from stolen chores (multiple threads). + // + // This stack based collection will wait on stolen chores at destruction time. In the event the collection is not + // used during the steal, this doesn't do much. + // + _TaskCollection indirectAlias(pTaskCollection, false); + + pContext->SetIndirectAlias(&indirectAlias); + + try + { + // + // We need to consider this a possible interruption point. It's entirely possible that we stole and raced with a + // cancellation thread. The collection was canceled after we stole(e.g.: removed from the WSQ) but before we added ourselves + // to the stealing chain list above. In this case, the entire context will wait until completion (bad). Immediately + // after we go on the list (a memory barrier), we need to check the collection cancellation flag. If the collection is going away, + // we need to get out *NOW* otherwise the entire subtree executes. + // + if (pTaskCollection->_M_pOriginalCollection->_M_exitCode != 0 || + (_CancellationTokenState::_IsValid(pTokenState) && pTokenState->_IsCanceled()) || + (pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_CLEAR && + pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_INLINE && + pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK)) + throw _Interruption_exception(); + + pChore->m_pFunction(pChore); + } + catch(const _Interruption_exception &) + { + // + // If someone manually threw _Interruption_exception, we will have a cancel count but not a canceled context. This + // means we need to apply the cancel one level up. Normally, the act of throwing would do that via being caught in the + // wait, but this is special "marshaling" for _Interruption_exception. + // + if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled()) + pTaskCollection->_Cancel(); + } + catch(...) + { + // + // Track the exception that was thrown here and subsequently cancel all work. _RaisedException makes the decision on what + // exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow. + // + pTaskCollection->_RaisedException(); + pTaskCollection->_Cancel(); + } + + indirectAlias._Wait(); + } + catch(const _Interruption_exception &) + { + // + // If someone manually threw _Interruption_exception out of a task on the indirect alias, the same thing applies as to + // a directly stolen chore (above). + // + if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled()) + pTaskCollection->_Cancel(); + } + catch(...) + { + // + // Track the exception that was thrown here and subsequently cancel all work. _RaisedException makes the decision on what + // exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow. + // + pTaskCollection->_RaisedException(); + pTaskCollection->_Cancel(); + } + + pContext->SetIndirectAlias(NULL); + ASSERT(pContext->GetGoverningTokenState() == NULL); + + if ( !pChore->_M_fDetached) + { + // + // pOriginContext may die at any point (detachment). When it does, it will transfer the stolen chore trace from the context to the + // given task collection (us) under lock. We can, therefore, take this lock and check if we are still okay to check the context. + // + pList->AcquireWrite(); + + if (pContext->IsContextChainedStealer()) + pOriginContext->RemoveStealer(pContext); + else + pList->UnlockedRemove(&(pContext->m_stealChain)); + + pTaskCollection->_M_activeStealersForCancellation--; + + pList->ReleaseWrite(); + + } + else + { + pList->Remove(&(pContext->m_stealChain)); + } + + if (pRegistration != NULL) + { + pTokenState->_DeregisterCallback(pRegistration); + pRegistration->_Release(); + } + + pContext->ClearCancel(); + pContext->ClearAliasTable(); + pContext->SetRootCollection(NULL); + pChore->_M_pTaskCollection = NULL; + pTaskCollection->_NotifyCompletedChoreAndFree(pChore); + } +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Context.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2328d6f2ca74bb52242a817c3a23160b99fd5fa6 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Context.cpp @@ -0,0 +1,180 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Context.cpp +// +// Implementation of static context APIs +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +/// +/// Returns a per scheduler unique identifier for the current context. +/// +/// +/// A per scheduler unique identifier for the current context or -1 if no such context exists. +/// +unsigned int Context::Id() +{ + const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext(); + return (pContext != NULL ? pContext->GetId() : UINT_MAX); +} + +/// +/// Returns an identifier for the virtual processor the current context is executing on. +/// +/// +/// An identifier for the virtual processor the current context is executing on or -1 if there is no such context +/// or it is not executing on a virtual processor at present. +/// +unsigned int Context::VirtualProcessorId() +{ + const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext(); + return (pContext != NULL ? pContext->GetVirtualProcessorId() : UINT_MAX); +} + +/// +/// Returns an identifier for the schedule group the current context is working on. +/// +/// +/// An identifier for the schedule group the current context is working on or -1 if there is no such context +/// or it is not executing a schedule group at present. +/// +unsigned int Context::ScheduleGroupId() +{ + const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext(); + return (pContext != NULL ? pContext->GetScheduleGroupId() : UINT_MAX); +} + +/// +/// Causes the current context to block, yielding execution to another context. If the current +/// thread does not have a ConcRT context associated with it, it is inducted into one. +/// +void Context::Block() +{ + return SchedulerBase::CurrentContext()->Block(); +} + +/// +/// Yields execution so that another context may execute. The current context is placed on the +/// scheduler's list of runnable contexts. If the current thread does not have a context, it is inducted +/// into a ConcRT context. If no other function is available to yield to, the function simply returns. +/// +void Context::Yield() +{ + SchedulerBase::CurrentContext()->Yield(); +} + +/// +/// Yields execution so that another context may execute. The current context is placed on the +/// scheduler's list of runnable contexts. If the current thread does not have a context, it is inducted +/// into a ConcRT context. If no other function is available to yield to, the function simply returns. +/// +/// This is intended for spin loops. +/// +void Context::_SpinYield() +{ + SchedulerBase::CurrentContext()->SpinYield(); +} + +/// +/// Returns an indication of whether the task collection which is currently executing inline on the current context +/// is in the midst of an active cancellation (or will be shortly). +/// +bool Context::IsCurrentTaskCollectionCanceling() +{ + ContextBase *pCurrentContext = SchedulerBase::SafeFastCurrentContext(); + if (pCurrentContext != NULL) + { + // + // If a structured collection has an unstructured collection as a parent, + // then GetExecutingCollection will always return the parent. + // + _TaskCollectionBase *pCollection = pCurrentContext->GetExecutingCollection(); + if (pCollection != NULL) + { + if (pCollection->_IsStructured()) + { + return static_cast(pCollection)->_IsCanceling(); + } + else if (static_cast(pCollection)->_IsAlias()) + { + return static_cast(pCollection)->_OriginalCollection()->_IsCanceling(); + } + else + { + return static_cast(pCollection)->_IsCanceling(); + } + } + } + return false; +} + +/// +/// Returns the ConcRT context associated with the current thread. +/// +/// +/// A pointer to the ConcRT context associated with the current thread if it exists. If one does not exist, +/// a new context is created. +/// +_Ret_notnull_ Context* Context::CurrentContext() +{ + return SchedulerBase::CurrentContext(); +} + +/// +/// Depending on the argument, causes the scheduler to add an extra virtual processor for the +/// duration of a block of code or remove a previously added one. +/// +/// Oversubscribe(true); +/// /* some slow kernel or I/O code, etc.*/ +/// Oversubscribe(false); +/// +/// An extra virtual processor is allocated on the current hardware thread between the two calls +/// to Oversubscribe. If additional idle virtual processors are available, the virtual processor is created +/// and made available, but if no available virtual processors exist, the virtual processor is kicked into +/// action with an internal context that searches for work. +/// Calls to Oversubscribe(TRUE) must be matched with calls to Oversubscribe(FALSE) -> calls can be nested, +/// but only a maximum of one additional virtual processor is created. The additional vproc, if any, will +/// be retired after the outermost call to Oversubscribe(FALSE), as soon as the currently executing root +/// chore on the vproc is completed. +/// +/// +/// [in] A boolean value specifying whether oversubscription is to be turned on or off. +/// +void Context::Oversubscribe(bool beginOversubscription) +{ + SchedulerBase::CurrentContext()->Oversubscribe(beginOversubscription); +} + +namespace details +{ + _Context _Context::_CurrentContext() + { + return _Context(SchedulerBase::CurrentContext()); + } + + void _Context::_Yield() + { + SchedulerBase::CurrentContext()->Yield(); + } + + void _Context::_Oversubscribe(bool _BeginOversubscription) + { + SchedulerBase::CurrentContext()->Oversubscribe(_BeginOversubscription); + } + + bool _Context::_IsSynchronouslyBlocked() const + { + return _M_pContext->IsSynchronouslyBlocked(); + } +} + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b49593d640f8b5175113a80394ab7b112e611623 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.cpp @@ -0,0 +1,1341 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ContextBase.cpp +// +// Source file containing the implementation for an execution ContextBase/stack/thread. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" + +#pragma warning (disable : 4702) + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructor + /// + ContextBase::ContextBase(SchedulerBase *pScheduler, bool fIsExternal) : + m_criticalRegionCount(0), + m_hyperCriticalRegionCount(0), + m_oversubscribeCount(0), + m_pScheduler(pScheduler), + m_pWorkQueue(NULL), + m_pParentContext(NULL), + m_blockedState(CONTEXT_BLOCKED), + m_contextSwitchingFence(0), + m_pRootCollection(NULL), + m_pExecutingCollection(NULL), + m_pGoverningTokenState(NULL), + m_governingTokenDepth(-1), + m_asyncTaskCollectionInlineDepth(0), + m_threadId(0), + m_fIsExternal(fIsExternal), +#if defined(_DEBUG) + m_fShutdownValidations(false), +#endif // _DEBUG + m_cancellationRefCount(0), + m_minCancellationDepth(-1), + m_maxCancellationDepth(-1), + m_inlineCancellations(0), + m_canceledContext(0), + m_pendingCancellations(0), + m_pIndirectAlias(NULL), + // + // The alias table must be sufficiently small that clearing it at the end of a stolen chore isn't a huge penalty, yet + // large enough to splay a few task collections. Hopefully, the number of collections being utilized in stolen chores isn't very + // large (1 or 2), so this size should be sufficient. + // + m_aliasTable(7) + { + m_id = m_pScheduler->GetNewContextId(); + TraceContextEvent(CONCRT_EVENT_START, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + } + + unsigned int ContextBase::ScheduleGroupRefCount() const + { + return m_pSegment != NULL ? (unsigned int)m_pSegment->GetGroup()->m_refCount : UINT_MAX; + } + + /// + /// Returns a unique identifier to the context + /// + unsigned int ContextBase::GetId() const + { + return m_id; + } + + /// + /// Returns an identifier to the schedule group the context is currently working on, if any. + /// + unsigned int ContextBase::GetScheduleGroupId() const + { + return (m_pSegment != NULL) ? m_pSegment->GetGroup()->Id() : UINT_MAX; + } + + /// + /// Places a reference on the context preventing it from being destroyed until such time as the stealer is added to the chain + /// via AddStealer. Note that the operation of AddStealer should happen rapidly as it will *BLOCK* cleanup of the context. + /// + void ContextBase::ReferenceForCancellation() + { + InterlockedIncrement(&m_cancellationRefCount); + } + + /// + /// Removes a reference on the context which was preventing it from being destroyed. + /// + void ContextBase::DereferenceForCancellation() + { + InterlockedDecrement(&m_cancellationRefCount); + } + + /// + /// Adds a stealing context. + /// + void ContextBase::AddStealer(ContextBase *pStealer, bool fDereferenceForCancellation) + { + m_stealers.AddTail(&(pStealer->m_stealChain)); + pStealer->m_fContextChainedStealer = true; + if (fDereferenceForCancellation) + DereferenceForCancellation(); + } + + /// + /// Removes a stealing context. + /// + void ContextBase::RemoveStealer(ContextBase *pStealer) + { + m_stealers.Remove(&(pStealer->m_stealChain)); + } + + /// + /// Cancel everything stolen from pCanceledCollection outward from this context. + /// + void ContextBase::CancelStealers(_TaskCollectionBase *pCanceledCollection) + { + ASSERT(pCanceledCollection != NULL || IsEntireContextCanceled()); + + SafeRWList::_Scoped_lock_read readLock(m_stealers); + ListEntry *pLE = m_stealers.First(); + while (pLE != NULL) + { + ContextBase *pStealingContext = CONTAINING_RECORD(pLE, ContextBase, m_stealChain); + + // + // We don't want to be recursively traversing the tree needlessly every time the exception propagates back + // up a given context. If a context is already canceled, nothing can steal from it and we don't need to traverse + // there. + // + if (!pStealingContext->IsEntireContextCanceled()) + { + _TaskCollectionBase *pRootCollection = pStealingContext->GetRootCollection(); + ASSERT(pRootCollection != NULL); + // + // If pCanceledCollection != NULL, it is an indication that we're at the first level. We can only cancel things that are stolen + // from greater inlining depth or things from equal if the root collection is pCollection. Further, we cannot cancel things which are not + // inlined. For example: + // + // _TaskCollection p1; + // p1.Schedule( [] { + // _TaskCollection *p2 = new _TaskCollection; + // p2.Schedule(alpha); + // _TaskCollection p3; + // p3.Schedule( [] { + // Blah; + // }); + // }); + // + // A cancel of p1 while p1->p3 is running inline cannot cancel p2. The exception that backflows might indeed cancel p2 if it was stack + // based, but remember we can have task collection pointers which are passed amongst threads and detached. + // + // Keep in mind that it's entirely possible to have a situation similar to above during the recursion where one of the stolen chores declared + // a task collection and pushed chores that will not be waited upon but instead will be passed out to another thread. We cannot tear down contexts + // that stole in this manner either. + // + + if ( + // A context whose root chore belongs to the task collection being canceled is fair game. No further checks are required. + (pRootCollection == pCanceledCollection) || + + // On recursion, as long as the root collection is inlined (no matter the depth), we are safe to cancel as it was inlined on a canceled + // context and that by definition gives it the correct parentage to be shot down. + (pCanceledCollection == NULL && pRootCollection->_IsCurrentlyInlined()) || + + // The only way cancellation can be satisfied if both aren't inlined is above. Otherwise, the one that stole must have greater + // inline depth than the one we're canceling. + (pCanceledCollection != NULL && pCanceledCollection->_IsCurrentlyInlined() && pRootCollection->_InliningDepth() > pCanceledCollection->_InliningDepth()) + ) + { + ASSERT(pRootCollection == pCanceledCollection || pCanceledCollection == NULL || pRootCollection->_IsCurrentlyInlined()); + // + // We must verify that it is okay to cancel the stealer based on any tokens which are present on 'this' context. We are further guaranteed + // stability on the inlining depth because of the lock on the stealers list. + // + bool fCancel = true; + if (pRootCollection != pCanceledCollection && m_governingTokenDepth != -1) + { + ASSERT(pRootCollection->_IsCurrentlyInlined() && m_pGoverningTokenState != NULL); + fCancel = IsCanceledAtDepth(pRootCollection); + } + + if (fCancel) + { + pStealingContext->CancelEntireContext(); + pStealingContext->CancelStealers(NULL); + } + } + } + + pLE = m_stealers.Next(pLE); + } + } + + /// + /// Cleans up the context. + /// + void ContextBase::Cleanup() + { + ReleaseWorkQueue(); + + TraceContextEvent(CONCRT_EVENT_END, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + } + + /// + /// Called on both internal and external contexts, either when the are put into an idle pool to + /// be recycled, or when they are ready to be deleted. The API moves the contexts that are in + /// the list of 'stealers' (used for cancellation) to lists in the task collections from which + /// those contexts have stolen chores. + /// + void ContextBase::DetachStealers() + { + // + // Make sure no one has a ref on us to add to the stealers list. We need to wait on that before running down the cancellation list. + // Note that waiting here should be *EXTREMELY RARE*. The only time we'd ever see it would be if a task collection was used between threads and + // and between the time of the steal and the time the wrapper executed the original thread went away. + // + + if (m_cancellationRefCount != 0) + { + // Spin wait (no yielding) + _SpinWaitNoYield spinWait; + + do + { + spinWait._SpinOnce(); + + } while (m_cancellationRefCount != 0); + } + + if (m_aliasTable.Count() > 0) + ClearAliasTable(); + + if (m_stealers.Empty()) + { + // + // After a DetachStealers, it is entirely possible that the context (the *this*) pointer goes away. Normally, the lock on the stealers + // list is what guards against manipulation by stolen chores; however -- the early exit above presents an interesting risk. It is now entirely + // possible that the last stolen chore is removing its context from the stealers list under the governance of the write lock and makes the + // list empty. The detachment wants to bail due to the above check (there's nothing there) and the context pointer is freed before the stealing + // thread releases the write lock. + // + // We do want the early bail to avoid taking and releasing a reader/writer frequently in this case for scenarios like parallel for. In order to + // prevent touching freed memory, we need to flush out any write owner (take and release the lock if someone holds a write). + // + m_stealers.FlushWriteOwners(); + return; + } + + // + // If there is anything left on the stealers list, it means that a context is dying while a task collection bound to that context lives + // on and still has stolen chores. In order to continue to facilitate cancellation of those task collections, any stealers in the list have + // to be moved to the individual task collection lists. + // + bool isDone = false; + + while(!isDone) + { + bool fContinue = true; + m_stealers.AcquireWrite(); + __try + { + fContinue = true; + ListEntry *pEntry = m_stealers.First(); + while (pEntry != NULL && fContinue) + { + ListEntry *pNext = m_stealers.Next(pEntry); + + ContextBase *pContext = CONTAINING_RECORD(pEntry, ContextBase, m_stealChain); + + _TaskCollectionBase *pCollectionBase = pContext->GetRootCollection(); + ASSERT(pCollectionBase != NULL && !pCollectionBase->_IsStructured()); + + _TaskCollection *pCollection = static_cast<_TaskCollection *>(pCollectionBase); + + // + // In all likelihood, we rarely get here; however -- there is an issue in that the lock ordering here is from the bottom up + // (task collection then context) in order to preserve patterns in stealing and cancellation. + // + // When we move, we must do so in a backwards order. The only time we should see contention on these locks is during minimal + // periods where we are cancelling or for tiny time frames during steal. We will play a pseudo-atomic lock acquire game. If we cannot + // get both, we back off and let the other thread through. + // + SafeRWList *pCollectionList = reinterpret_cast *> (pCollection->_GetStealTrackingList()); + if (!pCollectionList->TryAcquireWrite()) + { + // + // Yield in an attempt to force the other thread through. + // + m_stealers.ReleaseWrite(); + fContinue = false; + platform::__Sleep(1); + break; + } + + __try + { + m_stealers.UnlockedRemove(&(pContext->m_stealChain)); + pContext->m_fContextChainedStealer = false; + pCollectionList->UnlockedAddTail(&(pContext->m_stealChain)); + } + __finally + { + pCollectionList->ReleaseWrite(); + } + + pEntry = pNext; + } + + isDone = (pEntry == NULL); + } + __finally + { + // + // It may have been released due to a back-off. + // + if (fContinue) + { + m_stealers.ReleaseWrite(); + } + } + } + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue. + /// + void ContextBase::PushStructured(_UnrealizedChore *pChore, location *pLocation) + { + Mailbox<_UnrealizedChore>::Slot affinitySlot; + + // If the chore has been scheduled with a location and the scheduler supports location-based scheduling, the destination schedule + // group segment may be different from the current one. + ScheduleGroupSegmentBase * pDestinationSegment = m_pSegment; + + if (pLocation != NULL) + { + // + // If the current segment this context is operating within has the same affinity as the requested task, there is *NO NEED* to mail + // the task anywhere. It will get a natural affinity to pLocation without any additional work. + // + if (!pLocation->_Is_system()) + { + if (*pLocation != m_pSegment->GetAffinity()) + { + affinitySlot = m_pSegment->GetGroup()->MailChore(pChore, pLocation, &pDestinationSegment); + } + + pDestinationSegment->NotifyAffinitizedWork(); + } + } + + GetStructuredWorkQueue()->PushStructured(pChore, affinitySlot); + + // + // Update the enqueued task numbers for statistics. Since this is a critical performance + // path we avoid making a virtual call since that will imply two memory dereferences plus + // an indirect call. Instead, we make one memory dereference to get a condition and one + // branch. This is faster ONLY because target function call will be inlined. + // + if (IsExternal()) + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + else + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + + if (m_pScheduler->HasVirtualProcessorAvailableForNewWork()) + { + m_pScheduler->StartupNewVirtualProcessor(pDestinationSegment, pDestinationSegment->GetAffinity()); + } + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue. + /// + void ContextBase::PushStructured(_UnrealizedChore *pChore) + { + GetStructuredWorkQueue()->PushStructured(pChore); + + // + // Update the enqueued task numbers for statistics. Since this is a critical performance + // path we avoid making a virtual call since that will imply two memory dereferences plus + // an indirect call. Instead, we make one memory dereference to get a condition and one + // branch. This is faster ONLY because target function call will be inlined. + // + if (IsExternal()) + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + else + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + + if (m_pScheduler->HasVirtualProcessorAvailableForNewWork()) + { + m_pScheduler->StartupNewVirtualProcessor(m_pSegment); + } + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. + /// + /// + /// The chore to push onto the unstructured work stealing queue. + /// + int ContextBase::PushUnstructured(_UnrealizedChore *pChore, location *pLocation) + { + Mailbox<_UnrealizedChore>::Slot affinitySlot; + + // If the chore has been scheduled with a location and the scheduler supports location-based scheduling, the destination schedule + // group segment may be different from the current one. + ScheduleGroupSegmentBase * pDestinationSegment = m_pSegment; + + if (pLocation != NULL) + { + // + // If the current segment this context is operating within has the same affinity as the requested task, there is *NO NEED* to mail + // the task anywhere. It will get a natural affinity to pLocation without any additional work. + // + if (!pLocation->_Is_system()) + { + if (*pLocation != m_pSegment->GetAffinity()) + { + affinitySlot = m_pSegment->GetGroup()->MailChore(pChore, pLocation, &pDestinationSegment); + } + + pDestinationSegment->NotifyAffinitizedWork(); + } + } + + int cookie = GetWorkQueue()->PushUnstructured(pChore, affinitySlot); + + // + // Update the enqueued task numbers for statistics. Since this is a critical performance + // path we avoid making a virtual call since that will imply two memory dereferences plus + // an indirect call. Instead, we make one memory dereference to get a condition and one + // branch. This is faster ONLY because target function call will be inlined. + // + if (IsExternal()) + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + else + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + + if (m_pScheduler->HasVirtualProcessorAvailableForNewWork()) + { + m_pScheduler->StartupNewVirtualProcessor(pDestinationSegment, pDestinationSegment->GetAffinity()); + } + + return cookie; + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. + /// + /// + /// The chore to push onto the unstructured work stealing queue. + /// + int ContextBase::PushUnstructured(_UnrealizedChore *pChore) + { + int cookie = GetWorkQueue()->PushUnstructured(pChore); + + // + // Update the enqueued task numbers for statistics. Since this is a critical performance + // path we avoid making a virtual call since that will imply two memory dereferences plus + // an indirect call. Instead, we make one memory dereference to get a condition and one + // branch. This is faster ONLY because target function call will be inlined. + // + if (IsExternal()) + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + else + { + static_cast(this)->IncrementEnqueuedTaskCounter(); + } + + if (m_pScheduler->HasVirtualProcessorAvailableForNewWork()) + { + m_pScheduler->StartupNewVirtualProcessor(m_pSegment); + } + + return cookie; + } + + /// + /// Pops the topmost chore from the work stealing queue for structured parallelism. Failure + /// to pop typically indicates stealing. + /// + /// + /// An unrealized chore from the structured work stealing queue or NULL if none is present. + /// + _UnrealizedChore *ContextBase::PopStructured() + { + ASSERT(m_pWorkQueue != NULL); + _UnrealizedChore *pChore = m_pWorkQueue->PopStructured(); + + return pChore; + } + + /// + /// Attempts to pop the chore specified by a cookie value from the unstructured work stealing queue. Failure + /// to pop typically indicates stealing. + /// + /// + /// A cookie returned from PushUnstructured indicating the chore to attempt to pop from + /// the unstructured work stealing queue. + /// + /// + /// The specified unrealized chore (as indicated by cookie) or NULL if it could not be popped from + /// the work stealing queue + /// + _UnrealizedChore *ContextBase::TryPopUnstructured(int cookie) + { + ASSERT(m_pWorkQueue != NULL); + _UnrealizedChore *pChore = m_pWorkQueue->TryPopUnstructured(cookie); + + return pChore; + } + + /// + /// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them + /// based on the result of a callback. + /// + /// + /// The predicate for things to call pSweepFn on. + /// + /// + /// The data for the predicate callback + /// + /// + /// The sweep function + /// + void ContextBase::SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate, + void *pData, + WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn + ) + { + ASSERT(m_pWorkQueue != NULL); + return m_pWorkQueue->SweepUnstructured(pPredicate, pData, pSweepFn); + } + + /// + /// Create a workqueue for use in unstructured task collections. + /// + void ContextBase::CreateWorkQueue() + { + // + // First try and reuse a detached workqueue. + // + m_pWorkQueue = m_pSegment->GetDetachedWorkQueue(); + // + // A detached work queue is still on m_pGroup->m_workQueues. + // + if (m_pWorkQueue == NULL) + { + // + // If that failed, try and reuse a workqueue from the free pool. + // + m_pWorkQueue = m_pSegment->m_workQueues.PullFromFreePool(); + + if (m_pWorkQueue == NULL) + { + // + // Must create a new one. + // + m_pWorkQueue = _concrt_new WorkQueue(); + } + else + { + // + // Reinitialize the work queue from the free pool. + // + m_pWorkQueue->Reinitialize(); + } + + m_pSegment->m_workQueues.Add(m_pWorkQueue); + } + + ASSERT(m_pWorkQueue != NULL); + m_pWorkQueue->SetOwningContext(this); + } + + /// + /// Create a workqueue for use in structured task collections. + /// + void ContextBase::CreateStructuredWorkQueue() + { + // + // First, try and reuse a workqueue from the free pool. + // When using structured task collections, quite often there are + // no previous unstructured task collections that neglected to wait (thus generating detached workqueues). + // + m_pWorkQueue = m_pSegment->m_workQueues.PullFromFreePool(); + + if (m_pWorkQueue == NULL) + { + // + // If that failed, see if there is a workqueue on the detachedWorkQueues list to reuse. + // + m_pWorkQueue = m_pSegment->GetDetachedWorkQueue(); + + // + // A detached work queue is still on m_pSegment->m_workQueues. + // + if (m_pWorkQueue == NULL) + { + m_pWorkQueue = _concrt_new WorkQueue(); + m_pSegment->m_workQueues.Add(m_pWorkQueue); + } + } + else + { + // + // Reinitialize the work queue from the free pool. + // + m_pWorkQueue->Reinitialize(); + m_pSegment->m_workQueues.Add(m_pWorkQueue); + } + + ASSERT(m_pWorkQueue != NULL); + m_pWorkQueue->SetOwningContext(this); + } + + /// + /// Cleans up the internal workqueue. + /// + void ContextBase::ReleaseWorkQueue() + { + if (m_pWorkQueue != NULL) + { + // + // It's entirely possible that this particular work queue had chores left on the unstructured work queue. + // Someone could create an unstructured task collection within an LWT, queue chores, and subsequently pass + // the collection out of the LWT to be waited upon later. In this case, we must leave the work queue around + // in order for stealing to appropriately happen. This work queue will not be dechained from the schedule + // group, but will remain until empty. It will go on a lookaside and, while in this state, can be handed + // to some new context working on an item within the same schedule group. + // + + // Save off a local copy of the workqueue and work with that. The debugger mines the workqueue information + // held in this context, and if we remove the work queue while it's still pointed at by this context, the + // debugger can become confused. + WorkQueue* workQueue = m_pWorkQueue; + m_pWorkQueue = NULL; + + if ( !workQueue->IsUnstructuredEmpty()) + { + workQueue->LockedSetOwningContext(NULL); + m_pSegment->DetachActiveWorkQueue(workQueue); + } + else + { + // + // Unless someone really side-stepped the intent of _StructuredTaskCollection, it's almost certain that + // workQueue->IsStructuredEmpty() is true or else a missing_wait was already thrown. + // + if (workQueue->IsLockHeld()) + { + // Somebody is stealing, don't want to NULL out owning ctx until they're done. + workQueue->LockedSetOwningContext(NULL); + } + else + { + // We know workQueue has no unstructured, since we're on the owning thread. + // Moreover, structured must be empty at this point, because we cannot ever get here until the wait is satisfied. + // If the UnlockedSteal is entered, then we'll early exit w/o ever touching the owning ctx of workQueue. + workQueue->SetOwningContext(NULL); + } + m_pSegment->m_workQueues.Remove(workQueue); + } + } + + // + // Make sure that any detachment triggers the stealers to move into the task collection list. Otherwise, we can wind up with + // an A<-B<-A stealing pattern: + // + // TC 1 on thread A + // Thread B steals from TC 1 (A<-B) + // Thread A detaches (no wait on TC1) + // Thread A does SFW and steals from TC 2 deeper inline on thread B (B<-A) + // + // The overall stealers pattern is A<-B<-A which will wind up with lock traversal in this order. The recursive reacquire of + // R/W lock (or out of order acquire: A<-B on one thread, B<-A on the other) will result in later deadlock. + // + DetachStealers(); + } + + /// + /// Sets the 'this' context into the tls slot as the current context. This is used by internal contexts in + /// their dispatch loops. + /// + void ContextBase::SetAsCurrentTls() + { + platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, this); + } + + /// + /// When schedulers are nested on the same thread, the nested scheduler creates a new external context that overrides + /// the previous context. PopContextFromTls will restore the previous context by setting the TLS value appropriately. + /// + ContextBase* ContextBase::PopContextFromTls() + { + ContextBase* pPreviousContext = m_pParentContext; + platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, pPreviousContext); + m_pParentContext = NULL; + return pPreviousContext; + } + + /// + /// When schedulers are nested on the same thread, the nested scheduler creates a new external context that overrides + /// the previous context. PushContextToTls will store the previous context and set the new context into TLS. + /// + void ContextBase::PushContextToTls(ContextBase* pParentContext) + { + m_pParentContext = pParentContext; + + // For the first context on a thread, we expect the TLS values to be null. If there is a parent context, + // the TLS value should have been cleared right before nesting. + ASSERT(platform::__TlsGetValue(SchedulerBase::t_dwContextIndex) == NULL); + platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, this); + } + + /// + /// Context TLS is cleared during nesting on internal contexts before the external context TLS is correctly setup. If not, + /// code that executes between the clear and setting the new TLS could get confused. + /// + void ContextBase::ClearContextTls() + { + ASSERT(platform::__TlsGetValue(SchedulerBase::t_dwContextIndex) != NULL); + platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, NULL); + } + + /// + /// Returns the scheduler the specified context is associated with. + /// + SchedulerBase* ContextBase::GetScheduler() const + { + return m_pScheduler; + } + + /// + /// Returns the schedule group the specified context is associated with. + /// + ScheduleGroupBase* ContextBase::GetScheduleGroup() const + { + return m_pSegment != NULL ? m_pSegment->GetGroup() : NULL; + } + + /// + /// Returns the schedule group the specified context is associated with. + /// + ScheduleGroupSegmentBase* ContextBase::GetScheduleGroupSegment() const + { + return m_pSegment; + } + + /// + /// Gets the indirect alias. + /// + _TaskCollection *ContextBase::GetIndirectAlias() const + { + return m_pIndirectAlias; + } + + /// + /// Sets the indirect alias. + /// + void ContextBase::SetIndirectAlias(_TaskCollection *pAlias) + { + m_pIndirectAlias = pAlias; + } + + /// + /// Sweeps the alias table removing anything that's marked for delete. This is done every time we create a new direct alias + /// in order to avoid growing the table arbitrarily for a context which isn't going away. Note -- passing a task collection between + /// threads is expensive the first time it's used. + /// + void ContextBase::SweepAliasTable() + { + int x; + Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.First(&x); + while (pNode != NULL) + { + Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNextNode = m_aliasTable.Next(&x, pNode); + + if (pNode->m_value->_IsStaleAlias()) + { + _TaskCollection *pCollection = pNode->m_value; + m_aliasTable.Delete(pCollection->_OriginalCollection()); // may delete pNode + delete pCollection; + } + + pNode = pNextNode; + } + } + + /// + /// Clears the alias table. + /// + void ContextBase::ClearAliasTable() + { + int x; + Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.First(&x); + while (pNode != NULL) + { + pNode->m_value->_ReleaseAlias(); + pNode = m_aliasTable.Next(&x, pNode); + } + m_aliasTable.Wipe(); + } + + /// + /// Sets the cancellation token currently governing this context. + /// + void ContextBase::PushGoverningTokenState(_CancellationTokenState *pTokenState, int inliningDepth) + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + m_pGoverningTokenState = pTokenState; + m_governingTokenDepth = inliningDepth; + } + + /// + /// Reverts to the previously set cancellation token. + /// + void ContextBase::PopGoverningTokenState(_CancellationTokenState *pTokenState) + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_pGoverningTokenState == pTokenState); + ASSERT(m_pExecutingCollection->_InliningDepth() == m_governingTokenDepth); + + // Move back up to find the parent. Even if the parent has the same token, we need to change the + // governing token depth to *its* inlining depth + _TaskCollectionBase *pCollection = m_pExecutingCollection->_SafeGetParent(); + + while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_GetTokenState() == NULL) + { + pCollection = pCollection->_SafeGetParent(); + } + // + // We only keep governing tokens for THIS context. + // + if (pCollection != NULL && pCollection != m_pRootCollection) + { + ASSERT(pCollection->_GetTokenState() != NULL && pCollection->_InliningDepth() != -1); + m_pGoverningTokenState = pCollection->_GetTokenState(); + m_governingTokenDepth = pCollection->_M_inliningDepth; + } + else + { + m_pGoverningTokenState = NULL; + m_governingTokenDepth = -1; + } + } + + /// + /// Called in order to indicate that a collection executing on this context was canceled. This will often cause cancellation + /// and unwinding of the entire context (up to the point where we get to the canceled collection). This method is paired with + /// CancelCollectionComplete. + /// NOTE: Callers of CancelCollection must first guarantee through other means that the collection they're cancelling (the one at the + /// depth by the argument) will have a stable inlining depth through the duration of the CancelCollection call. + /// * For structured task collections, since cancel is only allowed to be called by the owning context or within a stolen chore, if an + /// inlining depth greater than zero is observed, it is stable since the owning thread will have to wait until the chore invoking CancelCollection + /// completes. + /// * For general task collections, cancel is allowed from arbitrary threads. If the calling thread is an indirect alias, the inlining + /// depth will be stable if observed to be greater than 0 (because CancelCollection is executing inside a stolen chore). Alternatively the thread can use + /// a CAS based state lock (see _TaskCollection::_CancelFromArbitraryThread) to ensure that inlining depth is stable. + /// + void ContextBase::CancelCollection(int inliningDepth) + { + InterlockedIncrement(&m_inlineCancellations); + + long curDepth = m_minCancellationDepth; + // + // Keep track of the minimum cancellation depth. + // + for(;;) + { + if (curDepth != -1 && inliningDepth > curDepth) + break; + + long xchgDepth = InterlockedCompareExchange(&m_minCancellationDepth, inliningDepth, curDepth); + if (xchgDepth == curDepth) + { + // + // Cancellation beacons are a bit different. If the entire context was canceled due to a steal, we flag top level cancellation + // beacons even though they are not considered to have inlining depth since the caller might not have been inlined. + // + FlagCancellationBeacons(IsEntireContextCanceled() ? -1 : inliningDepth); + break; + } + curDepth = xchgDepth; + } + + long curMaxDepth = m_maxCancellationDepth; + // + // Keep track of the maximum cancellation depth + // + for(;;) + { + if (curMaxDepth != -1 && inliningDepth < curMaxDepth) + break; + + long xchgDepth = InterlockedCompareExchange(&m_maxCancellationDepth, inliningDepth, curMaxDepth); + if (xchgDepth == curMaxDepth) + { + break; + } + curMaxDepth = xchgDepth; + } + } + + /// + /// Recomputes the maximum depth of cancellation after a canceled task group clears its cancellation flag. + /// + void ContextBase::RecomputeMaximumCancellationDepth() + { + // + // Before doing the recompute, we **MUST** reset to uninitialized to avoid a race between someone setting this in ::CancelCollection and + // someone doing a recompute across a boundary. + // + InterlockedExchange(&m_maxCancellationDepth, -1); + + long computedMaximumDepth = IsEntireContextCanceled() ? ENTIRE_CONTEXT_CANCELED : -1; + + _TaskCollectionBase *pCollection = m_pExecutingCollection; + while (pCollection != NULL && pCollection != m_pRootCollection) + { + if ((pCollection->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pCollection))->_IsMarkedForCancellation()) || + (!pCollection->_IsStructured() && (static_cast<_TaskCollection *>(pCollection))->_IsMarkedForAbnormalExit())) + { + computedMaximumDepth = pCollection->_M_inliningDepth; + break; + } + + pCollection = pCollection->_SafeGetParent(); + } + + long curMaxDepth = -1; + + // + // Keep track of the maximum cancellation depth + // + for(;;) + { + if (curMaxDepth != -1 && computedMaximumDepth < curMaxDepth) + break; + + long xchgDepth = InterlockedCompareExchange(&m_maxCancellationDepth, computedMaximumDepth, curMaxDepth); + if (xchgDepth == curMaxDepth) + { + break; + } + + curMaxDepth = xchgDepth; + } + } + + /// + /// When a cancellation bubbles up to the collection being canceled, this function is called in order to stop propagation of + /// the cancellation further up the work tree. This method is paired with CancelCollection. + /// + bool ContextBase::CancelCollectionComplete(int inliningDepth) + { + ASSERT(m_inlineCancellations > 0); + + // + // Keep track of minimum/maximum cancellation depth. + // + InterlockedCompareExchange(&m_minCancellationDepth, -1, inliningDepth); + RecomputeMaximumCancellationDepth(); + + return (InterlockedDecrement(&m_inlineCancellations) == 0); + } + + /// + /// Send a context ETW event. + /// + void ContextBase::ThrowContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId) + { + if (g_pEtw != NULL) + { + CONCRT_TRACE_EVENT_HEADER_COMMON concrtHeader = {0}; + + concrtHeader.header.Size = sizeof concrtHeader; + concrtHeader.header.Flags = WNODE_FLAG_TRACED_GUID; + concrtHeader.header.Class.Type = (UCHAR)eventType; + concrtHeader.header.Class.Level = level; + concrtHeader.header.Guid = ContextEventGuid; + + concrtHeader.SchedulerID = schedulerId; + concrtHeader.ContextID = contextId; + + g_pEtw->Trace(g_ConcRTSessionHandle, &concrtHeader.header); + } + } + + /// + /// Enters a critical region of the scheduler. Calling this guarantees that the virtual processor on which this context lives + /// is guaranteed to be stable throughout the critical region. For some context types, this is virtually a NOP. + /// Note that critical regions suppress asynchronous blocking but not synchronous blocking. + /// + int ContextBase::EnterCriticalRegion() + { + return 0; + } + + /// + /// Exits a critical region of the scheduler. + /// + int ContextBase::ExitCriticalRegion() + { + return 0; + } + + /// + /// Enters a hyper-critical region of the scheduler. Calling this guarantees not only the conditions of a critical region but it + /// guarantees that synchronous blocking is suppressed as well. This allows for lock sharing between the primary and hyper-critical + /// regions running on UTs. No lock sharing can occur between the inside of this region type and the outside of this region type + /// on a UT. + /// + int ContextBase::EnterHyperCriticalRegion() + { + return 0; + } + + /// + /// Exits a hyper-critical region of the scheduler. + /// + int ContextBase::ExitHyperCriticalRegion() + { + return 0; + } + + /// + /// Static version of EnterCriticalRegion. + /// + void ContextBase::StaticEnterCriticalRegion() + { + ContextBase *pContext = SchedulerBase::FastCurrentContext(); + if (pContext != NULL) + pContext->EnterCriticalRegion(); + } + + /// + /// Static version of EnterHyperCriticalRegion. + /// + void ContextBase::StaticEnterHyperCriticalRegion() + { + ContextBase *pContext = SchedulerBase::FastCurrentContext(); + if (pContext != NULL) + pContext->EnterHyperCriticalRegion(); + } + + /// + /// Static version of ExitCriticalRegion. + /// + void ContextBase::StaticExitCriticalRegion() + { + ContextBase *pContext = SchedulerBase::FastCurrentContext(); + if (pContext != NULL) + pContext->ExitCriticalRegion(); + } + + /// + /// Static version of ExitHyperCriticalRegion. + /// + void ContextBase::StaticExitHyperCriticalRegion() + { + ContextBase *pContext = SchedulerBase::FastCurrentContext(); + if (pContext != NULL) + pContext->ExitHyperCriticalRegion(); + } + + /// + /// Static version of GetCriticalRegionType. + /// + CriticalRegionType ContextBase::StaticGetCriticalRegionType() + { + ContextBase *pContext = SchedulerBase::FastCurrentContext(); + if (pContext != NULL) + return pContext->GetCriticalRegionType(); + return OutsideCriticalRegion; + } + + /// + /// Since critical region counts are turned off for thread schedulers, this method is used + /// where the return value is expected to be true. For a thread scheduler, it always returns true. + /// + bool ContextBase::IsInsideCriticalRegion() const + { + return true; + } + + /// + /// Returns a bool which can be polled from the current location in lieu of calling is_current_task_group_canceling. + /// + _Beacon_reference *ContextBase::PushCancellationBeacon() + { + int inliningDepth = m_pExecutingCollection ? m_pExecutingCollection->_InliningDepth() : -1; + + CancellationBeacon *pBeacon = m_cancellationBeacons.AcquirePushBeacon(inliningDepth); + + // + // AcquirePushBeacon has a full fence to guard R/W ordering here. + // + if (IsEntireContextCanceled() || (m_minCancellationDepth != -1 && m_minCancellationDepth <= pBeacon->m_beaconDepth)) + pBeacon->InternalSignal(); + + return &(pBeacon->m_beacon); + } + + /// + /// Releases the topmost bool acquired in RAII fashion from PushCancellationBeacon. + /// + void ContextBase::PopCancellationBeacon() + { + m_cancellationBeacons.ReleaseBeacon(); + } + + /// + /// Flags any cancellation beacons that are inlined at or below the specified point. + /// + void ContextBase::FlagCancellationBeacons(int inliningDepth) + { + LONG snapSize = m_cancellationBeacons.BeaconCount(); + for (LONG i = 0; i < snapSize; i++) + { + // + // The beacon list is guaranteed to exist. Further, because we do this during cancellation for inlined collections, we can + // never unpop and reuse a beacon for a lower depth until the cancellation is complete because of strict nesting on the + // beacon stack (RAII). + // + CancellationBeacon *pBeacon = m_cancellationBeacons[i]; + if (pBeacon->m_beaconDepth >= inliningDepth) + { + // + // We have one interesting conundrum here. Everything from depth 0 -> inliningDepth is guaranteed to be stable. Anything from + // inliningDepth + 1 -> N can change. That change might include what cancellation tokens are active. This might, in fact, change + // whether a cancellation has truly happened or not. + // + // In order to solve this, two things will happen: + // + // - Whoever observes a beacon signaled must do a further check to CONFIRM the cancellation. + // + // - If there is a guarantee that the cancellation will not hit us in THIS call, we will not flag the beacon as a performance + // optimization. + // + // This effectively means that we may see a **false positive** on the beacon but never a false negative due to the tokens. A false positive + // can be double checked. A false negative will never be flagged again and will lead to uncancellable trees! + // + int governingDepth = m_governingTokenDepth; // *MUST* be captured to be observationally consistent in the check below + if (governingDepth == -1 || governingDepth <= inliningDepth) + { + pBeacon->InternalSignal(); + } + } + } + } + + /// + /// Called to determine if a confirmed cancellation on this context is hidden at the depth of the caller. + /// A governing token that is not canceled could be protecting the task collection from cancellation from above. + /// The token of the supplied task collection is used to veto an interruption. See comments in IsCancellationVisible + /// + bool ContextBase::TokenHidesCancellation(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken) const + { + // + // An override token is used to determine visibility of cancellation at the end of _RunAndWait for structured + // and unstructured task collections. The governing token and cancellation depths apply to higher level task + // collections at this point, however, _RunAndWait should not interrupt if the token of pCurrentTaskCollection + // is not canceled, so that the token provides total isolation from parent cancellation. + // + if (hasOverrideToken) + { + _CancellationTokenState * pOverrideTokenState = pCurrentTaskCollection->_GetTokenState(); + if (pOverrideTokenState == _CancellationTokenState::_None() || !pOverrideTokenState->_IsCanceled()) + { + return true; + } + } + // + // Any token hides the propagation of implicit cancellation from above unless the token itself is EXPLICITLY canceled. + // Note, that m_maxCancellationDepth can be ENTIRE_CONTEXT_CANCELED, which is < -1, therefore we must check that the + // governing token depth is not -1. + // + if (m_maxCancellationDepth < m_governingTokenDepth && m_governingTokenDepth != -1) + { + ASSERT(m_pGoverningTokenState != NULL); + if (m_pGoverningTokenState == _CancellationTokenState::_None()) + { + return true; + } + return (!m_pGoverningTokenState->_IsCanceled()); + } + return false; + } + + /// + /// Called to determine whether a committed or pending cancellation on this context is visible at the level of the caller. + /// NOTE: This method should only be called on the current context from _RunAndWait for the task collection supplied at an argument. + /// The asserts below will check for that. + /// The interruption points at the end of _RunAndWait must use the token of the task collection to override cancellation from + /// above - i.e, even if the cancellation depth and governing token depth determine that an interruption point would've thrown + /// an interruption exception, if there was an uncanceled token on this task collection, no interruption should take place. + /// This allows total isolation from parent cancellation using cancellation tokens. + /// + bool ContextBase::IsCancellationVisible(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken /* = false */) const + { + ASSERT(SchedulerBase::FastCurrentContext() == this && pCurrentTaskCollection->_M_pOwningContext == this); + ASSERT(m_pExecutingCollection == pCurrentTaskCollection || m_pExecutingCollection == pCurrentTaskCollection->_M_pParent); + ASSERT(HasAnyCancellation()); + + return ((HasInlineCancellation() && !TokenHidesCancellation(pCurrentTaskCollection, hasOverrideToken)) || + (HasPendingCancellation() && pCurrentTaskCollection->_WillInterruptForPendingCancel())); + } + + /// + /// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is normally only valid when + /// called from the thread representing this context. There are times under the context chaining lock (stealers list) or from an indirect + /// alias of a collection on this context, where this can be called safely **FOR CERTAIN DEPTHS** from another thread. + /// + /// + /// The depth at which to check for cancellation. If the method is called from a thread other than the one representing this context, + /// the caller must guarantee that this context will not unwind past a task group or structured task group of inlining depth = 'depth'. + /// If the caller has observed a collection inlined at 'depth' != -1 while holding the stealers lock on this context, or the caller + /// is executing a chores on an indirect alias while the original task group is inlined, this guarantee is automatically provided. + /// + bool ContextBase::IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection, int depth) + { + ASSERT(pStartingCollection->_M_inliningDepth >= depth); + if (HasInlineCancellation() && m_minCancellationDepth <= depth) + { + // + // Normally, this would be an indication of a cancellation in progress. There may, however, be a cancellation token which stops + // us from observing it. Detecting this at arbitrary depth is more complex than detecting it at a current interruption point because + // we only track min/max on cancellation depth. Arbitrary depth requires us to walk back up the inlining tree until we find the token + // governing depth. + // + // If there is no token or all tokens are above the cancellation depth, clearly we do not need to do this. + // + if (m_governingTokenDepth == -1 || m_minCancellationDepth >= m_governingTokenDepth) + return true; + + // + // If we are checking a cancellation beacon in strictly nested order, this is a simple bottom check. + // + if (pStartingCollection == m_pExecutingCollection && depth == m_pExecutingCollection->_M_inliningDepth) + { + if (m_pGoverningTokenState == _CancellationTokenState::_None()) + return false; + + return m_pGoverningTokenState->_IsCanceled(); + } + + // + // At this point, we have exhausted every quick check since we can no longer rely on min/max. We need to walk the tree. Fortunately, + // this should not need to be done often. + // + _TaskCollectionBase *pCollection = pStartingCollection; + while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_M_inliningDepth != depth) + { + pCollection = pCollection->_SafeGetParent(); + } + + while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_GetTokenState() == NULL) + { + if ((pCollection->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pCollection))->_IsMarkedForCancellation()) || + (!pCollection->_IsStructured() && (static_cast<_TaskCollection *>(pCollection))->_IsMarkedForAbnormalExit())) + { + return true; + } + pCollection = pCollection->_SafeGetParent(); + } + + if (pCollection != NULL && pCollection != m_pRootCollection) + { + _CancellationTokenState *pGoverningTokenState = pCollection->_GetTokenState(); + ASSERT(pGoverningTokenState != NULL); + if (pGoverningTokenState != _CancellationTokenState::_None()) + { + return pGoverningTokenState->_IsCanceled(); + } + } + } + return false; + } + + _Cancellation_beacon::_Cancellation_beacon() + { + ContextBase *pContext = SchedulerBase::CurrentContext(); + _M_pRef = pContext->PushCancellationBeacon(); + } + + _Cancellation_beacon::~_Cancellation_beacon() + { + ContextBase *pContext = SchedulerBase::CurrentContext(); + pContext->PopCancellationBeacon(); + } + + bool _Cancellation_beacon::_Confirm_cancel() + { + ContextBase *pContext = SchedulerBase::CurrentContext(); + bool fCanceled = pContext->ConfirmCancel(_M_pRef); + if (!fCanceled) + { + _Lower(); + } + return fCanceled; + } + + /// + /// Return a reference to the ppltask inline schedule depth slot on current context + /// The inline depth will be set to 0 when the context is first initialized, + /// and the caller is responsible to maintain that depth. + /// + _CONCRTIMP size_t & __cdecl _StackGuard::_GetCurrentInlineDepth() + { + return SchedulerBase::CurrentContext()->m_asyncTaskCollectionInlineDepth; + } +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.h new file mode 100644 index 0000000000000000000000000000000000000000..8fc0f4280f8186c69c17c641e6dc59770d3730dd --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.h @@ -0,0 +1,1147 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ContextBase.h +// +// Header file containing the metaphor for an execution context/stack/thread. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +// Defines used for context blocking (m_blockedState): +// * Possible blocked states +#define CONTEXT_NOT_BLOCKED 0x0 +#define CONTEXT_BLOCKED 0x1 +#define CONTEXT_UMS_SYNC_BLOCKED 0x2 +#define CONTEXT_UMS_ASYNC_BLOCKED 0x4 + +// * Useful bit-masks +#define CONTEXT_SYNC_BLOCKED (CONTEXT_BLOCKED | CONTEXT_UMS_SYNC_BLOCKED) +#define CONTEXT_UMS_BLOCKED (CONTEXT_UMS_SYNC_BLOCKED | CONTEXT_UMS_ASYNC_BLOCKED) + +#define ENTIRE_CONTEXT_CANCELED -999 + +namespace Concurrency +{ +namespace details +{ + /// + /// Implements the base class for a ConcRT execution context. + /// +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class ContextBase : public Context + { + public: + // + // Public Methods + // + + /// + /// Constructor + /// + ContextBase(SchedulerBase *pScheduler, bool fIsExternal); + + /// + /// Returns a unique identifier to the context. + /// + virtual unsigned int GetId() const; + + /// + /// Returns an identifier to the virtual processor the context is currently executing on, if any. + /// + virtual unsigned int GetVirtualProcessorId() const =0; + + /// + /// Returns an identifier to the schedule group the context is currently working on, if any. + /// + virtual unsigned int GetScheduleGroupId() const; + + /// + /// Returns the reference count of the underlying schedule group, which is equivalent + /// to the number of contexts performing work on the schedule group. + /// + unsigned int ScheduleGroupRefCount() const; + + /// + /// Causes the context to block, yielding the virtual processor to another context. + /// + virtual void Block() =0; + + /// + /// Unblocks the context and makes it runnable. + /// + virtual void Unblock() =0; + + /// + /// Determines whether or not the context is synchronously blocked at this given time. + /// + /// + /// Whether context is in synchronous block state. + /// + virtual bool IsSynchronouslyBlocked() const =0; + + /// + /// Returns whether the context is blocked or not. Note that this definition of blocked is "blocked and requires + /// eventual reexecution -- e.g.: finalization will call this during the sweep phase). + /// + bool IsBlocked() const + { + return (m_blockedState != CONTEXT_NOT_BLOCKED); + } + + /// + /// Yields execution to a different runnable context, and puts this context on a runnables collection. + /// If no context is found to yield to, the context continues to run. + /// + virtual void Yield() =0; + + /// + /// Yields execution to a different runnable context, and puts this context on a runnables collection. + /// If no context is found to yield to, the context continues to run. + /// + /// This is intended for spin loops. + /// + virtual void SpinYield() =0; + + /// + /// See comments for Concurrency::Context::Oversubscribe. + /// + virtual void Oversubscribe(bool beginOversubscription) =0; + + /// + /// Cleans up the Context. + /// + void Cleanup(); + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + virtual void* Alloc(size_t numBytes) =0; + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + virtual void Free(void* pAllocation) =0; + + /// + /// Enters a critical region of the scheduler. Calling this guarantees that the virtual processor on which this context lives + /// is guaranteed to be stable throughout the critical region. For some context types, this is virtually a NOP. For others + /// (UMS), this makes it appear that blocking on the context actually blocks the UMS thread instead of triggering return to + /// primary. Note that critical regions suppress asynchronous blocking but not synchronous blocking. + /// + virtual int EnterCriticalRegionHelper() + { + CONCRT_COREASSERT(Context::CurrentContext() == this); + return ++m_criticalRegionCount; + } + + int EnterCriticalRegion(); + + /// + /// Static version of EnterCriticalRegion. + /// + static void StaticEnterCriticalRegion(); + + /// + /// Enters a hyper-critical region of the scheduler. Calling this guarantees not only the conditions of a critical region but it + /// guarantees that synchronous blocking is suppressed as well. This allows for lock sharing between the primary and hyper-critical + /// regions running on UTs. No lock sharing can occur between the inside of this region type and the outside of this region type + /// on a UT. + /// + virtual int EnterHyperCriticalRegionHelper() + { + m_criticalRegionCount++; + return ++m_hyperCriticalRegionCount; + } + + int EnterHyperCriticalRegion(); + + /// + /// Static version of EnterHyperCriticalRegion. + /// + static void StaticEnterHyperCriticalRegion(); + + /// + /// Exits a critical region of the scheduler. + /// + virtual int ExitCriticalRegionHelper() + { + CONCRT_COREASSERT(m_criticalRegionCount > 0); + CONCRT_COREASSERT(Context::CurrentContext() == this); + return --m_criticalRegionCount; + } + + int ExitCriticalRegion(); + + /// + /// Static version of ExitCriticalRegion. + /// + static void StaticExitCriticalRegion(); + + /// + /// Exits a hyper-critical region of the scheduler. + /// + virtual int ExitHyperCriticalRegionHelper() + { + CONCRT_COREASSERT(m_hyperCriticalRegionCount > 0); + CONCRT_COREASSERT(m_criticalRegionCount > 0); + m_criticalRegionCount--; + return --m_hyperCriticalRegionCount; + } + + int ExitHyperCriticalRegion(); + + /// + /// Static version of ExitHyperCriticalRegion. + /// + static void StaticExitHyperCriticalRegion(); + + /// + /// Checks if a context is in a critical region. This is only safe from either the current context or from a UMS primary which + /// has woken due to a given context blocking. + /// + virtual CriticalRegionType GetCriticalRegionType() const + { + if (m_hyperCriticalRegionCount > 0) + return InsideHyperCriticalRegion; + if (m_criticalRegionCount > 0) + return InsideCriticalRegion; + return OutsideCriticalRegion; + } + + /// + /// Since critical region counts are turned off for thread schedulers, this method is used + /// where the return value is expected to be true. For a thread scheduler, it always returns true. + /// For a ums scheduler it returns (GetCriticalRegionType() != OutsideCriticalRegion). + /// IsInsideContextLevelCriticalRegion only checks (ContextBase::GetCriticalRegionType() != OutsideCriticalRegion). + /// + bool IsInsideCriticalRegion() const; + + /// + /// Static version of GetCriticalRegionType. + /// + static CriticalRegionType StaticGetCriticalRegionType(); + + /// + /// Set critical region counts to zero + /// + void ClearCriticalRegion() + { + m_hyperCriticalRegionCount = m_criticalRegionCount = 0; + } + +#if defined(_DEBUG) + /// + /// Tells the context it's shutting down a virtual processor and normal lock validations don't apply. + /// + void SetShutdownValidations() + { + m_fShutdownValidations = true; + } + + /// + /// Re-enable normal lock validations + /// + void ClearShutdownValidations() + { + m_fShutdownValidations = false; + } + + /// + /// Returns whether or not the context is in a "shutting down a virtual processor" mode where normal lock validations don't apply. + /// + bool IsShutdownValidations() const + { + return m_fShutdownValidations; + } +#endif // _DEBUG + + /// + /// Wrapper for m_pWorkQueue for use in unstructured task collections + /// that performs delay construction as well as insertion into schedule group. + /// + WorkQueue *GetWorkQueue() + { + // want inlining + if (m_pWorkQueue == NULL) + CreateWorkQueue(); + return m_pWorkQueue; + } + + /// + /// Wrapper for m_pWorkQueue for use in structured task collections + /// that performs delay construction as well as insertion into schedule group. + /// + WorkQueue *GetStructuredWorkQueue() + { + // want inlining + if (m_pWorkQueue == NULL) + CreateStructuredWorkQueue(); + return m_pWorkQueue; + } + + /// + /// Create a workqueue for use in unstructured task collections. + /// + void CreateWorkQueue(); + + /// + /// Create a workqueue for use in structured task collections. + /// + void CreateStructuredWorkQueue(); + + /// + /// Returns a unique identifier for the work queue associated with this context. Note that this should only be used + /// for binding (e.g.: task collection binding) + /// + unsigned int GetWorkQueueIdentity() + { + return GetWorkQueue()->Id(); + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue. + /// + /// + /// The location where the unrealized chore should execute. + /// + void PushStructured(_UnrealizedChore *pChore, location *pLocation); + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue. + /// + void PushStructured(_UnrealizedChore *pChore); + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. + /// + /// + /// The chore to push onto the unstructured work stealing queue. + /// + /// + /// The location where the unrealized chore should execute. + /// + int PushUnstructured(_UnrealizedChore *pChore, location *pLocation); + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. + /// + /// + /// The chore to push onto the unstructured work stealing queue. + /// + int PushUnstructured(_UnrealizedChore *pChore); + + /// + /// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them + /// based on the result of a callback. + /// + /// + /// The predicate for things to call pSweepFn on. + /// + /// + /// The data for the predicate callback + /// + /// + /// The sweep function + /// + void SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate, + void *pData, + WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn + ); + + /// + /// Pops the topmost chore from the work stealing queue for structured parallelism. Failure + /// to pop typically indicates stealing. + /// + /// + /// An unrealized chore from the structured work stealing queue or NULL if none is present. + /// + _UnrealizedChore *PopStructured(); + + /// + /// Attempts to pop the chore specified by a cookie value from the unstructured work stealing queue. Failure + /// to pop typically indicates stealing. + /// + /// + /// A cookie returned from PushUnstructured indicating the chore to attempt to pop from + /// the unstructured work stealing queue. + /// + /// + /// The specified unrealized chore (as indicated by cookie) or NULL if it could not be popped from + /// the work stealing queue. + /// + _UnrealizedChore *TryPopUnstructured(int cookie); + + /// + /// Returns the scheduler the specified context is associated with. + /// + SchedulerBase *GetScheduler() const; + + /// + /// Returns the schedule group the specified context is associated with. + /// + ScheduleGroupBase *GetScheduleGroup() const; + + /// + /// Returns the schedule group segment the specified context is associated with. + /// + ScheduleGroupSegmentBase *GetScheduleGroupSegment() const; + + /// + /// Tells whether the context is an external context + /// + bool IsExternal() const { return m_fIsExternal; } + + /// + /// Gets the indirect alias. + /// + _TaskCollection *GetIndirectAlias() const; + + /// + /// Sets the indirect alias. + /// + void SetIndirectAlias(_TaskCollection *pAlias); + + /// + /// Returns whether a task collection or structured task collection executing on this context was canceled while it was inlined. + /// + bool HasInlineCancellation() const + { + return (m_inlineCancellations > 0); + } + + /// + /// Returns whether the entire context was canceled due to a steal. + /// + bool IsEntireContextCanceled() const + { + return (m_canceledContext != 0); + } + + /// + /// Called in order to indicate that a cancellation is happening for a structured task collection associated with this thread + /// that has not been inlined yet. + /// + void PendingCancel() + { + InterlockedIncrement(&m_pendingCancellations); + } + + /// + /// Called when a pending cancel completes. + /// + void PendingCancelComplete() + { + ASSERT(m_pendingCancellations > 0); + InterlockedDecrement(&m_pendingCancellations); + } + + /// + /// Returns whether a structured task collection executing on this context was canceled before it was inlined. + /// + bool HasPendingCancellation() const + { + return (m_pendingCancellations > 0); + } + + /// + /// Returns whether there is any cancellation on the context (pending or inline) + /// + bool HasAnyCancellation() const + { + return (m_pendingCancellations + m_inlineCancellations > 0); + } + + /// + /// Called to determine if a confirmed cancellation on this context is hidden at the depth of the caller. + /// A governing token that is not canceled could be protecting the task collection from cancellation from above. + /// + bool TokenHidesCancellation(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken) const; + + /// + /// Called to determine whether a inline or pending cancellation on this context is visible to the caller. + /// + bool IsCancellationVisible(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken = false) const; + + /// + /// Called in order to indicate that a collection executing on this context was canceled. This will often cause cancellation + /// and unwinding of the entire context (up to the point where we get to the canceled collection). + /// + void CancelCollection(int inliningDepth); + + /// + /// Called in order to indicate that we're blowing away the entire context. It's stolen from a collection which was canceled. + /// + void CancelEntireContext() + { + InterlockedExchange(&m_canceledContext, TRUE); + CancelCollection(ENTIRE_CONTEXT_CANCELED); + } + + /// + /// When a cancellation bubbles up to the collection being canceled, this function is called in order to stop propagation of + /// the cancellation further up the work tree. + /// + bool CancelCollectionComplete(int inliningDepth); + + /// + /// Completely clears the cancel count. This should be called when a root stolen chore completes on a context. + /// + void ClearCancel() + { + m_minCancellationDepth = -1; + m_maxCancellationDepth = -1; + m_inlineCancellations = 0; + m_canceledContext = 0; + } + + /// + /// Returns the task collection executing atop a stolen context. + /// + _TaskCollectionBase *GetRootCollection() + { + return m_pRootCollection; + } + + /// + /// Sets the task collection executing atop a stolen context. Note that this also sets the executing collection since the root + /// collection is executing at the time it is set. + /// + void SetRootCollection(_TaskCollectionBase *pRootCollection) + { + m_pRootCollection = pRootCollection; + m_pExecutingCollection = pRootCollection; + } + + /// + /// Gets the task collection currently executing atop the context. + /// + _TaskCollectionBase *GetExecutingCollection() + { + return m_pExecutingCollection; + } + + /// + /// Sets the task collection currently executing atop the context. + /// + void SetExecutingCollection(_TaskCollectionBase *pExecutingCollection) + { + m_pExecutingCollection = pExecutingCollection; + } + + /// + /// Gets the cancellation token currently governing this context. + /// + _CancellationTokenState *GetGoverningTokenState() + { + return m_pGoverningTokenState; + } + + /// + /// Sets the cancellation token currently governing this context. + /// + void PushGoverningTokenState(_CancellationTokenState *pTokenState, int inliningDepth); + + /// + /// Reverts to the previously set cancellation token. + /// + void PopGoverningTokenState(_CancellationTokenState *pTokenState); + + /// + /// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is only valid when + /// called from the thread representing this context. + /// + bool IsCanceledAtDepth(int depth) + { + return IsCanceledAtDepth(m_pExecutingCollection, depth); + } + + /// + /// Returns an indication as to whether a cancellation is occurring at the depth specified by the inlining depth of the given collection. This + /// may ONLY be called while the context chaining (stealers) lock is held and only where it is known that there is a steal from + /// pStartingCollection. + /// + bool IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection) + { + return IsCanceledAtDepth(pStartingCollection, pStartingCollection->_M_inliningDepth); + } + + /// + /// Verifies that a cancellation beacon signal is really a cancellation for that beacon. + /// + bool ConfirmCancel(_Beacon_reference *pBeaconRef) + { + CancellationBeacon *pBeacon = CONTAINING_RECORD(pBeaconRef, CancellationBeacon, m_beacon); + return IsCanceledAtDepth(pBeacon->m_beaconDepth); + } + + /// + /// Places a reference on the context preventing it from being destroyed until such time as the stealer is added to the chain + /// via AddStealer. Note that the operation of AddStealer should happen rapidly as it will *BLOCK* cleanup of the context. + /// + void ReferenceForCancellation(); + + /// + /// Removes a reference on the context which was preventing it from being destroyed. + /// + void DereferenceForCancellation(); + + /// + /// Adds a stealing context. Removes a reference. + /// + void AddStealer(ContextBase *pStealer, bool fDereferenceForCancellation); + + /// + /// Removes a stealing context. + /// + void RemoveStealer(ContextBase *pStealer); + + /// + /// Called by a stolen chore to flag the context as running a chore for which the steal is chained to a task collection instead + /// of the context. + /// + void NotifyTaskCollectionChainedStealer() + { + m_fContextChainedStealer = false; + } + + /// + /// Returns whether the given context's steal is chained to the context (true) or some task collection (false) + /// + bool IsContextChainedStealer() const + { + return m_fContextChainedStealer; + } + + /// + /// Called on both internal and external contexts, either when the are put into an idle pool to + /// be recycled, or when they are ready to be deleted. The API moves the contexts that are in + /// the list of 'stealers' (used for cancellation) to lists in the task collections from which + /// those contexts have stolen chores. + /// + void DetachStealers(); + + /// + /// Gets an arbitrary alias out of the context's alias table. + /// + _TaskCollection *GetArbitraryAlias(_TaskCollection *pCollection) + { + Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.Find(pCollection, NULL); + _TaskCollection *pAlias = (pNode != NULL ? pNode->m_value : NULL); + if (pAlias != NULL && pAlias->_IsStaleAlias()) + { + m_aliasTable.Delete(pAlias->_OriginalCollection()); + delete pAlias; + pAlias = NULL; + } + return pAlias; + } + + /// + /// Adds an arbitrary alias (direct or indirect) to the alias table. + /// + void AddArbitraryAlias(_TaskCollection *pOriginCollection, _TaskCollection *pAliasCollection) + { + SweepAliasTable(); + m_aliasTable.Insert(pOriginCollection, pAliasCollection); + } + + /// + /// Sweeps the alias table for stale entries. Anything considered stale is deleted. + /// + void SweepAliasTable(); + + /// + /// Clears the alias table. + /// + void ClearAliasTable(); + + /// + /// Cancel everything stolen from pCollection outward from this context. + /// + void CancelStealers(_TaskCollectionBase *pCollection); + + /// + /// Returns the highest inlining depth (tree wise) of a canceled task collection. Note that it will return -1 + /// if there is no in-progress cancellation on the context. + /// + int MinimumCancellationDepth() const + { + // + // If the entire context is canceled, the minimum depth is reported to be zero so as to be less than all inlining depths + // for the purposes of checking cancellation. Note that even if the top collection has inlining depth of zero, it does not matter + // since it **IS** the top collection. + // + return IsEntireContextCanceled() ? 0 : m_minCancellationDepth; + } + + // An enumerated type that tells the type of the underlying execution context. + enum ContextKind + { + ExternalContext, + ThreadContext, + }; + + /// + /// Returns the type of context + /// + virtual ContextKind GetContextKind() const = 0; + +#if _DEBUG + // _DEBUG helper + virtual DWORD GetThreadId() const = 0; +#endif + + /// + /// Returns a bool which can be polled from the current location in lieu of calling is_current_task_group_canceling. + /// + _Beacon_reference *PushCancellationBeacon(); + + /// + /// Releases the topmost bool acquired in RAII fashion from PushCancellationBeacon. + /// + void PopCancellationBeacon(); + + /// + /// Flags any cancellation beacons that are inlined at or below the specified point. + /// + void FlagCancellationBeacons(int inliningDepth); + + protected: + class ScopedCriticalRegion + { + public: + ScopedCriticalRegion(ContextBase* pCB) : m_pCB(pCB) + { + m_pCB->EnterCriticalRegion(); + } + + ~ScopedCriticalRegion() + { + m_pCB->ExitCriticalRegion(); + } + + private: + const ScopedCriticalRegion& operator=(const ScopedCriticalRegion&); //no assignment operator + ContextBase* m_pCB; + }; + + // + // Protected data members + // + + // Entry for freelist + SLIST_ENTRY m_slNext; + + // Unique identifier + unsigned int m_id; + + // Critical region counter. + DWORD m_criticalRegionCount; + + // Hyper-critical region counter. + DWORD m_hyperCriticalRegionCount; + + // Oversubscription count - the number of outstanding Oversubscribe(true) calls on this context. + DWORD m_oversubscribeCount; + + // The schedule group segment that the context picked up work from + ScheduleGroupSegmentBase *m_pSegment; + + // The scheduler instance the context belongs to. + SchedulerBase *m_pScheduler; + + // Workqueue for unrealized chores. + WorkQueue *m_pWorkQueue; + + // Link to implement the stack of parent contexts for nested schedulers. + ContextBase *m_pParentContext; + + // Flag indicating whether the context is blocked. + volatile LONG m_blockedState; + + // Memory fence to assist Block/Unblock. + volatile LONG m_contextSwitchingFence; + + // Tracks the task collection from which this context stole (if it's a context executing a stolen chore). + _TaskCollectionBase *m_pRootCollection; + + // Tracks the task collection currently executing (used to maintain parent/child relationships). + _TaskCollectionBase *m_pExecutingCollection; + + // Tracks the current cancellation token (for optimization) + _CancellationTokenState *m_pGoverningTokenState; + + // The inlining depth of the first construct on this stack to utilize the governing token + int m_governingTokenDepth; + + // The depth of ppltask being inlining scheduled on this context. + size_t m_asyncTaskCollectionInlineDepth; + + // The thread id for the thread backing the context. + DWORD m_threadId; + + // + // Protected methods + // + + /// + /// Clean up the work queue for this Context. + /// + void ReleaseWorkQueue(); + + /// + /// Sets the 'this' context into the tls slot as the current context. This is used by internal contexts in + /// their dispatch loops. + /// + void SetAsCurrentTls(); + + ///Send a context ETW event + void TraceContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId) + { + if (g_TraceInfo._IsEnabled(level, ContextEventFlag)) + ThrowContextEvent(eventType, level, schedulerId, contextId); + } + + static void ThrowContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId); + + private: + + // + // Friend declarations + // + friend class SchedulerBase; + friend class ThreadScheduler; + friend class InternalContextBase; + friend class SchedulingRing; + friend class VirtualProcessor; + friend class ScheduleGroupBase; + friend class ScheduleGroupSegmentBase; + friend class ScheduleGroup; + friend class FairScheduleGroup; + friend class CacheLocalScheduleGroup; + friend class _UnrealizedChore; + friend class _TaskCollection; + friend class _StructuredTaskCollection; + friend class _StackGuard; + template friend class LockFreeStack; + + // + // Private data + // + + // Used in finalization to distinguish between blocked and free-list contexts + LONG m_sweeperMarker; + + // Flag indicating context kind. + bool m_fIsExternal; + + // Keeps track as to whether this context is chained to a context (true) or a schedule group (false) for the purposes of stealing/cancellation. + bool m_fContextChainedStealer; + + // Indicates that normal lock validations should not be performed -- the context is shutting down a virtual processor. + bool m_fShutdownValidations; + + // Tracks all contexts which stole from any collection on *this* context. + SafeRWList m_stealers; + // Link for contexts added to m_stealers + ListEntry m_stealChain; + + // Reference count of things waiting to be added to the steal chain of this context. + volatile LONG m_cancellationRefCount; + + // Depth is inversely proportion to height in the description of min and max depths. If inlined tg A at depth 0 inlines tg B, + // tg A is considered to be higher than tg B on that context. + // The inlining depth of the highest canceled task collection. + volatile LONG m_minCancellationDepth; + // The inlining depth of the lowest canceled task collection. + volatile LONG m_maxCancellationDepth; + + // The number of task collections and structured task collections running on this context that were canceled when they were inlined + volatile LONG m_inlineCancellations; + // An indication that the context was shot down as it stole from a canceled collection. + volatile LONG m_canceledContext; + // An indication that there is a pending cancellation of a structured collection on this thread (the collection was canceled before it + // was inlined). + volatile LONG m_pendingCancellations; + // The indirect alias for this context. This allows an unstructured task collection to carry into a stolen chore and be + // utilized there without any cross threaded semantics within the task collection. + _TaskCollection *m_pIndirectAlias; + // The table of aliases for this context. This allows transitive indirect aliases as well as direct aliases (which + // are not presently implemented). + Hash<_TaskCollection*, _TaskCollection*> m_aliasTable; + + // + // A cancellation beacon is a flag that the runtime signals when cancellation occurs. It allows hot code paths to poll + // for cancellation in an inlinable way. Parallel for, for instance, gets huge performance wins utilizing this mechanism over + // a non-inlinable call to is_current_task_group_canceling. + // + // Beacons also allow manual raising from the outside for various things in conjunction with cancellation. + // + struct CancellationBeacon + { + _Beacon_reference m_beacon; + int m_beaconDepth; + + void Raise() + { + InterlockedIncrement(&m_beacon._M_signals); + } + + void Lower() + { + InterlockedDecrement(&m_beacon._M_signals); + } + + void InternalSignal() + { + Raise(); + } + }; + + // + // In order for the cancellation beacon mechanism to work, we must manage all storage for beacons. A cancellation beacon may disappear + // asynchronously with respect to cancellation walking the stack of the thread holding the beacon. Once we hand out a beacon flag, we must + // NOT allow that memory location to become invalid until the runtime owns the base of the stack again. + // + // Because of the rules and RAII idiom around this, it does not matter if we hand out the same beacon to a new owner on the same thread. + // + // The CancellationBeaconStack manages a growing stack of beacons without reallocations. + // + class CancellationBeaconStack + { + private: + + // Defines the number of segments in the index + static const LONG NODE_INDEX_SIZE = 4; + + // Defines how large (and the bitmasks) each segment is. + static const LONG BEACON_NODE_SIZE = 16; + static const LONG BEACON_NODE_MASK = 0xFFFFFFF0; + static const LONG BEACON_NODE_ITEM_MASK = 0xF; + static const LONG BEACON_NODE_SHIFT = 4; + + // + // A segment of the stack. Once allocated, data can never move (even after being released). + // + struct CancellationBeaconNode + { + CancellationBeaconNode() : m_pNext(NULL) + { + m_pBeacons = _concrt_new CancellationBeacon[BEACON_NODE_SIZE]; + } + + ~CancellationBeaconNode() + { + delete[] m_pBeacons; + } + + CancellationBeacon *m_pBeacons; + CancellationBeaconNode *m_pNext; + }; + + // The stack pointer + LONG m_beaconDepth; + + // The size of the stack + LONG m_size; + + // The index to stack segments + CancellationBeaconNode **m_pNodeIndex; + + /// + /// Increases the size of the beacon stack without moving any memory associated with beacons that have been handed + /// out. + /// + void Grow() + { + CancellationBeaconNode *pNewNode; + CancellationBeaconNode *pPrevNode = NULL; + + LONG idx = (m_size & BEACON_NODE_MASK) >> BEACON_NODE_SHIFT; + if (idx < NODE_INDEX_SIZE) + { + if (idx > 0) + pPrevNode = m_pNodeIndex[idx - 1]; + + pNewNode = m_pNodeIndex[idx] = _concrt_new CancellationBeaconNode; + } + else + { + pNewNode = pPrevNode = m_pNodeIndex[NODE_INDEX_SIZE - 1]; + + idx -= (NODE_INDEX_SIZE - 1); + while (idx--) + { + pPrevNode = pNewNode; + pNewNode = pNewNode->m_pNext; + } + + ASSERT(pNewNode == NULL); + pNewNode = _concrt_new CancellationBeaconNode; + } + + if (pPrevNode) + pPrevNode->m_pNext = pNewNode; + + m_size += BEACON_NODE_SIZE; + + } + + public: + + /// + /// Creates a new cancellation beacon stack. + /// + CancellationBeaconStack() : + m_beaconDepth(0), + m_size(0) + { + m_pNodeIndex = _concrt_new CancellationBeaconNode* [NODE_INDEX_SIZE]; + } + + /// + /// Destroys a cancellation beacon stack. + /// + ~CancellationBeaconStack() + { + if (m_size > 0) + { + CancellationBeaconNode *pNode = m_pNodeIndex[0]; + while (pNode != NULL) + { + CancellationBeaconNode *pNext = pNode->m_pNext; + delete pNode; + pNode = pNext; + } + } + + delete [] m_pNodeIndex; + } + + /// + /// Acquires memory for a new cancellation beacon and initializes it for the specified inlining depth. + /// + CancellationBeacon *AcquirePushBeacon(int inliningDepth) + { + if (m_beaconDepth >= m_size) + Grow(); + + CancellationBeacon *pBeacon = operator[](m_beaconDepth); + pBeacon->m_beacon._M_signals = 0; + pBeacon->m_beaconDepth = inliningDepth; + m_beaconDepth++; + + // + // Force a full fence here for any R/W dependencies between the cancellation thread reading the beacon stack and us reading + // the cancellation state later once the beacon is acquired. + // + MemoryBarrier(); + + return pBeacon; + } + + /// + /// Releases the topmost cancellation beacon. The beacon can be handed out + /// + void ReleaseBeacon() + { + ASSERT(m_beaconDepth > 0); + m_beaconDepth--; + } + + /// + /// Returns a view of the number of beacons. + /// + LONG BeaconCount() const + { + return m_beaconDepth; + } + + /// + /// Returns the cancellation beacon specified as specified by the supplied index. Note that the index must be within + /// the bounds of BeaconCount when used externally and m_size when used internally. + /// + CancellationBeacon *operator[](LONG idx) + { + CancellationBeaconNode *pNode = NULL; + + LONG nIdx = (idx & BEACON_NODE_MASK) >> BEACON_NODE_SHIFT; + if (nIdx < NODE_INDEX_SIZE) + { + pNode = m_pNodeIndex[nIdx]; + } + else + { + pNode = m_pNodeIndex[NODE_INDEX_SIZE - 1]; + nIdx -= (NODE_INDEX_SIZE - 1); + while(nIdx--) + { + pNode = pNode->m_pNext; + } + } + + return &(pNode->m_pBeacons[idx & BEACON_NODE_ITEM_MASK]); + } + }; + + CancellationBeaconStack m_cancellationBeacons; + + // + // Private member functions + // + + /// + /// When schedulers are nested on the same stack context, the nested scheduler creates a new external context that overrides + /// the previous context. PopContextFromTls will restore the previous context by setting the TLS value appropriately. + /// + ContextBase* PopContextFromTls(); + + /// + /// When schedulers are nested on the same stack context, the nested scheduler creates a new external context that overrides + /// the previous context. PushContextToTls will remember the parent context and set the new context into TLS. + /// + void PushContextToTls(ContextBase* pParentContext); + + /// + /// Context TLS is cleared during nesting on internal contexts before the external context TLS is correctly setup. If not, + /// code that executes between the clear and setting the new TLS could get confused. + /// + void ClearContextTls(); + + /// + /// Recomputes the maximum depth of cancellation after a canceled task group clears its cancellation flag. + /// + void RecomputeMaximumCancellationDepth(); + + /// + /// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is normally only valid when + /// called from the thread representing this context. There are times under the context chaining lock (stealers list) where this can be + /// called safely **FOR CERTAIN DEPTHS** from another thread. This variant should never be called directly. Always utilize one of the + /// other overloads. + /// + bool IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection, int depth); + }; +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CurrentScheduler.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CurrentScheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f84fadb718a0d2314db57b8f44d7af3232a9fd4e --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CurrentScheduler.cpp @@ -0,0 +1,236 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// CurrentScheduler.cpp +// +// Implementation of static scheduler APIs for CurrentScheduler:: +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +/// +/// Returns a unique identifier for the current scheduler. Returns -1 if no current scheduler exists. +/// +unsigned int CurrentScheduler::Id() +{ + const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler(); + return pScheduler != NULL ? pScheduler->Id() : UINT_MAX; +} + +/// +/// Returns a current number of virtual processors for the current scheduler. Returns -1 if no current scheduler exists. +/// No error state. +/// +unsigned int CurrentScheduler::GetNumberOfVirtualProcessors() +{ + const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler(); + return pScheduler != NULL ? pScheduler->GetNumberOfVirtualProcessors() : UINT_MAX; +} + +/// +/// Returns a copy of the policy the current scheduler is using. Returns NULL if no current +/// scheduler exists. +/// +SchedulerPolicy CurrentScheduler::GetPolicy() +{ + const SchedulerBase *pScheduler = SchedulerBase::CurrentScheduler(); + return pScheduler->GetPolicy(); +} + +/// +/// Returns a reference to the scheduler instance in TLS storage (viz., the current scheduler). +/// If one does not exist, the default scheduler for the process is attached to the calling thread and returned -- +/// if the default scheduler does not exist it is created +/// +/// +/// The TLS storage for the current scheduler is returned. +/// +Scheduler* CurrentScheduler::Get() +{ + return SchedulerBase::CurrentScheduler(); +} + +/// +/// The normal scheduler factory. (Implicitly calls Scheduler::Attach on the internally represented scheduler instance.) +/// The created scheduler will become the current scheduler for the current context (if it is an OS context it will be +/// inducted to a ConcRT context). To shutdown such a scheduler, Detach needs to be called. Any extra Reference calls +/// must be matched with Release for shutdown to commence. +/// +/// +/// [in] A const pointer to the scheduler policy (See Scheduler Policy API) +/// +void CurrentScheduler::Create(const SchedulerPolicy& policy) +{ + SchedulerBase *pScheduler = SchedulerBase::Create(policy); + pScheduler->Attach(); +} + +/// +/// Detaches the current scheduler from the calling thread and restores the previously attached scheduler as the current +/// scheduler. Implicitly calls Release. After this function is called, the calling thread is then managed by the scheduler +/// that was previously activated via Create() or Attach(). +/// +void CurrentScheduler::Detach() +{ + SchedulerBase* pScheduler = SchedulerBase::SafeFastCurrentScheduler(); + + if (pScheduler != NULL) + { + return pScheduler->Detach(); + } + else + { + throw scheduler_not_attached(); + } +} + +/// +/// Causes the OS event object 'shutdownEvent' to be set when the scheduler shuts down and destroys itself. +/// +/// +/// [in] A valid event object +/// +void CurrentScheduler::RegisterShutdownEvent(HANDLE shutdownEvent) +{ + SchedulerBase* pScheduler = SchedulerBase::SafeFastCurrentScheduler(); + + if (pScheduler != NULL) + { + return pScheduler->RegisterShutdownEvent(shutdownEvent); + } + else + { + throw scheduler_not_attached(); + } +} + +/// +/// Create a schedule group within the current scheduler. +/// +ScheduleGroup* CurrentScheduler::CreateScheduleGroup() +{ + return SchedulerBase::CurrentScheduler()->CreateScheduleGroup(); +} + +/// +/// Creates a new schedule group within the scheduler associated with the calling context. Tasks scheduled within the newly created +/// schedule group will be biased towards executing at the specified location. +/// +/// +/// A reference to a location where the tasks within the schedule group will biased towards executing at. +/// +/// +/// A pointer to the newly created schedule group. This ScheduleGroup object has an initial reference count placed on it. +/// +/// +/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no +/// scheduler currently associated with the calling context. +/// You must invoke the Release method on a schedule group when you are +/// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed. +/// Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before +/// you release your reference on the scheduler, via detaching the current context from it. +/// +/// +/// +/// +/// +ScheduleGroup* CurrentScheduler::CreateScheduleGroup(location& placement) +{ + return SchedulerBase::CurrentScheduler()->CreateScheduleGroup(placement); +} + +/// +/// Create a light-weight schedule within the current scheduler in an implementation dependent schedule group. +/// +/// +/// [in] A pointer to the main function of a task. +/// +/// +/// [in] A void pointer to the data that will be passed in to the task. +/// +_Use_decl_annotations_ +void CurrentScheduler::ScheduleTask(TaskProc proc, void *data) +{ + SchedulerBase::CurrentScheduler()->ScheduleTask(proc, data); +} + +/// +/// Schedules a light-weight task within the scheduler associated with the calling context. The light-weight task will be placed +/// within a schedule group of the runtime's choosing. It will also be biased towards executing at the specified location. +/// +/// +/// A pointer to the function to execute to perform the body of the light-weight task. +/// +/// +/// A void pointer to the data that will be passed as a parameter to the body of the task. +/// +/// +/// A reference to a location where the light-weight task will be biased towards executing at. +/// +/// +/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no +/// scheduler currently associated with the calling context. +/// +/// +/// +/// +_Use_decl_annotations_ +void CurrentScheduler::ScheduleTask(TaskProc proc, void * data, location& placement) +{ + SchedulerBase::CurrentScheduler()->ScheduleTask(proc, data, placement); +} + +/// +/// Determines whether a given location is available on the current scheduler. +/// +/// +/// A reference to the location to query the current scheduler about. +/// +/// +/// An indication of whether or not the location specified by the argument is available on the current +/// scheduler. +/// +/// +/// This method will not result in scheduler attachment if the calling context is not already associated with a scheduler. +/// Note that the return value is an instantaneous sampling of whether the given location is available. In the presence of multiple +/// schedulers, dynamic resource management may add or take away resources from schedulers at any point. Should this happen, the given +/// location may change availability. +/// +/**/ +bool CurrentScheduler::IsAvailableLocation(const location& _Placement) +{ + const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler(); + return pScheduler != NULL ? pScheduler->IsAvailableLocation(_Placement) : false; +} + +namespace details +{ + void _CurrentScheduler::_ScheduleTask(TaskProc _Proc, void * _Data) + { + SchedulerBase::CurrentScheduler()->ScheduleTask(_Proc, _Data); + } + + unsigned int _CurrentScheduler::_Id() + { + return CurrentScheduler::Id(); + } + + unsigned int _CurrentScheduler::_GetNumberOfVirtualProcessors() + { + return SchedulerBase::CurrentScheduler()->GetNumberOfVirtualProcessors(); + } + + _Scheduler _CurrentScheduler::_Get() + { + return _Scheduler(SchedulerBase::CurrentScheduler()); + } +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Exceptions.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Exceptions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..224c75a33c081860b10d47d037b6a735ad717500 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Exceptions.cpp @@ -0,0 +1,554 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Exceptions.cpp +// +// Implementation for concurrency runtime exceptions. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +// +// scheduler_resource_allocation_error +// + +/// +/// Construct a scheduler_resource_allocation_error exception with a message and an error code +/// +/// +/// Descriptive message of error +/// +/// +/// HRESULT of error that caused this exception +/// +_Use_decl_annotations_ +_CONCRTIMP scheduler_resource_allocation_error::scheduler_resource_allocation_error(const char* message, HRESULT hresult) noexcept + : exception(message), _Hresult(hresult) +{ } + +/// +/// Construct a scheduler_resource_allocation_error exception with an error code +/// +/// +/// HRESULT of error that caused this exception +/// +_CONCRTIMP scheduler_resource_allocation_error::scheduler_resource_allocation_error(HRESULT hresult) noexcept + : exception(), _Hresult(hresult) +{ +} + +/// +/// Get the error code that caused this exception +/// +///HRESULT of error that caused the exception +_CONCRTIMP HRESULT scheduler_resource_allocation_error::get_error_code() const noexcept +{ + return _Hresult; +} + +// +// scheduler_worker_creation_error +// + +/// +/// Constructs a scheduler_worker_creation_error object. +/// +/// +/// A descriptive message of the error. +/// +/// +/// The HRESULT value of the error that caused the exception. +/// +/**/ +_Use_decl_annotations_ +_CONCRTIMP scheduler_worker_creation_error::scheduler_worker_creation_error(const char * message, HRESULT hresult) noexcept + : scheduler_resource_allocation_error(message, hresult) +{ } + +/// +/// Constructs a scheduler_worker_creation_error object. +/// +/// +/// The HRESULT value of the error that caused the exception. +/// +/**/ +_CONCRTIMP scheduler_worker_creation_error::scheduler_worker_creation_error(HRESULT hresult) noexcept + : scheduler_resource_allocation_error(hresult) +{ } + +// +// unsupported_os -- exception thrown whenever an unsupported OS is used +// + +/// +/// Construct a unsupported_os exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP unsupported_os::unsupported_os(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a unsupported_os exception +/// +_CONCRTIMP unsupported_os::unsupported_os() noexcept + : exception() +{ +} + +// +// scheduler_not_attached +// + +/// +/// Construct a scheduler_not_attached exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP scheduler_not_attached::scheduler_not_attached(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a scheduler_not_attached exception +/// +_CONCRTIMP scheduler_not_attached::scheduler_not_attached() noexcept + : exception() +{ +} + +// +// improper_scheduler_attach +// + +/// +/// Construct a improper_scheduler_attach exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP improper_scheduler_attach::improper_scheduler_attach(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a improper_scheduler_attach exception +/// +_CONCRTIMP improper_scheduler_attach::improper_scheduler_attach() noexcept + : exception() +{ +} + +// +// improper_scheduler_detach +// + +/// +/// Construct a improper_scheduler_detach exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP improper_scheduler_detach::improper_scheduler_detach(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a improper_scheduler_detach exception +/// +_CONCRTIMP improper_scheduler_detach::improper_scheduler_detach() noexcept + : exception() +{ +} + +// +// improper_scheduler_reference +// + +/// +/// Construct a improper_scheduler_reference exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP improper_scheduler_reference::improper_scheduler_reference(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a improper_scheduler_reference exception +/// +_CONCRTIMP improper_scheduler_reference::improper_scheduler_reference() noexcept + : exception() +{ +} + +// +// default_scheduler_exists +// + +/// +/// Construct a default_scheduler_exists exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP default_scheduler_exists::default_scheduler_exists(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a default_scheduler_exists exception +/// +_CONCRTIMP default_scheduler_exists::default_scheduler_exists() noexcept + : exception() +{ +} + +// +// context_unblock_unbalanced +// + +/// +/// Construct a context_unblock_unbalanced exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP context_unblock_unbalanced::context_unblock_unbalanced(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a context_unblock_unbalanced exception +/// +_CONCRTIMP context_unblock_unbalanced::context_unblock_unbalanced() noexcept + : exception() +{ +} + +// +// context_self_unblock +// + +/// +/// Construct a context_self_unblock exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP context_self_unblock::context_self_unblock(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a context_unblock_unbalanced exception +/// +_CONCRTIMP context_self_unblock::context_self_unblock() noexcept + : exception() +{ +} + +// +// missing_wait -- Exception thrown whenever a task collection is destructed without being waited upon and still contains work +// + +/// +/// Construct a missing_wait exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP missing_wait::missing_wait(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a missing_wait exception +/// +_CONCRTIMP missing_wait::missing_wait() noexcept + : exception() +{ +} + +// +// bad_target -- Exception thrown whenever a messaging block is given a bad target pointer +// + +/// +/// Construct a bad_target exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP bad_target::bad_target(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a bad_target exception +/// +_CONCRTIMP bad_target::bad_target() noexcept + : exception() +{ +} + +// +// message_not_found -- Exception thrown whenever a messaging block is unable to find a requested message +// + +/// +/// Construct a message_not_found exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP message_not_found::message_not_found(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a message_not_found exception +/// +_CONCRTIMP message_not_found::message_not_found() noexcept + : exception() +{ +} + +// +// invalid_link_target -- Exception thrown whenever a messaging block tries to link a target twice +// when it should only occur once +// + +/// +/// Construct a invalid_link_target exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_link_target::invalid_link_target(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a message_not_found exception +/// +_CONCRTIMP invalid_link_target::invalid_link_target() noexcept + : exception() +{ +} + +// +// invalid_scheduler_policy_key -- Exception thrown whenever a policy key is invalid +// + +/// +/// Construct a invalid_scheduler_policy_key exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_scheduler_policy_key::invalid_scheduler_policy_key(const char* message) noexcept + : exception(message) +{ +} + +/// +/// Construct a invalid_scheduler_policy_key exception +/// +_CONCRTIMP invalid_scheduler_policy_key::invalid_scheduler_policy_key() noexcept + : exception() +{ +} + +// +// invalid_scheduler_policy_value -- Exception thrown whenever a policy value is invalid +// + +/// +/// Construct a invalid_scheduler_policy_value exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_scheduler_policy_value::invalid_scheduler_policy_value(const char* message) noexcept + : exception(message) +{ +} + +/// +/// Construct a invalid_scheduler_policy_value exception +/// +_CONCRTIMP invalid_scheduler_policy_value::invalid_scheduler_policy_value() noexcept + : exception() +{ +} + +// +// invalid_scheduler_policy_thread_specification -- Exception thrown whenever a combination of thread specifications are invalid +// + +/// +/// Construct a invalid_scheduler_policy_thread_specification exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_scheduler_policy_thread_specification::invalid_scheduler_policy_thread_specification(const char* message) noexcept + : exception(message) +{ +} + +/// +/// Construct a invalid_scheduler_policy_thread_specification exception +/// +_CONCRTIMP invalid_scheduler_policy_thread_specification::invalid_scheduler_policy_thread_specification() noexcept + : exception() +{ +} + +// +// nested_scheduler_missing_detach -- Exception thrown when the runtime can detect that +// a Detach() was missing for a nested scheduler. +// + +/// +/// Construct an nested_scheduler_missing_detach exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP nested_scheduler_missing_detach::nested_scheduler_missing_detach(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct an nested_scheduler_missing_detach exception +/// +_CONCRTIMP nested_scheduler_missing_detach::nested_scheduler_missing_detach() noexcept + : exception() +{ +} + +// +// operation_timed_out -- An operation has timed out. +// + +/// +/// Construct an operation_timed_out exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP operation_timed_out::operation_timed_out(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct an operation_timed_out exception +/// +_CONCRTIMP operation_timed_out::operation_timed_out() noexcept + : exception() +{ +} + +// +// invalid_multiple_scheduling -- An exception thrown when a chore/task_handle is scheduled multiple +// times on one or more *TaskCollection/*task_group constructs before completing. +// + +/// +/// Construct an invalid_multiple_scheduling exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_multiple_scheduling::invalid_multiple_scheduling(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct an invalid_multiple_scheduling exception +/// +_CONCRTIMP invalid_multiple_scheduling::invalid_multiple_scheduling() noexcept + : exception() +{ +} + +// +// +// invalid_oversubscribe_operation -- An exception thrown when Context::Oversubscribe(false) +// is called without calling Context::Oversubscribe(true) first. +// + +/// +/// Construct an invalid_oversubscribe_operation exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP invalid_oversubscribe_operation::invalid_oversubscribe_operation(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct an invalid_oversubscribe_operation exception +/// +_CONCRTIMP invalid_oversubscribe_operation::invalid_oversubscribe_operation() noexcept + : exception() +{ +} + +// +// improper_lock +// + +/// +/// Construct a improper_lock exception with a message +/// +/// +/// Descriptive message of error +/// +_Use_decl_annotations_ +_CONCRTIMP improper_lock::improper_lock(const char* message) noexcept + : exception(message) +{ } + +/// +/// Construct a improper_lock exception +/// +_CONCRTIMP improper_lock::improper_lock() noexcept + : exception() +{ +} + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..155434e1de9cd8f0a036545f431ebe7df5b345f3 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.cpp @@ -0,0 +1,222 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ExecutionResource.cpp +// +// Part of the ConcRT Resource Manager -- this file contains the internal implementation for the execution +// resource. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs a new execution resource. + /// + /// + /// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// The processor node that this resource belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + ExecutionResource::ExecutionResource(SchedulerProxy * pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex) + : m_pSchedulerProxy(pSchedulerProxy) + , m_pParentExecutionResource(NULL) + , m_pVirtualProcessorRoot(NULL) + , m_tlsResetValue(0) + , m_nodeId(pNode->m_id) + , m_coreIndex(coreIndex) + , m_numThreadSubscriptions(0) + { + // Derive the execution resource id from the node and the core. + m_executionResourceId = ((int)(pNode->m_processorGroup) << 8) + pNode->m_pCores[coreIndex].m_processorNumber; + } + + /// + /// Constructs a new execution resource. + /// + /// + /// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// The parent execution resource representing this thread. If there was already an execution resource on the + /// calling thread that was created in a different scheduler, it becomes the parent of this execution resource. + /// + ExecutionResource::ExecutionResource(SchedulerProxy * pSchedulerProxy, ExecutionResource * pParentExecutionResource) + : m_pSchedulerProxy(pSchedulerProxy) + , m_pParentExecutionResource(pParentExecutionResource) + , m_pVirtualProcessorRoot(NULL) + , m_tlsResetValue(0) + , m_nodeId(pParentExecutionResource->GetNodeId()) + , m_coreIndex(pParentExecutionResource->GetCoreIndex()) + , m_numThreadSubscriptions(0) + { + m_executionResourceId = pParentExecutionResource->GetExecutionResourceId(); + } + + + /// + /// Called to indicate that a scheduler is done with an execution resource and wishes to return it to the resource manager. + /// + /// + /// The scheduler making the request to remove this execution resource. + /// + void ExecutionResource::Remove(IScheduler *pScheduler) + { + if (pScheduler == NULL) + { + throw std::invalid_argument("pScheduler"); + } + + // Remove must be called on the same thread that called SubscribeCurrentThread. + ExecutionResource * pExecutionResource = m_pSchedulerProxy->GetCurrentThreadExecutionResource(); + if (pExecutionResource != this) + { + throw invalid_operation(); + } + + // The scheduler proxy should match the scheduler calling remove. + if (m_pSchedulerProxy->Scheduler() != pScheduler) + { + throw invalid_operation(); + } + + m_pSchedulerProxy->GetResourceManager()->RemoveExecutionResource(this); + } + + /// + /// Set this execution resource as current on this thread + /// + void ExecutionResource::SetAsCurrent() + { + // Save the information about this execution resource in the TLS for nested SubscribeCurrentThread calls. + DWORD tlsSlot = m_pSchedulerProxy->GetResourceManager()->GetExecutionResourceTls(); + m_tlsResetValue = (size_t) platform::__TlsGetValue(tlsSlot); + ASSERT((void *) m_tlsResetValue != (void *)this); + platform::__TlsSetValue(tlsSlot, this); + } + + /// + /// Clear the current execution resource on this thread. + /// + void ExecutionResource::ResetCurrent() + { + DWORD tlsSlot = m_pSchedulerProxy->GetResourceManager()->GetExecutionResourceTls(); + platform::__TlsSetValue(tlsSlot, (void *) m_tlsResetValue); + m_tlsResetValue = 0; + } + + /// + /// Increments the number of external threads that run on this execution resource as well as + /// the number of fixed threads that are running on the underlying core. + /// + /// + /// This information is used to validate matching SubscribeCurrentThread/Release calls, as well as + /// to mark a core on which this resource runs as fixed (not-movable). + /// + void ExecutionResource::IncrementUseCounts() + { + // The RM LOCK needs to be held before calling this routine + + if (m_numThreadSubscriptions++ == 0) + { + // For an execution resources associated with a vproc, the threadsubscription count is expected to + // go from 0 to 1 when a context running on that vproc subscribes a thread to the scheduler it is running + // on or a different scheduler. + + // For an execution resource *not* associated with a vproc, the threadsubscription count is expected to + // go from 0 to 1 when it is created. + bool isVPRoot = (m_pVirtualProcessorRoot != NULL); + + if (m_pParentExecutionResource == NULL) + { + // Mark on the core that this execution resource has added a new reference + m_pSchedulerProxy->IncrementFixedCoreCount(m_nodeId, m_coreIndex, !isVPRoot); + + if (!isVPRoot) + { + // Save old affinity + HANDLE hThread = GetCurrentThread(); + m_oldAffinity = HardwareAffinity(hThread); + + // Affinitize this thread to a given node + HardwareAffinity newAffinity = m_pSchedulerProxy->GetNodeAffinity(m_nodeId); + newAffinity.ApplyTo(hThread); + + m_pSchedulerProxy->IncrementCoreSubscription(this); + m_pSchedulerProxy->AddExecutionResource(this); + } + } + else + { + ASSERT(!isVPRoot); + m_pSchedulerProxy->AddThreadSubscription(this); + } + + SetAsCurrent(); + } + } + + /// + /// Called to update the proxy counts, which must be done under the RM lock. + /// + void ExecutionResource::DecrementUseCounts() + { + // The RM LOCK needs to be held before calling this routine + ASSERT(m_numThreadSubscriptions > 0); + + // This particular call does not have to worry about the RM receiving a SchedulerShutdown for the scheduler proxy in question. + if (--m_numThreadSubscriptions == 0) + { + bool isVPRoot = (m_pVirtualProcessorRoot != NULL); + // Reset the TLS to the previous state. + // The previous state could be either NULL (if this was not an external threads first subscription), + // a pointer to a thread proxy (it if was originally a vproc), or a parent execution resource (if this + // was a nested execution resource). + ResetCurrent(); + + if (m_pParentExecutionResource == NULL) + { + // Mark on the core that this execution resource has removed one of its references + m_pSchedulerProxy->DecrementFixedCoreCount(m_nodeId, m_coreIndex, !isVPRoot); + + if (!isVPRoot) + { + m_oldAffinity.ApplyTo(GetCurrentThread()); + m_pSchedulerProxy->DecrementCoreSubscription(this); + m_pSchedulerProxy->DestroyExecutionResource(this); + } + } + else + { + ASSERT(!isVPRoot); + m_pParentExecutionResource->DecrementUseCounts(); + m_pSchedulerProxy->RemoveThreadSubscription(this); + } + } + } + + /// + /// Returns the subscription level on the core that this execution resource represents + /// + /// + /// A current subscription level of the underlying execution resource. + /// + unsigned int ExecutionResource::CurrentSubscriptionLevel() const + { + return m_pSchedulerProxy->GetResourceManager()->CurrentSubscriptionLevel(m_nodeId, m_coreIndex); + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.h new file mode 100644 index 0000000000000000000000000000000000000000..c7a5d7d695a00f136f3c7cdb8e3616f84f2b31c6 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.h @@ -0,0 +1,204 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ExecutionResource.h +// +// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the +// execution resource. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + #pragma warning(push) + #pragma warning(disable: 4265) // non-virtual destructor in base class + /// + /// An abstraction for an execution resource -- an entity on top of which a single thread of execution (of whatever + /// type) runs. + /// + class ExecutionResource final : public IExecutionResource + { + public: + + /// + /// Constructs a new execution resource. + /// + /// + /// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// + /// The processor node that this resource belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + ExecutionResource(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex); + + /// + /// Constructs a new execution resource. + /// + /// + /// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// The parent execution resource representing this thread + /// scheduler proxy. + /// + ExecutionResource(SchedulerProxy * pSchedulerProxy, ExecutionResource * pParentExecutionResource); + + /// + /// Destroys an execution resource. + /// + ~ExecutionResource() + { + ASSERT(m_numThreadSubscriptions == 0); + } + + /// + /// Returns a unique identifier for the node that the given execution resource belongs to. The identifier returned + /// will fall in the range [0, nodeCount] where nodeCount is the value returned from Concurrency::GetProcessorNodeCount. + /// + virtual unsigned int GetNodeId() const + { + return m_nodeId; + } + + /// + /// Returns a unique identifier for the execution resource that this execution resource runs atop. + /// + virtual unsigned int GetExecutionResourceId() const + { + return m_executionResourceId; + } + + /// + /// Called to indicate that a scheduler is done with an execution resource and wishes to return it to the resource manager. + /// + /// + /// The scheduler making the request to remove this execution resource. + /// + virtual void Remove(IScheduler *pScheduler); + + /// + /// Returns the subscription level on the core that this execution resource represents + /// + /// + /// A current subscription level of the underlying execution resource. + /// + virtual unsigned int CurrentSubscriptionLevel() const; + + // ************************************************** + // Internal + // ************************************************** + + /// + /// Returns a pointer to the scheduler proxy this execution resource was created by. + /// + SchedulerProxy * GetSchedulerProxy() + { + return m_pSchedulerProxy; + } + + /// + /// Returns the core index into the array of cores, for the node that this execution resource is part of. + /// + unsigned int GetCoreIndex() + { + return m_coreIndex; + } + + /// + /// Retrieves a virtual processor root that contains this execution resource, if any. + /// + VirtualProcessorRoot * GetVirtualProcessorRoot() + { + return m_pVirtualProcessorRoot; + } + + /// + /// Set this execution resource as current on this thread + /// + void SetAsCurrent(); + + /// + /// Clear the current execution resource on this thread. + /// + void ResetCurrent(); + + /// + /// Initializes the execution resource as either standalone or belonging to virtual processor root. + /// + void MarkAsVirtualProcessorRoot(VirtualProcessorRoot * pVPRoot) + { + ASSERT(m_pVirtualProcessorRoot == NULL); + m_pVirtualProcessorRoot = pVPRoot; + } + + /// + /// Increments the number of external threads that run on this execution resource as well as + /// the number of fixed threads that are running on the underlying core. + /// + /// + /// This information is used to validate matching SubscribeCurrentThread/Release calls, as well as + /// to mark a core on which this resource runs as fixed (not-movable). + /// + void IncrementUseCounts(); + + /// + /// Called to update the crucial counts, which must be done under the RM lock. + /// + void DecrementUseCounts(); + + protected: + + // Guards critical regions of the Execution Resource + _NonReentrantLock m_lock; + + // The previous affinity of the external thread + HardwareAffinity m_oldAffinity; + + // The scheduler proxy associated with the scheduler for which + // this resource was created. + SchedulerProxy * m_pSchedulerProxy; + + // Parent execution resource in the case of a nested subscribe + ExecutionResource * m_pParentExecutionResource; + + // Virtual processor root that this execution resource is a part of, if any + VirtualProcessorRoot * m_pVirtualProcessorRoot; + + // The value to use when external resource subscription of a virtual processor is removed + size_t m_tlsResetValue; + + // The node to which this execution resource belongs. + unsigned int m_nodeId; + + // The core index within this node. + unsigned int m_coreIndex; + + // The hardware thread upon which this execution resource executes. + unsigned int m_executionResourceId; + + // Number of subscription requests that have been received for this execution resource. + unsigned int m_numThreadSubscriptions; + + private: + template friend class List; + + // Intrusive links + ExecutionResource * m_pPrev{}, * m_pNext{}; + }; + + #pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc1b2b4a77b5da8b355f95edabe939ca3ca2f4a0 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.cpp @@ -0,0 +1,325 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ExternalContextBase.cpp +// +// Source file containing the metaphor for an external execution ContextBase/stack/thread. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" + +#pragma warning (disable : 4702) + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs an external context. + /// + /// + /// The scheduler the context will belong to. + /// + /// + /// Whether or not this is an explicit attach. An explicit attach occurs as a result of calling a scheduler + /// creation API, or the scheduler attach API. The scheduler will not detach implicitly for explicitly + /// attached threads, on thread exit. + /// + ExternalContextBase::ExternalContextBase(SchedulerBase *pScheduler, bool explicitAttach) : + ContextBase(pScheduler, true), + m_pSubAllocator(NULL), + m_hPhysicalContext(NULL) + { + // Create an auto-reset event that is initially not signaled. + m_hBlock = platform::__CreateAutoResetEvent(); // VSO#459907 + + // External contexts are all grouped together in the 'anonymous' schedule group. + m_pSegment = m_pScheduler->GetAnonymousScheduleGroupSegment(); + + // Create external context statistics as a place where this external context we are about to create + // will store all the statistical data. + m_pStats = _concrt_new ExternalStatistics(); // VSO#459907 + m_pScheduler->AddExternalStatistics(m_pStats); + + // Initialize data that is reset each time the external context is reused. + PrepareForUse(explicitAttach); + } + +#if !defined(_ONECORE) + /// + /// Callback to indicate the exit of one of the external threads. This function + /// is invoked on the wait thread. It is assumed that this function is short and quick. + /// + void CALLBACK ExternalContextBase::ImplicitDetachHandler(PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WAIT waiter, TP_WAIT_RESULT waitResult) + { + ExternalContextBase * pContext = reinterpret_cast(parameter); + + ASSERT(waitResult == WAIT_OBJECT_0); + + pContext->m_pScheduler->DetachExternalContext(pContext, false); + + // This is non-blocking + UnRegisterAsyncWaitAndUnloadLibrary(instance, waiter); + } +#endif // !defined(_ONECORE) + + /// + /// Same callback function as ImplicitDetachHandler but used on XP. + /// + void CALLBACK ExternalContextBase::ImplicitDetachHandlerXP(PVOID parameter, BOOLEAN is_timeout) + { + ExternalContextBase * pContext = reinterpret_cast(parameter); + + // This is non-blocking + platform::__UnregisterWait(pContext->m_hWaitHandle); + + ASSERT(!is_timeout); + + pContext->m_pScheduler->DetachExternalContext(pContext, false); + } + + /// + /// Initializes fields that need re-initialization when an external context is recycled. This is called + /// in the constructor and when an external context is taken off the idle pool for reuse. + /// + /// + /// Whether or not this is an explicit attach. An explicit attach occurs as a result of calling a scheduler + /// creation API, or the scheduler attach API. The scheduler will not detach implicitly for explicitly + /// attached threads, on thread exit. + /// + void ExternalContextBase::PrepareForUse(bool explicitAttach) + { + // Even in the case of a nested external context being initialized, we expect the TLS slot to be clear. + ASSERT(SchedulerBase::FastCurrentContext() == NULL); + + m_fExplicitlyAttached = explicitAttach; + m_threadId = GetCurrentThreadId(); + + if (!explicitAttach) + { + // We only need to capture the current thread's handle for an implicit attach, so that we can register the + // handle for exit tracking, in order that references may be released on thread exit. + if (!DuplicateHandle(GetCurrentProcess(), + GetCurrentThread(), + GetCurrentProcess(), + &m_hPhysicalContext, + 0, + FALSE, + DUPLICATE_SAME_ACCESS)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + +#if !defined(_ONECORE) + // Request a thread pool thread to wait for this thread exit. + if ((m_hWaitHandle = RegisterAsyncWaitAndLoadLibrary(m_hPhysicalContext, ExternalContextBase::ImplicitDetachHandler, this)) == nullptr) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } +#else // ^^^ !defined(_ONECORE) / defined(_ONECORE) vvv + m_hWaitHandle = platform::__RegisterWaitForSingleObject(m_hPhysicalContext, ExternalContextBase::ImplicitDetachHandlerXP, this); +#endif // ^^^ defined(_ONECORE) ^^^ + } + } + + /// + /// Causes the external context to block. Since external contexts do not execute on virtual processors, + /// the context does not switch to another one. Instead, it stops executing until it is unblocked. + /// + void ExternalContextBase::Block() + { + ASSERT(this == SchedulerBase::FastCurrentContext()); + + TraceContextEvent(CONCRT_EVENT_BLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + if (InterlockedIncrement(&m_contextSwitchingFence) == 1) + { + WaitForSingleObjectEx(m_hBlock, INFINITE, FALSE); + } + else + { + // Skip the block, since an unblock has already been encountered. + } + } + + /// + /// Unblocks the external context causing it to start running. + /// + void ExternalContextBase::Unblock() + { + if (this != SchedulerBase::FastCurrentContext()) + { + TraceContextEvent(CONCRT_EVENT_UNBLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + LONG newValue = InterlockedDecrement(&m_contextSwitchingFence); + + if (newValue == 0) + { + SetEvent(m_hBlock); + } + else + { + if ((newValue < -1) || (newValue > 0)) + { + // Should not be able to get m_contextSwitchingFence above 0. + ASSERT(newValue < -1); + + throw context_unblock_unbalanced(); + } + } + } + else + { + throw context_self_unblock(); + } + } + + /// + /// Just a thread yield on the current processor. + /// + void ExternalContextBase::Yield() + { + TraceContextEvent(CONCRT_EVENT_YIELD, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + platform::__SwitchToThread(); + } + + /// + /// See comments for Concurrency::Context::Oversubscribe. + /// External contexts do not support oversubscription. However, we keep track of calls and throw exceptions + /// when appropriate. + /// + void ExternalContextBase::Oversubscribe(bool beginOversubscription) + { + if (beginOversubscription) + { + ++m_oversubscribeCount; + } + else + { + if (m_oversubscribeCount == 0) + { + throw invalid_oversubscribe_operation(); + } + --m_oversubscribeCount; + } + } + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + void* ExternalContextBase::Alloc(size_t numBytes) + { + void* pAllocation = NULL; + ASSERT(SchedulerBase::FastCurrentContext() == this); + + // Find the suballocator for this external context if there is one. Note that if we are unable to get an allocator now, + // we may be able to get one for a later Alloc or Free call (if a different external context released its allocator to + // the free pool). + SubAllocator* pAllocator = GetCurrentSubAllocator(); + + if (pAllocator != NULL) + { + pAllocation = pAllocator->Alloc(numBytes); + } + else + { + // Allocate from the CRT heap. At the point this allocation is freed, if the context has a suballocator, it will be + // freed to the suballocator of the context. + pAllocation = SubAllocator::StaticAlloc(numBytes); + } + + return pAllocation; + } + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + void ExternalContextBase::Free(void* pAllocation) + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(pAllocation != NULL); + + // Find the suballocator for this external context if there is one. Note that if we are unable to get an allocator now, + // we may be able to get one for a later Alloc or Free call (if a different external context released its allocator to + // the free pool). + SubAllocator* pAllocator = GetCurrentSubAllocator(); + + if (pAllocator != NULL) + { + pAllocator->Free(pAllocation); + } + else + { + // Free to the CRT heap. + SubAllocator::StaticFree(pAllocation); + } + } + + /// + /// Prepares an external context for the idle pool by releasing some resources. + /// + void ExternalContextBase::RemoveFromUse() + { + ReleaseWorkQueue(); + + CONCRT_COREASSERT(GetCriticalRegionType() == OutsideCriticalRegion); + + if (m_hPhysicalContext != NULL) + { + CloseHandle(m_hPhysicalContext); + m_hPhysicalContext = NULL; + } + } + + /// + /// Destroys an external thread based context. + /// + ExternalContextBase::~ExternalContextBase() + { + // This takes care of calling the cleanup routine for ContextBase. + Cleanup(); + } + + /// + /// Performs cleanup of the external context + /// + void ExternalContextBase::Cleanup() + { + ContextBase::Cleanup(); + // + // m_pGroup is an anonymous schedule group that is destroyed at scheduler shutdown, so don't release here. + // + if (m_hPhysicalContext != NULL) + { + CloseHandle(m_hPhysicalContext); + m_hPhysicalContext = NULL; + } + if (m_hBlock) + { + CloseHandle(m_hBlock); + } + if (m_pSubAllocator != NULL) + { + SchedulerBase::ReturnSubAllocator(m_pSubAllocator); + } + + // Mark the scheduler's list of non-internal contexts (external or non-bound to context) for removal. We + // can't remove this item yet because statistics might not have had a chance to aggregate this information yet. + DetachStatistics(); + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.h new file mode 100644 index 0000000000000000000000000000000000000000..61c181cf8f5385f0c61347a29383afe3a5689544 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.h @@ -0,0 +1,384 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ExternalContextBase.h +// +// Header file containing the metaphor for an external execution context. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + /// + /// Provides a storage area for external contexts bound to this scheduler or alien threads (threads not + /// associated with any scheduler or those associated with scheduler other than this one) where they can put + /// the statistical data necessary to track the rate of work. + /// + +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class ExternalStatistics + { + public: + // + // Public methods + // + + /// + /// Constructs the statistics object for an external context or alien thread. + /// + ExternalStatistics() : m_enqueuedTaskCounter(0), m_dequeuedTaskCounter(0), m_enqueuedTaskCheckpoint(0), m_dequeuedTaskCheckpoint(0), m_fIsActive(true) + { + } + + /// + /// Increments the count of work coming in. + /// + void IncrementEnqueuedTaskCounter() + { + m_enqueuedTaskCounter++; + } + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter() + { + m_dequeuedTaskCounter++; + } + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter(unsigned int count) + { + m_dequeuedTaskCounter += count; + } + + /// + /// Resets the count of work coming in. + /// + /// + /// This function will reset the state so that the next time it is called, it reports only the + /// units of work that came in since the last time. One obvious solution is to reset the + /// counter, but that introduces a race with a thread that tries to increment. Instead, + /// we update the trailing counter to match the current count. This way the difference + /// between the two is always the number of work coming in. By keeping these numbers unsigned + /// we make use of "modulo 2" behavior of unsigned ints and avoid overflow problems. + /// + /// NOTE: There is a highly rare condition present in this code. If, for some reason, + // statistics calls were infrequent enough that UINT_MAX units of work were enqueued + /// between two calls we will wrap around and consequently think that no work came in at all. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetEnqueuedTaskCount() + { + unsigned int currentValue = m_enqueuedTaskCounter; + unsigned int retVal = currentValue - m_enqueuedTaskCheckpoint; + + // Update the checkpoint value with the current value + m_enqueuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Resets the count of work being done. + /// + /// + /// Look at remarks for GetEnqueuedTaskCount. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetDequeuedTaskCount() + { + unsigned int currentValue = m_dequeuedTaskCounter; + unsigned int retVal = currentValue - m_dequeuedTaskCheckpoint; + + // Update the checkpoint value with the current value + m_dequeuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Marks this statistics as not active anymore. This means that external context + /// has gone away and it will no longer update the statistical information. However, + /// we can't remove statistics right away because they might not have been collected yet. + /// So, we mark it as inactive and we wait for the next collection to take place before + /// permanently retiring this statistics. + /// + void MarkInactive() + { + m_fIsActive = FALSE; + } + + /// + /// Checks whether this statistics class expects any new updates. + /// + /// + /// True if statistics is still active. + /// + bool IsActive() + { + // By the memory ordering rules the only way that m_fIsActive would be marked as false + // is if external context is being destroyed, which means there is no work coming in or + // out of this external context. The task counts are final and there is no race between + // task counts and active bit. + return (m_fIsActive || (m_enqueuedTaskCounter != m_enqueuedTaskCheckpoint) || (m_dequeuedTaskCounter != m_dequeuedTaskCheckpoint)); + } + + // A field that is necessary to store the statistics data structure in a ListArray + int m_listArrayIndex{}; + + private: + // + // Private data + // + + template friend class ListArray; + + // Intrusive links for list array. + SLIST_ENTRY m_listArrayFreeLink{}; + + // Statistics data counters + unsigned int m_enqueuedTaskCounter; + unsigned int m_dequeuedTaskCounter; + + // Statistics data checkpoints + unsigned int m_enqueuedTaskCheckpoint; + unsigned int m_dequeuedTaskCheckpoint; + + // Whether this statistics is actively worked on + volatile BOOL m_fIsActive; + }; +#pragma warning(pop) + + /// + /// Implements the base class for ConcRT external contexts. + /// + class ExternalContextBase : public ContextBase + { + public: + + // + // Public methods + // + + /// + /// Constructs an external context. + /// + ExternalContextBase(SchedulerBase *pScheduler, bool explicitAttach); + + /// + /// Destroys an external context. + /// + virtual ~ExternalContextBase(); + + /// + /// Causes the external context to block. Since external contexts do not execute on virtual processors, + /// the context does not switch to another one. Instead, it stops executing until it is unblocked. + /// + virtual void Block(); + + /// + /// Unblocks the external context causing it to start running. + /// + virtual void Unblock(); + + /// + /// Since there is no underlying virtual processor, the yield operation is a no-op for external contexts. + /// + virtual void Yield(); + + /// + /// Since there is no underlying virtual processor, the yield operation is a no-op for external contexts. + /// + virtual void SpinYield() + { + Yield(); + } + + /// + /// See comments for Concurrency::Context::Oversubscribe. + /// + virtual void Oversubscribe(bool beginOversubscription); + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + virtual void* Alloc(size_t numBytes); + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + virtual void Free(void* pAllocation); + + /// + /// Tells whether the context was explicitly attached to the scheduler at the time it was created + /// + bool WasExplicitlyAttached() const { return m_fExplicitlyAttached; } + + /// + /// Returns an identifier to the virtual processor the context is currently executing on, if any. + /// + virtual unsigned int GetVirtualProcessorId() const { return UINT_MAX; } + + /// + /// Initializes fields that need re-initialization when an external context is reused. This is called + /// in the constructor and when an external context is taken off the idle pool for reuse. + /// + void PrepareForUse(bool explicitAttach); + + /// + /// Prepares an external context for the idle pool by releasing some resources. + /// + void RemoveFromUse(); + + /// + /// Returns a handle to the underlying thread. + /// + HANDLE GetPhysicalContext() { return m_hPhysicalContext; } + + /// + /// Returns a pointer to the suballocator for this external context. Note that the RM call to get an + /// allocator can return NULL, since the RM only hands out a fixed number of allocators for external + /// contexts. + /// + SubAllocator* GetCurrentSubAllocator() + { + if (m_pSubAllocator == NULL) + { + m_pSubAllocator = SchedulerBase::GetSubAllocator(true); + } + return m_pSubAllocator; + } + + /// + /// Increments the count of work coming in. + /// + void IncrementEnqueuedTaskCounter() + { + m_pStats->IncrementEnqueuedTaskCounter(); + } + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter() + { + m_pStats->IncrementDequeuedTaskCounter(); + } + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter(unsigned int count) + { + m_pStats->IncrementDequeuedTaskCounter(count); + } + + /// + /// Orphan the statistics and let it know there will be no more updates. + /// + /// + /// The statistics that were attached to this external context. + /// + ExternalStatistics * DetachStatistics() + { + ExternalStatistics * externalStatistics = m_pStats; + m_pStats = NULL; + externalStatistics->MarkInactive(); + + return externalStatistics; + } + + /// + /// Determines whether or not the context is synchronously blocked at this given time. + /// + /// + /// Whether context is in synchronous block state. + /// + virtual bool IsSynchronouslyBlocked() const + { + return (m_contextSwitchingFence == 1); + } + +#if _DEBUG + // _DEBUG helper + DWORD GetThreadId() const { return m_threadId; } +#endif + + private: + friend class SchedulerBase; + template friend void _InternalDeleteHelper(T*); + + // + // Private data + // + + // Specifies whether the context was created as a result of an explicit or implicit attach. + bool m_fExplicitlyAttached; + + // Statistical information for this external context. + ExternalStatistics * m_pStats; + + // A pointer to the suballocator for this context. + SubAllocator * m_pSubAllocator; + + // Handle to the underlying thread. + HANDLE m_hPhysicalContext; + + // Handle to the event used for blocking. + HANDLE m_hBlock; + + // Wait handle for thread exit event (used on XP) + HANDLE m_hWaitHandle; + + // + // Private methods + // + + /// + /// Performs cleanup of the external context + /// + void Cleanup(); + + /// + /// Callback to indicate the exit of one of the external threads. + /// + static void CALLBACK ImplicitDetachHandler(PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WAIT waiter, TP_WAIT_RESULT waitResult); + + /// + /// Same callback function as ImplicitDetachHandler but used on XP. + /// + static void CALLBACK ImplicitDetachHandlerXP(PVOID parameter, BOOLEAN is_timeout); + + /// + /// Returns the type of context + /// + virtual ContextKind GetContextKind() const { return ExternalContext; } + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e1e7126232d85b7b3d48b10457c683dcafc9ef6 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.cpp @@ -0,0 +1,107 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FairScheduleGroup.cpp +// +// Implementation file for FairScheduleGroup. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Puts a runnable context into the runnables collection in the schedule group. + /// + void FairScheduleGroupSegment::AddToRunnablesCollection(InternalContextBase* pContext) + { + m_runnableContexts.Enqueue(pContext); + } + + /// + /// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement + /// and the origin of the thread making the call. + /// + /// + /// A segment with affinity to this particular location will be located. + /// + /// + /// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is + /// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found. + /// + /// + /// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned + /// if fCreateNew is specified as false and no appropriate segment yet exists for the group. + /// + ScheduleGroupSegmentBase *FairScheduleGroup::LocateSegment(location*, bool fCreateNew) + { + // Ignore the passed in affinity for fair schedule groups. + location unbiased; + if (m_kind & AnonymousScheduleGroup) + { + // + // In order to provide a "like" functionality to Dev10 for anonymous fair groups, we still let the group be split by rings. Non-anonymous + // groups are also treated identically to Dev10 -- they live in one ring which is more for separation than any biasing. + // + return ScheduleGroupBase::LocateSegment(&unbiased, fCreateNew); + } + else + { + ScheduleGroupSegmentBase *pSegment = m_pDefaultSegment; + if (fCreateNew && !pSegment) + { + m_segmentLock._Acquire(); + if (m_pDefaultSegment) + { + pSegment = m_pDefaultSegment; + } + else + { + pSegment = CreateSegment(&unbiased, m_pScheduler->GetNextSchedulingRing()); + // CreateSegment adds the segment to the list array as its last step, which generates a fence ensuring that the segment + // is fully initialized before it is published on weaker memory models. + m_pDefaultSegment = static_cast(pSegment); + } + m_segmentLock._Release(); + } + + return pSegment; + } + } + + /// + /// Internal routine which finds an appropriate segment for a task placement. + /// + /// + /// A segment with this affinity will be located. + /// + /// + /// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order + /// to keep work local. + /// + /// + /// A segment with the specified affinity close to the specified location. + /// + ScheduleGroupSegmentBase *FairScheduleGroup::FindSegment(location*, SchedulingRing *pRing) + { + // Ignore the passed in affinity for fair schedule groups + location unbiased; + if (m_kind & AnonymousScheduleGroup) + { + return ScheduleGroupBase::FindSegment(&unbiased, pRing); + } + else + { + return m_pDefaultSegment; + } + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.h new file mode 100644 index 0000000000000000000000000000000000000000..07cac10561f140319e1bc9ccece35973da3c1d58 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.h @@ -0,0 +1,199 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FairScheduleGroup.h +// +// Header file containing FairScheduleGroup related declarations. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + class FairScheduleGroup; + + class FairScheduleGroupSegment : public ScheduleGroupSegmentBase + { + + public: + + // + // Public Methods + // + + /// + /// Constructs a fair schedule group segment + /// + FairScheduleGroupSegment(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) : + ScheduleGroupSegmentBase(pOwningGroup, pOwningRing, pSegmentAffinity) + { + } + + /// + /// Notifies virtual processors that work affinitized to them has become available in the schedule group segment. + /// + virtual void NotifyAffinitizedWork() { } + + private: + friend class SchedulerBase; + friend class FairScheduleGroup; + friend class ContextBase; + friend class ExternalContextBase; + friend class InternalContextBase; + friend class ThreadInternalContext; + friend class SchedulingNode; + friend class SchedulingRing; + friend class VirtualProcessor; + + // + // Private data + // + + // Each schedule group has three stores of work. It has a collection of runnable contexts, + // a FIFO queue of realized chores and a list of workqueues that hold unrealized chores. + + // A collection of Runnable contexts. + SafeSQueue m_runnableContexts; + + // + // Private methods + // + + /// + /// Puts a runnable context into the runnables collection in the schedule group. + /// + void AddToRunnablesCollection(InternalContextBase *pContext); + + InternalContextBase *GetRunnableContext() + { + if (m_runnableContexts.Empty()) + return NULL; + + InternalContextBase *pContext = m_runnableContexts.Dequeue(); +#if defined(_DEBUG) + SetContextDebugBits(pContext, CTX_DEBUGBIT_REMOVEDFROMRUNNABLES); +#endif // _DEBUG + return pContext; + } + + }; + + class FairScheduleGroup : public ScheduleGroupBase + { + public: + + /// + /// Constructs a new fair schedule group. + /// + FairScheduleGroup(SchedulerBase *pScheduler, location* pGroupPlacement) : + ScheduleGroupBase(pScheduler, pGroupPlacement), + m_pDefaultSegment(NULL) + { + ASSERT(pGroupPlacement->_Is_system()); + m_kind = FairScheduling; + } + + /// + /// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement + /// and the origin of the thread making the call. + /// + /// + /// A segment with affinity to this particular location will be located. + /// + /// + /// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is + /// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found. + /// + /// + /// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned + /// if fCreateNew is specified as false and no appropriate segment yet exists for the group. + /// + virtual ScheduleGroupSegmentBase *LocateSegment(location* pSegmentAffinity, bool fCreateNew); + + /// + /// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified + /// location. For a fair schedule group, the function returns an empty slot + /// + /// + /// The chore to mail. + /// + /// + /// A pointer to a location where the chore will be mailed. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore, + location * pPlacement, + ScheduleGroupSegmentBase **) + { + (pChore); (pPlacement); + return Mailbox<_UnrealizedChore>::Slot(); + } + protected: + + /// + /// Allocates a new fair schedule group segment within the specified group and ring with the specified affinity. + /// + /// + /// The affinity for the segment. + /// + /// + /// The scheduling ring to which the newly allocated segment will belong. + /// + /// + /// A new fair schedule group within the specified group and ring with the specified affinity. + /// + virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity) + { + // + // For fair schedule groups, we completely ignore any location hint since we are directed to round robin the groups anyway! + // + (pSegmentAffinity); + location unbiased; + return _concrt_new FairScheduleGroupSegment(this, pOwningRing, &unbiased); + } + + /// + /// Internal routine which finds an appropriate segment for a task placement. + /// + /// + /// A segment with this affinity will be located. + /// + /// + /// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order + /// to keep work local. + /// + /// + /// A segment with the specified affinity close to the specified location. + /// + virtual ScheduleGroupSegmentBase *FindSegment(location* pSegmentAffinity, SchedulingRing *pRing); + + /// + /// Removes all schedule group segments from the group. + /// + virtual void RemoveSegments() + { + ScheduleGroupBase::RemoveSegments(); + m_pDefaultSegment = NULL; + } + + private: + + FairScheduleGroupSegment *m_pDefaultSegment; + + }; + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90bffac0f9ba5cf43b7f4fc4b11adac395aaabab --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.cpp @@ -0,0 +1,216 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FreeThreadProxy.cpp +// +// Part of the ConcRT Resource Manager -- this source file contains the internal definition for the free thread +// proxy. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Called in order to perform a cooperative context switch between one context and another. After this call, pContext will + /// be running atop the virtual processor root and the context which was running will not. What happens to the context that + /// was running depends on the value of the reason argument. + /// + /// + /// The context to cooperatively switch to. + /// + /// + /// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread + /// proxy and context. + /// + void FreeThreadProxy::SwitchTo(Concurrency::IExecutionContext *pContext, SwitchingProxyState switchState) + { + if (pContext == NULL) + throw std::invalid_argument("pContext"); + + // Find out if this context already has a thread proxy, if not, we have to request one from the factory. + FreeThreadProxy * pProxy = static_cast (pContext->GetProxy()); + + if (pProxy == NULL) + { + // Find a thread proxy from the pool that corresponds to the stack size and priority we need. Since this + // is a context in the same scheduler as the current context's scheduler, we can use existing values of + // stack size and priority. + pProxy = static_cast (m_pRoot->GetSchedulerProxy()->GetNewThreadProxy(pContext)); + } + + FreeVirtualProcessorRoot *pRoot = static_cast(m_pRoot); + m_pRoot = NULL; + + if (switchState == Blocking) + { + ASSERT(m_fBlocked == FALSE); + InterlockedExchange(&m_fBlocked, TRUE); + } + + // The 'next' thread proxy must be affinitized to a copy of the 'this' proxy's vproc root VPRoot1, snapped BEFORE the blocked flag + // is set. Not doing this could result in vproc root orphanage. See VirtualProcessorRoot::Affinitize for details. + pRoot->Affinitize(pProxy); + + switch (switchState) + { + case Blocking: + // + // Signal the other thread proxy and block until switched to, or until a virtual processor is activated with + // the context running on this thread proxy. + // + platform::__SignalObjectAndWait(pProxy->m_hBlock, m_hBlock, INFINITE, TRUE); + ASSERT(m_fBlocked == TRUE); + InterlockedExchange(&m_fBlocked, FALSE); + + break; + case Nesting: + // + // Signal the other thread proxy that now owns this virtual processor, but do not block. The current thread proxy + // is about to move to a nested scheduler. + // + ASSERT(pProxy->m_pRoot != NULL); + ASSERT(pProxy->m_pContext != NULL); + pProxy->ResumeExecution(); + + break; + case Idle: + // + // Return without blocking, indicating to the caller that the scheduler should yield this thread proxy + // back to the RM, by exiting the contexts dispatch loop. + // + ASSERT(pProxy->m_pRoot != NULL); + ASSERT(pProxy->m_pContext != NULL); + pProxy->ResumeExecution(); + + break; + default: + + ASSERT(false); + break; + } + } + + /// + /// Called in order to disassociate the currently executing context from its virtual processor root, and reinitialize the root + /// for future use. + /// + /// + /// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread + /// proxy and context. + /// + void FreeThreadProxy::SwitchOut(SwitchingProxyState switchState) + { + if ((switchState == Idle) || (m_pRoot == NULL && switchState != Blocking)) + throw std::invalid_argument("switchState"); + + ASSERT(m_fBlocked == 0); + + // + // If a virtual processor root is removed on the thread running atop it, the virtual processor root's removal will NULL out this field indicating + // that we are now a free thread. If there is a virtual processor root, the scheduler still wants to keep the vproc root around and we must + // correspondingly act as both a switch out and a deactivate. + // + if (m_pRoot != NULL) + { + FreeVirtualProcessorRoot * pRoot = static_cast(m_pRoot); + if (switchState == Nesting) + { + // IThreadProxy::SwitchOut can be called with Nesting, if the context tried to InternalContextBase::SwitchTo(NULL, Nesting). Ensure the + // root is set to NULL here so the right thing happens with this context/proxy rejoins the scheduler by calling IThreadProxy::SwitchOut(Blocking). + m_pRoot = NULL; + } + (static_cast(pRoot))->ResetOnIdle(switchState); + + // If we're nesting, we should return without blocking with the root unchanged. If not, we should have been affinitized to a different root. + ASSERT(m_pRoot != NULL || switchState == Nesting); + } + else + { + // There are currently only two cases where the m_pRoot field is expected to be NULL. + // - A virtual processor is being retired and the caller invokes SwitchOut to block the thread proxy. + // (root was set to NULL in FreeVirtualProcessorRoot::DeleteThis) + // - A thread proxy that previously switched to a different, nested scheduler, is now joining its original scheduler again. + // (root was set to NULL in FreeThreadProxy::SwitchOut or FreeThreadProxy::SwitchTo) + SuspendExecution(); + } + } + + /// + /// Called right after obtaining a thread proxy from the factory. Associates the thread proxy with the execution + /// context it is about to run. + /// + void FreeThreadProxy::AssociateExecutionContext(Concurrency::IExecutionContext * pContext) + { + m_pContext = pContext; + pContext->SetProxy(this); + } + + /// + /// Returns a thread proxy to the factory when it is no longer in use. + /// + void FreeThreadProxy::ReturnIdleProxy() + { + _CONCRT_ASSERT(m_pFactory != NULL); + m_pContext = NULL; + m_pFactory->ReclaimProxy(this); + } + + /// + /// The main dispatch loop for the free thread proxy. + /// + void FreeThreadProxy::Dispatch() + { + // Send the default dispatch state into Dispatch. + DispatchState dispatchState; + + if (!m_fCanceled) + { + platform::__TlsSetValue(m_pFactory->GetExecutionResourceTls(), (LPVOID) (((size_t) this) | TlsResourceInProxy)); + } + + while (!m_fCanceled) + { + _CONCRT_ASSERT(m_pContext != NULL); + _CONCRT_ASSERT(m_pRoot != NULL); + + // Call the dispatch loop of the registered context. + m_pContext->SetProxy(this); + m_pContext->Dispatch(&dispatchState); + + // + // The dispatch loop returns when the scheduler that the proxy was given to, has decided to return it back to the RM. + // It should be returned to the free proxy factory, so that it can be handed out to a different virtual processor root + // (bound to a different context). + // + // Before doing so, however, we restore the virtual processor to its original state so that it can be activated again. Note + // that if the virtual processor deleted on the way out, m_pRoot is already NULL. This is only thread which does this and + // we are on the same thread. There is no race. + // + FreeVirtualProcessorRoot *pRoot = static_cast(m_pRoot); + + m_pContext = NULL; + m_pRoot = NULL; + + // Return to the idle pool in the RM. If the pool is full, the proxy will be canceled. + ReturnIdleProxy(); + + if (pRoot != NULL) + { + pRoot->ResetOnIdle(Blocking); + } + else + { + SuspendExecution(); + } + } + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.h new file mode 100644 index 0000000000000000000000000000000000000000..75404ba3083ab7d7cd6188634b80b3262854bd60 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.h @@ -0,0 +1,139 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FreeThreadProxy.h +// +// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the free thread +// proxy. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class FreeThreadProxy : public ThreadProxy + { + public: + + /// + /// Construct a free thread proxy. + /// + FreeThreadProxy(IThreadProxyFactory * pFactory, unsigned int stackSize) + : ThreadProxy(pFactory, stackSize) + { } + + /// + /// Destroy a free thread proxy. + /// + virtual ~FreeThreadProxy() + { } + + /// + /// Called in order to perform a cooperative context switch between one context and another. After this call, pContext will + /// be running atop the virtual processor root and the context which was running will not. What happens to the context that + /// was running depends on the value of the reason argument. + /// + /// + /// The context to cooperatively switch to. + /// + /// + /// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread + /// proxy and context. + /// + virtual void SwitchTo(::Concurrency::IExecutionContext * pContext, SwitchingProxyState switchState); + + /// + /// Called in order to disassociate the currently executing context from its virtual processor root, and reinitialize the root + /// for future use. + /// + /// + /// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread + /// proxy and context. + /// + virtual void SwitchOut(SwitchingProxyState switchState = Blocking); + + /// + /// Called in order to yield to the underlying operating system. This allows the operating system to schedule + /// other work in that time quantum. + /// + virtual void YieldToSystem() + { + platform::__SwitchToThread(); + } + + /// + /// Returns the execution context currently attached to the thread proxy. + /// + ::Concurrency::IExecutionContext * GetExecutionContext() { return m_pContext; } + + /// + /// Called right after obtaining a thread proxy from the factory. Associates the thread proxy with the execution + /// context it is about to run. + /// + /// + /// The context to associate with the thread proxy. + /// + void AssociateExecutionContext(::Concurrency::IExecutionContext * pContext); + + /// + /// Returns a thread proxy to the factory when it is no longer in use. + /// + void ReturnIdleProxy(); + + /// + /// Set the thread affinity to the given affinity + /// + /// + /// The new affinity for the thread + /// + void SetAffinity(HardwareAffinity newAffinity) + { + // Set the new affinity only if it is different + if (m_previousAffinity != newAffinity) + { + newAffinity.ApplyTo(GetThreadHandle()); + } + + m_previousAffinity = newAffinity; + } + + private: + // + // Friend declarations + // + template friend class LockFreeStack; + + // + // Private member variables + // + + // Node affinity + HardwareAffinity m_previousAffinity; + + // Entry for freelist + SLIST_ENTRY m_slNext{}; + + // The context that the thread proxy is running at any time. This is updated when the free proxy is first created, and every time it + // is taken from the idle pool and associated with a virtual processor root that was handed to a scheduler. A free thread proxy + // is only associated with one context at a time. + ::Concurrency::IExecutionContext * m_pContext{}; + + // + // Private member functions + // + + /// + /// The main dispatch routine for a free thread proxy + /// + virtual void Dispatch(); + }; +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d15b7e9f00ce45d2d413d6528a7322f7b8768538 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.cpp @@ -0,0 +1,347 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FreeVirtualProcessorRoot.cpp +// +// Part of the ConcRT Resource Manager -- this header file contains the internal implementation for the free virtual +// processor root (represents a virtual processor as handed to a scheduler). +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + + /// + /// Constructs a new free virtual processor root. + /// + /// + /// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// + /// The processor node that this root belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + FreeVirtualProcessorRoot::FreeVirtualProcessorRoot(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex) + : VirtualProcessorRoot(pSchedulerProxy, pNode, coreIndex), + m_pExecutingProxy(NULL), + m_pDeactivatedProxy(NULL) + { + } + + /// + /// Deletes the virtual processor. + /// + void FreeVirtualProcessorRoot::DeleteThis() + { + // + // This comes in via a Remove() call on one of two threads: + // + // - The thread that is running the virtual processor root. + // - There can be no race. We just need to make sure that the thread on exit doesn't touch us after deletion. + // + // - An arbitrary thread. + // - We need to be careful that we aren't racing between that thread's getting out (SwitchOut followed by returning from + // the context's dispatch loop), and it trying to reset the vproc root in ResetOnIdle. We must spin until that has happened. + // + FreeThreadProxy *pCurrentProxy = NULL; + + DWORD tlsSlot = GetSchedulerProxy()->GetResourceManager()->GetExecutionResourceTls(); + void * tlsPointer = platform::__TlsGetValue(tlsSlot); + size_t tlsValue = (size_t) tlsPointer; + + if (tlsPointer != NULL && ((tlsValue & TlsResourceBitMask) == TlsResourceInProxy)) + pCurrentProxy = (FreeThreadProxy *) (tlsValue & ~TlsResourceInProxy); + + if (pCurrentProxy != NULL && pCurrentProxy == m_pExecutingProxy) + { + pCurrentProxy->SetVirtualProcessorRoot(NULL); + } + else + { + // + // Spin wait until there isn't anything running atop this virtual processor root. Yes -- this means that someone had better be + // on the way out. If you call Remove on a virtual processor that's still running something, the resulting behavior is pretty much + // undefined anyway. + // + SpinUntilIdle(); + } + + delete this; + } + + /// + /// Called in order to reset this virtual processor root to a completely quiescent state (not running anything). + /// + /// + /// Indicates the state of the thread proxy that is making the call. The parameter is of type . + /// + void FreeVirtualProcessorRoot::ResetOnIdle(SwitchingProxyState switchState) + { + FreeThreadProxy *pOriginalProxy = static_cast(m_pExecutingProxy); + + LONG newVal = InterlockedDecrement(&m_activationFence); + if (newVal <= 0) + { + // + // The value could be -1 if we raced with the virtual processor root being removed on a different thread. + // + ASSERT(newVal >= -1); + // + // The fence going down to zero arbitrates between a possible reset/remove race. + // + if (newVal == 0) + Unsubscribe(); + + m_pExecutingProxy = NULL; + + // + // *** READ THIS ***: + // + // It is imperative on this path that once m_pExecutingProxy has been set to NULL, nothing touches the this pointer. We are the race + // resolution between a client getting off a vproc and removing it. There can be a race between removal (DeleteThis) from outside and + // a SwitchOut (here) on the vproc. + // + if (switchState == Blocking) + { + pOriginalProxy->SuspendExecution(); + } + } + else + { + Concurrency::IExecutionContext *pActivatedContext = AcquireActivatedContext(); + ASSERT(newVal == 1 && pActivatedContext != NULL); + + // + // This means we had a race between an Activate and an Idling (via either SwitchOut or return from dispatch loop). In either + // of these cases, we stashed away the context which was activated in m_pActivatedContext. This context now needs to run atop us. + // + FreeThreadProxy *pProxy = static_cast (pActivatedContext->GetProxy()); + ASSERT(pProxy != NULL); + + // + // While it is safe to run through an X->X context switch after the blocked flag is set, there is no point. If we raced a SwitchOut/Activate + // for the same proxy on the same vproc, it's a NOP. + // + if (pOriginalProxy != pProxy) + { + pOriginalProxy->SwitchTo(pActivatedContext, switchState); + } + } + } + + /// + /// Causes the scheduler to start running a thread proxy on the specified virtual processor root which will execute + /// the Dispatch method of the context supplied by pContext. Alternatively, it can be used to resume a + /// virtual processor root that was de-activated by a previous call to Deactivate. + /// + /// + /// The context which will be dispatched on a (potentially) new thread running atop this virtual processor root. + /// + void FreeVirtualProcessorRoot::Activate(Concurrency::IExecutionContext *pContext) + { + if (pContext == NULL) + throw std::invalid_argument("pContext"); + + // + // If the context is being reused, it had better return a NULL thread proxy when we ask! This is part of the spec contract. + // + FreeThreadProxy * pProxy = static_cast (pContext->GetProxy()); + if (pProxy == NULL) + { + pProxy = static_cast (GetSchedulerProxy()->GetNewThreadProxy(pContext)); + } + + // + // All calls to Activate after the first one can potentially race with the paired deactivate. This is allowed by the API, and we use the fence below + // to reduce kernel transitions in case of this race. + // + // We must also be careful because calls to activate can race with ResetOnIdle from either a SwitchOut() or a return from dispatch and we must + // be prepared to deal with this and the implications around trying to bind pContext. + // + LONG newVal = InterlockedIncrement(&m_activationFence); + if (newVal == 2) + { + ASSERT(m_pDeactivatedProxy == NULL); + // + // We received two activations in a row. According to the contract with the client, this is allowed, but we should expect a deactivation, a + // SwitchOut, or a return from dispatch loop soon after. + // + // Simply return instead of signalling the event. The deactivation will reduce the count back to 1. In addition, we're not responsible + // for changing the idle state on the core. + // + SetActivatedContext(pContext); + } + else + { + ASSERT(newVal == 1); + + SpinUntilIdle(); + ASSERT(m_pExecutingProxy == m_pDeactivatedProxy); + + if (m_pExecutingProxy != NULL) + { + // + // The root already has an associated thread proxy. Check that the context provided is associated with + // the same proxy. + // + if (pProxy != m_pExecutingProxy) + { + // + // This is a fatal exception. We can potentially correct the state of the fence, but the scheduler is beyond confused about + // the spec. @TODO: Is it worth making some attempt to correct *our* state given that it's already messed up above us? + // + throw invalid_operation(); + } + } + + m_pDeactivatedProxy = NULL; + + // + // An activated root increases the subscription level on the underlying core. + // + Subscribe(); + + // + // Affinitization sets this as the executing proxy for the virtual processor root. + // + Affinitize(pProxy); + + ASSERT(m_pExecutingProxy == pProxy); + ASSERT(pProxy->GetVirtualProcessorRoot() != NULL); + ASSERT(pProxy->GetExecutionContext() != NULL); + + pProxy->ResumeExecution(); + } + } + + /// + /// Causes the thread proxy running atop this virtual processor root to temporarily stop dispatching pContext. + /// + /// + /// The context which should temporarily stop being dispatched by the thread proxy running atop this virtual processor root. + /// + bool FreeVirtualProcessorRoot::Deactivate(Concurrency::IExecutionContext *pContext) + { + if (pContext == NULL) + throw std::invalid_argument("pContext"); + + if (m_pExecutingProxy == NULL) + throw invalid_operation(); + + FreeThreadProxy * pProxy = static_cast (pContext->GetProxy()); + + if (m_pExecutingProxy != pProxy) + { + throw invalid_operation(); + } + + LONG newVal = InterlockedDecrement(&m_activationFence); + + if (newVal == 0) + { + // + // Reduce the subscription level on the core while the root is suspended. The count is used by dynamic resource management + // to tell which cores allocated to a scheduler are unused, so that they can be temporarily repurposed. + // + InterlockedExchangePointer(reinterpret_cast(&m_pDeactivatedProxy), m_pExecutingProxy); + Unsubscribe(); + pProxy->SuspendExecution(); + } + else + { + // + // There should be no Deactivate/Remove races. + // + ASSERT(newVal == 1); + + Concurrency::IExecutionContext *pActivatedContext = AcquireActivatedContext(); + + // + // If we got here, it means while activated we saw an activation of pCtxX and a subsequent deactivation of pCtxY. These contexts + // must be equal to be spec legal. + // + ASSERT(pActivatedContext == pContext); + + // + // The activation for this deactivation came in early, so we return early here without making a kernel transition. + // + } + + return true; + } + + /// + /// Forces all data in the memory heirarchy of one processor to be visible to all other processors. + /// + /// + /// The context which is currently being dispatched by this root. + /// + void FreeVirtualProcessorRoot::EnsureAllTasksVisible(Concurrency::IExecutionContext *pContext) + { + if (pContext == NULL) + throw std::invalid_argument("pContext"); + + if (m_pExecutingProxy == NULL) + throw invalid_operation(); + + FreeThreadProxy * pProxy = static_cast (pContext->GetProxy()); + + if (m_pExecutingProxy != pProxy) + { + throw invalid_operation(); + } + + GetSchedulerProxy()->GetResourceManager()->FlushStoreBuffers(); + } + + /// + /// Called to affinitize the given thread proxy to this virtual processor. + /// + /// + /// The new thread proxy to run atop this virtual processor root. + /// + void FreeVirtualProcessorRoot::Affinitize(FreeThreadProxy *pThreadProxy) + { + // + // Wait until the thread proxy is firmly blocked. This is essential to prevent vproc root orphanage + // if the thread proxy we're switching to is IN THE PROCESS of switching out to a different one. An example of how this + // could happen: + + // 1] ctxA is running on vp1. It is in the process of blocking, and wants to switch to ctxB. This means ctxA's thread proxy + // tpA must affinitize ctxB's thread proxy tpB to its own vproc root, vproot1. + + // 2] At the exact same time, ctxA is unblocked by ctxY and put onto a runnables collection in its scheduler. Meanwhile, ctxZ + // executing on vp2, has also decided to block. It picks ctxA off the runnables collection, and proceeds to switch to it. + // This means that ctxZ's thread proxy tpZ must affinitize ctxA's thread proxy tpA to ITS vproc root vproot2. + + // 3] Now, if tpZ affinitizes tpA to vproot2 BEFORE tpA has had a chance to affinitize tpB to vproot1, tpB gets mistakenly + // affinitized to vproot2, and vproot1 is orphaned. + + // In order to prevent this, tpZ MUST wait until AFTER tpA has finished its affinitization. This is indicated via the + // blocked flag. tpA will set its blocked flag to 1, after it has finished affintizing tpB to vproot1, at which point it is + // safe for tpZ to modify tpA's vproc root and change it from vproot1 to vproot2. + // + + pThreadProxy->SpinUntilBlocked(); + + m_pExecutingProxy = pThreadProxy; + pThreadProxy->SetVirtualProcessorRoot(this); + + HardwareAffinity newAffinity = GetSchedulerProxy()->GetNodeAffinity(GetNodeId()); + pThreadProxy->SetAffinity(newAffinity); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.h new file mode 100644 index 0000000000000000000000000000000000000000..22b25c0d41ea71166deb355b9c26b81db3264e82 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.h @@ -0,0 +1,112 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// FreeVirtualProcessorRoot.h +// +// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the free virtual +// processor root (represents a virtual processor as handed to a scheduler). +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + + class FreeVirtualProcessorRoot : public VirtualProcessorRoot + { + public: + + /// + /// Constructs a new free virtual processor root. + /// + /// + /// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// + /// The processor node that this root belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + FreeVirtualProcessorRoot(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex); + + /// + /// Causes the scheduler to start running a thread proxy on the specified virtual processor root which will execute + /// the Dispatch method of the context supplied by pContext. + /// + /// + /// The context which will be dispatched on a (potentially) new thread running atop this virtual processor root. + /// + virtual void Activate(::Concurrency::IExecutionContext *pContext); + + /// + /// Causes the thread proxy running atop this virtual processor root to temporarily stop dispatching pContext. + /// + /// + /// The context which should temporarily stop being dispatched by the thread proxy running atop this virtual processor root. + /// + virtual bool Deactivate(::Concurrency::IExecutionContext *pContext); + + /// + /// Forces all data in the memory heirarchy of one processor to be visible to all other processors. + /// + /// + /// The context which is currently being dispatched by this root. + /// + virtual void EnsureAllTasksVisible(::Concurrency::IExecutionContext *pContext); + + // ************************************************** + // Internal + // ************************************************** + + /// + /// Deletes the virtual processor. + /// + virtual void DeleteThis(); + + /// + /// Called to affinitize the given thread proxy to this virtual processor. + /// + /// + /// The new thread proxy to run atop this virtual processor root. + /// + void Affinitize(FreeThreadProxy *pThreadProxy); + + /// + /// Called in order to reset this virtual processor root to a completely quiescent state (not running anything). + /// + /// + /// Indicates the state of the thread proxy that is making the call. The parameter is of type . + /// + void ResetOnIdle(SwitchingProxyState switchState); + + protected: + + /// + /// Spins until there is no thread proxy executing atop the virtual processor root. + /// + void SpinUntilIdle() + { + _SpinWaitBackoffNone spinWait(_Sleep0); + while(m_pExecutingProxy != NULL && m_pDeactivatedProxy == NULL) + { + spinWait._SpinOnce(); + } + } + + // The thread proxy which is currently executing atop this virtual processor root. + ThreadProxy * volatile m_pExecutingProxy; + + // The deactivated proxy. + ThreadProxy * volatile m_pDeactivatedProxy; + + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bb795b76ad851c48cbbf88c0389bac1a17e06b9 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.cpp @@ -0,0 +1,892 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// HillClimbing.cpp +// +// Defines classes for the HillClimbing concurrency-optimization algorithm. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +#pragma warning(disable:4389) + +namespace Concurrency +{ +namespace details +{ + // + // Initial hill climbing configuration settings. These are the starting points for any hill climbing instance. + // + static const unsigned int AlwaysIncrease = 0; // Test setting for always allocating more resources + static const unsigned int ControlGain = 1; // Used to determine the magnitude of moves, in units of (coefficient of variation)/(thread count) + static const unsigned int MaxControlSettingChange = 0; // Maximum number of resources that can be changed in one transition (i.e. a capper) + static const unsigned int MinHistorySize = 3; // Minimum history size to consider relevant for climbing (used for significance test) + static const unsigned int MaxHistorySize = 5; // Maximum history size, after which a climbing move must be recommended + static const unsigned int WarmupSampleCount = 1; // How many samples are needed to warm up hill climbing + static const unsigned int MinCompletionsPerSample = 1; // Minimum number of completions needed to try hill climbing + static const unsigned int MaxInvalidCount = 3; // Maximum number of consecutive invalid samples; minimum recommended after this point + static const unsigned int MaxHistoryAge = 50; // Maximum amount of ticks to keep a history from a previous setting + + /// + /// Creates a new instance of hill climbing. + /// + /// + /// Scheduler id. + /// + /// + /// Number that represents the maximum resources available on the machine. + /// + /// + /// The scheduler proxy that controls this hill climbing instance. + /// + HillClimbing::HillClimbing(unsigned int id, unsigned int numberOfCores, SchedulerProxy * pSchedulerProxy) + : m_pSchedulerProxy(pSchedulerProxy) + , m_currentControlSetting(0) + , m_lastControlSetting(0) + , m_id(id) + , m_sampleCount(0) + , m_totalSampleCount(0) + , m_invalidCount(0) + , m_saveCompleted(0) + , m_saveIncoming(0) + , m_nextRandomMoveIsUp(true) + { + // + // Assign default configuration + // + m_controlGain = ControlGain * numberOfCores; + m_maxControlSettingChange = (MaxControlSettingChange != 0) ? MaxControlSettingChange : numberOfCores; + } + + /// + /// External call passing statistical information to hill climbing. Based on these + /// statistics, hill climbing will give a recommendation on the number of resources to be used. + /// + /// + /// The control setting used in this period of time. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The recommended number of resources to be used. + /// + unsigned int HillClimbing::Update(unsigned int currentControlSetting, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength) + { + HillClimbingStateTransition transition = Undefined; + int recommendedSetting = 0; + + // If there are no resources devoted to this scheduler proxy then there is + // no statistical analysis needed. + if (currentControlSetting == 0) + { + return 0; + } + + // + // Hill climbing made a recommendation for a number of resources to be used the next time around. However, that + // does not mean that this recommendation was accepted by the consumer of that information. Thus, first establish + // the control setting passed in by the consumer so that we can accurately track history information. Also, it is + // necessary to flush old, stale history information before trying to hill climb. + // + m_totalSampleCount++; + EstablishControlSetting(currentControlSetting); + + // + // If we had some invalid samples, then carefully modify the actual parameters to this function + // + if (m_invalidCount > 0) + { + completionRate += m_saveCompleted; + arrivalRate += m_saveIncoming; + } + + // + // If we have long running tasks that are not yet completed, report completions and arrivals for those + // tasks, effectively chunking them up into sample sized tasks. A long running task scenario is defined as: + // + // a) Number or completed tasks is smaller than number of resources used in the time interval, AND + // b) Number of completed tasks is smaller than a length of the queue (resources cannot be invalid) + // + if (completionRate < currentControlSetting && completionRate < queueLength) + { + arrivalRate += (currentControlSetting - completionRate); + completionRate = currentControlSetting; + } + + // + // Check if reported statistics are within the bounds of a valid sample. A sample is invalid iff: + // it is not a warmup run AND it is EITHER too short of a measurement OR there were not enough completions. + // + if (m_sampleCount >= WarmupSampleCount && MinCompletionsPerSample > completionRate && MinCompletionsPerSample > arrivalRate && queueLength == 0) + { + // + // If this is an invalid sample, save the data + // + m_invalidCount++; + m_saveCompleted = completionRate; + m_saveIncoming = arrivalRate; + + unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads(); + unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads(); + (maximumSetting); + + recommendedSetting = (m_invalidCount < MaxInvalidCount) ? m_currentControlSetting : minimumSetting; + + TRACE(CONCRT_TRACE_HILLCLIMBING, + L"********** Invalid sample!\n Process: %u\n Scheduler: %d\n Invalid count: %d\n Completions: %d\n Arrivals: %d\n Queue length: %d\n Minimum: %d\n Maximum: %d\n Current setting: %d\n Last setting: %d\n -----\n Recommended setting: %d\n**********\n", + GetCurrentProcessId(), + m_id, + m_invalidCount, + completionRate, + arrivalRate, + queueLength, + minimumSetting, + maximumSetting, + m_currentControlSetting, + m_lastControlSetting, + recommendedSetting); + + return recommendedSetting; + } + + unsigned int numberOfSamples = m_invalidCount + 1; + + // + // Reset the statistics kept for invalid samples and initiate a valid sample + // + m_sampleCount++; + m_saveCompleted = 0; + m_saveIncoming = 0; + m_invalidCount = 0; + + // Unless there is a good reason to climb, the current setting (set by EstablishControlSetting) will remain the same. + recommendedSetting = m_currentControlSetting; + + // Calculate the throughput for this given instance + double throughput = CalculateThroughput(numberOfSamples, completionRate, arrivalRate, queueLength); + + if (m_sampleCount <= WarmupSampleCount) + { + // + // We're in the "warmup" phase, where we simply bide our time (and initialize our current control setting). + // + _CONCRT_ASSERT(m_currentControlSetting != 0); + m_lastControlSetting = m_currentControlSetting; + transition = Warmup; + } + else + { + MeasuredHistory * currentHistory = GetHistory(m_currentControlSetting); + MeasuredHistory * lastHistory = GetHistory(m_lastControlSetting); + + currentHistory->Add(throughput, m_totalSampleCount); + + if (AlwaysIncrease > 0) + { + // + // We're in the "always increase" diagnostic mode. Just increase the control setting + // along the desired gradient. + // + unsigned int newSetting = (unsigned int) ((AlwaysIncrease / 1000.0) * m_sampleCount); + + if (newSetting > m_currentControlSetting) + { + recommendedSetting = RecommendControlSetting(newSetting); + transition = DoClimbing; + } + else + { + transition = ContinueLookingForClimb; + } + } + else if (lastHistory->Count() == 0 || currentHistory == lastHistory) + { + // + // If we have no previous history, then we need to initialize. We wait until + // the current history is stable, then make our first move. + // + if (IsStableHistory(currentHistory)) + { + // + // This is our first move; we have no history to use to predict the correct move. + // We'll just make a random move, and see what happens. + // + recommendedSetting = RecommendControlSetting(m_currentControlSetting + GetRandomMove()); + transition = CompletedInitialization; + } + else + { + transition = ContinueInitializing; + } + } + else if (!IsStableHistory(currentHistory)) + { + transition = ContinueLookingForClimb; + } + else + { + // + // We have two separate stable histories. We can compare them, and make a real climbing move. + // + double gradient = CalculateThroughputGradient(m_lastControlSetting, m_currentControlSetting); + double controlSettingAdjustment = gradient * m_controlGain; + unsigned int newControlSetting = (unsigned int) (m_currentControlSetting + controlSettingAdjustment); + + if (newControlSetting == m_currentControlSetting) + { + newControlSetting = (unsigned int) (m_currentControlSetting + sign(controlSettingAdjustment)); + } + + recommendedSetting = RecommendControlSetting(newControlSetting); + transition = DoClimbing; + } + } + + _CONCRT_ASSERT(transition != Undefined); // Unhandled case for HillClimbing controller + +#if defined(CONCRT_TRACING) + LogData(recommendedSetting, transition, numberOfSamples, completionRate, arrivalRate, queueLength, throughput); +#endif + + return recommendedSetting; + } + + /// + /// Calculates the throughput based on the input parameters. + /// + /// + /// The number of sample points in this measurement, including invalid ones. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The calculated throughput. + /// + double HillClimbing::CalculateThroughput(unsigned int numberOfSamples, unsigned int completionRate, unsigned int, unsigned int) + { + const double samplesPerSecond = 10.0; // A double constant representing number of valid samples per second + + // Compute the rate at which the queue is growing or shrinking. If it is growing, report a higher + // number which will cause more resources to be allocated for this instance; it the length of the queue + // is shrinking, try to take away resources while still shrinking the queue. + // + // /_\ length incoming - completed + // growth = ------------ = ---------------------- + // /_\ time t2 - t1 + // + // For now, instead of looking at the change in the queue length, completion rate will be used. This is due + // to the fact that typical loads in ConcRT are self-balancing, i.e. completion rate ~ incoming rate. + // + return (completionRate * samplesPerSecond) / (double) (numberOfSamples); + } + + /// + /// Recommends NewControlSetting to be used. + /// + /// + /// The control setting to be established. + /// + /// + /// New control setting to be used. + /// + unsigned int HillClimbing::RecommendControlSetting(unsigned int newControlSetting) + { + // + // Make sure that the new setting is within the biggest individual move bounds. + // + unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads(); + unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads(); + + newControlSetting = min(m_currentControlSetting + m_maxControlSettingChange, newControlSetting); + + if (m_currentControlSetting > m_maxControlSettingChange) + { + newControlSetting = max(m_currentControlSetting - m_maxControlSettingChange, newControlSetting); + } + + if (newControlSetting == m_currentControlSetting) // Can't draw a line with a single point + { + if (newControlSetting > minimumSetting) + { + newControlSetting--; + } + else + { + newControlSetting++; + } + } + + // + // Make sure that the new setting is within the min and max bounds of the scheduler proxy. + // + newControlSetting = max(minimumSetting, newControlSetting); + newControlSetting = min(maximumSetting, newControlSetting); + + if (AlwaysIncrease == 0 && newControlSetting != m_currentControlSetting) + { + // If this move would cause us to move through a setting that we know was recently worse than this + // one, then back off to one before that setting. + int direction = sign(newControlSetting - m_currentControlSetting); + + if (direction == -1) + { + for (int setting = m_currentControlSetting + direction; + setting == newControlSetting || sign(newControlSetting - setting) == direction; + setting += direction) + { + if (GetHistory(setting)->Count() > 0) + { + double gradient = CalculateThroughputGradient(m_currentControlSetting, setting) * direction; + + if (gradient <= 0) + { + newControlSetting = setting - direction; + break; + } + } + } + } + } + + return newControlSetting; + } + + /// + /// Establishes control setting as current. This is the only method that updates the control settings. + /// + /// + /// The control setting to be established. + /// + void HillClimbing::EstablishControlSetting(unsigned int newControlSetting) + { + if (newControlSetting != m_currentControlSetting) + { + m_lastControlSetting = m_currentControlSetting; + m_currentControlSetting = newControlSetting; + GetHistory(m_currentControlSetting)->Clear(0); + FlushHistories(); + } + } + + /// + /// Calculates the throughput gradient given two history measurements. + /// + /// + /// The control setting to move from. + /// + /// + /// The control setting to move to. + /// + /// + /// A value representing a gradient between two measurements. + /// + double HillClimbing::CalculateThroughputGradient(int fromSetting, int toSetting) + { + // + // Configurable constants to control reactiveness of hill climbing + // + const double minJustifiesChange = 0.15; // A minimum fractional change in measurement that justifies a change (cost for making a change) + const double changeAdjustmentMultiplier = 1.0; // Controls change factor by reducing uncertainty (bigger number pessimizes change frequency) + + double fractionalChangeInControlSetting = (double) (toSetting - fromSetting) / (double) fromSetting; + + MeasuredHistory * lastHistory = GetHistory(fromSetting); + MeasuredHistory * currentHistory = GetHistory(toSetting); + + double lastHistoryMean = lastHistory->Mean(); + double currentHistoryMean = currentHistory->Mean(); + double meanChangeInMeasuredValue = currentHistoryMean - lastHistoryMean; + double fractionalChangeInMeasuredValue = meanChangeInMeasuredValue / lastHistoryMean; + + double gradient = (fractionalChangeInMeasuredValue/fractionalChangeInControlSetting) - minJustifiesChange; + + double varianceOfcurrentHistory = currentHistory->VarianceMean(); + double varianceOflastHistory = lastHistory->VarianceMean(); + double standardDeviationOfDifferenceInMeans = sqrt(varianceOfcurrentHistory + varianceOflastHistory); + double coefficientOfVariationOfChangeInMeasuredValue = + (abs(meanChangeInMeasuredValue) > 0) ? abs(standardDeviationOfDifferenceInMeans / meanChangeInMeasuredValue) : 0; + + double adjustedGradient = gradient * exp(-changeAdjustmentMultiplier * coefficientOfVariationOfChangeInMeasuredValue); + + return adjustedGradient; + } + + /// + /// Determines whether a given history measurement is stable enough to make a hill climbing move. + /// + /// + /// True if history measurement is stable. + /// + bool HillClimbing::IsStableHistory(MeasuredHistory * pMeasuredHistory) + { + const double maxCoefficientOfVariation = 0.004; // Controls history relevance between min and max by bounding the error + + if (pMeasuredHistory->Count() > MaxHistorySize) + { + return true; + } + + if (pMeasuredHistory->Count() < MinHistorySize) + { + return false; + } + + if (abs(pMeasuredHistory->CoefficientOfVariationMean()) > maxCoefficientOfVariation) + { + return false; + } + + return true; + } + + /// + /// Flushes all measurement histories that are no longer relevant. + /// + void HillClimbing::FlushHistories() + { + for (int i = 0; i < MaxHistoryCount; i++) + { + if (m_histories[i].ControlSetting() != m_currentControlSetting && + m_histories[i].ControlSetting() != m_lastControlSetting && + m_totalSampleCount - m_histories[i].LastDataPointCount() > MaxHistoryAge) + { + m_histories[i].Clear(0); + } + } + } + + /// + /// Clears all measurement histories. + /// + void HillClimbing::ClearHistories() + { + for (int i = 0; i < MaxHistoryCount; i++) + { + m_histories[i].Clear(0); + } + } + + /// + /// Makes a pseudo-random hill climbing move by alternating between up and down. + /// + /// + /// The random move. + /// + int HillClimbing::GetRandomMove() + { + int result = m_nextRandomMoveIsUp ? 1 : 0; + m_nextRandomMoveIsUp = !m_nextRandomMoveIsUp; + return result; + } + + /// + /// Gets the history measurement for a given control setting. + /// + /// + /// The history measurement. + /// + HillClimbing::MeasuredHistory * HillClimbing::GetHistory(unsigned int controlSetting) + { + int i = controlSetting % MaxHistoryCount; + + if (m_histories[i].ControlSetting() != controlSetting) + { + m_histories[i].Clear(controlSetting); + } + + return &m_histories[i]; + } + + /// + /// Creates a new measurement history. + /// + HillClimbing::MeasuredHistory::MeasuredHistory() + { + Clear(0); + } + + /// + /// Clears the history values for this control setting. + /// + /// + /// The control setting to reset. + /// + void HillClimbing::MeasuredHistory::Clear(unsigned int controlSetting) + { + m_count = 0; + m_sum = 0; + m_sumOfSquares = 0; + m_controlSetting = controlSetting; + m_lastDataPointCount = 0; + } + + /// + /// Adds a new history data point. + /// + /// + /// The value representing throughput in this invocation. + /// + /// + /// The value representing the total number of samples for this history, including invalid samples and samples for previous settings. + /// + void HillClimbing::MeasuredHistory::Add(const double dataValue, unsigned int totalSampleCount) + { + m_sum += dataValue; + m_sumOfSquares += dataValue * dataValue; + m_count++; + m_lastDataPointCount = totalSampleCount; + } + + /// + /// Gets the count for this history measurement. + /// + /// + /// The count. + /// + int HillClimbing::MeasuredHistory::Count() + { + return m_count; + } + + /// + /// Gets the count at the last data point for this history measurement. + /// + /// + /// The last data point count. + /// + unsigned int HillClimbing::MeasuredHistory::LastDataPointCount() + { + return m_lastDataPointCount; + } + + /// + /// Gets the control setting for this history measurement. + /// + /// + /// The control setting. + /// + int HillClimbing::MeasuredHistory::ControlSetting() { + return m_controlSetting; + } + + /// + /// Computes the mean for a given history. + /// + /// + /// The mean. + /// + double HillClimbing::MeasuredHistory::Mean() + { + return (m_count == 0) ? 0.0 : (m_sum / m_count); + } + + /// + /// Computes the coefficient of variation for a given history. + /// + /// + /// The coefficient of variation. + /// + double HillClimbing::MeasuredHistory::CoefficientOfVariation() + { + double mean = Mean(); + return (mean <= 0.0) ? 0.0 : (StandardDeviation() / mean); + } + + /// + /// Computes the mean of coefficients of variation for a given history. + /// + /// + /// The mean of coefficients of variation. + /// + double HillClimbing::MeasuredHistory::CoefficientOfVariationMean() + { + return (StandardDeviation() / sqrt(1.0 * m_count)) / Mean(); + } + + /// + /// Computes the variance for a given history. + /// + /// + /// The variance. + /// + double HillClimbing::MeasuredHistory::Variance() + { + const double smallValue = 0.0001; + double variance = 0.0; + + if (m_count >= 2) + { + variance = (m_sumOfSquares - (m_sum * m_sum)/ m_count)/ (m_count - 1); + } + + return abs(variance) > smallValue ? variance : 0; + } + + /// + /// Computes the mean of variances for a given history. + /// + /// + /// The mean of variances. + /// + double HillClimbing::MeasuredHistory::VarianceMean() + { + return Variance() / Count(); + } + + /// + /// Computes the standard deviation for a given history. + /// + /// + /// The standard deviation. + /// + double HillClimbing::MeasuredHistory::StandardDeviation() + { + return sqrt(Variance()); + } + + /// + /// Computes the mean of standard deviations for a given history. + /// + /// + /// The mean of standard deviations. + /// + double HillClimbing::MeasuredHistory::StandardDeviationMean() + { + return (m_count == 0) ? 0.0 : (StandardDeviation() / sqrt(m_count * 1.0)); + } + + /// + /// Tests if the difference between two measurement histories is statistically significant to + /// make a hill climbing decision. + /// + /// + /// A two sided test is used. + /// + /// + /// The value representing the second history. + /// + /// + /// The significance level in percent. Accepts 1 through 10. + /// + /// + /// The value representing the total number of samples for this history, including invalid samples and samples for previous settings. + /// + /// + /// -1 - second history is larger than this history + /// 0 - statistically identical + /// 1 - this history is larger than second history + /// + int HillClimbing::MeasuredHistory::SignificanceTest(double value, const int significanceLevel, unsigned int totalSampleCount) + { + MeasuredHistory singleValue; + singleValue.Add(value, totalSampleCount); + + return MeasuredHistory::SignificanceTest(&singleValue, significanceLevel); + } + + /// + /// Tests if the difference between two measurement histories is statistically significant to + /// make a hill climbing decision. + /// + /// + /// A two sided test is used. + /// + /// + /// The pointer to second measurement history. + /// + /// + /// The significance level in percent. Accepts 1 through 10. + /// + /// + /// -1 - second history is larger than this history + /// 0 - statistically identical + /// 1 - this history is larger than second history + /// + int HillClimbing::MeasuredHistory::SignificanceTest(MeasuredHistory * pMeasuredHistory, const int significanceLevel) + { + const int critSize = 10; + double critArray[critSize] = { 2.576, 2.3263, 2.17, 2.05, 1.96, 1.88, 1.81, 1.75, 1.70, 1.64 }; + + double thisVariance = this->VarianceMean(); + double thisMean = Mean(); + double secondVariance = pMeasuredHistory->VarianceMean(); + double secondMean = pMeasuredHistory->Mean(); + + _CONCRT_ASSERT(significanceLevel > 0 && significanceLevel <= 10); // Invalid significance level + + int result = (int) sign(thisMean - secondMean); + + if (thisVariance > 0 && secondVariance > 0) + { + double pooledVar = thisVariance / Count() + secondVariance / pMeasuredHistory->Count(); + + double testStatistic = (thisMean - secondMean) / sqrt(pooledVar); + double critVal = critArray[significanceLevel-1]; + double absVal = abs(testStatistic); + + if (absVal < critVal) + { + result = 0; + } + } + + return result; + } + +#if defined(CONCRT_TRACING) + + // Logging mechanism + + struct HillClimbingLogEntry + { + long sampleCount; + unsigned int currentTotalSampleCount; + double throughput; + double currentHistoryMean; + double currentHistoryStd; + double lastHistoryMean; + double lastHistoryStd; + unsigned int currentControlSetting; + unsigned int lastControlSetting; + unsigned int currentHistoryCount; + unsigned int lastHistoryCount; + HillClimbingStateTransition transition; + }; + + static const int HillClimbingLogCapacity = 100; + static HillClimbingLogEntry HillClimbingLog[HillClimbingLogCapacity]; + static int HillClimbingLogFirstIndex = 0; + static int HillClimbingLogSize = 0; + + static const wchar_t * const HillClimbingTransitionNames[] = + { + L"Warmup", + L"ContinueInitializing", + L"CompletedInitialization", + L"DoClimbing", + L"ChangePoint", + L"ContinueLookingForClimb", + L"Undefined" + }; + + /// + /// Logs the hill climbing decision. + /// + /// + /// The control setting to be established. + /// + /// + /// The transition that is recommended by hill climbing. + /// + /// + /// The number of sample points in this measurement, including invalid ones. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The throughput of the given instance. + /// + void HillClimbing::LogData(unsigned int recommendedSetting, HillClimbingStateTransition transition, unsigned int numberOfSamples, + unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength, double throughput) + { + // + // First, log to memory so we can see it in the debugger + // + int index = (HillClimbingLogFirstIndex + HillClimbingLogSize) % HillClimbingLogCapacity; + if (HillClimbingLogSize == HillClimbingLogCapacity) + { + HillClimbingLogFirstIndex = (HillClimbingLogFirstIndex + 1) % HillClimbingLogCapacity; + HillClimbingLogSize--; //hide this slot while we update it + } + + HillClimbingLogEntry * entry = &HillClimbingLog[index]; + unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads(); + unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads(); + + entry->sampleCount = m_sampleCount; + entry->currentTotalSampleCount = numberOfSamples; + entry->throughput = throughput; + entry->transition = transition; + entry->currentControlSetting = m_currentControlSetting; + entry->lastControlSetting = m_lastControlSetting; + + MeasuredHistory * currentHistory = GetHistory(m_currentControlSetting); + entry->currentHistoryCount = currentHistory->Count(); + entry->currentHistoryMean = currentHistory->Mean(); + entry->currentHistoryStd = currentHistory->StandardDeviation(); + + MeasuredHistory * lastHistory = GetHistory(m_lastControlSetting); + entry->lastHistoryCount = lastHistory->Count(); + entry->lastHistoryMean = lastHistory->Mean(); + entry->lastHistoryStd = lastHistory->StandardDeviation(); + + HillClimbingLogSize++; + + const int bufferSize = 180; + const wchar_t * delim = L"*******************************************************"; + + wchar_t dateBuffer[bufferSize]; + SYSTEMTIME time; + GetLocalTime(&time); + int dateLen = GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, dateBuffer, bufferSize); + dateBuffer[dateLen-1] = L' '; + GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, TIME_FORCE24HOURFORMAT | TIME_NOTIMEMARKER, &time, NULL, dateBuffer + dateLen, bufferSize - dateLen); + + TRACE(CONCRT_TRACE_HILLCLIMBING, L"%ls\n Process: %u\n Scheduler: %d\n Date: %ls\n Number of samples: %d\n Number of samples in this measurement (including invalid): %d\n Completions: %d\n Arrivals: %d\n Queue length: %d\n Throughput: %.4f\n Transition: %ls\n Next random move: %ls\n Minimum: %d\n Maximum: %d\n Current setting: %d\n * count: %d mean: %g dev: %g varm: %g\n Last setting: %d\n * count: %d mean: %g dev: %g varm: %g\n -----\n Recommended setting: %d\n%ls\n", + delim, + GetCurrentProcessId(), + m_id, + dateBuffer, + m_sampleCount, + numberOfSamples, + completionRate, + arrivalRate, + queueLength, + throughput, + HillClimbingTransitionNames[transition], + m_nextRandomMoveIsUp ? L"Up" : L"Down", + minimumSetting, + maximumSetting, + m_currentControlSetting, + currentHistory->Count(), + currentHistory->Mean(), + currentHistory->StandardDeviation(), + currentHistory->CoefficientOfVariationMean(), + m_lastControlSetting, + lastHistory->Count(), + lastHistory->Mean(), + lastHistory->StandardDeviation(), + lastHistory->CoefficientOfVariationMean(), + recommendedSetting, + delim); + } +#endif +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.h new file mode 100644 index 0000000000000000000000000000000000000000..fa7b7c9ce0fb545279ba2c2fa963408c31446b26 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.h @@ -0,0 +1,410 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// HillClimbing.h +// +// Defines classes for the HillClimbing concurrency-optimization algorithm. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + + /// + /// An enum representing all possible hill climbing transition moves. + /// + enum HillClimbingStateTransition + { + Warmup, + ContinueInitializing, + CompletedInitialization, + DoClimbing, + ChangePoint, + ContinueLookingForClimb, + Undefined, + }; + + /// + /// A class responsible for hill climbing. + /// + class HillClimbing + { + public: + + /// + /// Creates a new instance of hill climbing. + /// + /// + /// Scheduler id. + /// + /// + /// Number that represents the maximum resources available on the machine. + /// + /// + /// The scheduler proxy that controls this hill climbing instance. + /// + HillClimbing(unsigned int id, unsigned int numberOfCores, SchedulerProxy * pSchedulerProxy); + + /// + /// External call passing statistical information to hill climbing. Based on these + /// statistics, hill climbing will give a recommendation on the number of resources to be used. + /// + /// + /// The control setting used in this period of time. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The recommended number of resources to be used. + /// + unsigned int Update(unsigned int currentControlSetting, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength); + + private: + + /// + /// A class responsible for keeping hill climbing history measurements. + /// + class MeasuredHistory + { + public: + + /// + /// Creates a new measurement history. + /// + MeasuredHistory(); + + /// + /// Adds a new history data point. + /// + /// + /// The value representing throughput in this invocation. + /// + /// + /// The value representing the total number of samples for this history, including invalid samples and samples for previous settings. + /// + void Add(const double data, unsigned int totalSampleCount); + + /// + /// Clears the history values for this control setting. + /// + /// + /// The control setting to reset. + /// + void Clear(unsigned int controlSetting); + + /// + /// Gets the count for this history measurement. + /// + /// + /// The count. + /// + int Count(); + + /// + /// Gets the count at the last data point for this history measurement. + /// + /// + /// The last data point count. + /// + unsigned int LastDataPointCount(); + + /// + /// Gets the control setting for this history measurement. + /// + /// + /// The control setting. + /// + int ControlSetting(); + + /// + /// Computes the mean for a given history. + /// + /// + /// The mean. + /// + double Mean(); + + /// + /// Computes the coefficient of variation for a given history. + /// + /// + /// The coefficient of variation. + /// + double CoefficientOfVariation(); + + /// + /// Computes the mean of coefficients of variation for a given history. + /// + /// + /// The mean of coefficients of variation. + /// + double CoefficientOfVariationMean(); + + /// + /// Computes the variance for a given history. + /// + /// + /// The variance. + /// + double Variance(); + + /// + /// Computes the mean of variances for a given history. + /// + /// + /// The mean of variances. + /// + double VarianceMean(); + + /// + /// Computes the standard deviation for a given history. + /// + /// + /// The standard deviation. + /// + double StandardDeviation(); + + /// + /// Computes the mean of standard deviations for a given history. + /// + /// + /// The mean of standard deviations. + /// + double StandardDeviationMean(); + + /// + /// Tests if the difference between two measurement histories is statistically significant to + /// make a hill climbing decision. + /// + /// + /// A two sided test is used. + /// + /// + /// The value representing the second history. + /// + /// + /// The significance level in percent. Accepts 1 through 10. + /// + /// + /// The value representing the total number of samples for this history, including invalid samples and samples for previous settings. + /// + /// + /// -1 - second history is larger than this history + /// 0 - statistically identical + /// 1 - this history is larger than second history + /// + int SignificanceTest(double value, const int significanceLevel, unsigned int totalSampleCount); + + /// + /// Tests if the difference between two measurement histories is statistically significant to + /// make a hill climbing decision. + /// + /// + /// A two sided test is used. + /// + /// + /// The pointer to second measurement history. + /// + /// + /// The significance level in percent. Accepts 1 through 10. + /// + /// + /// -1 - second history is larger than this history + /// 0 - statistically identical + /// 1 - this history is larger than second history + /// + int SignificanceTest(MeasuredHistory * pMeasuredHistory, const int significanceLevel); + + private: + + // Running sum of throughputs + double m_sum; + + // Sum of throughput squares + double m_sumOfSquares; + + // Count of measurements in this history + int m_count; + + // An integer representing the control setting for this history measurement + int m_controlSetting; + + // Last count value when a measurement was taken (used for relevance test) + unsigned int m_lastDataPointCount; + }; + + /// + /// Makes a pseudo-random hill climbing move by alternating between up and down. + /// + /// + /// The random move. + /// + int GetRandomMove(); + + /// + /// Recommends NewControlSetting to be used. + /// + /// + /// The control setting to be established. + /// + /// + /// New control setting to be used. + /// + unsigned RecommendControlSetting(unsigned int newControlSetting); + + /// + /// Establishes control setting as current. This is the only method that updates the control settings. + /// + /// + /// The control setting to be established. + /// + void EstablishControlSetting(unsigned int newControlSetting); + + /// + /// Determines whether a given history measurement is stable enough to make a hill climbing move. + /// + /// + /// True if history measurement is stable. + /// + bool IsStableHistory(MeasuredHistory * pMeasuredHistory); + + /// + /// Calculates the throughput based on the input parameters. + /// + /// + /// The number of sample points in this measurement, including invalid ones. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The calculated throughput. + /// + double CalculateThroughput(unsigned int numberOfSamples, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength); + + /// + /// Calculates the throughput gradient given two history measurements. + /// + /// + /// The control setting to move from. + /// + /// + /// The control setting to move to. + /// + /// + /// A value representing a gradient between two measurements. + /// + double CalculateThroughputGradient(int fromSetting, int toSetting); + + /// + /// Flushes all measurement histories that are no longer relevant. + /// + void FlushHistories(); + + /// + /// Clears all measurement histories. + /// + void ClearHistories(); + + /// + /// Gets the history measurement for a given control setting. + /// + /// + /// The history measurement. + /// + MeasuredHistory * GetHistory(unsigned int controlSetting); + + // The maximum number of histories to keep + static const unsigned int MaxHistoryCount = 64; + + // The array where history data is kept + MeasuredHistory m_histories[MaxHistoryCount]; + + // Scheduler proxy to which this hill climbing instance belongs + SchedulerProxy * m_pSchedulerProxy; + + // Used to determine the magnitude of moves, in units of (coefficient of variation)/(thread count) + double m_controlGain; + + // Maximum number of resources that can be changed in one transition + unsigned int m_maxControlSettingChange; + + // The current amount of resources allocated in this hill climbing instance + unsigned int m_currentControlSetting; + + // The amount of resources allocated in this hill climbing instance before the last move + unsigned int m_lastControlSetting; + + // Scheduler id + unsigned int m_id; + + // Number of samples collected + unsigned long m_sampleCount; + + // Number of samples collected including invalid samples, across settings + unsigned long m_totalSampleCount; + + // Number of consecutive invalid samples + unsigned long m_invalidCount; + + // Save sum of completions for consecutive invalid samples + unsigned int m_saveCompleted; + + // Save sum of arrivals for consecutive invalid samples + unsigned int m_saveIncoming; + + // Determines where the next random move is going + bool m_nextRandomMoveIsUp; + +#if defined(CONCRT_TRACING) + /// + /// Logs the hill climbing decision by constructing a CSV dump of data. + /// + /// + /// The control setting to be established. + /// + /// + /// The transition that is recommended by hill climbing. + /// + /// + /// The number of sample points in this measurement, including invalid ones. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The throughput of the given instance. + /// + void LogData(unsigned int recommendedSetting, HillClimbingStateTransition transition, unsigned int numberOfSamples, + unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength, double throughput); +#endif + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4628ea19f03bb8a0fd09de6ebf60280b1e278f4 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.cpp @@ -0,0 +1,2119 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// InternalContextBase.cpp +// +// Source file containing the implementation for an internal execution context. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + unsigned int GetProcessorMaskId(InternalContextBase* pContext) + { + return pContext->m_pVirtualProcessor->GetMaskId(); + } + +#if defined(_DEBUG) + void SetContextDebugBits(InternalContextBase *pContext, DWORD bits) + { + if (pContext != NULL) + pContext->SetDebugBits(bits); + } +#endif + + /// + /// Constructs the base class object for an internal context. + /// + InternalContextBase::InternalContextBase(SchedulerBase *pScheduler) : + ContextBase(pScheduler, false), + m_pThreadProxy(NULL), +#ifdef _DEBUG + _m_pVirtualProcessor(NULL), +#else + m_pVirtualProcessor(NULL), +#endif // _DEBUG + m_pOversubscribedVProc(NULL), + m_pAssociatedChore(NULL), + m_searchCount(0), + m_fCanceled(false), + m_fIsVisibleVirtualProcessor(false), + m_fHasDequeuedTask(false), + m_fWorkSkipped(false), +#ifdef _DEBUG + m_fEverRecycled(false), + m_workStartTimeStamp(0), + m_lastRunPrepareTimeStamp(0), + m_prepareCount(0), + m_ctxDebugBits(0), + m_lastDispatchedTid(0), + m_lastAcquiredTid(0), + m_lastAffinitizedTid(0), + m_pAssignedThreadProxy(NULL), + m_pLastAssignedThreadProxy(NULL), +#endif // _DEBUG + m_fCrossGroupRunnable(FALSE), + m_fIdle(true) + { + // Initialize base class members. + m_pSegment = NULL; + } + + /// + /// Called to find work to switch to when the current context needs to block or nest a different scheduler. + /// The function may return NULL if no work was found and thread creation was disallowed by the thread + /// throttler. + /// + InternalContextBase* InternalContextBase::FindWorkForBlockingOrNesting(bool& fSFWContext, bool& fBoundUnrealized) + { + InternalContextBase *pContext = NULL; + WorkItem work; + // + // Either search for some context or a placement token letting us know that we need to allocate a thread for it. If + // we are throttled, said thread creation will not happen. + // + if (m_pVirtualProcessor->SearchForWork(&work, m_pSegment, false, WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChoreToken | WorkItem::WorkItemTypeUnrealizedChoreToken)) + { + if (!work.IsContext()) + { + // + // Make sure we can get a thread. Further, make sure all of this happens outside a critical region to avoid the huge cost of + // allocation within one. + // + ExitCriticalRegion(); + CONCRT_COREASSERT(GetCriticalRegionType() == OutsideCriticalRegion); + + pContext = m_pScheduler->GetInternalContext(); + EnterCriticalRegion(); + + if (pContext != NULL) + { + if (work.ResolveToken()) + { + fBoundUnrealized = work.GetType() == WorkItem::WorkItemTypeUnrealizedChore; + work.BindTo(pContext); + } + else + { + if (m_pVirtualProcessor->SearchForWork(&work, m_pSegment, false, WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore | WorkItem::WorkItemTypeUnrealizedChore)) + { + if (!work.IsContext()) + { + fBoundUnrealized = work.GetType() == WorkItem::WorkItemTypeUnrealizedChore; + work.BindTo(pContext); + } + else + { + // Oops -- we have an extra thread due to a race. Do what's always done and pop it back on the free list. + m_pScheduler->ReleaseInternalContext(pContext, true); + pContext = work.Bind(); + } + } + else + { + // If we did not find anything in this SFW, the context we just grabbed will be utilized as the SFW context which + // deactivates the vproc. + // + // If this method was called during a Block operation, the context will not get prepared until we fully commit the block + // (it will get released in the case of a block/unblock race) + fSFWContext = true; + } + } + } + else + { + if (m_pVirtualProcessor->SearchForWork(&work, m_pSegment, false, WorkItem::WorkItemTypeContext)) + pContext = work.Bind(); + } + } + else + { + pContext = work.GetContext(); + } + } + else + { + // + // Get an SFW context ready. + // + pContext = m_pScheduler->GetInternalContext(); + fSFWContext = (pContext != NULL); + } + return pContext; + } + + /// + /// Causes the internal context to block yielding the virtual processor to a different internal context. + /// + void InternalContextBase::Block() + { + EnterCriticalRegion(); + ASSERT(this == SchedulerBase::FastCurrentContext()); + ASSERT(m_pVirtualProcessor != NULL); + + TraceContextEvent(CONCRT_EVENT_BLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + if (m_pVirtualProcessor->IsMarkedForRetirement()) + { + // The virtual processor has been marked for retirement. The context needs to switch out rather + // than switching to a different context. + + // The context switching fence needs to be modified in two steps to maintain parity + // with the regular block/unblock sequence. Else, we could get into a situation where + // it has an invalid value. + if ((InterlockedIncrement(&m_contextSwitchingFence) == 1) && (InterlockedCompareExchange(&m_contextSwitchingFence, 2, 1) == 1)) + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Block->switching out"); + SwitchOut(Blocking); + } + else + { + // Even if the unblock is skipped, we should not continue running this context since the + // virtual processor needs to be retired. It should be put on the runnables list and + // the context should block (which is the same series of steps as when yielding). + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Block->Unblock was skipped, switching out"); + SwitchOut(Yielding); + } + } + else + { + // Execute a different context on the underlying virtual processor. + if (InterlockedIncrement(&m_contextSwitchingFence) == 1) + { + bool fSFWContext = false; + bool fBoundUnrealized = false; + InternalContextBase *pContext = FindWorkForBlockingOrNesting(fSFWContext, fBoundUnrealized); + +#if defined(_DEBUG) + CONCRT_COREASSERT(this != pContext); + if (pContext != NULL) + { + CMTRACE(MTRACE_EVT_SFW_FOUND, this, m_pVirtualProcessor, pContext); + CMTRACE(MTRACE_EVT_SFW_FOUNDBY, pContext, m_pVirtualProcessor, this); + } +#endif + // Only switch to the other context if unblock has not been called since we last touched the + // context switching fence. If there was an unblock since, the comparison below will fail. + if (InterlockedCompareExchange(&m_contextSwitchingFence, 2, 1) == 1) + { + // + // *NOTE* After this point, we dare not block. A racing ::Unblock call can put *US* on the runnables list and the scheduler + // will get awfully confused if a UMS activation happens between now and the time we SwitchTo the context below. Note that + // page faults and suspensions are masked by the effect of being in a critical region. It just means that we cannot call + // *ANY* blocking API (including creating a new thread). + // + if (fSFWContext) + { + ASSERT(pContext != NULL); + pContext->PrepareForUse(m_pSegment, NULL, false); + } + // + // If pContext is NULL, we are stuck. This virtual processor is blocked and we cannot create a thread. We must make the virtual + // processor available and remove anything from running atop it. SwitchTo(NULL) implies this behavior. + // + SwitchTo(pContext, Blocking); + } + else + { + // A matching unblock was detected. Skip the block. If a runnable context was found, it needs to be + // put back into the runnables collection. + + // NOTE -- don't look at pContext after pContext->AddToRunnables; it might be gone + if (pContext != NULL) + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Block->innerskipblock(ctx=%d,grp=%d)", pContext->GetId(), pContext->GetScheduleGroupId()); + VCMTRACE(MTRACE_EVT_BLOCKUNBLOCKRACE, pContext, m_pVirtualProcessor, this); + +#if defined(_DEBUG) + // + // For a recycled context, this allows other assertions elsewhere in the codebase to be valid and continue to catch + // issues around recycling. + // + pContext->ClearDebugBits(CTX_DEBUGBIT_RELEASED); +#endif // _DEBUG + + if (fSFWContext) + m_pScheduler->ReleaseInternalContext(pContext, true); + else + { + // + // There is a reference count which is handed from the stealer to the chore wrapper which will block a thread from exiting. + // Placing a stolen chore bound to a context directly back on the runnables list has a risk of deadlock on 1 vproc unless we + // deal with this: transfer the reference count to the stealers list which would normally be done by the chore wrapper. + // This act will take a contended lock, so we exit critical region before doing it. + // + // + if (fBoundUnrealized) + { + CONCRT_COREASSERT(pContext->m_pAssociatedChore != NULL); + _UnrealizedChore *pChore = static_cast<_UnrealizedChore *>(pContext->m_pAssociatedChore); + + ExitCriticalRegion(); + pChore->_PrepareSteal(pContext); + EnterCriticalRegion(); + } + + pContext->AddToRunnables(pContext->GetScheduleGroupSegment()->GetAffinity()); + } + } + } + } + else + { + // Skip the block + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Block->outerskipblock(ctx=%d,grp=%d)", GetId(), GetScheduleGroupId()); + } + } + ExitCriticalRegion(); + } + + /// + /// Unblocks the internal context putting it on the runnables collection in its schedule group. + /// + void InternalContextBase::Unblock() + { + if (this != SchedulerBase::FastCurrentContext()) + { + LONG newValue = 0; + + newValue = InterlockedDecrement(&m_contextSwitchingFence); + + TraceContextEvent(CONCRT_EVENT_UNBLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + if (newValue == 1) + { + // Weak assign is ok. Any other 'LOCK' interaction with m_contextSwitchingFence will + // flush the correct value through. + m_contextSwitchingFence = 0; + + // Wait until this context is blocked. + // + // SpinUntilBlocked is essential here. Consider the case where the context being unblocked is currently executing the Block + // API on virtual processor VP1. It is at a point very close to SwitchTo, (after the second interlocked operation), which implies a + // different context is about to affinitized VP1, to take its place before, before it is switched out. + + // If Unblock puts the 'this' context on a runnables list, it could be pulled off by a different context running on VP2 and get + // affinitized to VP2. Then SwitchTo in Block is called and the new context is affinitized to VP2 instead of VP1 and VP1 is orphaned. + + // The wait until blocked ensures that the affinitize step in the Block takes place before the context is put onto runnables, by which + // the correct affinity is set for the new context by the blocking context. + + SpinUntilBlocked(); + + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Unblock->runnables(ctx=%d,grp=%d)", GetId(), GetScheduleGroupId()); + AddToRunnables(m_pSegment->GetAffinity()); + } + else + { + if ((newValue < -1) || (newValue > 0)) + { + // Should not be able to get m_contextSwitchingFence above 0. + ASSERT(newValue < -1); + + // Too many unblocks without intervening blocks. Block/unblock calls need to balance. + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Unblock->unbalanced(ctx=%d,grp=%d)", GetId(), GetScheduleGroupId()); + + throw context_unblock_unbalanced(); + } + else + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Unblock->skipunblock(ctx=%d)", GetId()); + } + } + } + else + { + // A context is not allowed to unblock itself. + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Unblock->selfunblock(ctx=%d,grp=%d)", GetId(), GetScheduleGroupId()); + throw context_self_unblock(); + } + } + + /// + /// Yields the virtual processor to a different runnable internal context if one is found. + /// + void InternalContextBase::Yield() + { + bool bSwitchToThread = false; + + EnterCriticalRegion(); + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_pVirtualProcessor != NULL); + + TraceContextEvent(CONCRT_EVENT_YIELD, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + if (m_pVirtualProcessor->IsMarkedForRetirement()) + { + // The virtual processor has been marked for retirement. The context needs to switch out rather + // than switching to a different context or continuing to run. + SwitchOut(Yielding); + } + else + { + InternalContextBase *pContext = NULL; + + WorkItem work; + if (m_pVirtualProcessor->SearchForWorkInYield(&work, m_pSegment, false, WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChoreToken)) + { + if (!work.IsContext()) + { + // + // Make sure we can get a thread. Further, make sure all of this happens outside a critical region to avoid the huge cost of + // allocation within one. + // + ExitCriticalRegion(); + CONCRT_COREASSERT(GetCriticalRegionType() == OutsideCriticalRegion); + + pContext = m_pScheduler->GetInternalContext(); + EnterCriticalRegion(); + + if (pContext != NULL) + { + if (work.ResolveToken()) + { + work.BindTo(pContext); + } + else + { + if (m_pVirtualProcessor->SearchForWorkInYield(&work, m_pSegment, false, WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore)) + { + if (!work.IsContext()) + { + work.BindTo(pContext); + } + else + { + // + // Oops -- we have an extra thread due to a race (we couldn't claim the token and instead found a runnable that requires + // no thread). Do what's always done and pop it back on the free list. + // + m_pScheduler->ReleaseInternalContext(pContext, true); + pContext = work.GetContext(); + } + } + else + { + // + // Oops -- we have an extra thread due to a race (we couldn't claim the token and could not find anything to run). + // Do what's always done and pop it back on the free list. + // + m_pScheduler->ReleaseInternalContext(pContext, true); + pContext = NULL; + } + } + } + else + { + if (m_pVirtualProcessor->SearchForWorkInYield(&work, m_pSegment, false, WorkItem::WorkItemTypeContext)) + pContext = work.Bind(); + } + } + else + pContext = work.GetContext(); + } + + if (pContext != NULL) + { + CMTRACE(MTRACE_EVT_SFW_FOUND, this, m_pVirtualProcessor, pContext); + CMTRACE(MTRACE_EVT_SFW_FOUNDBY, pContext, m_pVirtualProcessor, this); + + ASSERT(pContext != this); + + SwitchTo(pContext, Yielding); + } + else + { + // + // No need to cooperatively yield - there's no other runnable context to execute. + // However, it is wise to check if the OS has any other threads available to run on the hardware thread. + // On UMS, SwitchToThread will cause a transition to primary. We want to minimize such context + // switches within critical region. Exit the critical region and then SwitchToThread. + // + bSwitchToThread = true; + } + } + ExitCriticalRegion(); + + if (bSwitchToThread) + { + m_pThreadProxy->YieldToSystem(); + } + } + + /// + /// Yields the virtual processor to a different runnable internal context if one is found. + /// + /// This is intended for spin loops. + /// + void InternalContextBase::SpinYield() + { + bool bSwitchToThread = false; + + EnterCriticalRegion(); + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_pVirtualProcessor != NULL); + + TraceContextEvent(CONCRT_EVENT_YIELD, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + if (m_pVirtualProcessor->IsMarkedForRetirement()) + { + // The virtual processor has been marked for retirement. The context needs to switch out rather + // than switching to a different context or continuing to run. + SwitchOut(Yielding); + } + else + { + WorkItem work; + if (m_pVirtualProcessor->SearchForWork(&work, m_pSegment, false, WorkItem::WorkItemTypeContext)) + { + CMTRACE(MTRACE_EVT_SFW_FOUND, this, m_pVirtualProcessor, work.GetContext()); + CMTRACE(MTRACE_EVT_SFW_FOUNDBY, work.GetContext(), m_pVirtualProcessor, this); + + ASSERT(work.GetContext() != NULL && work.GetContext() != this); + + SwitchTo(work.GetContext(), Yielding); + } + else + { + // + // No need to cooperatively yield - there's no other runnable context to execute. + // However, it is wise to check if the OS has any other threads available to run on the hardware thread. + // On UMS, SwitchToThread will cause a transition to primary. We want to minimize such context + // switches within critical region. Exit the critical region and then SwitchToThread. + // + bSwitchToThread = true; + } + } + ExitCriticalRegion(); + + if (bSwitchToThread) + { + m_pThreadProxy->YieldToSystem(); + } + } + + /// + /// See comments for Concurrency::Context::Oversubscribe. + /// + void InternalContextBase::Oversubscribe(bool beginOversubscription) + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + if (beginOversubscription) + { + // Increment the context over-subscription counter and only create an additional virtual processor + // if the count goes from 0 to 1. + + if (++m_oversubscribeCount == 1) + { + ASSERT(m_pOversubscribedVProc == NULL); + + // Oversubscribe the hardware thread virtual processor by injecting a virtual processor into the current virtual processors + // group in the scheduling node. + EnterCriticalRegion(); + // Oversubscribe invokes a callback to stamp the value of the oversubscribed virtual processor onto the context. The reason + // for this is that we have to ensure that the vproc <-> context mapping is in place before the virtual processor is added + // to the collection of vprocs in the scheduler. This is in order to synchronize with RemoveVirtualProcessor, which assumes + // the virtual processor is fully initialized if it can find it in the collection. + m_pVirtualProcessor->Oversubscribe(); + ExitCriticalRegion(); + } + } + else + { + // Decrement the context over-subscription counter and retire the oversubscribed virtual processor + // if the count goes from 1 to 0. + if (m_oversubscribeCount == 0) + { + throw invalid_oversubscribe_operation(); + } + + if (--m_oversubscribeCount == 0) + { + VirtualProcessor * pExpectedVProc = m_pOversubscribedVProc; + + // Note that pExpectedVProc could be null if the RM has already snapped this vproc for removal. + VirtualProcessor * pVProc = GetAndResetOversubscribedVProc(pExpectedVProc); + ASSERT(pVProc == NULL || pVProc == pExpectedVProc); + + // We must synchronize with a potential RemoveVirtualProcessor for this virtual processor due to the RM taking the underlying + // core away. The winner of the interlocked exchange gets to retire the virtual processor. + if (pVProc != NULL) + { + pVProc->MarkForRetirement(); + } + } + } + } + + /// + /// Called to retrieve the oversubscribed vproc and reset it to null. + /// + VirtualProcessor * InternalContextBase::GetAndResetOversubscribedVProc(VirtualProcessor * pExpectedVirtualProcessor) + { + // Can be called concurrently by oversubscribing context and the RM. When called by the RM, the argument is + // non-NULL and represents what the RM thinks this context has as its oversubscribed vproc. The RM could + // have stale information and so if the virtual processor argument doesn't match what is on the context, + // we return NULL, informing the RM that the virtual processor it was looking for was already marked for + // retirement by this context previously. + VirtualProcessor * pVirtualProcessor = NULL; + + if ((pExpectedVirtualProcessor != NULL) && (pExpectedVirtualProcessor == m_pOversubscribedVProc) && + (InterlockedCompareExchangePointer((volatile PVOID *)(&m_pOversubscribedVProc), (void*) 0, pExpectedVirtualProcessor) == pExpectedVirtualProcessor)) + { + pVirtualProcessor = pExpectedVirtualProcessor; + } + + return pVirtualProcessor; + } + + /// + /// Returns an identifier to the virtual processor the context is currently executing on, if any. + /// + unsigned int InternalContextBase::GetVirtualProcessorId() const + { + // + // We really aren't changing anything, so cast away constness to enter the critical region. The critical region is necessary + // to guard volatility on UMS reentrancy due to PF when accessing m_pVirtualProcessor. + // + (const_cast(this))->EnterCriticalRegion(); + unsigned int id = (m_pVirtualProcessor != NULL) ? m_pVirtualProcessor->GetId() : UINT_MAX; + (const_cast(this))->ExitCriticalRegion(); + + return id; + } + + /// + /// Adds the context to a runnables collection, either on the virtual processor, or the schedule group + /// + /// + /// A location specifying where to bias the awakening of virtual processors to. + /// + void InternalContextBase::AddToRunnables(location bias) + { + ASSERT(m_pSegment != NULL); + ASSERT(m_pThreadProxy != NULL); + + TRACE(TRACE_SCHEDULER, L"InternalContextBase::AddRunnable(ctx=%d,grp=%d,grpRef=%d)", GetId(), GetScheduleGroupId(), ScheduleGroupRefCount()); + + ContextBase* pCurrentContext = SchedulerBase::FastCurrentContext(); + + CMTRACE(MTRACE_EVT_ADDEDTORUNNABLES, this, NULL, pCurrentContext); + CMTRACE(MTRACE_EVT_INVERTED_ADDEDTORUNNABLES, (pCurrentContext && !pCurrentContext->IsExternal()) ? static_cast(pCurrentContext) : NULL, NULL, this); + + // + // If there is an "inactive pending thread" virtual processor, this runnable should be shoved to it instead of going through the normal + // wake path. There is *NO REASON* to require an SFW context to immediately switch to this. + // + if (m_pScheduler->HasVirtualProcessorPendingThreadCreate() && m_pScheduler->PushRunnableToInactive(this, bias)) + return; + + // + // First see if there is room to place 'this' on the cache of local realized chores + // for the ambient context. This attempts to maintain cache locality when Block/Unblock + // is called in quick succession and the unblocking current context subsequently blocks. + // + if (pCurrentContext != NULL && !pCurrentContext->IsExternal() && (m_pScheduler == pCurrentContext->GetScheduler())) + { + InternalContextBase* pContext = static_cast(pCurrentContext); + int count; + // + // The current virtual processor is only safely accessed within a critical region + // + pContext->EnterCriticalRegion(); + + // + // We will only push to the LRC of this virtual processor if this virtual processor is within the affinity set of the segment + // to which the context belongs. + // + if (!m_pSegment->GetGroup()->IsFairScheduleGroup() + && + m_pSegment->GetAffinitySet().IsSet(pContext->m_pVirtualProcessor->GetMaskId()) + && + ((count = pContext->m_pVirtualProcessor->m_localRunnableContexts.Count()) < m_pScheduler->m_localContextCacheSize)) + { + // + // If the current context does not belong to the same group, the caller is not guaranteed to have a reference to the + // schedule group. We call CrossGroupRunnable() to make sure that scheduler and schedule group are kept around long + // enough, that we can attempt to startup the virtual processor without fear of the scheduler being finalized, or the + // schedule group being destroyed. + // If the current context DOES belong to same group as 'this', it is possible for it to be recycled to the idle pool + // once we add it to runnables collection. Since the m_pSegment field is reset to NULL when the context is recycled, + // we cache it up front. + // + ScheduleGroupSegmentBase * pSegment = m_pSegment; + if (pContext->GetScheduleGroup() != pSegment->GetGroup()) + { + // Set this flag to allow the calling thread to use m_pSegment safely once the context is pushed onto runnables. + // Note that this call does not need a fence. The addition of the context to the vproc LRC queue, which is a work-stealing + // queue, is unfenced, but since both, setting the flag, and adding to the queue, result in volatile writes, other processors + // will see the stores in the same order. That means that when this context is visible to a stealer, the stealer will also + // see the cross group runnable bit set. + CrossGroupRunnable(TRUE); + } + +#if defined(_DEBUG) + SetDebugBits(CTX_DEBUGBIT_ADDEDTOLOCALRUNNABLECONTEXTS); + if (m_pScheduler->HasVirtualProcessorAvailable()) + SetDebugBits(CTX_DEBUGBIT_LIKELYTOSTARTUPIDLEVPROCONOTHERCONTEXT); +#endif // _DEBUG + pContext->m_pVirtualProcessor->m_localRunnableContexts.Push(this); + // IMPORTANT NOTE: 'this' could be recycled and reused by this point, unless the cross group runnables flag is set. (If the + // flag IS set, we are guaranteed that the context's group will not be set to NULL/destroyed, and that the context will not + // be recycled until we set the flag to false below). + // We can, however, access m_pScheduler for a recycled context, since it retains the same value until the context is destroyed, + // and contexts are only destroyed during scheduler shutdown. + CMTRACE(MTRACE_EVT_AVAILABLEVPROCS, this, pContext->m_pVirtualProcessor, m_pScheduler->m_virtualProcessorAvailableCount); + + if (m_pScheduler->HasVirtualProcessorAvailable()) + { +#if defined(_DEBUG) + pContext->SetDebugBits(CTX_DEBUGBIT_STARTUPIDLEVPROCONADD); +#endif // _DEBUG + m_pScheduler->StartupIdleVirtualProcessor(pSegment, bias); + } + + if (pContext->GetScheduleGroup() != pSegment->GetGroup()) + { + // Reset the flag, if it was set, since we're done with touching scheduler/context data. + // This flag is not fenced. This means the reader could end up spinning a little longer until the data is + // propagated by the cache coherency mechanism. + CrossGroupRunnable(FALSE); + // NOTE: It is not safe to touch 'this' after this point, if this was a cross group runnable. + } + + pContext->ExitCriticalRegion(); + return; + } + pContext->ExitCriticalRegion(); + } + +#if defined(_DEBUG) + SetDebugBits(CTX_DEBUGBIT_ADDEDTORUNNABLES); +#endif // _DEBUG + + m_pSegment->AddRunnableContext(this, bias); + } + + /// + /// Spins until the 'this' context is in a firmly blocked state. + /// + /// + /// This implements a sort of barrier. At certain points during execution, it is essential to wait until a context + /// has set the flag indicating it is blocked, in order to preserve correct behavior. + /// One example is if there is a race between block and unblock for the same context, i.e. if a context is trying to + /// block at the same time a different context is trying to unblock it. + /// + void InternalContextBase::SpinUntilBlocked() + { + ASSERT(SchedulerBase::FastCurrentContext() != this); + + if (!IsBlocked()) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + + } while (!IsBlocked()); + } + ASSERT(IsBlocked()); + } + + /// + /// Swaps the existing schedule group with the one supplied. This function should be called when the context already + /// has a schedule group. It decrements the existing group reference count, and references the new one if the caller + /// indicates so. + /// + /// + /// The new segment to assign to the context. This may be NULL. + /// + /// + /// Whether the context should reference the new group. In some cases, there may be an existing reference + /// transferred to the context, in which case this parameter is false. + /// + void InternalContextBase::SwapScheduleGroupSegment(ScheduleGroupSegmentBase* pNewSegment, bool referenceNewGroup) + { + if (m_pSegment == NULL) + { + ASSERT(pNewSegment == NULL); + return; + } + + // We expect that a context modifies its non-null schedule group only when it is running. + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT((pNewSegment != NULL) || (!referenceNewGroup)); + + // Before releasing the reference count on the schedule group, which could end up destroying the schedule group if the ref + // count falls to zero, check if the m_fCrossGroupRunnable flag is set. If it is, it means a different thread that previously added + // this context to a runnables collection, is relying on the group being alive. Also, since the current call is executing within + // some context's dispatch loop, and every running dispatch loop has a reference on the scheduler, we are guaranteed that scheduler + // finalization will not proceed while this flag is set on any context inside a scheduler. + SpinUntilValueEquals(&m_fCrossGroupRunnable, FALSE); + + // Segments are bound to the lifetime of their group. + m_pSegment->GetGroup()->InternalRelease(); + if (referenceNewGroup) + { + pNewSegment->GetGroup()->InternalReference(); + } + m_pSegment = pNewSegment; + } + + /// + /// Switches from one internal context to another. + /// + /// + /// The context to switch to. If this is NULL, we switch to the default destination if one exists. If no default destination exists, + /// the virtual processor is turned inactive as determined by reason. On the UMS scheduler, the default destination is the primary. + /// On the thread scheduler, there is no default destination. + /// + /// + /// Specifies the reason the switch is occurring. + /// + void InternalContextBase::SwitchTo(InternalContextBase* pNextContext, ReasonForSwitch reason) + { + CMTRACE(MTRACE_EVT_SWITCHTO, this, m_pVirtualProcessor, pNextContext); + + SwitchingProxyState switchState = ::Concurrency::Blocking; + + // ************************************************** + // + // There is a dangerous zone between the call to Affinitize and the end of pThreadProxy->SwitchTo. If we trigger a UMS block for + // any reason, we can corrupt the virtual processor state as we reschedule someone else, come back, and don't properly have pNextContext + // affinitized. + // + // If we call any BLOCKING APIs (including utilization of our own locks), there are potential issues as something else might + // be rescheduled on this virtual processor from the scheduling context. + // + // ************************************************** + + // + // Various state manipulations which may take locks or make arbitrary blocking calls happen here. This must be done outside the inclusive + // region of [Affinitize, pThreadProxy->SwitchTo]. Otherwise, our state can become corrupted if a page fault or blocking operation triggers + // UMS activation in that region. + // + switch (reason) + { + case GoingIdle: + CONCRT_COREASSERT(m_pAssociatedChore == NULL); + VCMTRACE(MTRACE_EVT_SWITCHTO_IDLE, this, m_pVirtualProcessor, pNextContext); + + // + // The scheduler has an idle pool of contexts, however, before putting a context on this pool, we must + // disassociate it from its thread proxy - so that if it is picked up off the free list by a different + // caller, that caller will associate a new thread proxy with it. The reason for this disassociation is, + // that we want to pool thread proxies in the RM, and not the scheduler. + // + // The state of the context cannot be cleared until context reaches the blocked state. It's possible we + // block/page fault somewhere lower and require the information until m_blockedState is set to blocked. + // + TraceContextEvent(CONCRT_EVENT_IDLE, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id); + + // It makes no sense to SwitchTo with GoingIdle as a parameter if there is no context to switch to. This is true + // for thread and UMS schedulers. + CONCRT_COREASSERT(pNextContext != NULL); + TRACE(TRACE_SCHEDULER, L"InternalContextBase::SwitchTo(dispatch:pNextContext->(ctx=%d,grp=%d))", pNextContext->Id(), pNextContext->ScheduleGroupId()); + + m_pSegment->ReleaseInternalContext(this); + + // ************************************************** + // Read this extraordinarily carefully: + // + // This context is on the free list. Meaning someone can grab and switch to it. Unfortunately, this means + // we might page fault or block here. That operation would instantly set m_blockedState, which would release + // the guy spinning and suddenly we have two virtual processors in-fighting over the same context. + // + // Because we are inside a critical region, no page faults are observable to the scheduler code. This does + // mean that you cannot call *ANY BLOCKING* API between this marker and the EnterHyperCriticalRegion below. + // API between this marker and the EnterHyperCriticalRegion below. If you do, you will see random behavior + // or the primary will assert at you. + // ************************************************** + + switchState = ::Concurrency::Idle; + break; + + case Yielding: + // + // Add this to the runnables collection in the schedule group. + // + VCMTRACE(MTRACE_EVT_SWITCHTO_YIELDING, this, m_pVirtualProcessor, pNextContext); + + if (pNextContext != NULL) + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::SwitchTo(yield:pNextContext->(ctx=%d,grp=%d))", pNextContext->Id(), pNextContext->ScheduleGroupId()); + } + + CONCRT_COREASSERT(switchState == ::Concurrency::Blocking); + m_pSegment->AddRunnableContext(this, m_pSegment->GetAffinity()); + break; + + case Blocking: + VCMTRACE(MTRACE_EVT_SWITCHTO_BLOCKING, this, m_pVirtualProcessor, pNextContext); + + if (pNextContext != NULL) + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::SwitchTo(block:pNextContext->(ctx=%d,grp=%d))", pNextContext->Id(), pNextContext->ScheduleGroupId()); + } + + CONCRT_COREASSERT(switchState == ::Concurrency::Blocking); + break; + + case Nesting: + VCMTRACE(MTRACE_EVT_SWITCHTO_NESTING, this, m_pVirtualProcessor, pNextContext); + + if (pNextContext != NULL) + { + TRACE(TRACE_SCHEDULER, L"InternalContextBase::SwitchTo(nest:pNextContext->(ctx=%d,grp=%d))", pNextContext->Id(), pNextContext->ScheduleGroupId()); + } + + switchState = ::Concurrency::Nesting; + break; + } + + EnterHyperCriticalRegion(); + + // + // No one can reuse the context until we set the blocked flag. It can come off the idle list, but the thread pulling it off the idle list will + // immediately spin until blocked inside the acquisition. It is entirely possible, however, that the moment we flip the blocked flag, the spinner + // gets released and the proxy fields, etc... are overwritten. We still own the thread proxy from the RM's perspective and the RM will sort out + // races in its own way. We must, however, cache the thread proxy before we set the blocked flag and not rely on *ANY* fields maintained by the *this* + // pointer after the flag set. + // + VirtualProcessor *pVirtualProcessor = m_pVirtualProcessor; + SchedulerBase *pScheduler = m_pScheduler; + m_pVirtualProcessor = NULL; + + CONCRT_COREASSERT(!IsBlocked()); + +#if defined(_DEBUG) + ClearDebugBits(CTX_DEBUGBIT_AFFINITIZED); + + if (reason != GoingIdle) + SetDebugBits(CTX_DEBUGBIT_COOPERATIVEBLOCKED); +#endif // _DEBUG + + CONCRT_COREASSERT(m_pThreadProxy != NULL); + IThreadProxy *pThreadProxy = m_pThreadProxy; + + IExecutionContext *pDestination = (IExecutionContext *)pNextContext; + if (pDestination == NULL) + { + // + // A SwitchTo(, NULL) may have different semantic meaning depending on the scheduler. It may go to a default destination (e.g.: the UMS + // primary) or simply cause nothing to be run (e.g.: the thread scheduler). + // + pDestination = pVirtualProcessor->GetDefaultDestination(); + CONCRT_COREASSERT(pDestination != NULL || m_pScheduler->GetPolicy().GetPolicyValue(SchedulerKind) == ::Concurrency::ThreadScheduler); + } + + ASSERT(pDestination != NULL || reason != GoingIdle); + // + // The blocked flag needs to be set on the context to prevent the block-unblock race as described in + // VirtualProcessor::Affinitize. In addition, it is used during finalization to determine whether + // work exists in the scheduler. + // + InterlockedExchange(&m_blockedState, CONTEXT_BLOCKED); + + // ************************************************** + // At this point, it unsafe to touch the *this* pointer. You cannot touch it, debug with it, rely on it. It may be reused if + // reason == GoingIdle and represent another thread. + // ************************************************** + + // The 'next' context must be affinitized to a copy of the 'this' context's vproc that was snapped, BEFORE + // the blocked flag was set. Not doing this could result in vproc orphanage. See VirtualProcessor::Affinitize + // for details. We cache the vproc pointer in a local variable before setting m_blockedState. Thus re-affinitizing + // the 'this' context would not affect the vproc that the 'next' context is going to get affinitized to. + // With UMS, if the pNextContext is NULL, the vproc affinitizes the scheduling Context. + pVirtualProcessor->Affinitize(pNextContext); + + CONCRT_COREASSERT(pNextContext == NULL || pNextContext->m_pThreadProxy != NULL); + +#if defined(_DEBUG) + if (pNextContext != NULL && pNextContext->m_pAssociatedChore != NULL) + pNextContext->SetDebugBits(CTX_DEBUGBIT_SWITCHTOWITHASSOCIATEDCHORE); +#endif // _DEBUG + + // + // If there is no default place to switch to (e.g.: the UMS primary), we simply switch out and do not run anything atop the virtual processor. + // The caller has responsibility to do something intelligent with the virtual processor to mark it as available for whatever purpose they see. + // + if (pDestination == NULL) + { + // + // *** READ THIS: *** + // + // It is monumentally important that the below calls to make a virtual processor available in some form never finalize the scheduler. + // Though they may in certain cases lead to a sweep, they can never finalize. Our context is marked as blocked and is *NOT* on the free list. + // The sweep will find *this* and roll back. Granted, it is possible that another vproc grabs *this* and starts trying to execute it because + // its blocked flag is already set to true, but we have not yet executed the context switch from the RM's perspective and we rely on the RM to + // resolve that particular race. + // + switch(reason) + { + case Blocking: + case Nesting: + pVirtualProcessor->MakeAvailablePendingThread(); + pScheduler->DeferredGetInternalContext(); + break; + + default: + ASSERT(false); + break; + } + + pThreadProxy->SwitchOut(switchState); + } + else + { + // If this assert fires, you're executing on the UMS Scheduler. A bugfix was made to this function to allow InternalContextBase::SwitchTo(NULL, Nesting) + // to work for the thread scheduler. This fix should be evaluated for UMS it it becomes necessary. + CONCRT_COREASSERT(pDestination == pNextContext || reason != Nesting); + + pThreadProxy->SwitchTo(pDestination, switchState); + } + + // + // The m_blockedState is cleared in Affinitize() when someone tries to re-execute this context. + // + if (reason != GoingIdle) + ExitHyperCriticalRegion(); + } + + /// + /// Switches out the internal context. Useful, when the virtual processor is to be retired. + /// Is also used when un-nesting a scheduler and the context is returning to its original scheduler. + /// + /// ReleaseInternalContext(this); + } + + // + // If the reason is "blocking", the context could now appear on the runnables list. As a result we shall not make + // any synchronous UMS blocking calls such as attempting to acquire heap lock etc from this point on. If we do and + // are blocked on a lock that is held by a UT, the remaining vproc might not be able to run the UT as it could be + // spinning on this context. + // + + // + // In the event that this virtual processor hadn't yet observed safe points, we need to make sure that its removal commits + // all data observations that are okay with other virtual processors. Since safe point invocations could take arbitrary + // locks and block, we trigger safe points on all the virtual processors (we have removed ourselves from that list). + // + m_pScheduler->TriggerCommitSafePoints(&safePointMarker); + + // Reducing the active vproc count could potentially lead to finalization if we're in a shutdown semantic. + // If that happens to be the case (it can only happen if the context switch reason is GoingIdle), we will exit the + // dispatch loop and return the thread proxy to the RM - the virtual processor has been retired which means the + // underlying virtual processor root has been destroyed. We have already removed the virtual processor from the + // lists in the scheduler, so the underlying thread proxy will not get 'woken up' via a subsequent call to Activate + // on the underlying vproc root. + m_pScheduler->VirtualProcessorActive(false); + CONCRT_COREASSERT(!m_fCanceled || (m_pScheduler->HasCompletedShutdown() && (reason == GoingIdle))); + + // Make a local copy of m_fCanceled before we set m_blockedState. On scheduler shutdown, + // m_fCanceled is set to true. In this case, we need to do cleanup. The field need + // to be cached since another vproc could pick this context up and set the m_fCanceled flag + // before we do the check again to invoke cleanup. + isCanceled = m_fCanceled; + + if (reason == GoingIdle) + { + // After VirtualProcessorActive(false) and all accesses to 'this' it is safe to set m_blockedState while going idle. + CONCRT_COREASSERT(!IsBlocked()); + InterlockedExchange(&m_blockedState, CONTEXT_BLOCKED); + } + } + else + { + // This is a nested context returning to its parent scheduler. + CONCRT_COREASSERT(reason == Nesting); + CONCRT_COREASSERT(IsBlocked()); + } + + if (reason == Yielding || reason == Nesting) + { + // Add this to the runnables collection in the schedule group. + TRACE(TRACE_SCHEDULER, L"ThreadInternalContext::SwitchOut(yield/nest)"); + m_pSegment->AddRunnableContext(this, m_pSegment->GetAffinity()); + } + + // If we're going idle there is no need to execute a 'switch'. The underlying virtual processor root needs to be reset, + // since no one is going to run on it, and this will be done when the context returns from the dispatch loop in the + // thread proxy dispatch routine. + if (reason != GoingIdle) + { + // For both yielding and nesting, the intended outcome is to have the thread proxy block in the RM. Therefore we + // set the switch state to Blocking. + pThreadProxy->SwitchOut(::Concurrency::Blocking); + } + // + // m_blockedState will be reset when we affinitize the context to re-execute it. + // + if (isCanceled) + { + // We could be canceled only if we are going idle. + CONCRT_COREASSERT(reason == GoingIdle); + } + + return isCanceled; + } + + /// + /// Called when a context is nesting a scheduler. If nesting takes place on what is an internal context in + /// the 'parent' scheduler, the context must return the virtual processor to the parent scheduler + /// + void InternalContextBase::LeaveScheduler() + { + EnterCriticalRegion(); + + // Find a context to take over the underlying virtual processor and switch to it. When a context switches to a + // different context with the reason 'Nesting', the SwitchTo API will affinitize the context we found to + // the virtual processor 'this' context is running on, and return - allowing the underlying thread proxy to + // join a nested scheduler as an external context. + bool fSFWContext = false; + bool fBoundUnrealized = false; + InternalContextBase *pContext = FindWorkForBlockingOrNesting(fSFWContext, fBoundUnrealized); + ASSERT(this != pContext); + + if (fSFWContext) + { + ASSERT(pContext != NULL); + pContext->PrepareForUse(m_pSegment, NULL, false); + } + // If pContext is NULL due to thread throttling, the virtual processor will be made available and the throttler + // will be notified that this vproc is pending a thread. + SwitchTo(pContext, Nesting); + + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_pVirtualProcessor == NULL); + ASSERT(m_pSegment != NULL); + ASSERT(IsBlocked()); + + ExitCriticalRegion(); + } + + /// + /// Called when a internal context detaches from a nested scheduler. The context must find a virtual processor + /// on a previous context before it may run. + /// + void InternalContextBase::RejoinScheduler() + { + EnterCriticalRegion(); + + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_pVirtualProcessor == NULL); + ASSERT(m_pSegment != NULL); + ASSERT(IsBlocked()); + + // Switch out - this will take care of putting this context on a runnables queue and waking up a virtual processor + // if one is available. + SwitchOut(Nesting); + ExitCriticalRegion(); + } + + /// + /// Wait for work algorithm: + /// + /// We search numSearches times through the loop looking for work and then we allow other threads to claim this virtual processor + /// while we deactivate the virtual processor root, asking to be woken up when all processor write buffers are flushed + /// (signified by the m_fIsVisibleVirtualProcessor flag). After that we do *one* more full search for work. + /// + /// Scenario #1: If the final sweep (after the flush) does not yield any work, we set the virtual processor to Idle + /// deactivate the virtual processor root. We will be woken up when work comes in, when we are canceled + /// due to the scheduler shutting down, or when the virtual processor we're running on was marked for retirement. + /// If we are not canceled, we simply reset and start over. If we are, we cleanup and exit the dispatch loop. + /// + /// Scenario #2: If the final sweep does find work and this virtual processor is still available, we claim it and + /// do work. + /// + /// Scenario #3: If the final sweep does find work and this virtual processor is not available, then either someone has activated + /// the underlying root while adding more work (via StartupIdleVirtualProcessor), which takes it from available list + /// (pVProc->IsAvailable()), or the virtual processor we're running on was retired due to core migration (via RemoveVirtualProcessors). + /// In this we execute a Deactivate to consume the activation. Note that even if we were marked for retirement, we will execute + /// the chore we just picked up, which will delay retirement a bit. + /// + void InternalContextBase::WaitForWork() + { + const unsigned int numSearches = 256; + + // + // Once we've completed one pass of SFW, notify the scheduler that we're actively searching so anything that pops up affine to us isn't ripped + // out from underneath us. + // + if (++m_searchCount == 1) + { + m_pScheduler->NotifySearching(m_pVirtualProcessor->GetMaskId(), true); + } + + CMTRACE(MTRACE_EVT_SFW_NEXTLOOP, this, m_pVirtualProcessor, m_searchCount); + + if (m_searchCount < numSearches) + { + // Yield thread helps perf for oversubscribed vprocs + m_pThreadProxy->YieldToSystem(); + + CONCRT_COREASSERT(!m_fIsVisibleVirtualProcessor); + // Do another search for the work within the loop. + } + else if (m_searchCount == numSearches) + { + // At this point virtual processor has to be un-available for everyone but this + // internal context. + CONCRT_COREASSERT(!m_pVirtualProcessor->IsAvailable()); + + // At this point, we've made the virtual processor 'visible' to the rest of the scheduler. This means that anyone + // adding work to the scheduler is able to grab this virtual processor and assume that it will find the work that + // was added. + m_fIsVisibleVirtualProcessor = true; + + // Make this virtual processor available and force all tasks to be visible. The idea is that any work queued *before* + // the point at which we made the virtual processor available is visible after the API call, and we should be able to + // make one single pass through the scheduler to find any such work. Work queued *after* the point at which we made + // the virtual processor available should be able to wake up the virtual processor. + m_pVirtualProcessor->MakeAvailableForIdle(); + + m_pVirtualProcessor->EnsureAllTasksVisible(this); + // If we find work during our final search, we will reclaim the virtual processor and reset the search count. + + // Context could not have been canceled since this vproc is not 'idle'. + CONCRT_COREASSERT(m_fCanceled == 0); + } + else + { + CONCRT_COREASSERT(m_searchCount == numSearches + 1); + CONCRT_COREASSERT(m_fIsVisibleVirtualProcessor); + + if (m_fWorkSkipped) + { + m_searchCount--; + + // + // Account for the cases where we fail to check some of the work-stealing queues due to task collection cancellation in progress. + // If we skip work and deactivate the vproc, the work left in the queue could never be picked up. An example would be a + // chore that blocks on a win32 event that is to be signaled by a queued chore which essentially requires stealing. If the + // only other vproc goes idle incorrectly (because it wasn't able to steal from this queue), then the application would hang. + // + + // + // Go back and search again. Hopefully the owning context of the wsq that was skipped has finished canceling. + // + m_pThreadProxy->YieldToSystem(); + } + else + { + // Notify the scheduler that this virtual processor is idle, right before going into a sleep state. + m_pScheduler->VirtualProcessorIdle(true); + + // Note that the previous call to VirtualProcessorIdle could well be the one that takes the scheduler into PhaseTwoShutdown, + // if this happens to be the last active vproc in the scheduler to go idle, AND no external references to the scheduler exist, + // AND no work remains. In this case we expect that this context is canceled. + CONCRT_COREASSERT( !m_fCanceled || m_pScheduler->InFinalizationSweep() || m_pScheduler->HasCompletedShutdown()); + + // Deactivate the virtual processor for real this time. We will return out of deactivate for one of the following reasons: + // 1] Someone adds work and wakes us up. + // 2] The scheduler has shutdown and this context was canceled (and woken up) + // 3] The RM is in the process of removing virtual processors dut do core migration, and marks the underlying vproc for retirement. + // Even if we were canceled during the call to virtual processor idle, we must call deactivate to consume the + // signal sent to the thread proxy (via Activate, when the virtual processor was canceled). +#if defined(_DEBUG) + bool fRMAwaken = false; +#endif // _DEBUG + + CONCRT_COREASSERT(!IsBlocked()); + while ( !m_pVirtualProcessor->Deactivate(this)) + { + // + // The resource manager has woken us up because of a completion notification from the completion list. It's entirely possible + // that another thread was running, pulled it, and went idle. Since we are in idle the VirtualProcessorIdle call above, that other virtual + // processor could have triggered finalization and we could be *IN* phase two shutdown right now. Racing with phase two shutdown + // and VirtualProcessorIdle() / ClaimExclusiveOwnership() is *NOT* healthy for correct finalization. Instead, we simply pretend that this + // virtual processor is still idle and simply *borrow* the *thread* to move completion list items. The movement will translate into + // AddToRunnables calls which will activate virtual processors if there was something blocked. If that was the case, we couldn't be in phase + // two finalization. + // +#if defined(_DEBUG) + fRMAwaken = true; +#endif // _DEBUG + RMAwaken(); + // + // At this point, if things have moved from the completion list to runnables, the virtual processor might have been activated. The RM will handle + // the activate/deactivate race and the looping around will swallow the activate and let us continue running in *PROPER FORM*. + // + } + + CMTRACE(MTRACE_EVT_WOKEAFTERDEACTIVATE, this, m_pVirtualProcessor, NULL); +#if defined(_DEBUG) + if (fRMAwaken) + { + SetDebugBits(CTX_DEBUGBIT_ACTIVATEDAFTERRMAWAKEN); + } +#endif // _DEBUG + + CONCRT_COREASSERT( !m_fCanceled || m_pScheduler->InFinalizationSweep() || m_pScheduler->HasCompletedShutdown()); + + // We were woken up for one of the 3 reasons above. It is important to tell the scheduler we are not idle before + // proceeding. If we were woken up due to the addition of work we need to ensure that the work is visible to the scheduler + // until after we've reported that we are !IDLE. The scheduler makes one pass looking for work and blocked contexts + // once all virtual processors have reported that they are idle, and if it doesn't find any it will finalize the scheduler. + // Therefore, we must register as ACTIVE, via VirtualProcessorIdle(false), *before* removing any work from the scheduler queues. + // In addition, the call allows us to synchronize with finalization. If we were woken up for any reason, and finalization is in + // progress at the same time, we need to ensure the context does not continue to execute its dispatch loop while the scheduler + // is finalizing. + m_pScheduler->VirtualProcessorIdle(false); + + // It is possible that the previous call to VirtualProcessorIdle(false) was suspended on the shutdown gate if + // the scheduler is in the middle of shutdown, in which case the context could be canceled. + // It is ok for the context to canceled right after its virtual processor was marked for retirement. We simply exit + // the dispatch loop, and the virtual processor root in question is destroyed when the scheduler invokes + // ISchedulerProxy::Shutdown, instead of IVirtualProcessorRoot::Remove, which is the normal path for + // retired virtual processors. + CONCRT_COREASSERT(!m_fCanceled || m_pScheduler->InFinalizationSweep() || m_pScheduler->HasCompletedShutdown()); + + CONCRT_COREASSERT(!m_pVirtualProcessor->IsAvailable()); + CONCRT_COREASSERT(m_pVirtualProcessor->GetExecutingContext() == this); + + m_fIsVisibleVirtualProcessor = false; + + if (m_searchCount > 0) + m_pScheduler->NotifySearching(m_pVirtualProcessor->GetMaskId(), false); + + m_searchCount = 0; + } + } + } + + /// + /// This function is called to execute the associated chore if one is available. The chore can be a stolen unrealized + /// chore or realized chore. + /// + /// + /// Returns true if an associated chore was executed, false otherwise. + /// + bool InternalContextBase::ExecutedAssociatedChore() + { + if (m_pAssociatedChore != NULL) + { + +#if defined(_DEBUG) + m_workStartTimeStamp = _ReadTimeStampCounter(); + m_prepareCount = 0; +#endif // _DEBUG + + ExitCriticalRegion(); + if (m_fAssociatedChoreStolen) + { + static_cast<_UnrealizedChore*> (m_pAssociatedChore)->_Invoke(); + m_pAssociatedChore = NULL; + } + else + { + RealizedChore * pRealizedChore = static_cast (m_pAssociatedChore); + pRealizedChore->Invoke(); + // Set the associated chore to NULL before releasing it (which may cause it to be deleted). The associated chore is used by the parallel + // debugger to tell which task a ConcRT thread is executing, and if the chore is freed to the heap, the user may see invalid data. + m_pAssociatedChore = NULL; + m_pScheduler->ReleaseRealizedChore(pRealizedChore); + } + EnterCriticalRegion(); + ReleaseWorkQueue(); + + return true; + } + return false; + } + + /// + /// Performs the necessary cleanup for a canceled context in its dispatch routine. + /// + void InternalContextBase::CleanupDispatchedContextOnCancel() + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(m_fCanceled); + +#if defined(_DEBUG) + // + // At this point, we're shutting down this vproc/thread and we do not want to perform lock/heap validations that are no longer + // true. + // + SetShutdownValidations(); +#endif // _DEBUG + + // This indicates that the vproc is going away. From now until the end of time, this vproc is in a hyper-critical region. + // We are no longer responsible for scheduling anything, so this is "perfectly" safe -- we cannot deadlock + // between ourselves and some arbitrary piece of code we are responsible for scheduling. + EnterHyperCriticalRegion(); + + // The cleanup call *must* occur before the context releases its reference count on the scheduler. + // Part of cleanup involves releasing a reference on the context's schedule group, and in some cases + // we may need to spin until is safe to do so, keeping both the group and the scheduler alive. + Cleanup(); + + // NOTE: This call to DecrementInternalContextCount may well be the call that deletes the scheduler. The *this* pointer + // should not be touched after this point! + m_pScheduler->DecrementInternalContextCount(); + } + + /// + /// Called in the dispatch loop to check if the virtual processor the context is running on is marked for retirement, + /// and retires the virtual processor if it is. + /// + /// + /// True if the virtual processor was retired, false otherwise. + /// + bool InternalContextBase::IsVirtualProcessorRetired() + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + // + // It is not safe to retire a virtual processor that has been made visible. Once it has been made visible, it + // may have been activated to do some work. We cannot retire in this case, or else we risk missing the work it + // was activated to execute. + // + if (!m_fIsVisibleVirtualProcessor && m_pVirtualProcessor->IsMarkedForRetirement()) + { + // + // If we notified the scheduler that we were in SFW, make sure to notify it that we are no longer doing this. + // + if (m_searchCount > 0) + m_pScheduler->NotifySearching(m_pVirtualProcessor->GetMaskId(), false); + + m_searchCount = 0; + + bool isCanceled = SwitchOut(GoingIdle); + + // This is one of the two places we can find the context canceled due to scheduler shutdown. (the other please is + // on returning from WaitForWork). Perform the necessary required for a canceled context that is in its dispatch loop. + if (isCanceled) + { + CleanupDispatchedContextOnCancel(); + } + return true; + } + return false; + } + + /// + /// Searches for work using the search algorithm specified by the scheduler's policy. Also prepares the context to execute + /// work by reclaiming the virtual processor if necessary. + /// + /// + /// A pointer to a work item which is filled in if work was found. + /// + /// + /// True if work was found, false otherwise. + /// + bool InternalContextBase::WorkWasFound(WorkItem * pWork) + { + // + // If the virtual processor is visible, this is a last pass SFW before we go to sleep. Inform the search algorithm of this so it does not skip + // certain kinds of work (e.g.: affine to other). Doing so in certain cases may lead to deadlock if we race just right and go to sleep violating + // the client's expectation of maintained concurrency level. + // + if (m_pVirtualProcessor->SearchForWork(pWork, m_pSegment, m_fIsVisibleVirtualProcessor)) + { + ReclaimVirtualProcessor(); + + // + // We found work - reset the search counter and make sure to notify the scheduler that we are no longer searching for work if if had + // been previously notified that we were. + // + if (m_searchCount != 0) + m_pScheduler->NotifySearching(m_pVirtualProcessor->GetMaskId(), false); + + m_searchCount = 0; + return true; + } + return false; + } + + /// + /// Switches to the runnable context represented by the work item. + /// + /// + /// A pointer to a work item to be executed. + /// + void InternalContextBase::SwitchToRunnableContext(WorkItem * pWork) + { + ASSERT(pWork->IsContext()); + + InternalContextBase *pContext = pWork->GetContext(); +#if defined(_DEBUG) + // + // We need to perform extra validation here in the UMS case. If we've just picked up a context which is UMS blocked, + // we cannot block on any arbitrary lock -- doing so can leave us in a deadlock situation. This facilitates an assertion + // to catch this instead of relying on random stress hits. + // + if (pContext->GetDebugBits() & CTX_DEBUGBIT_UMSBLOCKED) + { + pContext->SetDebugBits(CTX_DEBUGBIT_HOLDINGUMSBLOCKEDCONTEXT); + } +#endif // _DEBUG + CMTRACE(MTRACE_EVT_SFW_FOUND, this, m_pVirtualProcessor, pContext); + CMTRACE(MTRACE_EVT_SFW_FOUNDBY, pContext, m_pVirtualProcessor, this); + + SwitchTo(pContext, GoingIdle); + // + // Ensure we do not touch anything referring to the *this* pointer. Return early out of the dispatch loop and let + // the RM do its thing. At this point, there may be another thread inside this loop! + // + } + + /// + /// Executes the chore (realized or unrealized) specified by the work item. + /// + /// + /// A pointer to a work item that represents a realized or unrealized chore. + /// + void InternalContextBase::ExecuteChoreInline(WorkItem * pWork) + { + ASSERT(!pWork->IsContext()); + +#if defined(_DEBUG) + m_workStartTimeStamp = _ReadTimeStampCounter(); + m_prepareCount = 0; +#endif // _DEBUG + + // + // Adjust the current group and perform any reference transfers necessary to inline the chore on this context. + // + pWork->TransferReferences(this); + // + // No client invocation can happen inside a critical region. + // + IncrementDequeuedTaskCounter(); + ExitCriticalRegion(); + CONCRT_COREASSERT(GetCriticalRegionType() == OutsideCriticalRegion); + pWork->Invoke(); + EnterCriticalRegion(); + ReleaseWorkQueue(); + } + + /// + /// The method that is called when a thread proxy starts executing a particular context. The thread proxy which executes + /// the context is passed into this method and must be saved and returned on a call to the get_Proxy method. + /// + /// + /// The state under which this IExecutionContext is being dispatched. + /// + void InternalContextBase::Dispatch(DispatchState * pDispatchState) + { + (pDispatchState); + bool fWinRTInitialized = false; + + m_threadId = GetCurrentThreadId(); + +#if defined(_DEBUG) + m_lastDispatchedTid = m_threadId; +#endif // _DEBUG + + // + // This dispatch context is live, set TLS on the current thread proxy. This must happen before any critical region is entered + // on this context. + // + SetAsCurrentTls(); + + if (m_pScheduler->GetPolicy().GetPolicyValue(WinRTInitialization) == ::Concurrency::InitializeWinRTAsMTA && + ::Concurrency::GetOSVersion() == ::Concurrency::IResourceManager::Win8OrLater) + { + fWinRTInitialized = true; + WinRT::RoInitialize(RO_INIT_MULTITHREADED); + } + + EnterCriticalRegion(); + + CONCRT_COREASSERT(m_pThreadProxy != NULL); + CONCRT_COREASSERT(!IsBlocked()); + CONCRT_COREASSERT(!m_fIsVisibleVirtualProcessor); + CONCRT_COREASSERT(!m_fCanceled); + + TRACE(TRACE_SCHEDULER, L"InternalContextBase::Dispatch: Start dispatch loop"); + + m_searchCount = 0; + bool fDoneSearchingForWork = false; + + // + // First try to execute an associated chore if there is one available. + // + if (ExecutedAssociatedChore()) + { + // Check for virtual processor retirement since we've just finished executing a root chore. + fDoneSearchingForWork = IsVirtualProcessorRetired(); + } + + while (!fDoneSearchingForWork) + { + WorkItem work; + // + // Indicate that no work is skipped at the start of the search loop. + // + m_fWorkSkipped = false; + // + // If the virtual processor is null, this could be an external context from a nested scheduler that neglected to + // invoke Detach. + // + if (m_pVirtualProcessor == NULL) + { + CONCRT_COREASSERT((SchedulerBase::FastCurrentContext() != this) && SchedulerBase::FastCurrentContext()->IsExternal()); + CONCRT_COREASSERT(IsInsideCriticalRegion()); + + ExitCriticalRegion(); + throw nested_scheduler_missing_detach(); + } + + // + // This virtual processor has reached a safe point. We are guaranteed to have made observations of data structures + // in the scheduler and have no information cached anywhere. Inform the virtual processor and if there is a new + // data revision that needs committed, do so. Any commits should happen outside a critical region so that the + // possible heap frees there do not trigger badly performing UMS behavior. + // + // If this virtual processor is visible, we're in-between marking ourselves available and going to sleep. Exiting + // the critical region to perform a commit is illegal in this region. + // + if (!m_fIsVisibleVirtualProcessor && m_pVirtualProcessor->SafePoint()) + { + ExitCriticalRegion(); + m_pScheduler->CommitSafePoints(); + EnterCriticalRegion(); + } + + // Search for work among the queues in the scheduler. + if (WorkWasFound(&work)) + { + if (work.IsContext()) + { + SwitchToRunnableContext(&work); + // This is now an idle context and should return from the dispatch loop immediately. + fDoneSearchingForWork = true; + } + else + { + ExecuteChoreInline(&work); + + // Check for virtual processor retirement since we've just finished executing a root chore. + fDoneSearchingForWork = IsVirtualProcessorRetired(); + } + } + else if (IsVirtualProcessorRetired()) + { + // Check for virtual processor retirement since we've made a full search through the scheduler without + // finding any work. + fDoneSearchingForWork = true; + } + else + { + WaitForWork(); + + // This is one of the two places we can find the context canceled due to scheduler shutdown. (the other is right after + // retiring a virtual processor). Perform the necessary required for a canceled context that is in its dispatch loop. + if (m_fCanceled) + { + CleanupDispatchedContextOnCancel(); + fDoneSearchingForWork = true; + } + } + } // end of while (!fDoneSearchingForWork) + + if (fWinRTInitialized) + { + WinRT::RoUninitialize(); + } + + // Clear the TLS as soon as possible for the debugger + ClearContextTls(); + } + + /// + /// If internal context does not own this virtual processor then claim it back. This might require + /// waiting until it becomes available. + /// + void InternalContextBase::ReclaimVirtualProcessor() + { + // If we were in the process of releasing (relinquishing) this virtual processor and we found work + // in the last search pass, then we have two options: + // + // 1) Virtual processor is still marked as available so we can reclaim it safely + // 2) Someone is in the process of adding work (calling StartupIdleVirtualProcessor) in which case + // we make sure that they see our context and we simply block until they signal. + if (m_fIsVisibleVirtualProcessor) + { + VirtualProcessor::ClaimTicket ticket; + if ( !m_pVirtualProcessor->ClaimExclusiveOwnership(ticket)) + { + // Someone has claimed this virtual processor exclusively for the purpose of activating it. We need to + // deactivate to consume the activation. + CONCRT_COREASSERT(m_pVirtualProcessor->GetExecutingContext() == this); + while (!m_pVirtualProcessor->Deactivate(this)) + { + RMAwaken(); + } + + CMTRACE(MTRACE_EVT_WOKEAFTERDEACTIVATE, this, m_pVirtualProcessor, NULL); + } + + CONCRT_COREASSERT(!m_pVirtualProcessor->IsAvailable()); + m_fIsVisibleVirtualProcessor = false; + } + else + { + // If this context was not releasing its virtual processor, it should still have it. + CONCRT_COREASSERT(!m_pVirtualProcessor->IsAvailable()); + CONCRT_COREASSERT(m_pVirtualProcessor->GetExecutingContext() == this); + } + } + + /// + /// Performs cleanup of the internal context + /// + void InternalContextBase::Cleanup() + { + ContextBase::Cleanup(); + + // Set the schedule group to null ensuring that no foreign threads/contexts are relying on it being alive. + SwapScheduleGroupSegment(NULL); + } + + /// + /// Cancels the context, causing it to exit the dispatch loop if it is running on a virtual processor. + /// + void InternalContextBase::Cancel() + { + ASSERT( !m_fCanceled); + ASSERT(m_pScheduler->InFinalizationSweep()); + + // This API must synchronize with scheduler finalization. The scheduler is kicked into finalization when no + // external references exist AND when all active vprocs are idle. Therefore the triggers for finalization are: + // 1] A thread decrements the last external reference count on the scheduler while idle and active counts + // are equal. + // 2] An internal context in the dispatch loop calls VirtualProcessorIdle(true) -> it raises the idle count + // and makes it equal to the active count. This context has a valid virtual processor. + // 3] An internal context in the dispatch loop calls SwitchOut since its virtual processor was marked for + // retirement, which in turn calls VirtualProcessorActive(false) -> it lowers the active count and makes + // it equal to the idle count. This context does NOT have a valid virtual processor since it has just + // retired it. + + // For each context in the list of 'all contexts' in the scheduler, we detect it if is executing on a virtual + // processor by checking if it has a non-null m_pVirtualProcessor. The current thread may very well be one of + // these contexts in the process of executing VirtualProcessorIdle(true), as described in 2] above.. We mark + // these contexts as canceled, and wake them up by attempting to activate their virtual processor. If their virtual + // processor was already activated, due to a race with StartupIdleVirtualProcessor (addition of work into the scheduler), + // or a race with RemoveVirtualProcessors (core migration), they will be suspended on the gate and woken up before + // PhaseTwoShutdown completes. When the contexts wake up, they will exit the dispatch loop, and since they are canceled, + // they will release their internal reference on the scheduler. + + // If the context does NOT have a valid virtual processor, we *must* cleanup and release the internal reference on + // the scheduler on its behalf. We need to be careful here, and ensure that the context has left its dispatch loop + // else we're in danger of having all references on the scheduler released and the scheduler being deleted while + // a context is in the process of leaving its dispatch loop. We DO NOT mark these contexts as canceled EXCEPT if + // the current thread is one such context executing VirtualProcessorActive(false) as described in 3] above. We can + // detect that a context without a virtual processor has left the dispatch loop by checking the m_fInDispatch member + // variable. + + if (m_pVirtualProcessor != NULL) + { + // Mark the context as canceled, so it will break out of its dispatch loop when it is resumed. + m_fCanceled = true; + + ASSERT(m_pVirtualProcessor->GetExecutingContext() == this); + + // We must synchronize with a potential external activation here. Virtual processors that were previously running + // and got deactivated could've been activated due to a race during adding the last work item, during the time at + // which the scheduler is shutting down. The context activating the virtual processor employs different meant of + // synchronization to ensure that that the actual deletion of scheduler data structures is delayed until it is done + // with trying to startup a virtual processor (an example of this is in ScheduleGroup::AddRunnableContext). However, + // the virtual processor root must only be activated once. For that reason, we must reclaim try to reclaim the virtual + // processor and if we fail, we can rely on the caller who beat us to it to activate the virtual processor root. + + // Claiming exclusive ownership also synchronizes with virtual processor retirement, as a result of core migration. + + // Since the suspend bit is set, the context is not allowed to get to a point where it can reset this flag. + ASSERT(m_fIsVisibleVirtualProcessor); + + VirtualProcessor::ClaimTicket ticket; + if (m_pVirtualProcessor->ClaimExclusiveOwnership(ticket)) + { + // + // We've succeeded in gaining ownership of this virtual processor, now we should activate it, since it has either + // already executed, or is about to execute, a call to Deactivate. + // + ticket.Exercise(); + } + else + { + ASSERT(m_pVirtualProcessor->GetExecutingContext() == this); + // + // Either someone added work and activated this virtual processor, after it executed VirtualProcessorIdle(true) + // or the virtual processor was activated after it was marked for retirement due to core migration. + // + // We do nothing here. + } + } + else + { + // DO NOT mark the context as canceled here unless it is the current context.(see case 3 above). With contexts that + // are not associated with virtual processors, we're not certain if they're left the dispatch loop for sure - we want + // to make sure they don't execute the cleanup code below, or we may have over-dereference errors. + if (SchedulerBase::FastCurrentContext() == this) + { + // If this is the current context executing PhaseTwoShutdown, it is in a VirtualProcessorActive(false) call, + // inside SwitchOut in its dispatch loop, we need this context to cleanup after itself (it cannot exit its + // dispatch routine until we are done with PhaseTwoShutdown), so we set its canceled flag to true here. + m_fCanceled = true; + return; + } + + // It is a possible that a context without a virtual processor is in SwitchOut but has not finished executing + // the function. Wait until its blocked flag is set, so we don't end up deleting the scheduler/context while + // the thread is still accessing them in its dispatch loop. + SpinUntilBlocked(); + + // The cleanup call *must* occur before the context releases its reference count on the scheduler. + // Part of cleanup involves releasing a reference on the context's schedule group, and in some cases + // we may need to spin until is safe to do so, keeping both the group and the scheduler alive. + Cleanup(); + m_pScheduler->DecrementInternalContextCount(); + } + } + + /// + /// Destroys the base class object for an internal context. + /// + InternalContextBase::~InternalContextBase() + { + Cleanup(); + } + + /// + /// Prepare a context for execution by associating a scheduler group/chore with it. Scheduler + // shall call this routine before executing an internal context + /// + void InternalContextBase::PrepareForUse(ScheduleGroupSegmentBase* pSegment, _Chore *pChore, bool choreStolen) + { + ASSERT(m_pSegment == NULL); + ASSERT(m_pAssociatedChore == NULL); + ASSERT(m_pWorkQueue == NULL); + ASSERT(m_pParentContext == NULL); + + // The context is no longer considered idle + ASSERT(m_fIdle); + m_fIdle = false; + + // Associate with a schedule group + m_pSegment = pSegment; + if (pChore == NULL) + { + // Reference the group since the context is now working on it. + pSegment->GetGroup()->InternalReference(); + } + else + { + // Realized chores already have a reference to their schedule group. This reference is transferred to + // the new context. If the chore is a stolen chore, the schedule group must be referenced. + if (choreStolen) + { + pSegment->GetGroup()->InternalReference(); + m_fAssociatedChoreStolen = true; + } + else + { + m_fAssociatedChoreStolen = false; + } + m_pAssociatedChore = pChore; + } + } + + /// + /// Remove a context from execution by dis-associating it from any scheduler group/chore. + /// + void InternalContextBase::RemoveFromUse() + { + // + // Due to the way in which recycling and reusing contexts happen, contexts on the free list must be inside critical + // regions until they are redispatched. + // + CONCRT_COREASSERT(IsInsideCriticalRegion()); + CMTRACE(MTRACE_EVT_CONTEXT_RELEASED, this, NULL, m_pVirtualProcessor); + + // + // Send this context back to the free list. If the free list is full, the context will be canceled, + // which will cause it to break out of the dispatch loop, cleanup and dereference the scheduler. + // If not, the context may be reused by the scheduler to schedule agents/steal chores. + // + ASSERT(m_pSegment != NULL && ScheduleGroupRefCount()> 0); + ASSERT(m_pAssociatedChore == NULL); + + ReleaseWorkQueue(); + + ASSERT(m_pParentContext == NULL); + + // Set the schedule group to null ensuring that no foreign threads/contexts are relying on it being alive. + SwapScheduleGroupSegment(NULL); + + // Mark the context as idle. + ASSERT(!m_fIdle); + m_fIdle = true; + + // For visualization purposes, the context is detached. + m_threadId = 0; + } + + /// + /// Returns a scheduler unique identifier for the context. + /// + /// + /// The context Id. + /// + unsigned int InternalContextBase::GetId() const + { + return m_id; + } + + /// + /// Returns the scheduler to which this context belongs. + /// + /// + /// The owning scheduler. + /// + IScheduler * InternalContextBase::GetScheduler() + { + return m_pScheduler->GetIScheduler(); + } + + /// + /// Returns the thread proxy which is executing this context. Until the Dispatch method has been called on the given + /// context, this will return NULL. Once the Dispatch method has been called, this returns the IThreadProxy which + /// was passed into the Dispatch method. + /// + /// + /// The thread proxy which dispatched this particular context, otherwise NULL. + /// + IThreadProxy * InternalContextBase::GetProxy() + { + return m_pThreadProxy; + } + +#if _DEBUG + // _DEBUG helper + DWORD InternalContextBase::GetThreadId() const + { + return ((const ThreadProxy*) m_pThreadProxy)->GetThreadId(); + } +#endif + + /// + /// Sets the thread proxy which is executing this context. The caller must save this and return it upon a call to the GetProxy method. + /// Note that the resource manager guarantees stability of the thread proxy while inside the Dispatch method. + /// + /// + /// The thread proxy which dispatched this particular context. + /// + /// + /// An indication of success. + /// + void InternalContextBase::SetProxy(IThreadProxy *pThreadProxy) + { + if (pThreadProxy == NULL) + { + throw std::invalid_argument("pThreadProxy"); + } + + m_pThreadProxy = pThreadProxy; +#if defined(_DEBUG) + m_pLastAssignedThreadProxy = m_pAssignedThreadProxy; + m_pAssignedThreadProxy = m_pThreadProxy; +#endif // _DEBUG + } + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + void* InternalContextBase::Alloc(size_t numBytes) + { + void* pAllocation = NULL; + ASSERT(SchedulerBase::FastCurrentContext() == this); + + // The alloc can throw an exception, we need to make sure we exit the critical region on this context before + // leaving the function. + + { + ContextBase::ScopedCriticalRegion cs(this); + SubAllocator * pAllocator = m_pVirtualProcessor->GetCurrentSubAllocator(); + ASSERT(pAllocator != NULL); + + pAllocation = pAllocator->Alloc(numBytes); + } + + return pAllocation; + } + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + void InternalContextBase::Free(void* pAllocation) + { + ASSERT(SchedulerBase::FastCurrentContext() == this); + ASSERT(pAllocation != NULL); + + EnterCriticalRegion(); + + SubAllocator * pAllocator = m_pVirtualProcessor->GetCurrentSubAllocator(); + ASSERT(pAllocator != NULL); + + pAllocator->Free(pAllocation); + + ExitCriticalRegion(); + } + + /// + /// Increments the count of work coming in. + /// + void InternalContextBase::IncrementEnqueuedTaskCounterHelper() + { + EnterCriticalRegion(); + + ASSERT(m_pVirtualProcessor != NULL); + ASSERT(SchedulerBase::FastCurrentContext() == this); + + m_pVirtualProcessor->m_enqueuedTaskCounter++; + + ExitCriticalRegion(); + } + + /// + /// Increments the count of work being done. + /// + void InternalContextBase::IncrementDequeuedTaskCounterHelper(unsigned int count) + { + EnterCriticalRegion(); + + ASSERT(m_pVirtualProcessor != NULL); + ASSERT(SchedulerBase::FastCurrentContext() == this); + + m_pVirtualProcessor->m_dequeuedTaskCounter += count; + + ExitCriticalRegion(); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.h new file mode 100644 index 0000000000000000000000000000000000000000..c1b59504c41bca7cc1a2198e360930fd607ff1c4 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.h @@ -0,0 +1,627 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// InternalContextBase.h +// +// Header file containing the base class definition for an internal execution context. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + + /// + /// Implements the base class for ConcRT internal contexts. + /// + +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class InternalContextBase : public IExecutionContext, public ContextBase + { + public: + + using ContextBase::GetId; + + // + // Public methods + // + + /// + /// Constructs the base class object for an internal context. + /// + InternalContextBase(SchedulerBase *pScheduler); + + /// + /// Causes the internal context to block yielding the virtual processor to a different internal context. + /// + virtual void Block(); + + /// + /// Unblocks the internal context putting it on a runnables collection in its schedule group. + /// + virtual void Unblock(); + + /// + /// Determines whether or not the context is synchronously blocked at this given time. + /// + /// + /// Whether context is in synchronous block state. + /// + virtual bool IsSynchronouslyBlocked() const + { + return (m_contextSwitchingFence == 2); + } + + /// + /// Yields the virtual processor to a different runnable internal context if one is found. + /// + virtual void Yield(); + + /// + /// Yields the virtual processor to a different runnable internal context if one is found. + /// + /// This is intended for spin loops. + /// + virtual void SpinYield(); + + /// + /// See comments for Concurrency::Context::Oversubscribe. + /// + virtual void Oversubscribe(bool beginOversubscription); + + /// + /// Destroys the base class object for an internal context. + /// + virtual ~InternalContextBase(); + + /// + /// Returns an identifier to the virtual processor the context is currently executing on, if any. + /// + virtual unsigned int GetVirtualProcessorId() const; + + /// + /// Toggle the flag that ensures that scheduler is not deleted until adding is completely finished. + /// + /// + /// The value to set the flag to. + /// + void CrossGroupRunnable(LONG value) { m_fCrossGroupRunnable = value; } + + /// + /// Set the value of the oversubscribed virtual processor for a context that invokes Oversubscribe. + /// + void SetOversubscribedVProc(VirtualProcessor * pVirtualProcessor) { m_pOversubscribedVProc = pVirtualProcessor; } + + /// + /// Called to retrieve the oversubscribed vproc and reset it to null. + /// + VirtualProcessor * GetAndResetOversubscribedVProc(VirtualProcessor * pExpectedVirtualProcessor); + + /// + /// Returns a scheduler unique identifier for the context. + /// + /// + /// The Id of the context. + /// + virtual unsigned int GetId() const; + + /// + /// Returns the scheduler to which this context belongs. + /// + /// + /// The owning scheduler. + /// + virtual IScheduler * GetScheduler(); + + /// + /// Returns the thread proxy which is executing this context. Until the Dispatch method has been called on the given + /// context, this will return NULL. Once the Dispatch method has been called, this returns the IThreadProxy which + /// was passed into the Dispatch method. + /// + /// + /// The thread proxy which dispatched this particular context, otherwise NULL. + /// + virtual IThreadProxy * GetProxy(); + +#if _DEBUG + // _DEBUG helper + DWORD GetThreadId() const; +#endif + + /// + /// Sets the thread proxy which is executing this context. The caller must save this and return it upon a call to the GetProxy method. + /// Note that the resource manager guarantees stability of the thread proxy while inside the Dispatch method. + /// + /// + /// The thread proxy which dispatched this particular context. + /// + /// + /// An indication of success. + /// + virtual void SetProxy(IThreadProxy *pThreadProxy); + + /// + /// The method that is called when a thread proxy starts executing a particular context. The thread proxy which executes + /// the context is passed into this method and must be saved and returned on a call to the get_Proxy method. + /// + /// + /// The state under which this IExecutionContext is being dispatched. + /// + virtual void Dispatch(DispatchState * pDispatchState); + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + virtual void* Alloc(size_t numBytes); + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + virtual void Free(void* pAllocation); + + /// + /// Swaps the existing schedule group with the one supplied. This function should be called when the context already + /// has a schedule group. It decrements the existing group reference count, and references the new one if the caller + /// indicates so. + /// + /// + /// The new group to assign to the context. This may be NULL. + /// + /// + /// Whether the context should reference the new group. In some cases there may be an existing reference + /// transferred to the context, in which case this parameter is false. + /// + void SwapScheduleGroupSegment(ScheduleGroupSegmentBase* pNewSegment, bool referenceNewGroup = false); + + /// + /// Increments the count of work coming in. + /// + void IncrementEnqueuedTaskCounter() + { + m_pVirtualProcessor->m_enqueuedTaskCounter++; + } + + void IncrementEnqueuedTaskCounterHelper(); + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter() + { + m_pVirtualProcessor->m_dequeuedTaskCounter++; + } + + /// + /// Increments the count of work being done. + /// + void IncrementDequeuedTaskCounter(unsigned int count) + { + m_pVirtualProcessor->m_dequeuedTaskCounter += count; + } + + void IncrementDequeuedTaskCounterHelper(unsigned int count); + + /// + /// In some cases internal context has not yet received a virtual processor so we have + /// to save the fact that the work was dequeued and we'll update it in Affinitize. + /// + void SaveDequeuedTask() + { + ASSERT(!m_fHasDequeuedTask); + m_fHasDequeuedTask = true; + } + + /// + /// Notifies that some work was skipped by an iteration of dispatch loop of this context + /// + void NotifyWorkSkipped() + { + m_fWorkSkipped = true; + } + +#if defined(_DEBUG) + /// + /// Gets the debug bits. + /// + DWORD GetDebugBits() const + { + return m_ctxDebugBits; + } + + /// + /// Sets a series of internal debugging bits for the context. + /// + /// + /// A bitmapped series of CTX_DEBUGBIT_* flags to set within the context. + /// + void SetDebugBits(DWORD bits) + { + m_ctxDebugBits |= bits; + } + + /// + /// Clears a series of internal debugging bits for the context. + /// + /// + /// A bitmapped series of CTX_DEBUGBIT_* flags to clear within the context. + /// + void ClearDebugBits(DWORD bits) + { + m_ctxDebugBits &= ~bits; + } + + /// + /// Completely clears all debug bits. + /// + void ClearDebugBits() + { + m_ctxDebugBits = 0; + } + + void NotifyAcquired() + { + m_lastAcquiredTid = GetCurrentThreadId(); + } +#endif // _DEBUG + + /// + /// Returns whether the context is in the idle pool or not. Finalization will call this during the sweep phase to + // determine all the blocked contexts. A context in the idle pool is considered "not blocked". + /// + bool IsIdle() const + { + return m_fIdle; + } + + /// + /// Prepare a context for execution by associating a scheduler group/chore with it. Scheduler + // shall call this routine before executing an internal context + /// + void PrepareForUse(ScheduleGroupSegmentBase* pSegment, _Chore *pChore, bool choreStolen); + + /// + /// Returns whether the context is prepared for execution or must be initialized prior to use. An unprepared context + /// must be initialized via PrepareForUse(). + /// + bool IsPrepared() const + { + return (m_pSegment != NULL); + } + + /// + /// Remove a context from execution by dis-associating it from any scheduler group/chore. + /// + void RemoveFromUse(); + + protected: + + // + // Protected types + // + + enum ReasonForSwitch + { + GoingIdle, + Blocking, + Yielding, + Nesting + }; + + // + // Protected data members + // + + // The thread proxy that is executing this context's dispatch loop, if any. + IThreadProxy * volatile m_pThreadProxy; // 4/8 + + // + // Protected methods + // + + /// + /// Spins until the 'this' context is in a firmly blocked state + /// + void SpinUntilBlocked(); + + /// + /// Adds the context to a runnables collection, either on the virtual processor, or the schedule group + /// + /// + /// A location specifying where to bias the awakening of virtual processors to. + /// + virtual void AddToRunnables(location bias = location()); + + /// + /// Switches from one internal context to another. + /// + void SwitchTo(InternalContextBase* pContext, ReasonForSwitch reason); + + /// + /// Switches out the internal context. Useful when the virtual processor is to be retired. + /// Is also used when un-nesting a scheduler and the context is returning to its original scheduler. + /// + /// + /// The reason for switching out of this vproc + /// + /// + /// True if the context has been canceled. + /// + bool SwitchOut(ReasonForSwitch reason); + + /// + /// Cancels the context, causing it to exit the dispatch loop if it is executing on a virtual processor + /// + virtual void Cancel(); + + /// + /// If internal context does not own this virtual processor then claim it back. This might require + /// waiting until it becomes available. + /// + void ReclaimVirtualProcessor(); + + /// + /// This function is called to execute the associated chore if one is available. The chore can be a stolen unrealized + /// chore or realized chore. + /// + /// + /// Returns true if an associated chore was executed, false otherwise. + /// + bool ExecutedAssociatedChore(); + + /// + /// Performs the necessary cleanup for a canceled context in its dispatch routine. + /// + void CleanupDispatchedContextOnCancel(); + + /// + /// Called in the dispatch loop to check if the virtual processor the context is running on is marked for retirement, + /// and retires the virtual processor if it is. + /// + /// + /// True if the virtual processor was retired, false otherwise. + /// + bool IsVirtualProcessorRetired(); + + /// + /// Searches for work using the search algorithm specified by the scheduler's policy. Also prepares the context to execute + /// work by reclaiming the virtual processor if necessary. + /// + /// + /// A pointer to a work item which is filled in if work was found. + /// + /// + /// True if work was found, false otherwise. + /// + bool WorkWasFound(WorkItem * pWork); + + /// + /// Switches to the runnable context represented by the work item. + /// + /// + /// A pointer to a work item to be executed. + /// + void SwitchToRunnableContext(WorkItem * pWork); + + /// + /// Executes the chore (realized or unrealized) specified by the work item. + /// + /// + /// A pointer to a work item that represents a realized or unrealized chore. + /// + void ExecuteChoreInline(WorkItem * pWork); + + /// + /// This method implements the wait-for-work and cancellation protocol. + /// + void WaitForWork(void); + + /// + /// Performs cleanup of the internal thread context. + /// + void Cleanup(); + + /// + /// Called before this executes on a given virtual processor. + /// + virtual void PrepareToRun(VirtualProcessor *pVProc) + { +#if defined(_DEBUG) + m_lastRunPrepareTimeStamp = _ReadTimeStampCounter(); + m_prepareCount++; + m_lastAffinitizedTid = GetCurrentThreadId(); +#endif // _DEBUG + m_pVirtualProcessor = pVProc; + CONCRT_COREASSERT(m_pSegment != NULL); + InterlockedExchange(&m_blockedState, CONTEXT_NOT_BLOCKED); + } + + // Virtual processor the context is executing on. +#if defined(_DEBUG) + void _PutVirtualProcessor(VirtualProcessor *pVirtualProcessor) + { + // + // If this assertion fires, someone is changing m_pVirtualProcessor outside a critical region. Doing this violates safety + // on a UMS scheduler. m_pVirtualProcessor is not guaranteed to be stable on a UMS context. All manipulation must happen + // inside a critical region. + // + CONCRT_COREASSERT(_m_pVirtualProcessor == NULL || IsInsideCriticalRegion()); + _m_pVirtualProcessor = pVirtualProcessor; + } + + VirtualProcessor *_GetVirtualProcessor() const + { + // + // If this assertion fires, someone is examining m_pVirtualProcessor outside a critical region. Doing this violates safety + // on a UMS scheduler. m_pVirtualProcessor is not guaranteed to be stable on a UMS context. All manipulation must happen + // inside a critical region. + // + CONCRT_COREASSERT(_m_pVirtualProcessor == NULL || IsInsideCriticalRegion()); + return _m_pVirtualProcessor; + } + + __declspec(property(get=_GetVirtualProcessor, put=_PutVirtualProcessor)) VirtualProcessor *m_pVirtualProcessor; + VirtualProcessor * volatile _m_pVirtualProcessor; + + VirtualProcessor *UNSAFE_CurrentVirtualProcessor() const + { + return _m_pVirtualProcessor; + } + + void UNSAFE_SetVirtualProcessor(VirtualProcessor *pVirtualProcessor) + { + _m_pVirtualProcessor = pVirtualProcessor; + } +#else + VirtualProcessor * volatile m_pVirtualProcessor; + + VirtualProcessor *UNSAFE_CurrentVirtualProcessor() const + { + return m_pVirtualProcessor; + } + + void UNSAFE_SetVirtualProcessor(VirtualProcessor *pVirtualProcessor) + { + m_pVirtualProcessor = pVirtualProcessor; + } +#endif + + private: + friend class ExternalContextBase; + friend class SchedulerBase; + friend class ThreadScheduler; + friend class VirtualProcessor; + friend class SchedulingRing; + friend class location; + template friend class Mailbox; + template friend class Stack; + template friend class SQueue; + + // This helper is used to avoid circular reference: + // Mailbox -> InternalContextBase -> ContextBase -> WorkStealingQueue -> Mailbox + friend unsigned int GetProcessorMaskId(InternalContextBase * pContext); + + // + // Private data + // + + // Pointer to an oversubscribed virtual processor if one is present. + VirtualProcessor * volatile m_pOversubscribedVProc; + + // Chore associated with the context - this could be a realized chore or a stolen chore. The chore is associated with the context + // either when the internal context first starts up, or it is picked out of the idle pool by the scheduler. The context must execute this chore + // before it starts looking for other work. This is used for indirect aliasing of unstructured task collections. + _Chore *m_pAssociatedChore; + + // Counter that indicates how many times the internal context has spun waiting for work. + unsigned int m_searchCount; + + // Flag that indicates whether the internal context is canceled. + volatile bool m_fCanceled; + + // Flag that indicates whether the associated chore is a stolen unrealized chore or a realized chore. + bool m_fAssociatedChoreStolen{}; + + // Flag that indicates whether internal context is in the final search for work state. + bool m_fIsVisibleVirtualProcessor; + + // Flag that indicates whether internal context has dequeued a piece of work without being able + // to immediately update the statistics numbers on a virtual processor (it was not affinitized). + bool m_fHasDequeuedTask : 1; + + // Indicates that some work was skipped in the dispatch loop. Currently, this is set if we failed to check some of the work stealing + // queues due to in-progress task collection cancellation. + bool m_fWorkSkipped : 1; + + // Debugging purposes: this informs whether the context was *EVER* put on a free list or whether it is a fresh context. + bool m_fEverRecycled : 1; + + // Debug information (particularly useful for UMS) + + // + // Time logging for forward progress determinations. + // + __int64 m_workStartTimeStamp{}; + __int64 m_lastRunPrepareTimeStamp{}; + DWORD m_prepareCount{}; + + DWORD m_ctxDebugBits{}; + + // The last TID this context was dispatched on. You can normally get this from m_pThreadProxy. + DWORD m_lastDispatchedTid{}; + + // The last TID this context was acquired/created on. + DWORD m_lastAcquiredTid{}; + + // The last TID this context was affinitized on. + DWORD m_lastAffinitizedTid{}; + + // + // Tracks the last assigned thread proxy (normally the same as m_pThreadProxy) -- but may not be for recycled contexts. + // + IThreadProxy *m_pAssignedThreadProxy{}; + IThreadProxy *m_pLastAssignedThreadProxy{}; + + // A flag that is used by contexts adding runnables to a scheduler. When those contexts (the ones performing the add) + // do not implicitly have a reference to the schedule group the runnable belongs to, setting this flag on the runnable + // context they are adding to the scheduler's queues, ensures that the group does not get destroyed and the scheduler + // does not get finalized while they are touching scheduler/schedule group data. + volatile LONG m_fCrossGroupRunnable; + + // Intrusive next pointer for SafeSQueue. + InternalContextBase *m_pNext{}; + + // Flag that indicates whether the internal context is in the idle pool or not + volatile bool m_fIdle; + + // + // Private methods + // + + /// + /// Called to find work to switch to, when the current context needs to block or nest a different scheduler. + /// The function may return NULL if no work was found and thread creation was disallowed by the thread + /// throttler. + /// + InternalContextBase* FindWorkForBlockingOrNesting(bool& fSFWContext, bool& fBoundUnrealized); + + /// + /// Called when a context is nesting a scheduler. If nesting takes place on what is an internal context in + /// the 'parent' scheduler, the context must return the virtual processor to the parent scheduler. + /// + void LeaveScheduler(); + + /// + /// Called when a context is un-nesting a scheduler. If the parent context is an internal context, it needs + /// to rejoin the parent scheduler by looking for a virtual processor it can execute on. + /// + void RejoinScheduler(); + + /// + /// Called when the RM wakes up the thread for some reason. + /// + virtual void RMAwaken() + { + } + + }; + + unsigned int GetProcessorMaskId(InternalContextBase* pContext); +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Mailbox.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Mailbox.h new file mode 100644 index 0000000000000000000000000000000000000000..e6301cc0c60fa9ab66da670aac9929118c893817 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Mailbox.h @@ -0,0 +1,591 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Mailbox.h +// +// Class definition for task affine mailbox. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +#define SLOT_PENDING_EXPIRY 1 +#define FIELD_RESERVED 1 + +namespace Concurrency +{ +namespace details +{ + // This helper is used to avoid circular reference: + // Mailbox -> InternalContextBase -> ContextBase -> WorkStealingQueue -> Mailbox + unsigned int GetProcessorMaskId(InternalContextBase * pContext); + + // *** NOTES *** + // + // Work stealing queues are associated with each context that the scheduler runs. Each context is, by nature of what it has executed or been bound to, + // associated with a given schedule group segment and hence has a natural affinity. This presents an interesting semantic with respect to work + // stealing tasks scheduled from that context. Imagine: + // + // CONTEXT A (affinity locA) + // + // tg.run(lambda1); + // tg.run(lambda2, loc2); + // tg.run(lambda3, loc3); + // tg.run(lambda4, loc4); + // tg.run(lambda5, loc5); + // tg.wait(); + // + // In this circumstance, lambda1 through lambda5 are pushed onto the work stealing queue associated with CONTEXT A. Because context A has an associated + // affinity (locA -- which might not be a *specific* affinity -- it might be the system), all of these tasks have a natural affinity to locA. When + // tasks lambda2 through lambda5 are scheduled, the caller has requested that, if stolen, those tasks run on locations other than the natural affinity + // of the work stealing queue. In order to accommodate this in a work stealing scheduler, we mail lambda2 through lambda5 to a mailbox. + // The mailbox will be contained within a segment with affinity loc2, loc3, ..., loc5 within the schedule *GROUP* of CONTEXT A. + // + // This means that tasks lambda2 through lambda5 will be contained in two places in the scheduler simultaneously: + // + // - On the work stealing queue for context A (which has natural affinity to locA) + // - On a mailbox within the group of context A with affinity loc* + // + // In this case, the affinities are chained. lambda2 has primary affinity to loc2 and secondary affinity to locA. If a vproc within loc2 is available, + // it will go there; otherwise, if a vproc within locA is available, it will go there; otherwise, it will go anywhere subject to the rules of SFW. + // + // Having a given task in two places presents an interesting problem: task lifetime. The ConcRT scheduler is not always in control of the lifetime of + // objects that are pushed onto the work stealing queue. A lambda which is scheduled to a task_group has lifetime owned by the scheduler. A task_handle + // which is scheduled to a (structured_)task_group has lifetime which is managed by the caller. + // + // Once a task is executed from *either* queue (the mailbox or the WSQ), the task can no longer safely be touched by the runtime. In order to allow + // for this, affine tasks work as follows: the low bit of the chore pointer on the WSQ is utilized to indicate whether a task is an affine (mailed) task + // or not. If the task is not affine, things work as they always have. If the task *IS* affine, the WSQ keeps a side structure which holds a slot + // for the given WSQ chore. The "slot" is Mailbox::Slot. The chore cannot be touched until ClaimSlot is called successfully. The mailbox can do + // whatever is necessary under the covers to implement this interface. + // + + // + // At present, there are some rather subtle lifetime rules about mailboxes and the objects which actually manage their storage. + // + // - A mailbox is bound to the lifetime of a schedule group segment. Mailboxes have two sub-objects: slots and segments. Both of these objects + // can outlive the mailbox! + // + // - A mailbox slot is a handle to some location within a given mailbox. The slot object is valid until Claim() is called on it. After this method + // returns, the slot is invalid. Calling a method on it again will result in undefined behavior. + // + // - A mailbox segment is the backing storage for a portion of the mailbox queue. Slots are chained and allocated in FIFO order to amortize the cost + // of allocation. Excepting the amortized allocation, a mailbox is lock-free (though not wait-free). Mailbox segments have an implicit reference on them + // for every slot within the segment. The segment is freed once EVERY reference is removed. Mailbox segments are only freed at safe points to give the + // Dequeue code extra safety. This implies that Dequeue operations on a mailbox must happen on an internal context within a critical region. + // + + // + /// + /// A lock-free fixed size FIFO of tasks associated with a particular object. The mailbox is typically used + /// for work stealing tasks affine to a particular location. + /// + template + class Mailbox + { + private: + + /// + /// Represents a segment of a mailbox which contains a fixed number of slots. + /// + struct Segment + { + /// + /// Constructs a new segment. + /// + Segment(SchedulerBase *pScheduler, const QuickBitSet &affinitySet, unsigned int size, unsigned int baseIdx) : + m_pScheduler(pScheduler), m_affinitySet(affinitySet), m_baseIdx(baseIdx), m_refs(0), m_pNext(NULL) + { + m_pQueue = _concrt_new T* volatile [size]; + memset((void*)(m_pQueue), 0, sizeof(T* volatile) * size); + } + + /// + /// Destroys a segment. + /// + ~Segment() + { + delete[] m_pQueue; + } + + bool AllSlotsClaimed(unsigned int count) + { + // Note that if this segment has already had its deletion refs set after all slots were claimed, this will + // return false. However, for the purpose we are using it for (deciding whether or not to set deletion refs), + // this is not a problem. + return (m_refs + count == 0); + } + + /// + /// Removes a reference from the segment. + /// + void Dereference() + { + if (static_cast(InterlockedDecrement(reinterpret_cast(&m_refs))) == 0) + Expire(); + } + + /// + /// Expires a segment. + /// + void Expire() + { + // + // This can be called during search-for-work as we touch a work stealing queue that has had a task mailed. We do *NOT* want heap + // operations in search-for-work at ANY point. As such, the deletion gets deferred to the scheduler's next safe point. + // + // This also guards against two Dequeuers (which are only on internal contexts during critical regions) from touching freed memory in + // locating their segment. Enqueues are guarded with a different mechanism. + // + m_deletionSafePoint.InvokeAtNextSafePoint(reinterpret_cast(&Segment::StaticDelete), + reinterpret_cast(this), + m_pScheduler); + } + + /// + /// Marks how many dereferences must happen before the segment can delete itself. + /// + void SetDeletionReferences(unsigned int count) + { + if ((static_cast(InterlockedExchangeAdd(reinterpret_cast(&m_refs), count)) + count) == 0) + Expire(); + } + + /// + /// Safe point routine to delete a segment. + /// + static void StaticDelete(Segment *pSegment) + { + delete pSegment; + } + + // The scheduler to which the segment belongs. + SchedulerBase *m_pScheduler; + + // The affinity of the segment. + QuickBitSet m_affinitySet; + + // The queue of objects within the segment. + T* volatile * m_pQueue; + + // The base index of the segment. + unsigned int m_baseIdx; + + // The number of references remaining on the segment. + volatile unsigned int m_refs; + + // The next segment within the mailbox. + Segment * m_pNext; + + // The safe point at which the segment will be deleted. + SafePointInvocation m_deletionSafePoint; + }; + + public: + + /// + /// An opaque handle to a slot of a mailbox. When an object is enqueued in the mailbox, a slot is returned. If the item + /// is placed on another list, the slot must be claimed before the object is utilized. + /// + class Slot + { + public: + + Slot() : m_pSegment(NULL), m_relativeIdx(0) + { + } + + Slot(const Slot& src) : m_pSegment(src.m_pSegment), m_relativeIdx(src.m_relativeIdx) + { + } + + Slot& operator=(const Slot& rhs) + { + m_pSegment = rhs.m_pSegment; + m_relativeIdx = rhs.m_relativeIdx; + + return *this; + } + + bool IsEmpty() const + { + return m_pSegment == NULL; + } + + /// + /// Claims an object from a slot in an out-of-order and thread-safe manner. If true is returned, this indicates that + /// the caller has exclusive ownership of the object within that slot. + /// + bool Claim(T ** pClaimedObject = nullptr) + { + T* pObject = m_pSegment->m_pQueue[m_relativeIdx]; + ASSERT(pObject != NULL); + + if (pObject != reinterpret_cast(SLOT_PENDING_EXPIRY)) + { + T* pXchgObject = reinterpret_cast( + InterlockedExchangePointer(reinterpret_cast(m_pSegment->m_pQueue + m_relativeIdx), + reinterpret_cast(SLOT_PENDING_EXPIRY))); + + if (pXchgObject == pObject) + { + if (pClaimedObject) + *pClaimedObject = pObject; + return true; + } + + } + + m_pSegment->Dereference(); + + return false; + } + + bool DeferToAffineSearchers() const + { + InternalContextBase * pContext = static_cast(SchedulerBase::FastCurrentContext()); + return (m_pSegment->m_pScheduler->HasSearchers(m_pSegment->m_affinitySet) && + !m_pSegment->m_affinitySet.IsSet(GetProcessorMaskId(pContext))); + } + + private: + + friend class Mailbox; + + Slot(Segment *pSegment, unsigned int relativeIdx) : m_pSegment(pSegment), m_relativeIdx(relativeIdx) + { + } + + Segment *m_pSegment; + unsigned int m_relativeIdx; + + }; + + /// + /// Constructs a new mailbox with the specified segment size. + /// + /// + /// The scheduler to which this mailbox belongs. + /// + /// + /// Indicates whether or not to defer allocation of the first segment until the first enqueue. + /// + /// + /// The size of the mailbox. Note that the mailbox size is fixed once constructed. + /// + + Mailbox(SchedulerBase *pScheduler, const QuickBitSet&, bool fDeferAlloc = false, unsigned int segmentSize = s_segmentSize) + : m_pScheduler(pScheduler) + , m_segmentSize(segmentSize) + , m_pTailSegment(NULL) + , m_pHeadSegment(NULL) + , m_head(0) + , m_tail(0) + { + ASSERT((segmentSize & (segmentSize - 1)) == 0); + + Initialize(m_affinitySet); + + if (!fDeferAlloc) + { + m_pTailSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, segmentSize, 0); + m_pHeadSegment = m_pTailSegment; + } + } + + /// + /// Destroys a mailbox. + /// + ~Mailbox() + { + Segment *pSegment = m_pHeadSegment; + while (pSegment != NULL) + { + Segment *pNextSegment = pSegment->m_pNext; + + if (pSegment != m_pTailSegment) + pSegment->SetDeletionReferences(m_segmentSize); + else + { + // + // How many items are in this segment? That is how many must dereference the segment in order for its memory to be freed. + // Set this number. Note that this should *ONLY* be for the tail segment. + // + unsigned int numElements = m_tail - pSegment->m_baseIdx; + ASSERT(numElements <= m_segmentSize); + + pSegment->SetDeletionReferences(numElements); + } + + pSegment = pNextSegment; + } + + } + + /// + /// Initializes key fields of the mailbox. + /// + void Initialize(const QuickBitSet& bitSet) + { + m_affinitySet = bitSet; + if (m_pHeadSegment) + m_pHeadSegment->m_affinitySet = bitSet; + } + + /// + /// Enqueues an object onto the mailbox and returns a pointer to the slot if the enqueue is successful. Note that + /// the Slot object may only be used in methods on the mailbox. + /// + /// + /// The object to enqueue. + /// + Slot Enqueue(T* pObject) + { + // + // Complete the pushes in order to avoid LocateMailboxSegment touching an invalid segment when an enqueue crosses a boundary in conjunction + // with a dequeue/claim -> free. + // + m_enqueueLock._Acquire(); + + Segment *pSegment = LocateMailboxSegment(m_tail, true); + + unsigned int relativeIdx = m_tail - pSegment->m_baseIdx; + pSegment->m_pQueue[relativeIdx] = pObject; + + // The Dequeue function will calculate the number of available messages based on m_tail. + // This memory fence will flush new m_tail to Dequeue. Be attention that there is no fence in the last lock release function. + // If the write to m_tail is observed by the Dequeue, all write operations before this point must be observed by Dequeue as well. + _InterlockedIncrement(reinterpret_cast(&m_tail)); + + m_enqueueLock._Release(); + return Slot(pSegment, relativeIdx); + } + + /// + /// Dequeues an object from the mailbox. + /// + /// + /// If the dequeue is successful, the dequeued element will be placed here. + /// + /// + bool Dequeue(T **pDequeuedElement) + { + // + // Keep dequeueing until we either get something or the queue is empty. We may dequeue a slot pending expiry. + // + for(;;) + { + unsigned int head = m_head; + for (;;) + { + if (head == m_tail) + return false; + + unsigned int xchgHead = static_cast ( + InterlockedCompareExchange(reinterpret_cast(&m_head), head + 1, head) + ); + + if (xchgHead == head) + break; + + head = xchgHead; + } + + Segment *pSegment = LocateMailboxSegment(head, false); + + // + // Check if we need to update the head pointers if we have gone past the head segment. We will only remove segments from the queue if + // all their slots have been claimed. This is so that we do not inadvertently remove a segment a different thread in this routine + // is trying to to locate. Segments can only be located if they are between head and tail. The update must handle multiple dequeues + // happening simultaneously and trying to update this simultaneously! + // + // There is no ABA here because segments are freed at a safe point and the calling thread is always an internal context which participates + // in this mechanism. + // + if (pSegment != m_pHeadSegment) + { + // Since the head is not moved until all slots are claimed, this segment's base index cannot be less than that of the head segment. + // i.e. this segment must still be in the set [head, tail]. + CONCRT_COREASSERT(pSegment->m_baseIdx >= m_pHeadSegment->m_baseIdx); + + Segment *pHeadSegment = m_pHeadSegment; + Segment *pReadSegment = pHeadSegment; + + // Travel forward from the head as long as we continue to find segments that have had all slots claimed. + for(;;) + { + while (pReadSegment->AllSlotsClaimed(m_segmentSize)) + { + pReadSegment = pReadSegment->m_pNext; + } + + // If we've found a chain of segments (or a single segment) that has all slots claimed, try to change the head + if (pReadSegment->m_baseIdx > pHeadSegment->m_baseIdx) + { + Segment *pXchgSegment = reinterpret_cast( + InterlockedCompareExchangePointer(reinterpret_cast(&m_pHeadSegment), + reinterpret_cast(pReadSegment), + reinterpret_cast(pHeadSegment)) + ); + + if (pXchgSegment == pHeadSegment) + { + // + // The person who removes a segment (or a series of segments) from the list via the head is responsible for + // setting their deletion references so that they properly delete! The segments in the sublist described by + // the half open range [pXchgSegment, pSegment) must be set. + // + Segment *pDelRef = pXchgSegment; + while (pDelRef != pReadSegment) + { + pDelRef->SetDeletionReferences(m_segmentSize); + pDelRef = pDelRef->m_pNext; + } + break; + } + + pHeadSegment = pReadSegment = pXchgSegment; + } + else + { + break; + } + } + + CONCRT_COREASSERT(m_pHeadSegment != NULL); + CONCRT_COREASSERT(pSegment->m_baseIdx >= m_pHeadSegment->m_baseIdx); + } + + unsigned int relativeIdx = head - pSegment->m_baseIdx; + + // If the slot we get has not been claimed by anyone else, + // we will claim it and dequeue it, otherwise, keep searching next. + if (Slot(pSegment, relativeIdx).Claim(pDequeuedElement)) + return true; + } + } + + /// + /// Returns whether the mailbox is empty or not. + /// + bool IsEmpty() const + { + return (m_head == m_tail); + } + + private: + + /// + /// Expires a slot. + /// + void ExpireSlot(Segment *pSegment, unsigned int relativeIdx) + { + pSegment->Dereference(); + } + + Segment *Grow(Segment *pPreviousSegment) + { + // This "Grow" function is always protected by the lock in "enqueue". + + Segment *pNewSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, m_segmentSize, pPreviousSegment->m_baseIdx + m_segmentSize); + m_pTailSegment = pNewSegment; + return pPreviousSegment->m_pNext = pNewSegment; + } + + /// + /// Performs one time demand initialization of the mailbox if the segments were set to be allocated on demand. + /// + void DemandInitialize() + { + if (m_pTailSegment == NULL) + { + Segment *pXchgSegment = reinterpret_cast( + InterlockedCompareExchangePointer(reinterpret_cast(&m_pTailSegment), + reinterpret_cast(FIELD_RESERVED), + NULL) + ); + + if (pXchgSegment == NULL) + { + Segment *pNewSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, m_segmentSize, 0); + m_pTailSegment = pNewSegment; + // sfence + m_pHeadSegment = pNewSegment; + } + } + + if (m_pHeadSegment == NULL) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + while(m_pHeadSegment == NULL) + { + spinWait._SpinOnce(); + } + } + } + + /// + /// Locates the appropriate mailbox segment for the specified absolute index. This is only utilized during enqueue and dequeue and *NOT* during + /// an arbitrary slot claim! + /// + Segment *LocateMailboxSegment(unsigned int absoluteIdx, bool fStartTail) + { + if (m_pHeadSegment == NULL) + DemandInitialize(); + + // lfence + + Segment *pSegment = fStartTail ? m_pTailSegment : m_pHeadSegment; + ASSERT(absoluteIdx >= pSegment->m_baseIdx); + + Segment *pPreviousSegment = pSegment; + while (pSegment && absoluteIdx >= pSegment->m_baseIdx + m_segmentSize) + { + pSegment = pSegment->m_pNext; + if (pSegment == NULL) + { + ASSERT(fStartTail); // Only enqueue will "Grow" the queue. + pSegment = Grow(pPreviousSegment); + } + pPreviousSegment = pSegment; + } + + return pSegment; + } + + // + // Determines the size of a mailbox segment. Every mailbox pre-allocates a single segment. The size should be large enough to amortize heap + // allocation but small enough not to be prohibitively waste memory. + // + // This value should be a power of two. + // + static const unsigned int s_segmentSize = 64; + + // The scheduler to which the mailbox belongs + SchedulerBase *m_pScheduler; + + // The mailbox's affinity set + QuickBitSet m_affinitySet; + + // The size of segments for this mailbox. + unsigned int m_segmentSize; + + // The head and tail segments for the mailbox. These are within [m_head, m_tail]. + Segment * volatile m_pTailSegment; + Segment * volatile m_pHeadSegment; + + // The current head pointer + volatile unsigned int m_head; + + // The current tail pointer + volatile unsigned int m_tail; + + // Protect enqueue function, which should only accept one message for a time. + _NonReentrantLock m_enqueueLock; + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d4d3ba19307eba364c98d94aa82eacab5cf0eac --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.cpp @@ -0,0 +1,921 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Platform.cpp +// +// Platform API abstraction. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" +#include +#include + +#pragma warning (push) +#pragma warning (disable: 4702 4100) + +namespace Concurrency { namespace details { namespace platform { + +/************** Events ***************************/ + +/// +/// Creates an auto reset event +/// +HANDLE __CreateAutoResetEvent(bool initialSet) +{ + DWORD flags = 0; + + if (initialSet) + { + flags |= CREATE_EVENT_INITIAL_SET; + } + + HANDLE hEvent = CreateEventExW(NULL, NULL, flags, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE); + if (hEvent == NULL) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + return hEvent; +} + +/// +/// Creates a manual reset event +/// +HANDLE __CreateManualResetEvent(bool initialSet) +{ + DWORD flags = CREATE_EVENT_MANUAL_RESET; + + if (initialSet) + { + flags |= CREATE_EVENT_INITIAL_SET; + } + + HANDLE hEvent = CreateEventExW(NULL, NULL, flags, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE); + if (hEvent == NULL) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + return hEvent; +} + +/************** Tickcount ***************************/ + +/// +/// Gets the current tick count +/// +ULONGLONG __GetTickCount64() +{ + return GetTickCount64(); +} + +/************** Windows critical section ***************************/ + +/// +/// Initializes the critical section +/// +BOOL __InitializeCriticalSectionEx(CRITICAL_SECTION * cs, DWORD spinCount) +{ + return InitializeCriticalSectionEx(cs, spinCount, 0); +} + +/************** Thread Local Storage ***************************/ + +/// +/// Allocates a TLS slot +/// +DWORD __TlsAlloc() +{ +#if defined(_ONECORE) + // We use Fls (Fiber local storage) as TLS is not supported for MSDK. + DWORD index = FlsAlloc(nullptr); + if (index == FLS_OUT_OF_INDEXES) +#else + // Use TLS for desktop because multiple schedulers are supported. + DWORD index = TlsAlloc(); + if (index == TLS_OUT_OF_INDEXES) +#endif + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + return index; +} + +/// +/// Frees a TLS slot +/// +void __TlsFree(DWORD index) +{ +#if defined(_ONECORE) + if (index != FLS_OUT_OF_INDEXES) + { + FlsFree(index); + // Ignore error + } +#else + TlsFree(index); +#endif +} + +/// +/// Gets the value stored in the specified TLS slot +/// +PVOID __TlsGetValue(DWORD index) +{ +#if defined(_ONECORE) + // Leave it up to the caller to decide if there was an error when + // the return value is NULL. + return FlsGetValue(index); +#else + return TlsGetValue(index); +#endif +} + +/// +/// Stores a value in the specified TLS slot +/// +void __TlsSetValue(DWORD index, PVOID value) +{ +#if defined(_ONECORE) + if (!FlsSetValue(index, value)) +#else + if (!TlsSetValue(index, value)) +#endif + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } +} + +/************** Thread Priority ***************************/ + +/// +/// Sets the thread priority +/// +void __SetThreadPriority(HANDLE hThread, int priority) +{ +#if defined(_ONECORE) + // Dynamic thread priority modification is not supported under MSDK + ENSURE_NOT_APP(); +#else + if (SetThreadPriority(hThread, priority) == 0) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } +#endif // _ONECORE +} + +/// +/// Retrieves the thread priority +/// +int __GetThreadPriority(HANDLE hThread) +{ +#if defined(_CRT_APP) + // MSDK does not support GetThreadPriority + ENSURE_NOT_APP(); + return THREAD_PRIORITY_ERROR_RETURN; +#else + return GetThreadPriority(hThread); +#endif // defined(_CRT_APP) +} + +/************** Thread Affinity ***************************/ + +/// +/// Retrieves the thread group affinity +/// +BOOL __GetThreadGroupAffinity(HANDLE hThread, PGROUP_AFFINITY affinity) +{ + // Don't do anything when targeting OneCore (We could set it to active processor mask in the future) +#if !defined(_ONECORE) + CONCRT_VERIFY(GetThreadGroupAffinity(hThread, affinity)); +#endif // !defined(_ONECORE) + + return 1; +} + +/// +/// Sets the thread group affinity +/// +BOOL __SetThreadGroupAffinity(HANDLE hThread, const GROUP_AFFINITY * affinity) +{ + // Don't do anything when targeting MSDK +#if !defined(_ONECORE) + CONCRT_VERIFY(SetThreadGroupAffinity(hThread, affinity, NULL)); +#endif // !defined(_ONECORE) + + return 1; +} + +/************** System Info ***************************/ + +/// +/// Retrieves the information about the relationships of logical processors and related hardware +/// +PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX __GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relation, PDWORD retLength) +{ +#if defined(_ONECORE) + // MSDK does not support this API. It is an error to call this API + ENSURE_NOT_APP(); +#else + + ASSERT(retLength != nullptr); + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pSysInfo = nullptr; + + GetLogicalProcessorInformationEx(relation, NULL, retLength); + + if (ERROR_INSUFFICIENT_BUFFER != GetLastError()) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + DWORD len = *retLength; + ASSERT(len > 0); + + pSysInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) malloc(len); + + if (pSysInfo == NULL) + { + throw std::bad_alloc(); + } + + if (!GetLogicalProcessorInformationEx(relation, pSysInfo, retLength)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + return pSysInfo; +#endif // defined(_ONECORE) +} + +/// +/// Retrieves the information about logical processors and related hardware +/// +PSYSTEM_LOGICAL_PROCESSOR_INFORMATION __GetLogicalProcessorInformation(PDWORD retLength) +{ +#if defined(_ONECORE) + // MSDK does not support this API. It is an error to call this API + ENSURE_NOT_APP(); +#else +#if (defined(_M_IX86) || defined(_M_X64)) + ASSERT(retLength != nullptr); + + GetLogicalProcessorInformation(NULL, retLength); + if (ERROR_INSUFFICIENT_BUFFER != GetLastError()) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + DWORD len = *retLength; + ASSERT(len > 0); + + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pSysInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION) malloc(len); + if (pSysInfo == NULL) + { + throw std::bad_alloc(); + } + if (!GetLogicalProcessorInformation(pSysInfo, retLength)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + return pSysInfo; +#else + throw invalid_operation(); +#endif // (defined(_M_IX86) || defined(_M_X64)) +#endif // defined(_ONECORE) +} + +/// +/// Retrieves the processor group and number of the logical processor where the thread is running +/// +void __GetCurrentProcessorNumberEx(PPROCESSOR_NUMBER procNum) +{ +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + GetCurrentProcessorNumberEx(procNum); +#endif // defined(_ONECORE) +} + +/// +/// Returns the highest numa node number +/// +ULONG __GetNumaHighestNodeNumber() +{ + ULONG highestNodeNumber; +#if defined(_ONECORE) + // For MSDK we assume a single NUMA node + highestNodeNumber = 0; +#else + if (!GetNumaHighestNodeNumber(&highestNodeNumber)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } +#endif // defined(_ONECORE) + return highestNodeNumber; +} + +/************** Thread yield ***************************/ + +/// +/// Yield execution to another ready thread +/// +void __SwitchToThread() +{ +#if defined(_ONECORE) + // TODO: Do we need to yield our time quantum? +#else + SwitchToThread(); +#endif +} + +/// +/// Yield execution to another ready thread (ms is assumed to be 0 or 1) +/// +void __Sleep(DWORD ms) +{ + Sleep(ms); +} + +//***********************************************/ +// Timer / +//***********************************************/ + +/// +/// Creates a timer +/// +BOOL __CreateTimerQueueTimer( + PHANDLE phNewTimer, + HANDLE timerQueue, + WAITORTIMERCALLBACK lpStartAddress, + PVOID lpParameter, + DWORD dueTime, + DWORD period, + ULONG flags +) +{ +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + return CreateTimerQueueTimer(phNewTimer, + timerQueue, + lpStartAddress, + lpParameter, + dueTime, + period, + flags); +#endif // defined(_ONECORE) +} + +/// +/// Deletes the timer +/// +void __DeleteTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, HANDLE completionEvent) +{ +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + for(int maximalRetry = 16; maximalRetry > 0; --maximalRetry) + { + if (!DeleteTimerQueueTimer(timerQueue, hTimer, completionEvent)) + { + if (GetLastError() == ERROR_IO_PENDING) + break; + } + else + { + break; + } + } +#endif // defined(_ONECORE) +} + +/// +/// Changes the due time of the timer. +/// +BOOL __ChangeTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, ULONG dueTime, ULONG period) +{ +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + return ChangeTimerQueueTimer(timerQueue, hTimer, dueTime, period); +#endif // defined(_ONECORE) +} + +//***********************************************/ +// CreateThread / +//***********************************************/ + +/// +/// Creates a thread +/// +HANDLE __CreateThread(LPSECURITY_ATTRIBUTES lpAttributes, + size_t stackSize, + LPTHREAD_START_ROUTINE startAddress, + LPVOID param, + DWORD flags, + LPDWORD threadId) +{ + return CreateThread(lpAttributes, stackSize, startAddress, param, flags, threadId); +} + +/// +/// Releases the thread handle +/// +void __CloseThreadHandle(HANDLE hThread) +{ + CloseHandle(hThread); +} + +/// +/// Waits for the thread to exit +/// +DWORD __WaitForThread(HANDLE hThread, DWORD timeout) +{ + return WaitForSingleObjectEx(hThread, timeout, FALSE); +} + +/// +/// Signals hSignal object and waits for hWait. Returns the reason for returning from wait +/// +DWORD __SignalObjectAndWait(HANDLE hSignal, HANDLE hWait, DWORD ms, BOOL alertable) +{ +#if defined(_ONECORE) + SetEvent(hSignal); + return WaitForSingleObjectEx(hWait, ms, alertable); +#else + return SignalObjectAndWait(hSignal, hWait, ms, alertable); +#endif +} + + +//***********************************************/ +// RegisterWaitForSingleObject / +//***********************************************/ + +/// +/// Represents a collection of events and a background thread for handling those event notifications. Essentially +/// it performs the equivalent functionality of RegisterWaitForSingleObject. +/// +class WaiterThread +{ +public: + WaiterThread() : m_numEvents(0), m_numWaiting(0), m_pendingRemove(0) + { + for (int i = 0; i < MAXIMUM_WAIT_OBJECTS; i++) + { + m_waitHandles[i] = &m_eventData[i]; + } + } + + /// + /// Create the background thread + /// + void start() + { + // Create the background thread + HANDLE threadHandle = __CreateThread(NULL, + 0, + WaiterThread::wait_bridge, + this, + 0, + NULL); + + __CloseThreadHandle(threadHandle); + } + + /// + /// Indicate that the handler should be deleted when the background thread exits + /// + void stop() + { + auto waiterData = m_waitHandles[0]; + waiterData->handler = nullptr; + notify(true); + + // The background thread will eventually exit and reclaim this handler + } + + /// + /// Indicates whether there are slots available in this handler + /// + bool is_available() + { + return m_numEvents < MAXIMUM_WAIT_OBJECTS; + } + + /// + /// Adds a waiter for the given handle + /// + HANDLE add_handle(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context) + { + HANDLE hWait = nullptr; + { + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + if (m_numEvents == 0) + { + // Create the wake event + HANDLE hWake = CreateEventExW(NULL, NULL, 0, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE); + if (hWake== NULL) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + add_wait(hWake, wake_bridge, this); + } + + // Add the user event + hWait = add_wait(hEvent, callback, context); + + // Snap shot numWaiting + if (m_numWaiting == 0) + { + // Not started yet + m_numWaiting = m_numEvents; + } + } + + // Notify the background thread after releasing the lock + notify(false); + return hWait; + } + + /// + /// Remove the waiter for the given handle + /// + static void remove_handle(HANDLE hWait) + { + auto waiterData = static_cast(hWait); + auto handler = static_cast(waiterData->handler); + handler->remove_wait(waiterData); + } + +private: + + typedef struct _WAITER_DATA + { + void * handler; + WAITORTIMERCALLBACK callback; + PVOID context; + } WAITER_DATA; + + /// + /// Add the waiter to the list + /// + HANDLE add_wait(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context) + { + WAITER_DATA * waiterData = m_waitHandles[m_numEvents]; + waiterData->callback = callback; + waiterData->context = context; + waiterData->handler = this; + + m_hEvents[m_numEvents] = hEvent; + m_numEvents++; + + return static_cast(waiterData); + } + + /// + /// Indicates that the waiter is to be removed from the list. The background + /// thread is notified which in turn would remove it from the list. + /// + void remove_wait(WAITER_DATA * waiterData) + { + waiterData->handler = nullptr; + notify(true); + } + + /// + /// Notify the background thread + /// + void notify(bool isRemoval) + { + if (isRemoval) + { + // Wake up the background thread for the first removal + if (_InterlockedIncrement(&m_pendingRemove) == 1) + { + SetEvent(m_hEvents[0]); + } + } + else + { + // Avoid waking up the background thread for every event we add... + if (m_numEvents - m_numWaiting == 1) + { + SetEvent(m_hEvents[0]); + } + } + } + + /// + /// Invokes the callback + /// + void invoke_handler(DWORD index) + { + ASSERT(index < MAXIMUM_WAIT_OBJECTS); + + auto waiterData = m_waitHandles[index]; + + // Skip the callback if the callback was removed + // Special case the wake handler + if ((index == 0) || (waiterData->handler != nullptr)) + { + waiterData->callback(waiterData->context, FALSE); + } + } + + /// + /// The main wait loop + /// + void wait_handler() + { + while (m_numWaiting > 0) + { + // Wait for the array of events + DWORD waitResult = WaitForMultipleObjectsEx((DWORD)m_numWaiting, m_hEvents, false, INFINITE, FALSE); + if (waitResult == WAIT_FAILED) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + // Invoke the callback + DWORD waitHandleIndex = waitResult - WAIT_OBJECT_0; + ASSERT(waitHandleIndex < m_numWaiting); + invoke_handler(waitHandleIndex); + + // If the callback removed a waiter or if it was already removed, process it here + if ((m_numWaiting > 0) && (WaitForSingleObjectEx(m_hEvents[0], 0, FALSE) == WAIT_OBJECT_0)) + { + invoke_handler(0); + } + } + } + + /// + /// static bridge that calls the wait loop + /// + static DWORD WINAPI wait_bridge(PVOID context) + { + auto handler = static_cast(context); + handler->wait_handler(); + delete handler; + return 0; + } + + /// + /// The main handler for the back ground thread + /// + void wake_handler() + { + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + auto pendingRemove = _InterlockedExchange(&m_pendingRemove, 0); + + if (pendingRemove != 0) + { + process_remove(); + } + + // Update the num waiters (which is common for add and remove of handlers) + m_numWaiting = m_numEvents; + } + + /// + /// Static bridge for the wake handler + /// + static void CALLBACK wake_bridge(PVOID context, BOOLEAN) + { + auto handler = static_cast(context); + handler->wake_handler(); + } + + /// + /// Removes waiters and compacts the array of handles + /// + void process_remove() + { + // Walk all the handler and remove the ones that are marked (handler == nullptr) + // Skip the first event which is our wake handler + DWORD i = 1; + while (i < m_numEvents) + { + auto waiterData = m_waitHandles[i]; + + if (waiterData->handler == nullptr) + { + // Remove the event + CloseHandle(m_hEvents[i]); + m_numEvents--; + + if (i != m_numEvents) + { + // Swap the last event + m_hEvents[i] = m_hEvents[m_numEvents]; + m_hEvents[m_numEvents] = NULL; + + m_waitHandles[i] = m_waitHandles[m_numEvents]; + m_waitHandles[m_numEvents] = waiterData; + } + + // Process this event again + continue; + } + + i++; + } + + // If the last user event is removed attempt to remove the + // wake handler. It is not safe to remove the wake event without + // it being marked for removal by register_wait. + if ((m_numEvents == 1) && (m_waitHandles[0]->handler == nullptr)) + { + CloseHandle(m_hEvents[0]); + m_hEvents[0] = NULL; // For debugging + m_numEvents--; + } + + m_numWaiting = m_numEvents; + } + + +private: + + // Array of handles that is being waited on + HANDLE m_hEvents[MAXIMUM_WAIT_OBJECTS]{}; + + // The handlers corresponding to the event array (matching index) + WAITER_DATA * m_waitHandles[MAXIMUM_WAIT_OBJECTS]; + + // All the handles (including ones that are removed/not yet added etc). + WAITER_DATA m_eventData[MAXIMUM_WAIT_OBJECTS]{}; + + // Total number of events including the ones that are not yet waited upon + DWORD m_numEvents; + + // The number of events that are being waited on + DWORD m_numWaiting; + + // The number of pending remove requests + volatile long m_pendingRemove; + + // Lock for insertion and deletion of handles + _NonReentrantBlockingLock m_lock; +}; + +/// +/// Manages all the waiter threads. A waiter thread can only handle upto +/// MAXIMUM_WAIT_OBJECTS events. This class maintains multiple such waiter threads +/// +class WaiterThreadPool +{ +public: + + WaiterThreadPool() : m_waiter(nullptr) + { + } + + /// + /// Destructor + /// + ~WaiterThreadPool() + { + if (m_waiter != nullptr) + { + m_waiter->stop(); + } + } + + /// + /// Creates an event handler if required and registers a waiter for the given event in that handler + /// instance + /// + HANDLE add_waiter(HANDLE hSource, WAITORTIMERCALLBACK callback, PVOID context) + { + HANDLE hEvent; + if (!DuplicateHandle(GetCurrentProcess(), + hSource, + GetCurrentProcess(), + &hEvent, + 0, + FALSE, + DUPLICATE_SAME_ACCESS)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + HANDLE hWait = nullptr; + WaiterThread * newWaiter = nullptr; + { + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + // Get the event handler + if ((m_waiter == nullptr) || (!m_waiter->is_available())) + { + if (m_waiter != nullptr) + { + m_waiter->stop(); + m_waiter = nullptr; + } + + m_waiter = new WaiterThread(); + newWaiter = m_waiter; + } + + // Add the wait event under the lock + hWait = m_waiter->add_handle(hEvent, callback, context); + } + + // Start the handler after we release the lock + if (newWaiter != nullptr) + { + newWaiter->start(); + } + + return hWait; + } + +private: + + WaiterThread * m_waiter; + _NonReentrantBlockingLock m_lock; +}; + +// Maintains a default global waiter threadpool instance +// which will be released on process exit +static WaiterThreadPool * s_waiterPool = nullptr; +class DefaultWaiterPool +{ +public: + DefaultWaiterPool() + { + } + + ~DefaultWaiterPool() + { + if (s_waiterPool != nullptr) + { + delete s_waiterPool; + s_waiterPool = nullptr; + } + } + + static WaiterThreadPool * get_waiter() + { + #pragma warning(suppress: 28112) // False positive warning, VSO-1807048 + if (s_waiterPool == nullptr) + { + // Allocate on demand + auto waiterPool = new WaiterThreadPool; + if (_InterlockedCompareExchangePointer((volatile PVOID *)&s_waiterPool, waiterPool, nullptr) != nullptr) + { + delete waiterPool; + } + } + + #pragma warning(suppress: 28112) // False positive warning, VSO-1807048 + return s_waiterPool; + } +}; + +static DefaultWaiterPool s_defaultWaiterPool; + +HANDLE __RegisterWaitForSingleObject(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context) +{ + HANDLE hWait; +#if defined(_ONECORE) + auto waiterPool = DefaultWaiterPool::get_waiter(); + hWait = waiterPool->add_waiter(hEvent, callback, context); +#else // !(_ONECORE) + // Request a thread pool thread to wait for this thread exit. + if (!RegisterWaitForSingleObject(&hWait, + hEvent, + callback, + context, INFINITE, (WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } +#endif // !(_ONECORE) + return hWait; +} + +void __UnregisterWait(HANDLE hWait) +{ +#if defined(_ONECORE) + WaiterThread::remove_handle(hWait); +#else + // Ignore both pseudo-failure (when a callback is already running) and real failure + // (as this is called by ExternalContextBase::ImplicitDetachHandlerXP() which cannot report failure). + (void) UnregisterWait(hWait); +#endif // !(_ONECORE) +} + +}}} // namespace Concurrency::details::platform + +#pragma warning (pop) diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.h new file mode 100644 index 0000000000000000000000000000000000000000..cbc7e4362fcb3b336c54fe435f8f5850934ca885 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.h @@ -0,0 +1,206 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Platform.h : abstracts the underlying platform APIs +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +// Windows headers that we need + +#include +#include +#include + +#include + +#undef Yield // The windows headers #define Yield, a name we want to use + +#include +#include +#include + +namespace Concurrency { namespace details { namespace platform { + +/****************** Events ***************************/ + +/// +/// Creates an auto reset event +/// +HANDLE __CreateAutoResetEvent(bool initialSet = false); + +/// +/// Creates a manual reset event +/// +HANDLE __CreateManualResetEvent(bool initialSet = false); + +/************** Tickcount ***************************/ + +/// +/// Gets the current tick count +/// +ULONGLONG __GetTickCount64(); + +/************** Windows critical section ***************************/ + +/// +/// Initializes the critical section +/// +BOOL __InitializeCriticalSectionEx(CRITICAL_SECTION * cs, DWORD spinCount); + +/************** Thread Local Storage *****************************/ + +/// +/// Allocates a TLS slot +/// +DWORD __TlsAlloc(); + +/// +/// Frees a TLS slot +/// +void __TlsFree(DWORD index); + +/// +/// Gets the value stored in the specified TLS slot +/// +PVOID __TlsGetValue(DWORD index); + +/// +/// Stores a value in the specified TLS slot +/// +void __TlsSetValue(DWORD index, PVOID value); + +/************** Thread Priority ***************************/ + +/// +/// Sets the thread priority +/// +void __SetThreadPriority(HANDLE hThread, int priority); + +/// +/// Retrieves the thread priority +/// +int __GetThreadPriority(HANDLE hThread); + +/************** Thread Affinity ***************************/ + +/// +/// Retrieves the thread group affinity +/// +BOOL __GetThreadGroupAffinity(HANDLE hThread, PGROUP_AFFINITY affinity); + +/// +/// Sets the thread group affinity +/// +BOOL __SetThreadGroupAffinity(HANDLE hThread, const GROUP_AFFINITY * affinity); + +/************** Thread yield ***************************/ + +/// +/// Yield execution to another ready thread +/// +void __SwitchToThread(); + +/// +/// Yield execution to another ready thread (ms is assumed to be 0 or 1) +/// +void __Sleep(DWORD ms); + +/************ Thread *********************************************/ +/// +/// Creates a thread +/// +HANDLE __CreateThread(LPSECURITY_ATTRIBUTES lpAttributes, + size_t stackSize, + LPTHREAD_START_ROUTINE startAddress, + LPVOID param, + DWORD flags, + LPDWORD threadId); + +/// +/// Releases the thread handle +/// +void __CloseThreadHandle(HANDLE hThread); + +/// +/// Waits for the thread to exit +/// +DWORD __WaitForThread(HANDLE hThread, DWORD timeout); + +/// +/// Signals hSignal object and waits for hWait. Returns the reason for returning from wait +/// +DWORD __SignalObjectAndWait(HANDLE hSignal, HANDLE hWait, DWORD ms, BOOL alertable); + +/************ Timer *********************************************/ +/// +/// Creates a timer +/// +BOOL __CreateTimerQueueTimer( + PHANDLE phNewTimer, + HANDLE timerQueue, + WAITORTIMERCALLBACK lpStartAddress, + PVOID lpParameter, + DWORD dueTime, + DWORD period, + ULONG flags +); + +/// +/// Deletes the timer +/// +void __DeleteTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, HANDLE completionEvent); + +/// +/// Changes the due time of the timer. +/// +BOOL __ChangeTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, ULONG dueTime, ULONG period); + +/************** RegisterWaitForsingleObject ***********/ + +/// +/// Registers a waiter for the given handle. The callback is invoked when the handle is signalled +/// +HANDLE __RegisterWaitForSingleObject(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context); + +/// +/// Removes the waiter for the given handle. Pending callbacks are cancelled. If a callback is +/// already running then this will NOT wait for the callback to complete. +/// +void __UnregisterWait(HANDLE hWait); + +/************** System Info ***************************/ + +/// +/// Retrieves the information about the relationships of logical processors and related hardware +/// +PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX __GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relation, PDWORD retLength); + +/// +/// Retrieves the information about logical processors and related hardware +/// +/// Retrieves the processor group and number of the logical processor where the thread is running +/// +void __GetCurrentProcessorNumberEx(PPROCESSOR_NUMBER procNum); + +/// +/// Returns the highest numa node number +/// +ULONG __GetNumaHighestNodeNumber(); + +/// +/// Returns current thread ID +/// +#if defined(_CRTBLD) && !defined(CRTDLL2) +_CONCRTIMP +#endif +long __cdecl GetCurrentThreadId(); + +}}} // namespace Concurrency::details::platform diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f7d3b054d0c75594fb0857da9ba333700682114 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.cpp @@ -0,0 +1,28 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// RealizedChore.cpp +// +// Miscellaneous implementations of things related to realized chores +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ + /// + /// Method that executes the realized chore. Not inline-able because debugger needs to + /// locate executing realized chores by looking for this method's signature in the call + /// frame. + /// + __declspec(noinline) + void RealizedChore::Invoke() + { + m_pFunction(m_pParameters); + } +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.h new file mode 100644 index 0000000000000000000000000000000000000000..0f222e01f0c1a2e93ec12de6027addc19022f199 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.h @@ -0,0 +1,73 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// RealizedChore.h +// +// Header file containing the realized chore type declaration. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + + /// + /// The class RealizedChore is used to implement light-weight tasks and Agents. + /// + + class RealizedChore : public _Chore + { + + public: + + /// + /// Constructor. + /// + RealizedChore(TaskProc pFunction, void* pParameters) + { + Initialize(pFunction, pParameters); + } + + /// + /// Initializes a realized chore, on construction and reuse. + /// + void Initialize(TaskProc pFunction, void* pParameters) + { + m_pFunction = pFunction; + m_pParameters = pParameters; + m_pNext = NULL; + } + + /// + /// Method that executes the realized chore. + /// + __declspec(noinline) + void Invoke(); + + private: + template friend class SQueue; + template friend class LockFreeStack; + + // Parameter to the chore procedure. + void *m_pParameters; + +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + union + { + // Next pointer for the locked runnables queue. + RealizedChore *m_pNext; + + // List entry for lock free slist (free pool) + SLIST_ENTRY m_slNext; + }; +#pragma warning(pop) + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0114fb3b852b0f36f2750c7500f8e98c6bf78a41 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.cpp @@ -0,0 +1,4654 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ResourceManager.cpp +// +// Implementation of IResourceManager. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include +#include +#include + +#pragma warning(push) +#pragma warning(disable : 4702) +#pragma warning(disable : 4100) + +namespace Concurrency +{ + /// + /// Returns the OS version. + /// + _CONCRTIMP IResourceManager::OSVersion __cdecl GetOSVersion() + { + return ::Concurrency::details::ResourceManager::Version(); + } + + /// + /// Returns an interface that represents the singleton resource manager instance. The API references the + /// resource manager, and must be matched by a call to IResourceManager::Release(), when the caller is done. + /// + _CONCRTIMP IResourceManager* __cdecl CreateResourceManager() + { + return ::Concurrency::details::ResourceManager::CreateSingleton(); + } + + /// + /// The number of hardware threads on the underlying machine is returned here. + /// + _CONCRTIMP unsigned int __cdecl GetProcessorCount() + { + return ::Concurrency::details::ResourceManager::GetCoreCount(); + } + + /// + /// The number of NUMA nodes or processor packages on the underlying machine is returned here. + /// If the processor contains more NUMA nodes than processor packages, the number of NUMA nodes + /// is returned, otherwise the number of packages is returned. + /// + _CONCRTIMP unsigned int __cdecl GetProcessorNodeCount() + { + return ::Concurrency::details::ResourceManager::GetNodeCount(); + } + + /// + /// Returns an identifier for a scheduler. Before calling an API with an IScheduler interface as a parameter, + /// an identifier must be obtained for the scheduler using this API. + /// + _CONCRTIMP unsigned int __cdecl GetSchedulerId() + { + return ::Concurrency::details::ResourceManager::GetSchedulerId(); + } + + /// + /// Returns an identifier for an execution context. Before calling an API with an IExecutionContext interface as a parameter, + /// an identifier must be obtained for the execution context using this API. + /// + _CONCRTIMP unsigned int __cdecl GetExecutionContextId() + { + return ::Concurrency::details::ResourceManager::GetExecutionContextId(); + } + + /// + /// Restricts the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified. + /// It is only valid to call this method before the Resource Manager has been created, or between two Resource Manager lifetimes. + /// It may be invoked multiple times as long as the Resource Manager does not exist at the time of invocation. Once an affinity limit + /// has been set, it remains in effect until the next valid call to the set_task_execution_resources method. + /// The affinity mask provided need not be a subset of the process affinity mask. The process affinity will be updated if necessary. + /// + /// + /// The affinity mask that the Concurrency Runtime's worker threads are to be restricted to. Use this method on a system with greater than 64 + /// hardware threads only if you want to limit the Concurrency Runtime to a subset of the current processor group. In general, you should + /// use the version of the method that accepts an array of group affinities as a parameter to restrict affinity on machines with greater + /// than 64 hardware threads. + /// + /// + /// The method will throw an invalid_operation exception if a Resource Manager is present at + /// the time it is invoked, and an invalid_argument exception if the affinity specified results in an empty set of resources. + /// The version of the method that takes an array of group affinities as a parameter should only be used on operating systems with version + /// Windows 7 or higher. Otherwise, an invalid_operation exception is thrown. + /// Programmatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate + /// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method. + /// + /**/ + _CONCRTIMP void __cdecl set_task_execution_resources(DWORD_PTR dwProcessAffinityMask) + { + // This API should not be called by modern APPs + ENSURE_NOT_APP(); + ::Concurrency::details::ResourceManager::SetTaskExecutionResources(dwProcessAffinityMask); + } + + /// + /// Restricts the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified. + /// It is only valid to call this method before the Resource Manager has been created, or between two Resource Manager lifetimes. + /// It may be invoked multiple times as long as the Resource Manager does not exist at the time of invocation. Once an affinity limit + /// has been set, it remains in effect until the next valid call to the set_task_execution_resources method. + /// The affinity mask provided need not be a subset of the process affinity mask. The process affinity will be updated if necessary. + /// + /// + /// The number of GROUP_AFFINITY entries in the array specified by the parameter . + /// + /// + /// An array of GROUP_AFFINITY entries. + /// + /// + /// The method will throw an invalid_operation exception if a Resource Manager is present at + /// the time it is invoked, and an invalid_argument exception if the affinity specified results in an empty set of resources. + /// The version of the method that takes an array of group affinities as a parameter should only be used on operating systems with version + /// Windows 7 or higher. Otherwise, an invalid_operation exception is thrown. + /// Programmatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate + /// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method. + /// + /**/ + _CONCRTIMP void __cdecl set_task_execution_resources(USHORT count, PGROUP_AFFINITY pGroupAffinity) + { + // This API should not be called by modern APPs + ENSURE_NOT_APP(); + ::Concurrency::details::ResourceManager::SetTaskExecutionResources(count, pGroupAffinity); + } +} + +namespace Concurrency +{ +namespace details +{ + // Static counters to generate unique identifiers. + volatile LONG ResourceManager::s_schedulerIdCount = -1L; + volatile LONG ResourceManager::s_executionContextIdCount = -1L; + volatile LONG ResourceManager::s_threadProxyIdCount = -1L; + + // Operating system characteristics. + unsigned int ResourceManager::s_coreCount = 0; + unsigned int ResourceManager::s_nodeCount = 0; + + DWORD_PTR ResourceManager::s_processAffinityMask = 0; + DWORD_PTR ResourceManager::s_systemAffinityMask = 0; + + ResourceManager::AffinityRestriction * ResourceManager::s_pUserAffinityRestriction = NULL; + ResourceManager::AffinityRestriction * ResourceManager::s_pProcessAffinityRestriction = NULL; + + IResourceManager::OSVersion ResourceManager::s_version = IResourceManager::UnsupportedOS; + ResourceManager *ResourceManager::s_pResourceManager = NULL; + + // Variables used to obtain information about the topology of the system. + DWORD ResourceManager::s_logicalProcessorInformationLength = 0; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ResourceManager::s_pSysInfo = NULL; + + /// + /// Constructs a hardware affinity from a given thread. + /// + HardwareAffinity::HardwareAffinity(HANDLE hThread) + { + memset(&m_affinity, 0, sizeof(m_affinity)); + platform::__GetThreadGroupAffinity(hThread, &m_affinity); + } + + /// + /// Applies this hardware affinity to a thread. + /// + /// + /// The thread handle to which to apply this affinity. + /// + void HardwareAffinity::ApplyTo(HANDLE hThread) + { + platform::__SetThreadGroupAffinity(hThread, &m_affinity); + } + + /// + /// Returns the OS version. + /// + IResourceManager::OSVersion ResourceManager::Version() + { + if (s_version == ::Concurrency::IResourceManager::UnsupportedOS) + { + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_version == ::Concurrency::IResourceManager::UnsupportedOS) + { + RetrieveSystemVersionInformation(); + } + } // end locked region + } + return s_version; + } + + /// + /// Returns the number of nodes (processor packages or NUMA nodes, whichever is greater) + /// + unsigned int ResourceManager::GetNodeCount() + { + if (s_nodeCount == 0) + { + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_nodeCount == 0) + { + InitializeSystemInformation(); + } + } // end locked region + } + return s_nodeCount; + } + + /// + /// Returns the number of cores. + /// + unsigned int ResourceManager::GetCoreCount() + { + if (s_coreCount == 0) + { + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_coreCount == 0) + { + InitializeSystemInformation(); + } + } // end locked region + } + return s_coreCount; + } + + /// + /// Returns the current thread's node id and core id (relative to that node). + /// + unsigned int ResourceManager::GetCurrentNodeAndCore(unsigned int * pCore) + { +#if defined(_ONECORE) + // MSDK does not provide an API to determine the current node and core information + // For MSDK we assume a single node + if (pCore != NULL) + { + *pCore = 0; + } + return 0; +#else // ^^^ defined(_ONECORE) ^^^ // vvv !defined(_ONECORE) vvv + // For Win7 or later, we can use a simple function + PROCESSOR_NUMBER procNum; + platform::__GetCurrentProcessorNumberEx(&procNum); + DWORD processorNumber = procNum.Number; +#ifndef _WIN64 + processorNumber &= 31; // Map CPUs too high to reference on WOW64 down +#endif // _WIN64 + + ULONG_PTR processorAffinity = static_cast(1) << processorNumber; + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; nodeIndex++) + { + GlobalNode * pNode = &m_pGlobalNodes[nodeIndex]; + if ((pNode->m_processorGroup == procNum.Group) && ((pNode->m_nodeAffinity & processorAffinity) != 0)) + { + for (unsigned int coreIndex = 0; coreIndex < pNode->m_coreCount; coreIndex++) + { + if (pNode->m_pCores[coreIndex].m_processorNumber == processorNumber) + { + if (pCore != nullptr) + { + *pCore = coreIndex; + } + return nodeIndex; + } + } + } + } + + ASSERT(UNREACHED); + return 0; +#endif // defined(_ONECORE) + } + + /// + /// Creates the static singleton instance of the Resource Manager. + /// + ResourceManager* ResourceManager::CreateSingleton() + { + ResourceManager *pRM = NULL; + + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_pResourceManager == NULL) + { + pRM = _concrt_new ResourceManager(); + pRM->Reference(); + s_pResourceManager = (ResourceManager*) Security::EncodePointer(pRM); + } + else + { + pRM = (ResourceManager*) Security::DecodePointer(s_pResourceManager); + if ( !pRM->SafeReference()) + { + // pRM has refcnt=0 and will be deleted as soon as the lock is released + pRM = _concrt_new ResourceManager(); + pRM->Reference(); + s_pResourceManager = (ResourceManager*) Security::EncodePointer(pRM); + } + } + } // end locked region + + return pRM; + } + + /// + /// Constructs the resource manager. + /// + ResourceManager::ResourceManager() + : m_referenceCount(0L) + , m_numSchedulers(0) + , m_maxSchedulers(16) + , m_numSchedulersNeedingNotifications(0) + , m_allocationRound(0) + , m_dynamicRMWorkerState(Standby) + , m_pGlobalNodes(NULL) + , m_hDynamicRMThreadHandle(NULL) + , m_hDynamicRMEvent(NULL) + , m_ppProxyData(NULL) + , m_ppGivingProxies(NULL) + , m_ppReceivingProxies(NULL) + { + // Initialize static information about the system asking for the topology information to be saved + // so we can use it right after. + InitializeSystemInformation(true); + DetermineTopology(); + + m_pPageVirtualProtect = NULL; + + // The dynamic RM thread is not created up front. It is created when the number of schedulers go from 1 to 2 + // In addition, once it is created, it is placed on standby if the number of schedulers goes down to 1 again. + // The event is created here, since it could be signaled even before the thread is created. + // Auto reset event that is not signalled initially + m_hDynamicRMEvent = platform::__CreateAutoResetEvent(); + + // Allocate common memory used for static and dynamic allocation. Buffers specific to dynamic core migration + // are only allocated when the DRM thread is started up. + m_ppProxyData = _concrt_new AllocationData * [m_maxSchedulers]; + +#if defined(CONCRT_TRACING) + // Assumes a m x n allocation. + m_numTotalCores = m_nodeCount * m_pGlobalNodes[0].m_coreCount; + m_drmInitialState = _concrt_new GlobalCoreData[m_numTotalCores]; + memset(m_drmInitialState, 0, sizeof(GlobalCoreData) * m_numTotalCores); + + // Maintains a trace for every core removed during preprocessing. + memset(m_preProcessTraces, 0, sizeof(PreProcessingTraceData) * 100); + m_preProcessTraceIndex = 0; + + // Maintains a trace for each core allocation or assignment. + memset(m_dynAllocationTraces, 0, sizeof(DynamicAllocationTraceData) * 100); + m_dynAllocationTraceIndex = 0; +#endif + } + + /// + /// This API is called by the dynamic RM worker thread when it starts up, and right after its state changed to + /// LoadBalance after being on Standby for a while. We need to find the existing schedulers, and discard the + /// statistics they have collected so far if any. Either we've never collected statistics for this scheduler before, + /// or too much/too little time has passed since we last collected statistics, and this information cannot be trusted. + /// + void ResourceManager::DiscardExistingSchedulerStatistics() + { + // NOTE: This routine must be called while holding m_lock. + ASSERT(m_numSchedulers > 1); + ASSERT(m_dynamicRMWorkerState == LoadBalance); + + SchedulerProxy * pSchedulerProxy = NULL; + + for (pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + // Initialize variables needed for statistics. + unsigned int taskCompletionRate = 0, taskArrivalRate = 0; + + // Get the stored scheduler queue length. + unsigned int numberOfTasksEnqueued = pSchedulerProxy->GetQueueLength(); + + // Collect statistical information about this scheduler. + pSchedulerProxy->Scheduler()->Statistics(&taskCompletionRate, &taskArrivalRate, &numberOfTasksEnqueued); + + // Update the queue length using the number computed by the statistics. + pSchedulerProxy->SetQueueLength(numberOfTasksEnqueued); + } + } + + /// + /// Restricts the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified. + /// + /// + /// The affinity mask that the Concurrency Runtime's worker threads are to be restricted to. Use this method on a system with greater than 64 + /// hardware threads only if you want to limit the Concurrency Runtime to a subset of the current processor group. In general, you should + /// use the version of the method that accepts an array of group affinities as a parameter to restrict affinity on machines with greater + /// than 64 hardware threads. + /// + /// + /// The method will throw an invalid_operation exception if a Resource Manager is present at + /// the time it is invoked, and an invalid_argument exception if the affinity specified results in an empty set of resources. + /// The version of the method that takes an array of group affinities as a parameter should only be used on operating systems with version + /// Windows 7 or higher. Otherwise, an invalid_operation exception is thrown. + /// Programmatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate + /// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method. + /// + /**/ + void ResourceManager::SetTaskExecutionResources(DWORD_PTR dwAffinityMask) + { +#if defined(_ONECORE) + // This API should not be called by modern APPs + ENSURE_NOT_APP(); +#else + // This API can be invoked on all operating systems supported by ConcRT. On a multigroup machine, we will take + // the affinity to be the affinity of the process for the current group. + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_pResourceManager != NULL) + { + // It is invalid to call the API if the RM is already in existence. + throw invalid_operation(); + } + + if (s_version == ::Concurrency::IResourceManager::UnsupportedOS) + { + RetrieveSystemVersionInformation(); + } + + // Get the current thread affinity which will populate the group correctly on a machine with multiple groups. + HardwareAffinity currentThreadAffinity(GetCurrentThread()); + + // Use the correct group number and the provided user affinity to construct an affinity that the RM should restrict itself + // to. Note that on operating systems that do not support multiple groups, the group is set to 0 by default. + HardwareAffinity * pAffinity = _concrt_new HardwareAffinity(currentThreadAffinity.GetGroup(), dwAffinityMask); + + CaptureProcessAffinity(); + + pAffinity->IntersectWith(s_systemAffinityMask); + + if (pAffinity->GetMask() == (KAFFINITY)0) + { + throw std::invalid_argument("dwAffinityMask"); + } + // Check if the provided affinity is outside the process affinity mask. If so, adjust the process affinity. + if ((pAffinity->GetMask() & (~s_processAffinityMask)) != 0) + { + SetProcessAffinityMask(GetCurrentProcess(), (pAffinity->GetMask() | s_processAffinityMask)); + } + + // We have a valid affinity restriction. Delete any existing restriction structure if it is present. + delete s_pUserAffinityRestriction; + s_pUserAffinityRestriction = _concrt_new AffinityRestriction(1, pAffinity); + + // We don't need the process affinity anymore. + delete s_pProcessAffinityRestriction; + s_pProcessAffinityRestriction = NULL; + } // end locked region + +#endif // defined(_ONECORE) + } + + /// + /// Restricts the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified. + /// + /// + /// The number of GROUP_AFFINITY entries in the array specified by the parameter . + /// + /// + /// An array of GROUP_AFFINITY entries. + /// + /// + /// The method will throw an invalid_operation exception if a Resource Manager is present at + /// the time it is invoked, and an invalid_argument exception if the affinity specified results in an empty set of resources. + /// Programmatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate + /// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method. + /// + void ResourceManager::SetTaskExecutionResources(USHORT count, PGROUP_AFFINITY pGroupAffinity) + { +#if defined(_ONECORE) + // This API should not be called by modern APPs + ENSURE_NOT_APP(); +#else + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (s_pResourceManager != NULL) + { + throw invalid_operation(); + } + + if (s_version == ::Concurrency::IResourceManager::UnsupportedOS) + { + RetrieveSystemVersionInformation(); + } + + if (count == 0) + { + throw std::invalid_argument("count"); + } + + if (pGroupAffinity == NULL) + { + throw std::invalid_argument("pGroupAffinity"); + } + + HardwareAffinity * pAffinity = _concrt_new HardwareAffinity[count]; + for (int i = 0; i < count; ++i) + { + pAffinity[i] = HardwareAffinity(pGroupAffinity[i].Group, pGroupAffinity[i].Mask); + } + + // Sort by the group number -> lowest first selection sort. Duplicates are invalid. + for (unsigned int i = 0; i < count; ++i) + { + unsigned int minIndex = i; + for (unsigned int j = i + 1; j < count; ++j) + { + if (pAffinity[j].GetGroup() == pAffinity[minIndex].GetGroup()) + { + throw std::invalid_argument("pGroupAffinity"); + } + else if (pAffinity[j].GetGroup() < pAffinity[minIndex].GetGroup()) + { + minIndex = j; + } + } + if (i != minIndex) + { + HardwareAffinity tempAffinity = pAffinity[i]; + pAffinity[i] = pAffinity[minIndex]; + pAffinity[minIndex] = tempAffinity; + } + } + + // There is no need to capture process affinity, since we will override process affinity, if necessary. There is no need to + // modify the process affinity if the user supplied affinity doesn't intersect with it, as we do in the case of Vista, since + // the APIs we use to set thread affinity on Win7 and higher are able to override process affinity themselves. + // Ensure that the passed in affinity is a subset of what is available on the system. + GetTopologyInformation(RelationGroup); + // Cast this buffer as a PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, which is needed for GetLogicalProcessorInformationEx + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pSysInfoEx = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) s_pSysInfo; + + ASSERT(pSysInfoEx->Relationship == RelationGroup); + PGROUP_RELATIONSHIP pGroupRelationship = (PGROUP_RELATIONSHIP) &(pSysInfoEx->Group); + if (count > pGroupRelationship->ActiveGroupCount) + { + throw std::invalid_argument("count"); + } + + // This variable is used to check if the overall affinity is 0 and we throw an error if it is. + KAFFINITY mergedAffinity = 0; + + // Go through the groups listed and ensure that the affinity requested by the user is a subset of the affinity offered by the system. + // 'i' iterates through the array of groups provided by the user whereas 'j' iterates through the array of groups we obtained from the system. + for (unsigned short i = 0, j = 0; i < count; ++i) + { + // Increment through the system group array until we find a group that matches the next one in the user provided array. + while (j < pAffinity[i].GetGroup() && j < pGroupRelationship->ActiveGroupCount) + { + ++j; + } + if (j == pGroupRelationship->ActiveGroupCount) + { + // The user has specified an invalid group number. + throw std::invalid_argument("pGroupAffinity"); + } + ASSERT(j == pAffinity[i].GetGroup()); + pAffinity[i].IntersectWith(pGroupRelationship->GroupInfo[j].ActiveProcessorMask); + mergedAffinity |= pAffinity[i].GetMask(); + } + + if (mergedAffinity == 0) + { + // The user has a mask that results in 0 processors being assigned to the RM. + throw std::invalid_argument("pGroupAffinity"); + } + + CleanupTopologyInformation(); + + // We have a valid affinity restriction. Delete any existing restriction structure if it is present. + delete s_pUserAffinityRestriction; + s_pUserAffinityRestriction = _concrt_new AffinityRestriction(count, pAffinity); + + } // end locked region + +#endif // defined(_ONECORE) + } + + /// + /// Creates the dynamic RM worker thread and allocates memory for its use. The worker thread wakes up at + /// fixed intervals and load balances resources among schedulers, until it it put on standby. + /// + void ResourceManager::CreateDynamicRMWorker() + { + // MSDK compliant applications are not allowed to create multiple schedulers. + // We do not need the dynamic RM worker for a single scheduler. + ENSURE_NOT_APP(); + + // NOTE: This routine is called *without* holding m_lock. + // Set up a background thread for dynamic RM. + m_hDynamicRMThreadHandle = LoadLibraryAndCreateThread(NULL, + DEFAULTCONTEXTSTACKSIZE, + DynamicRMThreadProc, + this, + 0, + NULL); + + if (m_hDynamicRMThreadHandle == NULL) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + // Make sure the background thread is running at the highest priority. + platform::__SetThreadPriority(m_hDynamicRMThreadHandle, THREAD_PRIORITY_TIME_CRITICAL); + } + + /// + /// Initializes static variables related to the operating system version. + /// + void ResourceManager::RetrieveSystemVersionInformation() + { + // This implementation assumes that the target OS is Windows 10 or later. Win8OrLater is the highest enumerator. + s_version = ::Concurrency::IResourceManager::Win8OrLater; + + // Initialize other information based on the OS version + WinRT::Initialize(); + } + + /// + /// Captures the process affinity if it is not equal to the system affinity. + /// + void ResourceManager::CaptureProcessAffinity() + { +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + if (!GetProcessAffinityMask(GetCurrentProcess(), &s_processAffinityMask, &s_systemAffinityMask)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + // Check if the system affinity is different from the process affinity. + if (s_processAffinityMask != s_systemAffinityMask) + { + // On a multigroup machine, a process is assigned to one group by default, and the system and process affinity reflect the + // affinity of the system/process within that group. If the process affinity is different from the system affinity for a + // multigroup machine, we will limit this process to the process affinity in the current group. + HardwareAffinity currentThreadAffinity(GetCurrentThread()); + HardwareAffinity * pCurrentProcessAffinity = _concrt_new HardwareAffinity(currentThreadAffinity.GetGroup(), s_processAffinityMask); + ASSERT(s_pProcessAffinityRestriction == NULL); + s_pProcessAffinityRestriction = _concrt_new AffinityRestriction(1, pCurrentProcessAffinity); + } +#endif // defined(_ONECORE) + } + + /// + /// Modify the passed in affinity based on any user or process affinity restrictions. + /// + void ResourceManager::ApplyAffinityRestrictions(PGROUP_AFFINITY pGroupAffinity) + { +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + ASSERT(s_pProcessAffinityRestriction == NULL || s_pUserAffinityRestriction == NULL); + if (pGroupAffinity->Mask != 0) + { + if (s_pProcessAffinityRestriction != NULL) + { + s_pProcessAffinityRestriction->ApplyAffinityLimits(pGroupAffinity); + } + else if (s_pUserAffinityRestriction != NULL) + { + s_pUserAffinityRestriction->ApplyAffinityLimits(pGroupAffinity); + } + } +#endif // defined(_ONECORE) + } + + /// + /// Modify the passed in affinity based on any user or process affinity restrictions. + /// + void ResourceManager::ApplyAffinityRestrictions(PULONG_PTR pProcessorMask) + { +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + GROUP_AFFINITY groupAffinity = {0}; + groupAffinity.Group = 0; + groupAffinity.Mask = *pProcessorMask; + + ApplyAffinityRestrictions(&groupAffinity); + + *pProcessorMask = groupAffinity.Mask; +#endif // defined(_ONECORE) + } + + /// + /// Retrieves a buffer from the operating system that contains topology information. + /// + void ResourceManager::GetTopologyInformation(LOGICAL_PROCESSOR_RELATIONSHIP relationship) + { +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + ASSERT(s_version != ::Concurrency::IResourceManager::UnsupportedOS); + + s_pSysInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION) platform::__GetLogicalProcessorInformationEx(relationship, &s_logicalProcessorInformationLength); +#endif // defined(_ONECORE) + } + + /// + /// Cleans up the variables that store operating system topology information. + /// + void ResourceManager::CleanupTopologyInformation() + { +#if defined(_ONECORE) + ENSURE_NOT_APP(); +#else + free(s_pSysInfo); + s_pSysInfo = NULL; + s_logicalProcessorInformationLength = 0; + +#endif // defined(_ONECORE) + } + + /// + /// Initializes static information related to the operating system and machine topology. + /// + void ResourceManager::InitializeSystemInformation(bool fSaveTopologyInfo) + { + if (s_version == ::Concurrency::IResourceManager::UnsupportedOS) + { + RetrieveSystemVersionInformation(); + } + + ASSERT(s_version != ::Concurrency::IResourceManager::UnsupportedOS); + ASSERT(s_pSysInfo == NULL); + +#if defined(_ONECORE) + SYSTEM_INFO sysInfo; + GetNativeSystemInfo(&sysInfo); + + // These static variables should be updated exactly once, so that concurrent reads do not see intermediate values. + s_nodeCount = 1; + s_coreCount = sysInfo.dwNumberOfProcessors; +#else + // If the user specified an affinity restriction, use it. If not, we should ensure that + // the RM will adhere to the process affinity. + if (s_pUserAffinityRestriction == NULL) + { + CaptureProcessAffinity(); + } + + { + // Retrieve topology related information. This populates s_pSysInfo and s_logicalProcessorInformationLength, using the correct + // API, based on the operating system version. + GetTopologyInformation(RelationAll); + + unsigned int groupCountInNumaNodes = 0; + unsigned int coreCount = 0; + + // Traverse the processor information buffer to find s_nodeCount and s_coreCount. + // We will create one scheduling node per processor group in NUMA nodes. + // (Note that the number of processor groups in NUMA nodes isn't necessarily + // the same as the number of processor groups in processor packages. + // Here, we use the processor groups in NUMA nodes because that + // makes it easy to associate each group to a NUMA node number.) + + // In addition to traversing the buffer and calculating the number of nodes, modify the buffer to reflect the affinity + // limitations either due to process affinity restrictions or because the user has specified a limited affinity. + ASSERT(s_logicalProcessorInformationLength > 0); + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pSysInfoEx; + for (auto raw = reinterpret_cast(s_pSysInfo), end = raw + s_logicalProcessorInformationLength; + raw < end; raw += pSysInfoEx->Size) + { + pSysInfoEx = reinterpret_cast(raw); + switch (pSysInfoEx->Relationship) + { + case RelationProcessorPackage: + for (WORD index = 0; index < pSysInfoEx->Processor.GroupCount; ++index) + { + PGROUP_AFFINITY pGroupAffinity = &pSysInfoEx->Processor.GroupMask[index]; + ApplyAffinityRestrictions(pGroupAffinity); + } + break; + case RelationNumaNode: + { + // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-numa_node_relationship + // GroupCount + // The number of groups included in the GroupMasks array. + // This field was introduced in Windows 20H2. + // On earlier versions, this value is always 0. + const WORD rawGroupCount = pSysInfoEx->NumaNode.GroupCount; + const WORD totalGroupCount = rawGroupCount == 0 ? 1 : rawGroupCount; + for (WORD index = 0; index < totalGroupCount; ++index) + { + PGROUP_AFFINITY pGroupAffinity = &pSysInfoEx->NumaNode.GroupMasks[index]; + ApplyAffinityRestrictions(pGroupAffinity); + if (pGroupAffinity->Mask != 0) + { + ++groupCountInNumaNodes; + } + } + } + break; + case RelationProcessorCore: + { + PGROUP_AFFINITY pGroupAffinity = &pSysInfoEx->Processor.GroupMask[0]; + ApplyAffinityRestrictions(pGroupAffinity); + coreCount += NumberOfBitsSet(pGroupAffinity->Mask); + } + break; + } + } + + ASSERT(groupCountInNumaNodes > 0); + ASSERT(coreCount > 0); + + // These static variables should be updated exactly once, so that concurrent reads do not see intermediate values. + s_nodeCount = groupCountInNumaNodes; + s_coreCount = coreCount; + + if (!fSaveTopologyInfo) + { + CleanupTopologyInformation(); + } + } + + delete s_pProcessAffinityRestriction; + s_pProcessAffinityRestriction = NULL; + +#endif // defined(_ONECORE) + + ASSERT(s_coreCount > 0 && s_coreCount <= USHORT_MAX); + } + + /// + /// Creates a structure of nodes and cores based on the machine topology. + /// + void ResourceManager::DetermineTopology() + { + ASSERT(m_pGlobalNodes == NULL); + ASSERT(s_nodeCount > 0 && s_nodeCount <= INT_MAX); + + m_nodeCount = s_nodeCount; + m_coreCount = s_coreCount; + + m_pGlobalNodes = _concrt_new GlobalNode[m_nodeCount]; + memset(m_pGlobalNodes, 0, m_nodeCount * sizeof(GlobalNode)); + +#if defined(_ONECORE) + SYSTEM_INFO sysInfo; + GetNativeSystemInfo(&sysInfo); + ULONG_PTR affinityMask = (s_pUserAffinityRestriction != NULL) ? s_pUserAffinityRestriction->FindGroupAffinity(0)->GetMask() : sysInfo.dwActiveProcessorMask; + + ASSERT(m_coreCount == sysInfo.dwNumberOfProcessors); + m_pGlobalNodes[0].Initialize(this, 0, 0, affinityMask); +#else + + // Win7 or higher has a PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX structure to support > 64 cores + { + // Traverse the processor information buffer for a second time to populate the node structures. + DWORD byteOffset = 0; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pSysInfoEx = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) s_pSysInfo; + unsigned int nodeIndex = 0; + + while (byteOffset < s_logicalProcessorInformationLength) + { + if (pSysInfoEx->Relationship == RelationNumaNode) + { + // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-numa_node_relationship + // GroupCount + // The number of groups included in the GroupMasks array. + // This field was introduced in Windows 20H2. + // On earlier versions, this value is always 0. + const WORD rawGroupCount = pSysInfoEx->NumaNode.GroupCount; + const WORD totalGroupCount = rawGroupCount == 0 ? 1 : rawGroupCount; + for (WORD index = 0; index < totalGroupCount; ++index) + { + PGROUP_AFFINITY pGroupAffinity = &pSysInfoEx->NumaNode.GroupMasks[index]; + if (pGroupAffinity->Mask != 0) + { +#pragma warning(push) +#pragma warning(disable: 6385) // TRANSITION, VSO-1806041, avoid warning C6385: Reading invalid data from 'm_pGlobalNodes'. + // This index is valid due to ResourceManager::InitializeSystemInformation() above. + ASSERT(nodeIndex < m_nodeCount); // Below, we also assert that the final value of the index is equal to the count. + // Note that the group affinity mask has already been modified to reflect affinity restrictions placed by process affinity or the user. + m_pGlobalNodes[nodeIndex].Initialize(this, static_cast(nodeIndex), pGroupAffinity->Group, pGroupAffinity->Mask); + m_pGlobalNodes[nodeIndex].m_numaNodeNumber = pSysInfoEx->NumaNode.NodeNumber; + ++nodeIndex; +#pragma warning(pop) + } + } + } + + byteOffset += pSysInfoEx->Size; + pSysInfoEx = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) ((PBYTE)pSysInfoEx + pSysInfoEx->Size); + } + + ASSERT(nodeIndex == m_nodeCount); + + CleanupTopologyInformation(); + } +#endif // defined(_ONECORE) + } + + /// + /// Increments the reference count of a resource manager. + /// + /// + /// Returns the resulting reference count. + /// + unsigned int ResourceManager::Reference() + { + return (unsigned int) InterlockedIncrement(&m_referenceCount); + } + + /// + /// Increments the reference count to RM but does not allow a 0 to 1 transition. + /// + /// + /// True if RM was referenced, false, if the reference count was 0. + /// + bool ResourceManager::SafeReference() + { + return SafeInterlockedIncrement(&m_referenceCount); + } + + /// + /// Decrements the reference count of a resource manager. + /// + unsigned int ResourceManager::Release() + { + long rc = InterlockedDecrement(&m_referenceCount); + if (rc == 0) + { + { // begin locked region + _StaticLock::_Scoped_lock lock(s_lock); + if (this == (ResourceManager*) Security::DecodePointer(s_pResourceManager)) + { + // A new s_pRM could be created in CreateSingleton, we can only set the static pointer to null + // if it is the same as 'this'. + s_pResourceManager = NULL; + } + } // end locked region + + if (m_hDynamicRMThreadHandle != NULL) + { + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + ASSERT(m_hDynamicRMThreadHandle != (HANDLE)1); + // Cause the dynamic RM background thread to Exit and wait for it to finish executing + ASSERT(m_dynamicRMWorkerState == Standby); + m_dynamicRMWorkerState = Exit; + } // end locked region + + WakeupDynamicRMWorker(); + platform::__WaitForThread(m_hDynamicRMThreadHandle, INFINITE); + } + + delete this; + } + return (unsigned int) rc; + } + + /// + /// Debug CRT test hook to create artificial topologies. With the retail CRT, this API simply returns. + /// + void ResourceManager::CreateNodeTopology(unsigned int nodeCount, unsigned int *pCoreCount, unsigned int **pNodeDistance, unsigned int *pProcessorGroups) + { +#if defined(_ONECORE) + (nodeCount); (pCoreCount); (pNodeDistance); (pProcessorGroups); + ENSURE_NOT_APP(); +#else +#if defined(_DEBUG) + + if (pCoreCount == NULL) + { + throw std::invalid_argument("pCoreCount"); + } + + if (nodeCount < 1) + { + throw std::invalid_argument("nodeCount"); + } + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + if ( !m_schedulers.Empty()) + { + throw invalid_operation(); + } + + // Destroy the existing node structure. + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + delete [] m_pGlobalNodes[i].m_pCores; + } + delete [] m_pGlobalNodes; +#if defined(CONCRT_TRACING) + delete [] m_drmInitialState; +#endif + s_nodeCount = m_nodeCount = nodeCount; + unsigned int coreCount = 0; + + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + coreCount += pCoreCount[i]; + } + m_coreCount = s_coreCount = coreCount; + + m_pGlobalNodes = _concrt_new GlobalNode[m_nodeCount]; + memset(m_pGlobalNodes, 0, sizeof(GlobalNode) * m_nodeCount); + + // + // This is a patch for the test hook to allow schedulers to actually be created with the "fake" underlying + // topology as long as the group numbers are valid for the machine. + // + ULONG_PTR processAffinityMask = 0; + ULONG_PTR systemAffinityMask = 0; + + BOOL retVal = GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask, &systemAffinityMask); + ASSERT(retVal); + + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + USHORT processorGroup = 0; + unsigned int baseProcNum = 0; + + if (pProcessorGroups != NULL) + { + if (i > 0 && (pProcessorGroups[i] != pProcessorGroups[i - 1])) + { + // Reset the proc number to zero since we've encountered a new group. + baseProcNum = 0; + } + processorGroup = static_cast(pProcessorGroups[i]); + } + + m_pGlobalNodes[i].Initialize(this, static_cast(i), processorGroup, processAffinityMask, (unsigned int)pCoreCount[i], baseProcNum); + } +#if defined(CONCRT_TRACING) + // Assumes a m x n allocation. + m_numTotalCores = m_nodeCount * m_pGlobalNodes[0].m_coreCount; + m_drmInitialState = _concrt_new GlobalCoreData[m_numTotalCores]; + memset(m_drmInitialState, 0, sizeof(GlobalCoreData) * m_numTotalCores); +#endif + } // end locked region +#endif // if defined(_DEBUG) + +#endif // defined(_ONECORE) + } + + /// + /// Associate an IScheduler with the ISchedulerProxy that represents that part + // of IResourceManager associated with the IScheduler. + /// + /// + /// The scheduler be associated. + /// + /// + /// The version of the RM<->Scheduler communication channel that is being utilized. + /// + ISchedulerProxy *ResourceManager::RegisterScheduler(IScheduler *pScheduler, unsigned int version) + { + if (pScheduler == NULL) + throw std::invalid_argument("pScheduler"); + + if (version != CONCRT_RM_VERSION_1) + throw std::invalid_argument("version"); + + return CreateSchedulerProxy(pScheduler); + } + + /// + /// Allocates and initializes the data structure that will represent the allocated nodes for a scheduler proxy. + /// This function is called the first time a scheduler proxy requests an allocation. + /// + SchedulerNode * ResourceManager::CreateAllocatedNodeData() + { + SchedulerNode * pNodes = _concrt_new SchedulerNode[m_nodeCount]; + memset(pNodes, 0, m_nodeCount * sizeof(SchedulerNode)); + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pNode = &pNodes[nodeIndex]; + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + + // Copy the base class portion of the node, which is shared. + memcpy(pNode, pGlobalNode, sizeof(ProcessorNode)); + ASSERT(pNode->m_availableCores == 0); + + pNode->m_pCores = _concrt_new SchedulerCore[pNode->m_coreCount]; + memset(pNode->m_pCores, 0, pNode->m_coreCount * sizeof(SchedulerCore)); + + for (unsigned int coreIndex = 0; coreIndex < pNode->m_coreCount; ++coreIndex) + { + // Copy the base class portion of the core. + memcpy(&pNode->m_pCores[coreIndex], &pGlobalNode->m_pCores[coreIndex], sizeof(ProcessorCore)); + // All cores in the local map start out 'unassigned' to the scheduler proxy. + pNode->m_pCores[coreIndex].m_coreState = ProcessorCore::Unassigned; + + // Each scheduler core has a pointer to the global use count for that core. + pNode->m_pCores[coreIndex].m_pGlobalUseCountPtr = &pGlobalNode->m_pCores[coreIndex].m_useCount; + } + } + return pNodes; + } + + /// + /// Destroys the data structures representing nodes/cores allocated to a scheduler proxy when the proxy has + /// shutdown. + /// + void ResourceManager::DestroyAllocatedNodeData(SchedulerNode * pAllocatedNodes) + { + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + delete [] pAllocatedNodes[i].m_pCores; + } + delete [] pAllocatedNodes; + } + + /// + /// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request + /// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request + /// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to + /// IScheduler::AddVirtualProcessors. + /// + /// + /// The scheduler proxy that is making the allocation request. + /// + /// + /// Whether to subscribe the current thread and account for it during resource allocation. + /// + /// + /// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise. + /// + IExecutionResource * ResourceManager::RequestInitialVirtualProcessors(SchedulerProxy *pProxy, bool doSubscribeCurrentThread) + { + bool createWorkerThread = false; + ExecutionResource * pExecutionResource = NULL; + bool doExternalThreadAllocation = false; + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + ASSERT(pProxy->GetNumExternalThreads() == 0); + + if (doSubscribeCurrentThread) + { + // If the current thread is either already subscribed, or represents a virtual processor root, we return the + // existing execution resource. + pExecutionResource = pProxy->ReferenceCurrentThreadExecutionResource(); + + if (pExecutionResource == NULL) + { + doExternalThreadAllocation = true; + } + } + + // Increment this count before performing the allocation. If the new scheduler activates vprocs at the time + // they are added, we use this information to decide whether core busy/idle notifications need to be sent to other schedulers. + if (pProxy->ShouldReceiveNotifications()) + { + ++m_numSchedulersNeedingNotifications; + } + + ++m_numSchedulers; + m_schedulers.AddTail(pProxy); + + // Based on the policy of the scheduler proxy, and the load on the system, allocate cores to this proxy. + // The API will invoke a scheduler proxy callback (GrantAllocation) before it returns. + ExecutionResource * pNewExecutionResource = PerformAllocation(pProxy, true, doExternalThreadAllocation); + + // If this external thread did not exist in the RM already, get it from PerformAllocation. + if (pExecutionResource == NULL) + { + pExecutionResource = pNewExecutionResource; + } + else + { + ASSERT(pNewExecutionResource == NULL); + } + + if (pProxy->ShouldReceiveNotifications()) + { + SendResourceNotifications(pProxy); + } + + if (m_numSchedulers != 2) + { + return pExecutionResource; + } + + // We've just added the second scheduler. We need to either create or wake up the dynamic RM worker thread. + ASSERT(m_dynamicRMWorkerState == Standby); + m_dynamicRMWorkerState = LoadBalance; + + if (m_hDynamicRMThreadHandle == NULL) + { + // Store a temporary value before releasing the lock and proceeding to allocate memory/create the thread. + // This is to prevent a duplicate allocation if the refcount goes from 2->1 and back to 2 after the lock is released. + m_hDynamicRMThreadHandle = (HANDLE)1; + + // Initialize the memory used for DRM under the lock, since these variables are touched in the static RM path as well + ASSERT(m_ppProxyData != NULL); + m_ppGivingProxies = _concrt_new DynamicAllocationData * [m_maxSchedulers]; + m_ppReceivingProxies = _concrt_new DynamicAllocationData * [m_maxSchedulers]; + + createWorkerThread = true; + } + } // end locked region + + // Set the event outside the lock to prevent the high priority thread from having to block immediately upon starting up. + WakeupDynamicRMWorker(); + + // Create the thread/data or set the dynamic RM event after releasing the lock to prevent the high priority thread + // from having to block immediately upon starting up. + if (createWorkerThread) + { + CreateDynamicRMWorker(); + } + + return pExecutionResource; + } + + /// + /// This API registers the current thread with the resource manager associating it with this scheduler proxy, + /// and returns an instance of IExecutionResource back to the scheduler, for bookkeeping and maintenance. + /// + /// + /// The IExecutionResource instance representing current thread in the runtime. + /// + ExecutionResource * ResourceManager::SubscribeCurrentThread(SchedulerProxy *pSchedulerProxy) + { + ExecutionResource * pExecutionResource = NULL; + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + pExecutionResource = pSchedulerProxy->ReferenceCurrentThreadExecutionResource(); + + // Create an execution resources if the current thread does not already have one. + if (pExecutionResource == NULL) + { + pExecutionResource = PerformAllocation(pSchedulerProxy, false, true); + } + + } // end locked region + + return pExecutionResource; + } + + /// + /// Removes an execution resource that was created for an external thread. + /// + void ResourceManager::RemoveExecutionResource(ExecutionResource * pExecutionResource) + { + bool signalDRM = false; + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + SchedulerProxy * pSchedulerProxy = pExecutionResource->GetSchedulerProxy(); + pExecutionResource->DecrementUseCounts(); + + // We have to manually redistribute available cores in the case where the DRM thread is not running. + if ((pSchedulerProxy->GetNumAllocatedCores() < pSchedulerProxy->DesiredHWThreads()) && m_numSchedulers == 1) + { + ASSERT(m_dynamicRMWorkerState == Standby); + if (!DistributeCoresToSurvivingScheduler()) + { + // Retry from the background thread + signalDRM = true; + } + } + } // end locked region + + if (signalDRM) + { + WakeupDynamicRMWorker(); + } + } + + /// + /// Called in order to notify the resource manager that the given scheduler is shutting down. This + /// will cause the resource manager to immediately reclaim all resources granted to the scheduler. + /// + void ResourceManager::Shutdown(SchedulerProxy *pProxy) + { + bool signalDRM = false; + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + m_schedulers.Remove(pProxy); + + SchedulerNode *pAllocatedNodes = pProxy->GetAllocatedNodes(); + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + SchedulerNode *pAllocatedNode = &pAllocatedNodes[i]; + if (pAllocatedNode->m_allocatedCores > 0) + { + for (unsigned int j = 0; j < pAllocatedNode->m_coreCount; ++j) + { + if (pAllocatedNode->m_pCores[j].m_coreState == ProcessorCore::Allocated) + { + SchedulerCore *pAllocatedCore = &pAllocatedNode->m_pCores[j]; + + ASSERT(*pAllocatedCore->m_pGlobalUseCountPtr > 0); + --(*pAllocatedCore->m_pGlobalUseCountPtr); + } + } + } + } + + if (pProxy->ShouldReceiveNotifications()) + { + --m_numSchedulersNeedingNotifications; + } + if (--m_numSchedulers == 1) + { + // Put the dynamic RM worker thread on standby. + ASSERT(m_dynamicRMWorkerState == LoadBalance); + m_dynamicRMWorkerState = Standby; + signalDRM = true; + } + } // end locked region + + if (signalDRM) + { + // Set the event outside the lock to prevent the high priority thread from having to block immediately upon starting up. + WakeupDynamicRMWorker(); + } + pProxy->FinalShutdown(); + } + + + /// + /// When the number of schedulers in the RM goes from 2 to 1, this routine is invoked to make sure the remaining scheduler + /// has its desired number of cores, before putting the dynamic RM worker on standby. It is also called when there is just + /// one scheduler with external subscribed threads that it removes -> there is a chance that this move may allow us to allocate + /// more vprocs. + /// + bool ResourceManager::DistributeCoresToSurvivingScheduler() + { + // NOTE: This routine must be called while m_lock is held. + ASSERT(m_numSchedulers <= 1); + + if (!m_schedulers.Empty()) + { + SchedulerProxy * pSchedulerProxy = m_schedulers.First(); + + ASSERT(pSchedulerProxy != NULL); + ASSERT(pSchedulerProxy->GetNumAllocatedCores() <= pSchedulerProxy->DesiredHWThreads()); + ASSERT(pSchedulerProxy->GetNumBorrowedCores() <= (pSchedulerProxy->DesiredHWThreads() - pSchedulerProxy->MinHWThreads())); + + // Since this is the only scheduler in the RM, we should able to satisfy its MaxConcurrency. + if (pSchedulerProxy->GetNumAllocatedCores() < pSchedulerProxy->DesiredHWThreads() || + pSchedulerProxy->GetNumBorrowedCores() > 0) + { + unsigned int suggestedAllocation = pSchedulerProxy->AdjustAllocationIncrease(pSchedulerProxy->DesiredHWThreads()); + unsigned int remainingCores = suggestedAllocation - pSchedulerProxy->GetNumAllocatedCores(); + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = pSchedulerProxy->GetSortedNodeOrder(); + + // Sort the array of nodes in the proxy by number of allocated cores, largest first, if we're allocating + // to it less cores than the total available. This is so that we pack nodes as tightly as possible. + bool sortNodes = pSchedulerProxy->DesiredHWThreads() != m_coreCount; + + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + // No need to sort nodes the next time around, if there are no more cores to add. + sortNodes &= remainingCores > 0; + + if (sortNodes) + { + unsigned int maxAllocationIndex = i; + SchedulerNode *pMaxNode = &pAllocatedNodes[pSortedNodeOrder[maxAllocationIndex]]; + + for (unsigned int j = i + 1; j < m_nodeCount; ++j) + { + SchedulerNode * pNode = &pAllocatedNodes[pSortedNodeOrder[j]]; + if (pNode->m_allocatedCores > pMaxNode->m_allocatedCores) + { + maxAllocationIndex = j; + pMaxNode = pNode; + } + } + + if (i != maxAllocationIndex) + { + // Swap the index at 'maxAllocationIndex' with the index at 'i'. The next iteration will traverse nodes starting at + // m_pSortedNodeOrder[i + i]. + unsigned int tempIndex = pSortedNodeOrder[i]; + pSortedNodeOrder[i] = pSortedNodeOrder[maxAllocationIndex]; + pSortedNodeOrder[maxAllocationIndex] = tempIndex; + } + } + + // Assign cores until the desired number of cores is reached. In addition, check if there are + // any borrowed cores and switch them to owned. + SchedulerNode * pCurrentNode = &pAllocatedNodes[pSortedNodeOrder[i]]; + for (unsigned int coreIndex = 0; coreIndex < pCurrentNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pCore = &pCurrentNode->m_pCores[coreIndex]; + if (pCore->m_coreState == ProcessorCore::Unassigned) + { + if (remainingCores > 0) + { + ASSERT(*pCore->m_pGlobalUseCountPtr == 0); + + ++(*pCore->m_pGlobalUseCountPtr); + + pSchedulerProxy->AddCore(pCurrentNode, coreIndex, false); + --remainingCores; + } + } + else + { + ASSERT(pCore->m_coreState == ProcessorCore::Allocated); + if (pCore->IsBorrowed()) + { + ASSERT(*pCore->m_pGlobalUseCountPtr == 1); + pSchedulerProxy->ToggleBorrowedState(pCurrentNode, coreIndex); + } + } + } + } + } + + if (pSchedulerProxy->ShouldReceiveNotifications()) + { + SendResourceNotifications(); + } + +#if defined(CONCRT_TRACING) + if (pSchedulerProxy->GetNumAllocatedCores() != pSchedulerProxy->DesiredHWThreads()) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"Surviving Scheduler %d: Allocated: %d, Desired: %d", + pSchedulerProxy->GetId(), pSchedulerProxy->GetNumAllocatedCores(), pSchedulerProxy->DesiredHWThreads()); + } +#endif + return (pSchedulerProxy->GetNumAllocatedCores() == pSchedulerProxy->DesiredHWThreads()); + } + + return true; + } + + /// + /// Denote the doubles in the input array AllocationData[*].m_scaledAllocation by: r[1],..., r[n]. + /// Split r[j] into b[j] and fract[j] where b[j] is the integral floor of r[j] and fract[j] is the fraction truncated. + /// Sort the set { r[j] | j = 1,...,n } from largest fract[j] to smallest. + /// For each j = 0, 1, 2,... if fract[j] > 0, then set b[j] += 1 and pay for the cost of 1-fract[j] by rounding + /// fract[j0] -> 0 from the end (j0 = n-1, n-2,...) -- stop before j > j0. b[j] is stored in AllocationData[*].m_allocation. + /// totalAllocated is the sum of all AllocationData[*].m_scaledAllocation upon entry, which after the function call is over will + /// necessarily be equal to the sum of all AllocationData[*].m_allocation. + /// + void ResourceManager::RoundUpScaledAllocations(AllocationData **ppData, unsigned int count, unsigned int totalAllocated) + { + ASSERT(count > 1 && ppData != NULL); + double epsilon = 1e-07; // epsilon allows forgiveness of reasonable round-off errors. + +#if defined(_DEBUG) + double sumScaledAllocation = 0.0; + for (unsigned int i = 0; i < count; ++i) + { + sumScaledAllocation += ppData[i]->m_scaledAllocation; + } + ASSERT(sumScaledAllocation <= totalAllocated + epsilon && sumScaledAllocation >= totalAllocated - epsilon); +#endif + + double fraction = 0.0; + + for (unsigned int i = 0; i < count; ++i) + { + ppData[i]->m_allocation = (unsigned int) ppData[i]->m_scaledAllocation; + ppData[i]->m_scaledAllocation -= ppData[i]->m_allocation; + } + + // Sort by scaledAllocation, highest first selection sort. + for (unsigned int i = 0; i < count; ++i) + { + unsigned int maxIndex = i; + for (unsigned int j = i + 1; j < count; ++j) + { + if (ppData[j]->m_scaledAllocation > ppData[maxIndex]->m_scaledAllocation + epsilon) + { + maxIndex = j; + } + } + if (i != maxIndex) + { + AllocationData * pTemp = ppData[i]; + ppData[i] = ppData[maxIndex]; + ppData[maxIndex] = pTemp; + } + } + + // Round up those with the largest truncation, stealing the fraction from those with the least. + for (unsigned int i = 0, j = count - 1; i < count; ++i) + { + while (fraction > epsilon) + { + if (ppData[j]->m_scaledAllocation > epsilon) + { + do + { + ASSERT(j < count); + fraction -= ppData[j]->m_scaledAllocation; + ppData[j]->m_scaledAllocation = 0.0; + --j; + } + while (fraction > epsilon); + ASSERT(i <= j+1); + } + else + { + --j; + ASSERT(i <= j && j < count); + } + } + + if (i <= j) + { + ASSERT(j < count); + if (ppData[i]->m_scaledAllocation > epsilon) + { + fraction += (1.0 - ppData[i]->m_scaledAllocation); + ppData[i]->m_scaledAllocation = 0.0; + ppData[i]->m_allocation += 1; + } + } + else + break; + } + + ASSERT(fraction <= epsilon && fraction >= -epsilon); + +#if defined(_DEBUG) + unsigned int sumAllocation = 0; + for (unsigned int i = 0; i < count; ++i) + { + sumAllocation += ppData[i]->m_allocation; + } + ASSERT(sumAllocation == totalAllocated); +#endif + + // Sort by index, lowest first selection sort. + for (unsigned int i = 0; i < count; ++i) + { + unsigned int minIndex = i; + for (unsigned int j = i + 1; j < count; ++j) + { + if (ppData[j]->m_index < ppData[minIndex]->m_index) + { + minIndex = j; + } + } + if (i != minIndex) + { + AllocationData * pTemp = ppData[i]; + ppData[i] = ppData[minIndex]; + ppData[minIndex] = pTemp; + } + } + } + + /// + /// Tries to redistribute cores allocated to all schedulers proportional to each schedulers value for 'DesiredHardwareThreads', + /// and reserve any freed cores for the new scheduler. + /// + unsigned int ResourceManager::RedistributeCoresAmongAll(SchedulerProxy* pSchedulerProxy, unsigned int allocated, unsigned int minimum, unsigned int desired) + { + // The argument 'allocated' is the sum of cores that have been previously allocated, and cores that were reserved during this allocation attempt. + unsigned int reservation = 0; + ASSERT(m_numSchedulers > 0 && m_ppProxyData[0]->m_pProxy == pSchedulerProxy); + + // Try to proportionally allocate cores to all schedulers w/o oversubscription. The proportions used will be + // 'desired' for each scheduler, except that no existing scheduler will be forced to increase the current allocation. + if (m_numSchedulers > 1) + { + unsigned int totalMinimum = minimum; + unsigned int totalAllocated = allocated; + unsigned int numSchedulers = 1; // includes the current scheduler + + // Let totalAllocated be the number of cores we have allocated to the new scheduler so far, plus the number of 'owned' cores + // allocated to all existing schedulers. Let s1,...sn be the currently allocated schedulers with 'desired' des[1], + // ...,des[n] and 'minimum' min[1],...,min[n]. The new scheduler requesting an allocation is s0 with desired des[0] and + // minimum min[0]. + for (unsigned int i = 1; i < m_numSchedulers; ++i) + { + SchedulerProxy * pProxy = m_ppProxyData[i]->m_pProxy; + ASSERT(pSchedulerProxy != pProxy); + // Only take into account existing schedulers that have > Min. We work with the number of 'owned' cores here instead of + // the number of 'allocated' cores (which includes borrowed cores). The borrowed cores should already have been released, + // but they are accounted for in the total allocated count, until the release is confirmed. + if (pProxy->GetNumOwnedCores() > pProxy->MinHWThreads()) + { + ++numSchedulers; + + totalMinimum += pProxy->MinHWThreads(); + totalAllocated += pProxy->GetNumOwnedCores(); + } + } + + if (numSchedulers > 1 && totalMinimum <= totalAllocated) + { + // We have found schedulers with cores greater than min. Moreover, the sum of all cores already allocated to + // existing schedulers can at least satisfy all mins (including the min requirement of the current scheduler). + + double totalDesired = 0.0; + double scaling = 0.0; +#if defined(_DEBUG) + double epsilon = 1e-07; // epsilon allows forgiveness of reasonable round-off errors +#endif + // For the purpose of rounding up scaled allocation, we need an array of pointers to AllocationData. + StaticAllocationData ** ppProxies = _concrt_new StaticAllocationData* [numSchedulers]; + + ppProxies[0] = static_cast(m_ppProxyData[0]); + ASSERT(ppProxies[0]->m_index == 0); + // 'desired' may not be the same as DesiredHWThreads, but it is the number desired for this allocation attempt. + ppProxies[0]->m_adjustedDesired = desired; + totalDesired += ppProxies[0]->m_adjustedDesired; + + unsigned int index = 1; + for (unsigned int i = 1; i < m_numSchedulers; ++i) + { + SchedulerProxy * pProxy = m_ppProxyData[i]->m_pProxy; + ASSERT(pSchedulerProxy != pProxy); + + if (pProxy->GetNumOwnedCores() > pProxy->MinHWThreads()) + { + ppProxies[index] = pProxy->GetStaticAllocationData(); + ASSERT(ppProxies[index]->m_adjustedDesired == pProxy->DesiredHWThreads()); + totalDesired += ppProxies[index]->m_adjustedDesired; + ++index; + } + } + + ASSERT(index == numSchedulers); + + while (true) + { + // We're trying to pick a scaling factor r such that r * (Sum { des[j] | j = 0,...,n }) = totalAllocated. + scaling = totalAllocated/totalDesired; + + // Multiply the scaling factor by each schedulers 'desired'. + for (index = 0; index < numSchedulers; ++index) + { + ppProxies[index]->m_scaledAllocation = ppProxies[index]->m_adjustedDesired * scaling; + } + + // Convert the floating point scaled allocations into integer allocations, using the algorithm below. + // Denote the n+1 scaled allocations by: + // r[0],..., r[n] + // Split r[j] into b[j] and fract[j] where b[j] is the integral floor of r[j] and fract[j] is the fraction truncated. + // + // Sort the set { r[j] | j = 0,...,n } from largest fract[j] to smallest. + // + // For each j = 0, 1, 2,... if fract[j] > 0, then set b[j] += 1 and pay for the cost of 1-fract[j] by + // rounding fract[j0] -> 0 from the end (j0=n, n-1, n-2,...) -- stop before j > j0. + // + // The new allocations for schedulers s0,...,sn and s is b[0],...,b[n] -- where the original order is preserved. + // + // { 1.6, 1.5, 1.7, 1.3, 1.8, 1.2, 1.3, 1.1, 1.4, 1.2, 1.9 } + // --> { 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.3, 1.2, 1.2, 1.1 } // sort + // --> { 2, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.3, 1.2, 1.2, 1 } + // --> { 2, 2, 1.7, 1.6, 1.5, 1.4, 1.3, 1.3, 1.2, 1, 1 } + // --> { 2, 2, 2, 1.6, 1.5, 1.4, 1.3, 1.2, 1, 1, 1 } + // --> { 2, 2, 2, 2, 1.5, 1.4, 1.1, 1, 1, 1, 1 } + // --> { 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1 } + // --> { 2, 2, 2, 1, 2, 1, 1, 1, 1, 1, 2 } // put back in original order + // + // Since all changes are properly accounted for, the sum will not change. + // + RoundUpScaledAllocations((AllocationData **)ppProxies, numSchedulers, totalAllocated); + + bool fReCalculate = false; + for (unsigned int i = 1; i < numSchedulers; ++i) + { + // Keep recursing until previous allocations do not increase (excluding the current scheduler). + SchedulerProxy *pProxy = ppProxies[i]->m_pProxy; + if (ppProxies[i]->m_allocation > pProxy->GetNumOwnedCores()) + { + double modifier = pProxy->GetNumOwnedCores()/(double)ppProxies[i]->m_allocation; + + // Reduce adjustedDesired by multiplying it with 'modifier', to try to bias allocation to the original size or less. + totalDesired -= ppProxies[i]->m_adjustedDesired * (1.0 - modifier); + ppProxies[i]->m_adjustedDesired = modifier * ppProxies[i]->m_adjustedDesired; + + fReCalculate = true; + } + } + + if (fReCalculate) + { +#if defined(_DEBUG) + double sumDesired = 0.0; + for (unsigned int i = 0; i < numSchedulers; ++i) + { + sumDesired += ppProxies[i]->m_adjustedDesired; + } + ASSERT(totalDesired <= sumDesired + epsilon && totalDesired >= sumDesired - epsilon); +#endif + continue; + } + + for (unsigned int i = 0; i < numSchedulers; ++i) + { + // Keep recursing until all allocations are no greater than desired (including the current scheduler). + SchedulerProxy *pProxy = ppProxies[i]->m_pProxy; + if (ppProxies[i]->m_allocation > pProxy->DesiredHWThreads()) + { + double modifier = pProxy->DesiredHWThreads()/(double)ppProxies[i]->m_allocation; + + // Reduce adjustedDesired by multiplying with it 'modifier', to try to bias allocation to desired or less. + totalDesired -= ppProxies[i]->m_adjustedDesired * (1.0 - modifier); + ppProxies[i]->m_adjustedDesired = modifier*ppProxies[i]->m_adjustedDesired; + + fReCalculate = true; + } + } + + if (fReCalculate) + { +#if defined(_DEBUG) + double sumDesired = 0.0; + for (unsigned int i = 0; i < numSchedulers; ++i) + sumDesired += ppProxies[i]->m_adjustedDesired; + ASSERT(totalDesired <= sumDesired + epsilon && totalDesired >= sumDesired - epsilon); +#endif + continue; + } + + for (unsigned int i = 0; i < numSchedulers; ++i) + { + // Keep recursing until all allocations are at least minimum (including the current scheduler). + SchedulerProxy *pProxy = ppProxies[i]->m_pProxy; + if (pProxy->MinHWThreads() > ppProxies[i]->m_allocation) + { + double newDesired = pProxy->MinHWThreads()/scaling; + + // Bias desired to get allocation closer to min. + totalDesired += newDesired - ppProxies[i]->m_adjustedDesired; + ppProxies[i]->m_adjustedDesired = newDesired; + + fReCalculate = true; + } + } + + if (fReCalculate) + { +#if defined(_DEBUG) + double sumDesired = 0.0; + for (unsigned int i = 0; i < numSchedulers; ++i) + sumDesired += ppProxies[i]->m_adjustedDesired; + ASSERT(totalDesired <= sumDesired + epsilon && totalDesired >= sumDesired - epsilon); +#endif + continue; + } +#if defined(_DEBUG) + for (unsigned int i = 1; i < numSchedulers; ++i) + { + ASSERT(ppProxies[i]->m_pProxy->MinHWThreads() <= ppProxies[i]->m_allocation && ppProxies[i]->m_allocation <= ppProxies[i]->m_pProxy->GetNumOwnedCores()); + } + ASSERT(ppProxies[0]->m_pProxy->MinHWThreads() <= ppProxies[0]->m_allocation); + ASSERT(ppProxies[0]->m_pProxy == pSchedulerProxy); +#endif + break; + } // end of while (true) + + if (ppProxies[0]->m_allocation > allocated) + { + for (unsigned int i = 1; i < numSchedulers; ++i) + { + unsigned int reduceBy = ppProxies[i]->m_pProxy->GetNumOwnedCores() - ppProxies[i]->m_allocation; + if (reduceBy > 0) + { + ReleaseSchedulerResources(pSchedulerProxy, ppProxies[i]->m_pProxy, reduceBy); + } + } + + // Reserve out of the cores we just freed. + reservation = ReserveCores(pSchedulerProxy, ppProxies[0]->m_allocation - allocated, 0); + } + + delete [] ppProxies; + } + } + return reservation; + } + + /// + /// Instructs existing schedulers to release cores. Then tries to reserve available cores for the new scheduler. + /// The parameter numberToFree can be one of the two special values: + /// ReleaseCoresDownToMin: used to release cores until they are at min, or + //// ReleaseOnlyBorrowedCores: only release borrowed cores. + /// + unsigned int ResourceManager::ReleaseCoresOnExistingSchedulers(SchedulerProxy * pNewProxy, unsigned int request, unsigned int numberToFree) + { + ASSERT(m_numSchedulers > 0 && m_ppProxyData[0]->m_pProxy == pNewProxy); + ASSERT(numberToFree == ReleaseCoresDownToMin || numberToFree == ReleaseOnlyBorrowedCores); + + // Ask previously allocated schedulers to release surplus cores, until either the request is satisfied, or we're out of schedulers. + bool releasedCores = false; + + for (unsigned int index = 1; index < m_numSchedulers; ++index) + { + ASSERT(pNewProxy != m_ppProxyData[index]->m_pProxy); + if (ReleaseSchedulerResources(pNewProxy, m_ppProxyData[index]->m_pProxy, numberToFree)) + { + releasedCores = true; + } + } + unsigned int reservation; + if (releasedCores) + { + reservation = ReserveCores(pNewProxy, request, 0); + } + else + { + reservation = 0; + } + return reservation; + } + + /// + /// Reserves cores for the new scheduler at higher use counts - this is used only to satisfy MinHWThreads. + /// + unsigned int ResourceManager::ReserveAtHigherUseCounts(SchedulerProxy* pSchedulerProxy, unsigned int request) + { + unsigned int reuseCount = 0; + unsigned int reservation = 0; + + while (reservation < request) + { + reservation += ReserveCores(pSchedulerProxy, request - reservation, ++reuseCount); + } + + return reservation; + } + + /// + /// The main allocation routine that allocates cores to a scheduler proxy. + /// + ExecutionResource * ResourceManager::PerformAllocation(SchedulerProxy *pSchedulerProxy, bool fInitialAllocation, bool fSubscribeCurrentThread) + { + ASSERT(pSchedulerProxy != NULL && m_pGlobalNodes != NULL); + ASSERT(fInitialAllocation || pSchedulerProxy->GetAllocatedNodes()); + ASSERT(fInitialAllocation || fSubscribeCurrentThread); + ASSERT(!fInitialAllocation || pSchedulerProxy->GetNumAllocatedCores() == 0); + + if (fInitialAllocation) + { + pSchedulerProxy->SetAllocatedNodes(CreateAllocatedNodeData()); + } + + // Calculate the number of cores to attempt to allocate to the scheduler proxy. Note, that the only incremental allocation request + // currently supported (fInitialAllocation == false), is the request for a single thread subscription. + unsigned int minimum = 0; + unsigned int desired = 0; + unsigned int allocated = pSchedulerProxy->GetNumAllocatedCores(); + unsigned int reserved = 0; + + unsigned int request = 0; + unsigned int minRequest = 0; // The request we have to make to satisfy the minimum for the scheduler proxy. + if (fSubscribeCurrentThread) + { + minimum = pSchedulerProxy->ComputeMinHWThreadsWithExternalThread(); + desired = pSchedulerProxy->ComputeDesiredHWThreadsWithExternalThread(); + if (fInitialAllocation) + { + request = desired; + minRequest = minimum; + } + else + { + // This is a subsequent allocation. Currently only external thread subscriptions are supported via this path. + unsigned int currentMinimum = pSchedulerProxy->MinHWThreads(); + ASSERT(currentMinimum <= m_coreCount && currentMinimum <= allocated); + ASSERT(currentMinimum < m_coreCount || (desired == m_coreCount && minimum == m_coreCount && allocated == m_coreCount)); + + // We will look for 1 more core for the scheduler unless all cores are already allocated to the scheduler. + // If we cannot find any cores at a use count of 0, the subscribed thread will either oversubscribe an existing core + // or replace an existing core allocated to the scheduler if it can afford to give up vprocs. + request = (currentMinimum < m_coreCount) ? 1 : 0; + // Note that 'minimum' takes into account the external thread we're currently allocating a core for. + minRequest = (allocated < minimum) ? 1 : 0; + } + } + else + { + ASSERT(allocated == 0); + minimum = minRequest = pSchedulerProxy->MinHWThreads(); + desired = request = pSchedulerProxy->DesiredHWThreads(); + } + ASSERT(request >= minRequest); + + bool coresStolen = false; + if (reserved < request) + { + // Capture data needed for static allocation for all existing schedulers. + SetupStaticAllocationData(pSchedulerProxy, fSubscribeCurrentThread); + + // Handle a subset of idle and borrowed cores up front. + PreProcessStaticAllocationData(); + + // Try for an initial reservation of cores with a useCount = 0 (viz, no sharing) + reserved = ReserveCores(pSchedulerProxy, request, 0); + + if (reserved < request && (fInitialAllocation || minRequest > 0)) + { + // For subsequent requests for thread subscription, we only proceed if we need a core to satisfy the new minimum. + // If not, we should be able to use an already allocated core to satisfy the new request, by removing the virtual + // processors from that core. + + // At this point we will start stealing cores from other schedulers, so we set a flag to true to remember to + // commit any changes that are made to the allocations of these schedulers. + coresStolen = true; + + // Have schedulers give up all borrowed cores first. These are cores that were temporarily borrowed and + // assigned to a scheduler by dynamic RM when it was noticed that other schedulers that had that core + // were not using it. While this does not necessarily free up cores at 0 use count, it's possible that + // a combination of this and the attempt to redistribute cores, yields some free cores. + reserved += ReleaseCoresOnExistingSchedulers(pSchedulerProxy, request - reserved, ReleaseOnlyBorrowedCores); + + if (reserved < request) + { + // Next try to divide cores among schedulers, proportional to each scheduler's Desired value. + reserved += RedistributeCoresAmongAll(pSchedulerProxy, allocated + reserved, minimum, allocated + request); + + if (reserved < minRequest) + { + // Finally force schedulers to reduce down to min, but this time only to satisfy the minimum requirement + // for the requesting scheduler. + reserved += ReleaseCoresOnExistingSchedulers(pSchedulerProxy, minRequest - reserved, ReleaseCoresDownToMin); + + // If we still haven't satisfied the minimum request we have no choice but to share cores with other schedulers. + if (reserved < minRequest) + { + reserved += ReserveAtHigherUseCounts(pSchedulerProxy, minRequest - reserved); + } + } + } + + ASSERT(reserved >= minRequest && reserved + allocated >= minimum); + } + + // Revert the changes made to global state while setting up data for allocation. + ResetGlobalAllocationData(); + } + + ExecutionResource * pExecutionResource = pSchedulerProxy->GrantAllocation(reserved, fInitialAllocation, fSubscribeCurrentThread); + + if (coresStolen) + { + // We have potentially stolen cores from other schedulers. CommitStolenCores will either inform + // previously allocated schedulers that certain cores have been taken away (if those cores were used to + // satisfy the allocation for the current scheduler), or will reclaim them for the schedulers they were + // stolen from. + // This needs to be done after the allocation is granted, since the subscription level for the newly allocated cores + // could've increased, and we take that into account during the restore. + CommitStolenCores(pSchedulerProxy); + } + +#if defined(_DEBUG) + // Ensure that allocations are between min and max for all schedulers after a new scheduler receives its initial allocation. + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + SchedulerProxy * pSchedulerProxy = m_ppProxyData[index]->m_pProxy; + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + ASSERT(pSchedulerProxy->GetNumAllocatedCores() <= pSchedulerProxy->DesiredHWThreads()); + } +#endif + + return pExecutionResource; + } + + /// + /// Worker routine that does actual core reservation, using the supplied use count. It tries to + /// pack reserved cores onto nodes by preferring nodes where more free cores are available. + /// + unsigned int ResourceManager::ReserveCores(SchedulerProxy * pSchedulerProxy, unsigned int request, unsigned int useCount) + { + unsigned int currentNodeIndex = (unsigned int) -1; + + // + // If this is an external thread allocation, we need to look at which node the external thread is already + // affinitized to in order to bias the reservation to that node. + // + StaticAllocationData * pStaticData = pSchedulerProxy->GetStaticAllocationData(); + if (pStaticData->m_fNeedsExternalThreadAllocation) + { + currentNodeIndex = GetCurrentNodeAndCore(NULL); + } + + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = pSchedulerProxy->GetSortedNodeOrder(); + + // + // GlobalCore::m_useCount which is the same as *SchedulerCore::m_pGlobalUseCountPtr is the number of schedulers utilizing + // this core. The reservation routine works by looking at cores with m_useCount=0, grabs all it can, then looks at m_useCount=1, + // then m_useCount=2, etc. At a given use count, say m_useCount = count, the number of cores available for a possible allocation + // in a node is SchedulerNode::m_availableCores. The number of cores reserved at m_useCount < count, is SchedulerNode::m_reservedCores. + // Previously allocated cores are represented by SchedulerNode::m_allocatedCores (these cores already have virtual processors or + // execution resources associated with them). + // + bool fAvailableCores = false; + + ASSERT(request > 0); + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode *pAllocatedNode = &pAllocatedNodes[nodeIndex]; + for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &(pAllocatedNode->m_pCores[coreIndex]); + if (pAllocatedCore->m_coreState == ProcessorCore::Unassigned) + { + if (useCount == *pAllocatedCore->m_pGlobalUseCountPtr) + { + fAvailableCores = true; + + // Temporarily mark the core as available, for a possible reservation below. + pAllocatedCore->m_coreState = ProcessorCore::Available; + + // m_availableCores is the number of cores that satisfy request at the current useCount. + ++pAllocatedNode->m_availableCores; + } + } + else + { + ASSERT(pAllocatedCore->m_coreState == ProcessorCore::Allocated || pAllocatedCore->m_coreState == ProcessorCore::Reserved); + } + } + } + + unsigned int reserved = 0; + + if (fAvailableCores) + { + // Now that we've found available cores at the current use count, reserve upto 'request' of them for the new scheduler. + // Order the search for such cores by first looking at nodes that will have the most cores allocated from it. + // Even after we satisfy 'request', walk through the remaining nodes, marking the cores marked Available as Unassigned. + + // As we go through the reservation, we want to satisfy the request by picking nodes with the largest possible allocation + // first. However we still want to maintain the order of nodes in the array we give the scheduler proxy, + // such that a node with a nodeId 'm', is at location 'm' in the allocated nodes array. + // + // What we do here is sort the array without moving items around. We store information in a different array of + // indices where the indices are sorted such that they point to nodes with decreasing allocation when we're done. + + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + unsigned int maxAllocationIndex = i; + + // We use the array of sorted indices to 'sort' nodes, instead of swapping the nodes themselves. + SchedulerNode *pMaxNode = &pAllocatedNodes[pSortedNodeOrder[maxAllocationIndex]]; + + unsigned int remainingRequest = request - reserved; + + // If we've satisfied the request on previous iterations of the loop, don't bother comparing this node + // with the nodes further down. + if (remainingRequest > 0) + { + // Lower the availability for reasons described below. + if (pMaxNode->m_availableCores > remainingRequest) + { + pMaxNode->m_availableCores = remainingRequest; + } + + for (unsigned int j = i + 1; j < m_nodeCount; ++j) + { + SchedulerNode *pNode = &pAllocatedNodes[pSortedNodeOrder[j]]; + + if (pNode->m_availableCores > remainingRequest) + { + pNode->m_availableCores = remainingRequest; + } + + // Q. Why did we just lower the number of available cores on this node down to request, if it was greater? + // A. The primary reason is to ensure that we pack nodes as tightly as possible while still taking into account + // use counts. Take a look at the example below. Let's say the system has 2 nodes 4 cores/node for + // a total of 8 cores. The scheduler has requested 6 cores. We were able to satisfy 5 of these six at a lower + // use count of 1, 3 belong to NodeA and 2 belong to NodeB. The remaining three cores have the same use count + // of 2. At this point NodeA.m_reservedCores = 3 and NodeA.m_availableCores = 1 whereas NodeB.m_reservedCores = 2 and + // NodeB.m_availableCores = 2. It would be beneficial for us to collocate the 6th core with the 3 on node A and + // leave the 2 cores (with use count 2) on node B unallocated for this scheduler. + // + // --------------- --------------- + // | - - | | - - | + // | |1| |1| | | |1| |1| | + // | - - | | - - | + // | | | | + // | - | | | + // | |1| 2 | | 2 2 | + // | - | | | + // --------------- --------------- + // Node A Node B + // + // Lowering the number of available cores on NodeB to the value of request allows us to preferentially allocate as many cores as + // possible on the same node (NodeA) to take advantage of, for instance, a node common L3 and use the same node TLB. + // Moreover, with the NUMA architecture of all current nodes, it is a much higher priority to collocate scheduler + // core allocation on a minimum number of nodes and pack each a full as possible. + + if (pMaxNode->m_availableCores + pMaxNode->m_reservedCores + pMaxNode->m_allocatedCores < + pNode->m_availableCores + pNode->m_reservedCores + pNode->m_allocatedCores) + { + // m_reservedCores is the number of cores reserved on previous passes for a lower useCount, and m_allocatedCores is + // the number allocated on a previous allocation attempt. So this will set pMaxNode to be the one where the greatest + // number of cores are or will be allocated from. + maxAllocationIndex = j; + pMaxNode = &pAllocatedNodes[pSortedNodeOrder[maxAllocationIndex]]; + } + else if (pMaxNode->m_availableCores + pMaxNode->m_reservedCores + pMaxNode->m_allocatedCores == + pNode->m_availableCores + pNode->m_reservedCores + pNode->m_allocatedCores) + { + // If all things are equal from the core-packing perspective, bias towards this node if we need an external + // thread allocation and this node is the one the external thread is affinitized to. + if (pStaticData->m_fNeedsExternalThreadAllocation && pSortedNodeOrder[j] == currentNodeIndex) + { + maxAllocationIndex = j; + pMaxNode = &pAllocatedNodes[pSortedNodeOrder[maxAllocationIndex]]; + } + } + } + } // end of if (remainingRequest > 0) + + ASSERT(pMaxNode->m_availableCores <= INT_MAX); + + if (pMaxNode->m_availableCores > 0) + { + for (unsigned int k = 0; k < pMaxNode->m_coreCount; ++k) + { + SchedulerCore *pCore = &pMaxNode->m_pCores[k]; + if (pCore->m_coreState == ProcessorCore::Available) + { + if (reserved < request) + { + // Reserve this core for the scheduler proxy. + pCore->m_coreState = ProcessorCore::Reserved; + ++(*pCore->m_pGlobalUseCountPtr); + ++pMaxNode->m_reservedCores; + + // If we needed an external thread allocation and the allocation to this node satisfies that + // external allocation, clear the flag so no more biasing will be needed. + if (pStaticData->m_fNeedsExternalThreadAllocation && pSortedNodeOrder[maxAllocationIndex] == currentNodeIndex) + { + pStaticData->m_fNeedsExternalThreadAllocation = false; + } + ++reserved; + } + else + { + // This is an 'extra' available core. Set its state back to Unassigned. + pCore->m_coreState = ProcessorCore::Unassigned; + } + } + } + pMaxNode->m_availableCores = 0; + } + + if (i != maxAllocationIndex) + { + // Swap the index at 'maxAllocationIndex' with the index at 'i'. The next iteration will traverse nodes starting at + // m_pSortedNodeOrder[i + i]. + unsigned int tempIndex = pSortedNodeOrder[i]; + pSortedNodeOrder[i] = pSortedNodeOrder[maxAllocationIndex]; + pSortedNodeOrder[maxAllocationIndex] = tempIndex; + } + } + } + + return reserved; + } + +#pragma warning(push) +#pragma warning(disable:26017) // bogus overflow warning +#pragma warning(disable:26011) // bogus overflow warning + + /// + /// Instruct a scheduler proxy to free up a fixed number of resources. This is only a temporary release of resources. The + /// use count on the global core is decremented and the scheduler proxy remembers the core as temporarily released. At a later + /// point, the release is either confirmed or rolled back, depending on whether the released core was used to satisfy the + /// receiving scheduler's allocation. + /// + /// + /// The scheduler proxy for which the cores are being stolen - this is the proxy that is being currently allocated to. + /// + /// + /// The scheduler proxy that needs to free up resources. + /// + /// + /// The number of resources to free. This parameter can have a couple of special values: + /// ReleaseCoresDownToMin - scheduler should release all cores above its minimum. Preference is giving to releasing borrowed cores. + /// ReleaseOnlyBorrowedCores - scheduler should release all borrowed cores. + /// If the parameter is not a special value, a call should have previously been made for this scheduler with the value ReleaseOnlyBorrowedCores. + /// i.e., the scheduler should not have any borrowed cores to release. + /// + bool ResourceManager::ReleaseSchedulerResources(SchedulerProxy * pReceivingProxy, SchedulerProxy *pGivingProxy, unsigned int numberToFree) + { + ASSERT(pReceivingProxy != NULL && pGivingProxy != NULL); + + unsigned int numBorrowedCores = 0; + unsigned int numOwnedCores = 0; + StaticAllocationData * pStaticData = pGivingProxy->GetStaticAllocationData(); + + if (numberToFree == ReleaseOnlyBorrowedCores) + { + // We should only get one request to release borrowed cores - there should be no cores already stolen at this time. + ASSERT(pStaticData->m_numCoresStolen == 0); + + numberToFree = numBorrowedCores = pGivingProxy->GetNumBorrowedCores(); + } + else if (numberToFree == ReleaseCoresDownToMin) + { + ASSERT(pGivingProxy->GetNumBorrowedCores() == 0 || pStaticData->m_numCoresStolen >= pGivingProxy->GetNumBorrowedCores()); + ASSERT(pGivingProxy->GetNumOwnedCores() >= pGivingProxy->MinHWThreads()); + + // Number to stolen includes all borrowed cores, if any, and possibly some owned cores. + numberToFree = (pGivingProxy->GetNumOwnedCores() - pGivingProxy->MinHWThreads()) - + (pStaticData->m_numCoresStolen - pGivingProxy->GetNumBorrowedCores()); + numBorrowedCores = 0; + } + else + { + // If we're asked to release a specific number of cores, borrowed cores should already have been released, and we should + // not encounter any borrowed cores during our search. + ASSERT(pStaticData->m_numCoresStolen == pGivingProxy->GetNumBorrowedCores()); + ASSERT(pGivingProxy->GetNumOwnedCores() >= pGivingProxy->MinHWThreads()); + ASSERT(numberToFree > 0 && numberToFree <= pGivingProxy->GetNumOwnedCores() - pGivingProxy->MinHWThreads()); + numBorrowedCores = 0; + } + + // We are only allowed to free numOwnedCores owned cores. + ASSERT(numberToFree >= numBorrowedCores && numberToFree <= INT_MAX); + numOwnedCores = numberToFree - numBorrowedCores; + + if (numberToFree > 0) + { + SchedulerNode *pGivingNodes = pGivingProxy->GetAllocatedNodes(); + SchedulerNode *pReceivingNodes = pReceivingProxy->GetAllocatedNodes(); + unsigned int * pReceivingNodeOrder = pReceivingProxy->GetSortedNodeOrder(); + + // Walk through the sorted indices array, and try to release cores in nodes that appear earlier in the array. That way + // we increase the possibility of giving up cores on a node the new scheduler already has some cores on. + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode *pReceivingNode = &pReceivingNodes[pReceivingNodeOrder[nodeIndex]]; + + // Even if all the cores in this node are already allocated or reserved for the new scheduler, we need to traverse the releasing + // scheduler proxy's node, to accurately maintain counts. + SchedulerNode *pGivingNode = &pGivingNodes[pReceivingNodeOrder[nodeIndex]]; + + ASSERT(pGivingNode->m_id == pReceivingNode->m_id); + ASSERT(pGivingNode->m_coreCount == pReceivingNode->m_coreCount); + + // Only traverse the cores if the giving scheduler proxy was allocated cores from this node. + if (pGivingNode->GetNumMigratableCores() > 0) + { + for (unsigned int coreIndex = 0; coreIndex < pGivingNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pGivingNode->m_pCores[coreIndex]; + if ((pAllocatedCore->m_coreState == ProcessorCore::Allocated) && !pAllocatedCore->IsFixed()) + { + ASSERT(numBorrowedCores > 0 || !pAllocatedCore->IsBorrowed()); + + // We may have to skip over some owned cores so that we can release the required number of borrowed cores. + if (pAllocatedCore->IsBorrowed() || numOwnedCores > 0) + { + ASSERT(!pAllocatedCore->IsBorrowed() || *pAllocatedCore->m_pGlobalUseCountPtr > 1); + + pAllocatedCore->m_coreState = ProcessorCore::Stolen; + ++pStaticData->m_numCoresStolen; + + // Only the global use count is decremented here. The number allocated to this proxy is updated once the + // allocation is finished (in CommitStolenCores), if this core was allocated to the new scheduler. + + --(*pAllocatedCore->m_pGlobalUseCountPtr); + if (!pAllocatedCore->IsBorrowed()) + { + ASSERT(numOwnedCores > 0); + --numOwnedCores; + } + + ASSERT(numberToFree > 0 && numberToFree <= INT_MAX); + if (--numberToFree == 0) + { + ValidateStaticSchedulerState(pGivingProxy); + return true; + } + } + } + } + } + } + + ASSERT(numberToFree == 0); + } + ValidateStaticSchedulerState(pGivingProxy); + // The scheduler proxy does not have any cores available to free. + return false; + } + + /// + /// Called to claim back any previously released cores that were not allocated to a different scheduler. If released + /// cores were allocated (stolen), the proxy needs to notify its scheduler to give up the related virtual processor + /// roots. + /// + void ResourceManager::CommitStolenCores(SchedulerProxy * pNewSchedulerProxy) + { + ASSERT(pNewSchedulerProxy == m_ppProxyData[0]->m_pProxy); + SchedulerNode * pNewNodes = pNewSchedulerProxy->GetAllocatedNodes(); + + // Go through one core at a time, and check all schedulers. + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pNewNode = &pNewNodes[nodeIndex]; + for (unsigned int coreIndex = 0; coreIndex < pNewNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pNewCore = &pNewNode->m_pCores[coreIndex]; + unsigned int fAlreadyBorrowed = false; + for (unsigned int index = 1; index < m_numSchedulers; ++index) + { + SchedulerProxy * pSchedulerProxy = m_ppProxyData[index]->m_pProxy; + StaticAllocationData * pStaticData = pSchedulerProxy->GetStaticAllocationData(); + if (pStaticData->m_numCoresStolen > 0) + { + SchedulerNode * pAllocatedNodes = m_ppProxyData[index]->m_pProxy->GetAllocatedNodes(); + SchedulerNode * pAllocatedNode = &pAllocatedNodes[nodeIndex]; + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + if (pAllocatedCore->m_coreState == ProcessorCore::Stolen) + { + if (pNewCore->m_coreState == ProcessorCore::Allocated) + { + // The core was allocated to the new scheduler - we need to decide what to do with + // the stolen core on the original scheduler. + if (pNewCore->m_subscriptionLevel == 0) + { + // The new scheduler is not using the core yet. Check if the original scheduler + // is using the core. + if (pAllocatedCore->IsIdle() || fAlreadyBorrowed) + { + // Either the original scheduler is not using the core, or if it is, we lent it to + // a different scheduler earlier in the iteration. We cannot have two schedulers borrowing + // a core at the same time, so we have to remove it here. + pSchedulerProxy->RemoveCore(pAllocatedNode, coreIndex); + } + else + { + // The original scheduler is still using the core. We mark the core as borrowed if it + // is not already marked as borrowed. + ++(*pAllocatedCore->m_pGlobalUseCountPtr); + pAllocatedCore->m_coreState = ProcessorCore::Allocated; + if (!pAllocatedCore->IsBorrowed()) + { + pSchedulerProxy->ToggleBorrowedState(pAllocatedNode, coreIndex); + } + fAlreadyBorrowed = true; + } + } + else + { + // The core is in use by the new scheduler. We need to remove it from the + // scheduler we stole it from. This is expected if the core was allocated for a + // subscribed thread, or if the scheduler activated it at the time it was + // added. + pSchedulerProxy->RemoveCore(pAllocatedNode, coreIndex); + } + } + else + { + ASSERT(pNewCore->m_coreState == ProcessorCore::Unassigned); + // If the was core not allocated to the new scheduler, this scheduler can claim it back. + ++(*pAllocatedCore->m_pGlobalUseCountPtr); + pAllocatedNode->m_pCores[coreIndex].m_coreState = ProcessorCore::Allocated; + } + } + } + } + } + } + + // Ensure that we did not end up lending a core to more than scheduler. + ValidateBorrowedCores(); + } + + /// + /// Creates a scheduler proxy for an IScheduler that registers with the RM. + /// + SchedulerProxy* ResourceManager::CreateSchedulerProxy(IScheduler *pScheduler) + { + SchedulerPolicy policy = pScheduler->GetPolicy(); + return _concrt_new SchedulerProxy(pScheduler, this, policy); + } + +#pragma warning(pop) + + // DYNAMIC RM OVERVIEW + // A high priority background thread is responsible for waking up at fixed intervals and rebalancing cores among + // schedulers. The RM first gathers statistical information based on information about task completion and queue length + // from each scheduler, then feeds it into a hill climbing instance, which uses history to generate a number between + // MinHWThreads and MaxHWThreads for that scheduler. This number is the suggested new allocation for the scheduler. + // At the same time, RM also finds the number of 'idle cores' on the machine (cores such that every scheduler that was + // allocated on it is not using it). Idle cores are game for temporary oversubscription, if unused cores and cores the RM + // can take from schedulers are not enough to satisfy the schedulers that need cores. + // + // The RM then starts to assign cores to schedulers that need cores to satisfy their new suggested allocation. It + // takes away cores from schedulers that have more cores than their suggested allocation and looks for any unused + // cores from schedulers that have finished execution and shutdown. After all unused cores and cores taken from other + // schedulers have been assigned, it starts assigning idle cores to schedulers in need, oversubscribing them with + // the original core owners (these cores are shared rather than transferred because they contribute to the minimum + // requirement for the schedulers they belong to, and cannot be taken away). These cores are termed as borrowed cores, + // and may be taken away if the original scheduler(s) the core was assigned to start using them). + // + // Once the RM has a list of schedulers willing to give up cores (termed as givers) and schedulers that need cores + // (termed as receivers), it tries to maximize locality while taking/assigning cores. It does this in two phases. + // For each receiver , it first tries to see if it can find an available core to assign to a partially + // allocated node on the receiver. It cycles through the receivers assigning one core per receiver if possible, + // until all partially allocated nodes are filled, or no cores are available on those nodes. + // + // If there are receivers that still need cores, it attempts to pick an empty node on each receiver in turn, which will + // give the best fit allocation (from among available cores on that node), and proceeds to allocate to that node first. + // It continues this process, picking a single node on a receiver per iteration until all request are satisfied. + +#if defined(CONCRT_TRACING) + + /// + /// Captures the initial state of the global map at the beginning of core migration, each cycle. + /// + void ResourceManager::TraceInitialDRMState() + { + // Capture the initial state after calculating idle core information. + int traceCoreIndex = 0; + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + for (unsigned int coreIndex = 0; coreIndex < pGlobalNode->m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &pGlobalNode->m_pCores[coreIndex]; + GlobalCoreData * pCoreData = &m_drmInitialState[traceCoreIndex++]; + pCoreData->m_nodeIndex = (unsigned char)nodeIndex; + pCoreData->m_coreIndex = (unsigned char)coreIndex; + pCoreData->m_useCount = (unsigned char)pGlobalCore->m_useCount; + pCoreData->m_idleSchedulers = (unsigned char)pGlobalCore->m_idleSchedulers; + } + } + ASSERT(traceCoreIndex == m_numTotalCores); + + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + m_ppProxyData[index]->m_pProxy->TraceInitialDRMState(); + } + } + + /// + /// Captures data relating to an action during DRM preprocessing. + /// + void ResourceManager::TracePreProcessingAction(SchedulerProxy * pProxy, unsigned int nodeIndex, unsigned int coreIndex, + bool fMarkedAsOwned, bool fBorrowedCoreRemoved, bool fSharedCoreRemoved, + bool fIdleCore) + { + PreProcessingTraceData * pTraceData = &m_preProcessTraces[m_preProcessTraceIndex++]; + ASSERT(m_preProcessTraceIndex <= 100); + + pTraceData->m_pProxy = pProxy; + pTraceData->m_nodeIndex = (unsigned char)nodeIndex; + pTraceData->m_coreIndex = (unsigned char)coreIndex; + pTraceData->m_fMarkedAsOwned = fMarkedAsOwned; + pTraceData->m_fBorrowedCoreRemoved = fBorrowedCoreRemoved; + pTraceData->m_fSharedCoreRemoved = fSharedCoreRemoved; + pTraceData->m_fIdleCore = fIdleCore; + + if (fMarkedAsOwned) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Scheduler %d[min=%d, max=%d]: Preprocessing: Marking borrowed core [%d, %d] as owned (%ls))\n", + pProxy->GetId(), pProxy->MinHWThreads(), pProxy->DesiredHWThreads(), nodeIndex, coreIndex, fIdleCore ? L"idle" : L""); + } + else if (fBorrowedCoreRemoved) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Scheduler %d[min=%d, max=%d]: Preprocessing: Removing borrowed core [%d, %d] since it is used by owner(s)(%ls)\n", + pProxy->GetId(), pProxy->MinHWThreads(), pProxy->DesiredHWThreads(), nodeIndex, coreIndex, fIdleCore ? L"idle" : L""); + } + else if (fSharedCoreRemoved) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Scheduler %d[min=%d, max=%d]: Preprocessing: Removing shared core [%d, %d] (%ls)\n", + pProxy->GetId(), pProxy->MinHWThreads(), pProxy->DesiredHWThreads(), nodeIndex, coreIndex, fIdleCore ? L"idle" : L""); + } + } + + /// + /// Captures data relating to an action during DRM core migration. + /// + void ResourceManager::TraceCoreMigrationAction(SchedulerProxy * pGiver, SchedulerProxy * pReceiver, unsigned int round, unsigned int nodeIndex, + unsigned int coreIndex, bool fUnusedCoreMigration, bool fIdleCoreSharing, bool fBorrowedByGiver, + bool fIdleOnGiver) + { + DynamicAllocationTraceData * pTraceData = &m_dynAllocationTraces[m_dynAllocationTraceIndex++]; + ASSERT(m_dynAllocationTraceIndex <= 100); + + pTraceData->m_pGiver = pGiver; + pTraceData->m_pReceiver = pReceiver, + pTraceData->m_round = (unsigned char)round; + pTraceData->m_nodeIndex = (unsigned char)nodeIndex; + pTraceData->m_coreIndex = (unsigned char)coreIndex; + pTraceData->m_fUnusedCoreMigration = fUnusedCoreMigration; + pTraceData->m_fIdleCoreSharing = fIdleCoreSharing; + pTraceData->m_fBorrowedByGiver = fBorrowedByGiver; + pTraceData->m_fIdleOnGiver = fIdleOnGiver; + + if (fUnusedCoreMigration) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Assigned unused core [%d, %d] to scheduler %d[min=%d, max=%d]\n", + nodeIndex, coreIndex, pReceiver->GetId(), pReceiver->MinHWThreads(), pReceiver->DesiredHWThreads()); + } + else if (fIdleCoreSharing) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Assigned idle core [%d, %d] to scheduler %d[min=%d, max=%d]\n", + nodeIndex, coreIndex, pReceiver->GetId(), pReceiver->MinHWThreads(), pReceiver->DesiredHWThreads()); + } + else + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Migrated core [%d, %d] from scheduler %d[min=%d, max=%d] to scheduler %d[min=%d, max=%d] (%ls%ls%ls)\n", + nodeIndex, coreIndex, pGiver->GetId(), pGiver->MinHWThreads(), pGiver->DesiredHWThreads(), + pReceiver->GetId(), pReceiver->MinHWThreads(), pReceiver->DesiredHWThreads(), fBorrowedByGiver ? L"borrowed" : L"", + fBorrowedByGiver && fIdleOnGiver ? L", " : L"", fIdleOnGiver ? L"idle" : L"" ); + } + } + +#endif + + /// + /// Performs state validations during static allocation. + /// + void ResourceManager::ValidateStaticSchedulerState(SchedulerProxy * pSchedulerProxy) + { +#if defined (_DEBUG) + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + unsigned int numAllocated = 0; + + // For each core, go through every scheduler and find out if more than 1 scheduler has that core borrowed + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode *pAllocatedNode = &pAllocatedNodes[nodeIndex]; + + for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + if (pAllocatedCore->m_coreState == ProcessorCore::Allocated) + { + numAllocated++; + } + } + } + + ASSERT(numAllocated >= pSchedulerProxy->MinVprocHWThreads()); +#endif + } + + /// + /// Performs state validations during dynamic core migration. + /// + void ResourceManager::ValidateDRMSchedulerState() + { +#if defined (_DEBUG) + // No schedulers should have any borrowed idle cores left + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + ASSERT(m_ppProxyData[index]->m_numBorrowedIdleCores == 0); + } + ValidateBorrowedCores(); +#endif + } + + /// + /// Performs borrowed core validation. A core can be borrowed by only one scheduler at a time. + /// + void ResourceManager::ValidateBorrowedCores() + { +#if defined (_DEBUG) + // For each core, go through every scheduler and find out if more than 1 scheduler has that core borrowed. + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + for (unsigned int coreIndex = 0; coreIndex < m_pGlobalNodes[nodeIndex].m_coreCount; ++coreIndex) + { + unsigned int numBorrowingSchedulers = 0; + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + SchedulerNode * pAllocatedNodes = m_ppProxyData[index]->m_pProxy->GetAllocatedNodes(); + SchedulerCore * pAllocatedCore = &pAllocatedNodes[nodeIndex].m_pCores[coreIndex]; + if (pAllocatedCore->m_coreState == ProcessorCore::Allocated && pAllocatedCore->IsBorrowed()) + { + ++numBorrowingSchedulers; + ASSERT(numBorrowingSchedulers < 2); + } + } + } + } +#endif + } + + /// + /// Ensures that the memory buffers needed for dynamic RM are of the right size, and initializes them. + /// + void ResourceManager::InitializeRMBuffers() + { + if (m_maxSchedulers < m_numSchedulers) + { + // Resize the buffers. + while (m_maxSchedulers < m_numSchedulers) + { + m_maxSchedulers *= 2; + } + + delete [] m_ppProxyData; + delete [] m_ppGivingProxies; + delete [] m_ppReceivingProxies; + + m_ppProxyData = _concrt_new AllocationData *[m_maxSchedulers]; + if (m_ppGivingProxies != NULL) + { + ASSERT(m_ppReceivingProxies != NULL); + m_ppGivingProxies = _concrt_new DynamicAllocationData *[m_maxSchedulers]; + m_ppReceivingProxies = _concrt_new DynamicAllocationData *[m_maxSchedulers]; + } + } + + memset(m_ppProxyData, 0, sizeof(AllocationData *) * m_numSchedulers); + if (m_ppGivingProxies != NULL) + { + ASSERT(m_ppReceivingProxies != NULL); + memset(m_ppGivingProxies, 0, sizeof(DynamicAllocationData *) * m_numSchedulers); + memset(m_ppReceivingProxies, 0, sizeof(DynamicAllocationData *) * m_numSchedulers); + } + +#if defined(CONCRT_TRACING) + memset(m_preProcessTraces, 0, sizeof(PreProcessingTraceData) * m_preProcessTraceIndex); + memset(m_dynAllocationTraces, 0, sizeof(DynamicAllocationTraceData) * m_dynAllocationTraceIndex); + m_preProcessTraceIndex = m_dynAllocationTraceIndex = 0; +#endif + } + + /// + /// Toggles the idle state on a core during the dynamic RM phase and updates tracking counts. + /// + void ResourceManager::ToggleRMIdleState(SchedulerNode * pAllocatedNode, SchedulerCore * pAllocatedCore, + GlobalNode * pGlobalNode, GlobalCore * pGlobalCore, AllocationData * pDRMData) + { + if (pAllocatedCore->IsIdle()) + { + pAllocatedCore->m_fIdleDuringDRM = false; + + --pDRMData->m_numIdleCores; + --pAllocatedNode->m_numDRMIdle; + + if (pAllocatedCore->IsBorrowed()) + { + --pDRMData->m_numBorrowedIdleCores; + --pAllocatedNode->m_numDRMBorrowedIdle; + } + + if (pGlobalCore->m_coreState == ProcessorCore::Idle) + { + pGlobalCore->m_coreState = ProcessorCore::Unknown; + --pGlobalNode->m_idleCores; + --m_dynamicIdleCoresAvailable; + } + --pGlobalCore->m_idleSchedulers; + } + else + { + pAllocatedCore->m_fIdleDuringDRM = true; + + ++pDRMData->m_numIdleCores; + ++pAllocatedNode->m_numDRMIdle; + + if (pAllocatedCore->IsBorrowed()) + { + ++pDRMData->m_numBorrowedIdleCores; + ++pAllocatedNode->m_numDRMBorrowedIdle; + } + + ASSERT(pGlobalCore->m_coreState != ProcessorCore::Idle); + + ++pGlobalCore->m_idleSchedulers; + ASSERT(pGlobalCore->m_idleSchedulers <= pGlobalCore->m_useCount); + } + } + + /// + /// Populates data needed for allocation (static or dynamic). + /// + void ResourceManager::PopulateCommonAllocationData(unsigned int index, SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData) + { + pAllocationData->m_index = index; + pAllocationData->m_scaledAllocation = 0.0; + pAllocationData->m_pProxy = pSchedulerProxy; + + // We need to find the number of inactive cores on this scheduler proxy. Note that since cores can be activated and deactivated at any + // time, any number we use for number of idle cores could be stale the moment we compute it. However, that is the nature of the problem. + // We work from data at a particular snapshot in time. + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + if (pAllocatedNodes != NULL) // this could be the scheduler that is just being created, in which case the field is NULL. + { + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pAllocatedNode = &pAllocatedNodes[nodeIndex]; + // Set these to zero before we start counting up idle cores we find. + pAllocatedNode->m_numDRMIdle = 0; + pAllocatedNode->m_numDRMBorrowedIdle = 0; + if (pAllocatedNode->m_allocatedCores > 0) + { + for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + pAllocatedCore->m_fIdleDuringDRM = false; + + if (pAllocatedCore->m_coreState == ProcessorCore::Allocated) + { + // Subscription level can change out from under us. + if (pAllocatedCore->m_subscriptionLevel == 0) + { + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + GlobalCore * pGlobalCore = &pGlobalNode->m_pCores[coreIndex]; + // If the subscription level is 0 this core is idle in the current scheduler proxy. Increment the count of idle schedulers + // on the global core - this represents the number of schedulers the core has been assigned to, that are not currently + // using the core. + + // Note that a fixed core can end up with a subscription level of 0, if it was fixed because code running on a virtual + // processor subscribed to a scheduler, and the virtual processor switched to a different context for whatever reason. + // If this core is idle, it cannot be taken away because it is fixed, and the fact that it contributes to min will take + // care of that. It can however be lent to a different scheduler. + ToggleRMIdleState(pAllocatedNode, pAllocatedCore, pGlobalNode, pGlobalCore, pAllocationData); + + // As noted above, this information could become stale soon after, but for the purpose of this iteration of core migration, + // we consider the core to be idle. + } + } + } + } + } + } + } + + /// + /// Captures data needed for static allocation, for all existing schedulers. This includes determining which + /// cores on a scheduler are idle. + /// + void ResourceManager::SetupStaticAllocationData(SchedulerProxy * pNewSchedulerProxy, bool fSubscribeCurrentThread) + { + InitializeRMBuffers(); + + // The scheduler we're allocating cores to, goes at index 0 in the array for convenience. + StaticAllocationData * pStaticData = pNewSchedulerProxy->GetStaticAllocationData(); + memset(pStaticData, 0, sizeof(StaticAllocationData)); + PopulateCommonAllocationData(0, pNewSchedulerProxy, pStaticData); + + // Initialize the static allocation specific fields. + pStaticData->m_adjustedDesired = pNewSchedulerProxy->DesiredHWThreads(); // for the new scheduler this value could be reset later + pStaticData->m_fNeedsExternalThreadAllocation = fSubscribeCurrentThread; + m_ppProxyData[0] = pStaticData; + + // Start the index at 1 for the remaining schedulers. + unsigned int index = 1; + SchedulerProxy * pSchedulerProxy = NULL; + + for (pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + if (pSchedulerProxy != pNewSchedulerProxy) + { + StaticAllocationData * pStaticData = pSchedulerProxy->GetStaticAllocationData(); + memset(pStaticData, 0, sizeof(StaticAllocationData)); + + PopulateCommonAllocationData(index, pSchedulerProxy, pStaticData); + + // Initialize the static allocation specific fields. + pStaticData->m_adjustedDesired = pSchedulerProxy->DesiredHWThreads(); + m_ppProxyData[index] = pStaticData; + ++index; + } + } + ASSERT(index == m_numSchedulers); + } + + /// + /// Captures data needed for dynamic allocation for all existing schedulers. This includes gathering statistics + /// and invoking a per scheduler hill climbing instance to get a suggested future allocation. Also determines how many + /// idle cores a scheduler has. + /// + void ResourceManager::PopulateDynamicAllocationData() + { + unsigned int index = 0; + SchedulerProxy * pSchedulerProxy = NULL; + + InitializeRMBuffers(); + + for (pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + DynamicAllocationData * pDynamicData = pSchedulerProxy->GetDynamicAllocationData(); + memset(pDynamicData, 0, sizeof(DynamicAllocationData)); + + PopulateCommonAllocationData(index, pSchedulerProxy, pDynamicData); + + // Initialize the dynamic allocation specific fields. + if (pSchedulerProxy->IsHillClimbingEnabled()) + { + // Initialize variables needed for statistics + unsigned int taskCompletionRate = 0, taskArrivalRate = 0; + + // Get the stored scheduler queue length + unsigned int numberOfTasksEnqueued = pSchedulerProxy->GetQueueLength(); + + // Get the current number of cores allocated to this scheduler + unsigned int numCoresAllocated = pSchedulerProxy->GetNumAllocatedCores(); + + // Collect statistical information about this scheduler + pSchedulerProxy->Scheduler()->Statistics(&taskCompletionRate, &taskArrivalRate, &numberOfTasksEnqueued); + + // Let hill climbing decide on the future allocation of cores for this scheduler. + pDynamicData->m_suggestedAllocation = pSchedulerProxy->DoHillClimbing(numCoresAllocated, + taskCompletionRate, + taskArrivalRate, + numberOfTasksEnqueued); + + // Ensure that the new allocation does not exceed maxconcurrency. Take in-use cores into account + if (pDynamicData->m_suggestedAllocation > pSchedulerProxy->GetNumAllocatedCores()) + { + pDynamicData->m_suggestedAllocation = pSchedulerProxy->AdjustAllocationIncrease(pDynamicData->m_suggestedAllocation); + } + +#if defined(CONCRT_TRACING) + pDynamicData->m_originalSuggestedAllocation = pDynamicData->m_suggestedAllocation; +#endif + + // Update the queue length using the number computed by the statistics + pSchedulerProxy->SetQueueLength(numberOfTasksEnqueued); + + ASSERT(pDynamicData->m_suggestedAllocation >= pSchedulerProxy->MinHWThreads() + && pDynamicData->m_suggestedAllocation <= pSchedulerProxy->DesiredHWThreads()); + } + else + { + pDynamicData->m_suggestedAllocation = pSchedulerProxy->GetNumAllocatedCores(); + } + + // Fully loaded is used to mark schedulers that: + // 1) Have a non-zero number of cores (or nested thread subscriptions), but no idle cores. + // 2) Have a suggested allocation greater than or equal to what they currently have. + // 3) Have less cores than they desire. + // If we have extra cores to give away or share, these schedulers could benefit from extra cores. + if (pSchedulerProxy->GetNumAllocatedCores() > 0) + { + pDynamicData->m_fFullyLoaded = (pDynamicData->m_numIdleCores == 0 && + pSchedulerProxy->GetNumAllocatedCores() <= pDynamicData->m_suggestedAllocation && + pSchedulerProxy->GetNumAllocatedCores() < pSchedulerProxy->DesiredHWThreads()); + } + else + { + // Account for external thread subscriptions on a nested scheduler with min = 0 + ASSERT(pSchedulerProxy->GetNumAllocatedCores() == 0); + ASSERT(pDynamicData->m_numIdleCores == 0); + pDynamicData->m_fFullyLoaded = (pSchedulerProxy->GetNumNestedThreadSubscriptions() > 0 && + pSchedulerProxy->GetNumAllocatedCores() <= pDynamicData->m_suggestedAllocation && + pSchedulerProxy->GetNumAllocatedCores() < pSchedulerProxy->DesiredHWThreads()); + } + + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Scheduler %d[min=%d, max=%d]: Initial values - Allocated: %d, Suggested: %d, Idle: %d, Borrowed: %d\n", + pSchedulerProxy->GetId(), pSchedulerProxy->MinHWThreads(), pSchedulerProxy->DesiredHWThreads(), pSchedulerProxy->GetNumAllocatedCores(), + pDynamicData->m_suggestedAllocation, pDynamicData->m_numIdleCores, pSchedulerProxy->GetNumBorrowedCores()); + + m_ppProxyData[index] = pDynamicData; + ++index; + } + +#if defined(CONCRT_TRACING) + TraceInitialDRMState(); +#endif + ASSERT(index == m_numSchedulers); + } + + /// + /// Undo global state that was initialized to perform static allocation or dynamic core migration. + /// + void ResourceManager::ResetGlobalAllocationData() + { + // Clear changes we've potentially made to the global nodes. + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + pGlobalNode->m_availableCores = 0; + pGlobalNode->m_idleCores = 0; + + for (unsigned int coreIndex = 0; coreIndex < pGlobalNode->m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &pGlobalNode->m_pCores[coreIndex]; + + pGlobalCore->m_coreState = ProcessorCore::Unknown; + pGlobalCore->m_idleSchedulers = 0; + } + } + } + + /// + /// Preprocessing steps for borrowed cores - both static and dynamic allocation start out with a call to this API. + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore. + /// + void ResourceManager::HandleBorrowedCores(SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData) + { + ASSERT(pSchedulerProxy->GetNumBorrowedCores() > 0); + + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pAllocatedNode = &pAllocatedNodes[nodeIndex]; + if (pAllocatedNode->m_numBorrowedCores > 0) + { + ASSERT(pAllocatedNode->m_allocatedCores >= pAllocatedNode->m_numBorrowedCores); + for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + if ((pAllocatedCore->m_coreState == ProcessorCore::Allocated) && pAllocatedCore->IsBorrowed()) + { + ASSERT(!pAllocatedCore->IsFixed()); + GlobalCore * pGlobalCore = &(m_pGlobalNodes[nodeIndex].m_pCores[coreIndex]); + if (pGlobalCore->m_useCount == 1) + { +#if defined(CONCRT_TRACING) + TracePreProcessingAction(pSchedulerProxy, + nodeIndex, + coreIndex, + true, /* borrowed core marked as owned */ + false, /* borrowed core removed */ + false, /* shared core removed */ + pAllocatedCore->IsIdle()); +#endif + + // This scheduler is the only one this core is assigned to. This could happen if + // the scheduler(s) the core was being shared with were shutdown. + ASSERT(pGlobalCore->m_idleSchedulers == 0 || (pAllocatedCore->IsIdle() && pGlobalCore->m_idleSchedulers == 1)); + ASSERT(pAllocatedCore->IsBorrowed()); + pSchedulerProxy->ToggleBorrowedState(pAllocatedNode, coreIndex); + if (pAllocatedCore->IsIdle()) + { + --pAllocatedNode->m_numDRMBorrowedIdle; + --pAllocationData->m_numBorrowedIdleCores; + } + } + else if ((pGlobalCore->m_useCount - pGlobalCore->m_idleSchedulers) > (unsigned int)(pAllocatedCore->IsIdle() ? 0 : 1)) + { +#if defined(CONCRT_TRACING) + TracePreProcessingAction(pSchedulerProxy, + nodeIndex, + coreIndex, + false, /* borrowed core marked as owned */ + true, /* borrowed core removed */ + false, /* shared core removed */ + pAllocatedCore->IsIdle()); +#endif + + // One or more of the other scheduler(s) this core is assigned to are using it. Since this was a borrowed core, + // we take it away here. + --pGlobalCore->m_useCount; + // Update the dynamic allocation data if this core is idle. + if(pAllocatedCore->IsIdle()) + { + ToggleRMIdleState(pAllocatedNode, pAllocatedCore, &m_pGlobalNodes[nodeIndex], pGlobalCore, pAllocationData); + } + pSchedulerProxy->RemoveCore(pAllocatedNode, coreIndex); + } + } + } + } + } + } + + /// + /// Preprocessing steps for shared cores - this is used during dynamic core migration. + /// - If the suggested allocation is less than the current allocation for a scheduler that has shared cores (cores oversubscribed + /// with a different scheduler), those cores are taken away here, since we want to minimize sharing. + /// + void ResourceManager::HandleSharedCores(SchedulerProxy * pSchedulerProxy, DynamicAllocationData * pAllocationData) + { + ASSERT(pAllocationData->m_numBorrowedIdleCores <= pSchedulerProxy->GetNumAllocatedCores() - pAllocationData->m_suggestedAllocation); + unsigned int maxCoresToRemove = min(pSchedulerProxy->GetNumAllocatedCores() - pAllocationData->m_suggestedAllocation - pAllocationData->m_numBorrowedIdleCores, + pSchedulerProxy->GetNumOwnedCores() - pSchedulerProxy->MinHWThreads()); + + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + for (unsigned int nodeIndex = 0; maxCoresToRemove > 0 && nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pAllocatedNode = &pAllocatedNodes[nodeIndex]; + if (pAllocatedNode->GetNumMigratableCores() > 0) + { + ASSERT(pAllocatedNode->m_allocatedCores >= pAllocatedNode->m_numBorrowedCores); + for (unsigned int coreIndex = 0; maxCoresToRemove > 0 && coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + if (pAllocatedCore->m_coreState == ProcessorCore::Allocated && + !pAllocatedCore->IsFixed() && !pAllocatedCore->IsBorrowed()) + { + GlobalCore * pGlobalCore = &(m_pGlobalNodes[nodeIndex].m_pCores[coreIndex]); + ASSERT(pGlobalCore->m_useCount > 0); + if (pGlobalCore->m_useCount > 1) + { +#if defined(CONCRT_TRACING) + TracePreProcessingAction(pSchedulerProxy, + nodeIndex, + coreIndex, + false, /* borrowed core marked as owned */ + false, /* borrowed core removed */ + true, /* shared core removed */ + pAllocatedCore->IsIdle()); +#endif + + --pGlobalCore->m_useCount; + + // Update the dynamic allocation data if this core is idle. + if(pAllocatedCore->IsIdle()) + { + ToggleRMIdleState(pAllocatedNode, pAllocatedCore, &m_pGlobalNodes[nodeIndex], pGlobalCore, pAllocationData); + } + + pSchedulerProxy->RemoveCore(pAllocatedNode, coreIndex); + --maxCoresToRemove; + } + } + } + } + } + ASSERT(pAllocationData->m_suggestedAllocation <= pSchedulerProxy->GetNumAllocatedCores()); + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + ASSERT(pAllocationData->m_numBorrowedIdleCores <= pSchedulerProxy->GetNumAllocatedCores() - pAllocationData->m_suggestedAllocation); + } + + /// + /// A number of preprocessing steps are performed before we are ready to allocate cores. They include handling of borrowed and idle + /// cores, as follows: + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore. + /// + void ResourceManager::PreProcessStaticAllocationData() + { + // Borrowed cores must be handled only after ALL schedulers have gone through populating allocation data. + // We need global information about idle cores when we deal with borrowed cores below. + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + SchedulerProxy * pSchedulerProxy = m_ppProxyData[index]->m_pProxy; + if (pSchedulerProxy->GetNumBorrowedCores() > 0) + { + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + HandleBorrowedCores(pSchedulerProxy, m_ppProxyData[index]); + } + } + } + + /// + /// A number of preprocessing steps are preformed before we are ready to migrate cores. They include handling of borrowed, idle, + /// and shared cores, as follows: + /// + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore. + /// - If hill climbing has suggested an allocation increase for a scheduler that has idle cores, or an allocation decrease that + /// does not take away all its idle cores, the RM overrides it, setting the suggested allocation for that scheduler to + /// max(minCores, allocatedCores - idleCores). + /// + /// The new value of suggested allocation is used for the following: + /// - If the suggested allocation is less than the current allocation for a scheduler that has shared cores (cores oversubscribed + /// with a different scheduler), those cores are taken away here, since we want to minimize sharing. + /// + void ResourceManager::PreProcessDynamicAllocationData() + { + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + DynamicAllocationData * pDynamicData = static_cast(m_ppProxyData[index]); + SchedulerProxy * pSchedulerProxy = pDynamicData->m_pProxy; + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + + if (pSchedulerProxy->GetNumBorrowedCores() > 0) + { + HandleBorrowedCores(pSchedulerProxy, pDynamicData); + } + + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + ASSERT(pDynamicData->m_numIdleCores <= pSchedulerProxy->GetNumAllocatedCores()); + + // If hill climbing has suggested an allocation increase for a scheduler with idle cores, or an allocation decrease that does not + // take away all its idle cores over the minimum, we override the suggested allocation here. + if (pDynamicData->m_numIdleCores > 0 && + pDynamicData->m_suggestedAllocation > pSchedulerProxy->GetNumAllocatedCores() - pDynamicData->m_numIdleCores) + { + pDynamicData->m_suggestedAllocation = max(pSchedulerProxy->MinHWThreads(), pSchedulerProxy->GetNumAllocatedCores() - pDynamicData->m_numIdleCores); + ASSERT(pDynamicData->m_fFullyLoaded == false); + } + + // Make another pass, since the loop above could change the state of some cores, as well as the borrowed and allocated counts. + // Check if we can take away any owned shared cores from this scheduler. We don't want to migrate these cores, so we can minimize + // sharing if possible. While taking away cores, we must ensure that there are enough owned cores to satisfy MinHWThreads(). + + // Since we must migrate all borrowed idle cores, (we don't want to lend the underlying core to a different scheduler as part of the + // distribute idle cores phase), we need to take that into account while deciding how many shared owned cores we can give up, if any. + + if (pDynamicData->m_suggestedAllocation < pSchedulerProxy->GetNumAllocatedCores() && + pSchedulerProxy->GetNumOwnedCores() > pSchedulerProxy->MinHWThreads()) + { + HandleSharedCores(pSchedulerProxy, pDynamicData); + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + } + + // Fix for Intel - Prevent current concurrency from going over max concurrency. + if (!pSchedulerProxy->IsHillClimbingEnabled() && (pDynamicData->m_suggestedAllocation > pSchedulerProxy->GetNumAllocatedCores())) + { + pDynamicData->m_suggestedAllocation = pSchedulerProxy->GetNumAllocatedCores(); + } + } + } + + /// + /// This routine increases the suggested allocation to desired, for schedulers with the following characteristics: + /// 1) Hill climbing has *not* recommended an allocation decrease. + /// 2) They are using all the cores allocated to them (no idle cores). + /// In the second round of core migration, we try to satisfy these schedulers' desired allocation. + /// + void ResourceManager::IncreaseFullyLoadedSchedulerAllocations() + { + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + DynamicAllocationData * pDynamicData = static_cast(m_ppProxyData[index]); + if (pDynamicData->m_fFullyLoaded == true) + { + SchedulerProxy * pSchedulerProxy = pDynamicData->m_pProxy; + ASSERT(pDynamicData->m_suggestedAllocation >= pSchedulerProxy->GetNumAllocatedCores()); + ASSERT(pDynamicData->m_numIdleCores == 0); + // Increase the suggested allocation to it's max. Note that this will ONLY be satisfied if cores can be taken away from other schedulers, + // or if there are idle/unused cores available. + pDynamicData->m_suggestedAllocation = pSchedulerProxy->AdjustAllocationIncrease(pSchedulerProxy->DesiredHWThreads()); + } + } + } + + /// + /// Decides on the number of additional cores to give a set of schedulers given what the schedulers need and what is available. + /// If the sum of needed cores is less than the sum of all available cores, it reduces the amount of cores it will give each + /// scheduler. The additional allocation is proportional to the difference between the suggested allocation and what the + /// scheduler already has allocated to it. + /// + unsigned int ResourceManager::AdjustDynamicAllocation(unsigned int coresAvailable, unsigned int coresNeeded, unsigned int numReceivers) + { + unsigned int coresTransferred = 0; + if (coresAvailable < coresNeeded) + { + // We cannot satisfy the requirement with what we have available. We take the cores available and distribute them + // proportional to the requirement of the schedulers that need cores. + if (numReceivers == 1) + { + // If there is just one receiver, we can simply assign the available cores to it. + m_ppReceivingProxies[0]->m_allocation = coresAvailable; + } + else + { + // Go through the receivers and reduce their new allocation proportional to the difference between + // what they already have and the suggested new allocation, so we can satisfy it. + double scaling = (double)coresAvailable/(double)coresNeeded; + + for (unsigned int rec = 0; rec < numReceivers; ++rec) + { + // Scale the difference between the new allocation and what the proxy already has. After rounding up, + // we get an integer that represents the additional number of cores to give to this scheduler out of + // what we have available. + m_ppReceivingProxies[rec]->m_scaledAllocation = scaling * (m_ppReceivingProxies[rec]->m_suggestedAllocation - + m_ppReceivingProxies[rec]->m_pProxy->GetNumAllocatedCores()); + } + + // RoundUpScaledAllocations populates m_ppReceivingProxies[rec]->m_allocation, such that the sum of all allocations + // is the number of cores available. + RoundUpScaledAllocations((AllocationData **)m_ppReceivingProxies, numReceivers, coresAvailable); + } + coresTransferred = coresAvailable; + } + else + { + // We can satisfy all receivers with the number available. + for (unsigned int rec = 0; rec < numReceivers; ++rec) + { + m_ppReceivingProxies[rec]->m_allocation = m_ppReceivingProxies[rec]->m_suggestedAllocation - + m_ppReceivingProxies[rec]->m_pProxy->GetNumAllocatedCores(); + } + coresTransferred = coresNeeded; + } + return coresTransferred; + } + + /// + /// Initializes receiving proxy data in preparation for core transfer. Calculates the number of partially filled nodes + /// for schedulers that are receiving cores, and sorts the receiving proxy data in increasing order of partial nodes. + /// + /// + /// Number of receivers that still need cores (allocation field of the receiving proxy data > 0). + /// + unsigned int ResourceManager::PrepareReceiversForCoreTransfer(unsigned int numReceivers) + { + // For all receiving proxies with an allocation > 0 sort them by the number of partially filled nodes + // (nodes which have some but not cores on it allocated to the proxy), lowest first. We only care about + // proxies with non-zero partial nodes. + for (unsigned int i = 0; i < numReceivers; ++i) + { + while ((i < numReceivers) && (m_ppReceivingProxies[i]->m_allocation == 0)) + { + // Swap this element into the end of the array - we are not interested in it for the sort. + --numReceivers; + DynamicAllocationData * pTemp = m_ppReceivingProxies[i]; + m_ppReceivingProxies[i] = m_ppReceivingProxies[numReceivers]; + m_ppReceivingProxies[numReceivers] = pTemp; + } + + // Initialize variables that are used during core transfer; + m_ppReceivingProxies[i]->m_numPartiallyFilledNodes = 0; + m_ppReceivingProxies[i]->m_startingNodeIndex = 0; + m_ppReceivingProxies[i]->m_fExactFitAllocation = true; + } + + // At this point numReceivers is the number of receivers with a non-zero suggested allocation increase. + ASSERT(numReceivers > 0); + unsigned int remainingReceivers = numReceivers; + + for (unsigned int i = 0; i < numReceivers; ++i) + { + while ((i < numReceivers) && (m_ppReceivingProxies[i]->m_numPartiallyFilledNodes == 0)) + { + // Calculate the number of partially filled nodes for this receiver. + SchedulerNode * pAllocatedNodes = m_ppReceivingProxies[i]->m_pProxy->GetAllocatedNodes(); + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + if ((pAllocatedNodes[nodeIndex].m_allocatedCores > 0) && + (pAllocatedNodes[nodeIndex].m_allocatedCores < pAllocatedNodes[nodeIndex].m_coreCount)) + { + ++m_ppReceivingProxies[i]->m_numPartiallyFilledNodes; + } + } + + // If this proxy has 0 partially filled nodes - swap it into the end of the array - we are not interested in + // it for the purposes of sorting. + if (m_ppReceivingProxies[i]->m_numPartiallyFilledNodes == 0) + { + --numReceivers; + DynamicAllocationData * pTemp = m_ppReceivingProxies[i]; + m_ppReceivingProxies[i] = m_ppReceivingProxies[numReceivers]; + m_ppReceivingProxies[numReceivers] = pTemp; + } + } + } + + // The elements in the array with indices [0, numReceivers) has proxies with non-zero partially filled nodes. + // Perform a lowest first selection sort. + for (unsigned int i = 0; i < numReceivers; ++i) + { + unsigned int minIndex = i; + for (unsigned int j = i + 1; j < numReceivers; ++j) + { + if (m_ppReceivingProxies[j]->m_numPartiallyFilledNodes < m_ppReceivingProxies[minIndex]->m_numPartiallyFilledNodes) + { + minIndex = j; + } + } + if (i != minIndex) + { + DynamicAllocationData * pTemp = m_ppReceivingProxies[i]; + m_ppReceivingProxies[i] = m_ppReceivingProxies[minIndex]; + m_ppReceivingProxies[minIndex] = pTemp; + } + + // Now, for the scheduler proxy at location i, sort the nodes, using the sorted indices array. + // Place the partial nodes at the beginning of the array, and among partially filled nodes, + // sort by number of unallocated cores (lowest first). + SchedulerNode * pAllocatedNodes = m_ppReceivingProxies[i]->m_pProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = m_ppReceivingProxies[i]->m_pProxy->GetSortedNodeOrder(); + + // The outer loop only needs to make as many iterations as there are partially filled nodes in this + // scheduler proxy. + for (unsigned int m = 0; m < m_ppReceivingProxies[i]->m_numPartiallyFilledNodes; ++m) + { + unsigned int minIndex = m; + // We use the array 'sorted node order' to sort nodes, instead of swapping the nodes themselves + SchedulerNode * pMinNode = &pAllocatedNodes[pSortedNodeOrder[minIndex]]; + + // The inner node must make as many iterations as there are nodes. + for (unsigned int n = m + 1; n < m_nodeCount; ++n) + { + SchedulerNode * pNode = &pAllocatedNodes[pSortedNodeOrder[n]]; + + // Check if the current node is a partially filled node, and set it to be min, either if min + // is not a partially filled node itself, or if the current node is more tightly packed than the min node. + if ((pNode->m_allocatedCores > 0 && pNode->m_allocatedCores < pNode->m_coreCount) && + (!(pMinNode->m_allocatedCores > 0 && pMinNode->m_allocatedCores < pMinNode->m_coreCount) || + (pNode->m_allocatedCores > pMinNode->m_allocatedCores))) + { + minIndex = n; + pMinNode = &pAllocatedNodes[pSortedNodeOrder[minIndex]]; + } + } + + if (m != minIndex) + { + // Swap the index at 'minIndex' with the index at 'm'. The next iteration will traverse nodes starting at + // m_pSortedNodeOrder[m + 1]. + unsigned int tempIndex = pSortedNodeOrder[m]; + pSortedNodeOrder[m] = pSortedNodeOrder[minIndex]; + pSortedNodeOrder[minIndex] = tempIndex; + } + } + } + + return remainingReceivers; + } + + /// + /// Assigns a fixed number of unused cores to a scheduler. + /// + void ResourceManager::DynamicAssignCores(SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToAssign, bool fIdle) + { + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + ASSERT(numCoresToAssign > 0); + ASSERT ((!fIdle && pGlobalNode->m_availableCores >= numCoresToAssign) || + (fIdle && pGlobalNode->m_idleCores >= numCoresToAssign)); + + for (unsigned int coreIndex = 0; coreIndex < pGlobalNode->m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &pGlobalNode->m_pCores[coreIndex]; + // We claim reserved cores when fIdle is false, and idle cores when fIdle is true. + if ((pGlobalCore->m_coreState == ProcessorCore::Available && !fIdle) + || (pGlobalCore->m_coreState == ProcessorCore::Idle && fIdle)) + { +#if defined(CONCRT_TRACING) + TraceCoreMigrationAction(NULL, /* no giving proxy */ + pReceivingProxy, + m_allocationRound, + nodeIndex, + coreIndex, + !fIdle, /* unused core assignment */ + fIdle, /* idle core lending */ + false, /* borrowed by giving proxy (no giving proxy) */ + false); /* idle on giving proxy (no giving proxy) */ + +#endif + // Update the global core to reflect state for this scheduler proxy. + ++pGlobalCore->m_useCount; + + pGlobalCore->m_coreState = ProcessorCore::Unknown; + if (fIdle) + { + ASSERT(pGlobalNode->m_idleCores != 0); + --pGlobalNode->m_idleCores; + } + else + { + ASSERT(pGlobalNode->m_availableCores != 0); + --pGlobalNode->m_availableCores; + } + + // Update the allocation map for the scheduler proxy. + pReceivingProxy->AddCore(&pReceivingProxy->GetAllocatedNodes()[nodeIndex], coreIndex, fIdle); + if (--numCoresToAssign == 0) + { + return; + } + } + } + ASSERT(false); + } + + /// + /// Transfers a fixed number of cores from one scheduler to another. + /// + void ResourceManager::DynamicMigrateCores(DynamicAllocationData * pGivingProxyData, SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToMigrate) + { + SchedulerProxy * pGivingProxy = pGivingProxyData->m_pProxy; + SchedulerNode * pGivingNodes = pGivingProxy->GetAllocatedNodes(); + SchedulerNode * pGivingNode = &pGivingNodes[nodeIndex]; + + ASSERT (numCoresToMigrate > 0 && pGivingNode->GetNumMigratableCores() >= numCoresToMigrate); + // If there are borrowed cores, we prefer to take those away first. In addition, among borrowed, or owned cores, + // we prefer to take away idle core if we can find them. + ASSERT(pGivingNode->m_numBorrowedCores >= pGivingNode->m_numDRMBorrowedIdle); + ASSERT(pGivingNode->m_numDRMIdle >= pGivingNode->m_numDRMBorrowedIdle); + + // Calculate the number of each type of core we need to migrate. + unsigned int numBorrowedIdle = min(numCoresToMigrate, pGivingNode->m_numDRMBorrowedIdle); + unsigned int numBorrowedInUse = min (numCoresToMigrate - numBorrowedIdle, pGivingNode->m_numBorrowedCores - pGivingNode->m_numDRMBorrowedIdle); + + unsigned int remainingCores = numCoresToMigrate - numBorrowedIdle - numBorrowedInUse; + ASSERT(remainingCores <= pGivingNode->GetNumMigratableCores() - pGivingNode->GetNumBorrowedCores()); + + unsigned int numOwnedIdle = min(remainingCores, pGivingNode->m_numDRMIdle - pGivingNode->m_numDRMBorrowedIdle); + unsigned int numOwnedInUse = remainingCores - numOwnedIdle; + + ASSERT(numOwnedInUse <= (pGivingNode->m_allocatedCores - pGivingNode->m_numBorrowedCores) - (pGivingNode->m_numDRMIdle - pGivingNode->m_numDRMBorrowedIdle)); + ASSERT(numBorrowedIdle + numBorrowedInUse + numOwnedIdle + numOwnedInUse == numCoresToMigrate); + + for (unsigned int coreIndex = 0; coreIndex < pGivingNode->m_coreCount; ++coreIndex) + { + bool fMigrateCore = false; + SchedulerCore * pGivenCore = &pGivingNode->m_pCores[coreIndex]; + if (pGivenCore->m_coreState == ProcessorCore::Allocated && !pGivenCore->IsFixed()) + { + if (pGivenCore->IsBorrowed()) + { + if (pGivenCore->IsIdle() && numBorrowedIdle > 0) + { + --numBorrowedIdle; + fMigrateCore = true; + } + else if (numBorrowedInUse > 0) + { + --numBorrowedInUse; + fMigrateCore = true; + } + } + else if (pGivenCore->IsIdle() && numOwnedIdle > 0) + { + --numOwnedIdle; + fMigrateCore = true; + } + else if (numOwnedInUse > 0) + { + --numOwnedInUse; + fMigrateCore = true; + } + + if (fMigrateCore) + { +#if defined(CONCRT_TRACING) + TraceCoreMigrationAction(pGivingProxy, + pReceivingProxy, + m_allocationRound, + nodeIndex, + coreIndex, + false, /* unused core assignment */ + false, /* idle core lending */ + pGivenCore->IsBorrowed(), /* borrowed by giving proxy */ + pGivenCore->IsIdle()); /* idle on giving proxy */ + +#endif + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + GlobalCore * pGlobalCore = &(m_pGlobalNodes[nodeIndex].m_pCores[coreIndex]); + + // The use count on the global core remains unchanged, since we're just migrating a core. + bool isIdleCore = pGivenCore->IsIdle(); + if (isIdleCore) + { + ToggleRMIdleState(pGivingNode, pGivenCore, pGlobalNode, pGlobalCore, pGivingProxyData); + } + + bool isBorrowedCore = false; + if (pGivenCore->IsBorrowed()) + { + isBorrowedCore = true; + if (isIdleCore) + { + ASSERT(pGivingProxyData->m_borrowedIdleCoresToMigrate > 0); + --pGivingProxyData->m_borrowedIdleCoresToMigrate; + } + else + { + ASSERT(pGivingProxyData->m_borrowedInUseCoresToMigrate > 0); + --pGivingProxyData->m_borrowedInUseCoresToMigrate; + } + } + else + { + ASSERT(pGivingProxyData->m_ownedCoresToMigrate > 0); + --pGivingProxyData->m_ownedCoresToMigrate; + } + + // Update the allocation map for the giving scheduler proxy. + pGivingProxy->RemoveCore(pGivingNode, coreIndex); + + // Update the allocation map for the receiving scheduler proxy. If the core we are migrating is borrowed, that state + // is transferred to the receiving proxy's core. + pReceivingProxy->AddCore(&pReceivingProxy->GetAllocatedNodes()[nodeIndex], coreIndex, isBorrowedCore); + + if (--numCoresToMigrate == 0) + { + ASSERT(numBorrowedIdle + numBorrowedInUse + numOwnedIdle + numOwnedInUse == 0); + return; + } + } + } + } + ASSERT(false); + } + + /// + /// Assigns one core at a time to a partially filled node on a receiving scheduler proxy, if possible. + /// + bool ResourceManager::FindCoreForPartiallyFilledNode(unsigned int& unusedCoreQuota, + unsigned int& usedCoreQuota, + DynamicAllocationData * pReceivingProxyData, + unsigned int numGivers) + { + bool foundCore = false; + + // Consider one partially filled node in this receiver Try to find a core on that node, either from + // the set of unused cores or one of the schedulers that are willing to give up cores. Perform a + // core transfer to the receiver if one is available, else advance the pointer 'startingNodeIndex' + // to the next node and return. + + SchedulerNode * pAllocatedNodes = pReceivingProxyData->m_pProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = pReceivingProxyData->m_pProxy->GetSortedNodeOrder(); + + ASSERT(pReceivingProxyData->m_allocation > 0); + ASSERT(pReceivingProxyData->m_numPartiallyFilledNodes > pReceivingProxyData->m_startingNodeIndex); + + unsigned int nodeIndex = pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex]; + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + // This node should be a partially filled node + ASSERT(pReceivingNode->m_allocatedCores > 0 && pReceivingNode->m_allocatedCores < pReceivingNode->m_coreCount); + + if ((unusedCoreQuota > 0) && (m_pGlobalNodes[nodeIndex].m_availableCores> 0)) + { + foundCore = true; + // There are unused cores available in this node. + DynamicAssignCores(pReceivingProxyData->m_pProxy, nodeIndex, 1, false); + + --unusedCoreQuota; + } + else if (usedCoreQuota > 0) + { + for (unsigned int giv = 0; giv < numGivers && !foundCore; ++giv) + { + SchedulerProxy * pGivingProxy = m_ppGivingProxies[giv]->m_pProxy; + if (pGivingProxy->GetNumAllocatedCores() > m_ppGivingProxies[giv]->m_suggestedAllocation) + { + // Note that we cannot migrate cores in a way that drops the owned core count below MinHWThreads. + SchedulerNode * pNodes = pGivingProxy->GetAllocatedNodes(); + SchedulerNode * pGivingNode = &pNodes[nodeIndex]; + if ((pGivingNode->GetNumBorrowedIdleCores() > 0) || + (pGivingNode->GetNumBorrowedInUseCores() > 0 && m_ppGivingProxies[giv]->m_borrowedInUseCoresToMigrate > 0) || + (pGivingNode->GetNumMigratableCores() > 0 && m_ppGivingProxies[giv]->m_ownedCoresToMigrate > 0)) + { + ASSERT(pGivingNode->GetNumBorrowedIdleCores() == 0 || m_ppGivingProxies[giv]->m_borrowedIdleCoresToMigrate > 0); + + foundCore = true; + DynamicMigrateCores(m_ppGivingProxies[giv], pReceivingProxyData->m_pProxy, nodeIndex, 1); + // Reduce the quota since we've allocated one core. + --usedCoreQuota; + } + } + } + } + + if (foundCore) + { + // If the node is fully allocated, move the node index along. + if (pReceivingNode->m_allocatedCores == pReceivingNode->m_coreCount) + { + ++pReceivingProxyData->m_startingNodeIndex; + } + pReceivingProxyData->m_allocation -= 1; + } + else + { + // We couldn't find any cores for this receiver in the partially filled node in the node we're looking at. + // Move the starting node index along so that we look at the next partially filled node, if any, during + // the next iteration. + ++pReceivingProxyData->m_startingNodeIndex; + } + + return foundCore; + } + + /// + /// Attempts to assign cores to a receiver on a single empty node, taking cores from multiple givers, if necessary. + /// + unsigned int ResourceManager::FindBestFitExclusiveAllocation(unsigned int& unusedCoreQuota, + unsigned int& usedCoreQuota, + DynamicAllocationData * pReceivingProxyData, + unsigned int remainingReceivers, + unsigned int numTotalGivers) + { + SchedulerNode * pAllocatedNodes = pReceivingProxyData->m_pProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = pReceivingProxyData->m_pProxy->GetSortedNodeOrder(); + + // Unless only one receiver is present, we first look for an exact fit while satisfying an allocation. + // For instance if we find a node with 3 cores available, but the current scheduler proxy needs only 2, + // we do not allocate out of that node just yet, in case a different scheduler down the line needs + // exactly two, and we can satisfy those cores out of the node we found. The next time around, we + // will allocate out of the node that has the most cores available and so on. + bool exactFit = (remainingReceivers == 1) ? false : pReceivingProxyData->m_fExactFitAllocation; + + unsigned int coresTransferred = 0; + + unsigned int bestFitNodeIndex = static_cast(-1); + unsigned int bestFitAllocation = 0; + unsigned int bestNumGivers = 0; + + // Go through all nodes, starting at startingNodeIndex. The nodes before that node have already been considered. + for (unsigned int i = pReceivingProxyData->m_startingNodeIndex; i < m_nodeCount; ++i) + { + unsigned int nodeIndex = pSortedNodeOrder[i]; + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + // We've already looked at the partially filled nodes on all receivers. The node is either empty or full, + // proceed only if it is empty. + ASSERT(pReceivingNode->m_allocatedCores == 0 || pReceivingNode->m_allocatedCores == pReceivingNode->m_coreCount); + + if (pReceivingNode->m_allocatedCores == 0) + { + unsigned int currentAllocation = min(pReceivingProxyData->m_allocation, pReceivingNode->m_coreCount); + ASSERT(currentAllocation > 0); + + // We're going to try to satisfy 'currentAllocation' at this iteration. Find the + // best fit node that will satisfy currentAllocation. + unsigned int foundUnusedCores = 0; + unsigned int numGivers = 0; + + if ((unusedCoreQuota > 0) && (m_pGlobalNodes[nodeIndex].m_availableCores > 0)) + { + foundUnusedCores = min(unusedCoreQuota, m_pGlobalNodes[nodeIndex].m_availableCores); + ++numGivers; + } + + unsigned int foundUsedCores = 0; + if (usedCoreQuota > 0) + { + // Go through the giving proxies. + for (unsigned int giv = 0; giv < numTotalGivers && foundUsedCores < usedCoreQuota; ++giv) + { + if (m_ppGivingProxies[giv]->m_pProxy->GetNumAllocatedCores() > m_ppGivingProxies[giv]->m_suggestedAllocation) + { + ASSERT((m_ppGivingProxies[giv]->m_pProxy->GetNumAllocatedCores() - m_ppGivingProxies[giv]->m_suggestedAllocation) == + (m_ppGivingProxies[giv]->m_borrowedIdleCoresToMigrate + m_ppGivingProxies[giv]->m_borrowedInUseCoresToMigrate + + m_ppGivingProxies[giv]->m_ownedCoresToMigrate)); + // Find the number of cores this proxy can contribute to this node. This is the minimum of + // - the remaining quota + // - the number of migratable cores of the right type (borrowed or owned) the proxy has on this node + // - the number of cores the proxy is able to give up (as suggested by hill climbing) + SchedulerNode * pNodes = m_ppGivingProxies[giv]->m_pProxy->GetAllocatedNodes(); + SchedulerNode * pGivingNode = &pNodes[nodeIndex]; + if (pGivingNode->GetNumMigratableCores() > 0) + { + // Calculate the number of cores that actually correspond to the numbers of borrowed and owned cores we are allowed + // to migrate from the giving scheduler. For instance, if this node has 3 available owned cores, but + // m_ppGivingProxies[giv]->m_ownedCoresToMigrate is 1, we cannot migrate the remaining 2 owned cores. + unsigned int numMigratableCores = min(pGivingNode->GetNumBorrowedIdleCores(), m_ppGivingProxies[giv]->m_borrowedIdleCoresToMigrate) + + min(pGivingNode->GetNumBorrowedInUseCores(), m_ppGivingProxies[giv]->m_borrowedInUseCoresToMigrate) + + min(pGivingNode->GetNumOwnedMigratableCores(), m_ppGivingProxies[giv]->m_ownedCoresToMigrate); + + ASSERT(numMigratableCores <= m_ppGivingProxies[giv]->m_pProxy->GetNumAllocatedCores() - m_ppGivingProxies[giv]->m_suggestedAllocation); + if (numMigratableCores > 0) + { + foundUsedCores += min(usedCoreQuota - foundUsedCores, numMigratableCores); + ++numGivers; + } + } + } + } + } + + unsigned int foundAllocation = foundUnusedCores + foundUsedCores; + if ((exactFit && ((foundAllocation == currentAllocation) && (numGivers > bestNumGivers))) + || + (!exactFit && ((bestFitAllocation < currentAllocation && foundAllocation > bestFitAllocation) || + (foundAllocation == bestFitAllocation && numGivers > bestNumGivers)))) + { + bestFitNodeIndex = i; + bestFitAllocation = foundAllocation; + ASSERT(bestFitAllocation > 0); + bestNumGivers = numGivers; + } + } + } + + if (bestFitNodeIndex != -1) + { + // Satisfy the allocation at this node + unsigned int nodeIndex = pSortedNodeOrder[bestFitNodeIndex]; + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + ASSERT(pReceivingNode->m_allocatedCores == 0); + ASSERT(bestFitAllocation <= pReceivingNode->m_coreCount); + + unsigned int satisfiedAllocation = min(pReceivingProxyData->m_allocation, bestFitAllocation); + ASSERT(satisfiedAllocation > 0); + coresTransferred = satisfiedAllocation; + + pReceivingProxyData->m_allocation -= satisfiedAllocation; + + if ((unusedCoreQuota > 0) && (m_pGlobalNodes[nodeIndex].m_availableCores > 0)) + { + unsigned int coresToTransfer = min(min(unusedCoreQuota, m_pGlobalNodes[nodeIndex].m_availableCores), satisfiedAllocation); + DynamicAssignCores(pReceivingProxyData->m_pProxy, nodeIndex, coresToTransfer, false); + + ASSERT(unusedCoreQuota >= coresToTransfer); + ASSERT(satisfiedAllocation >= coresToTransfer); + + unusedCoreQuota -= coresToTransfer; + satisfiedAllocation -= coresToTransfer; + } + + // Go through the giving proxies. + if (satisfiedAllocation > 0 && usedCoreQuota > 0) + { + for (unsigned int giv = 0; satisfiedAllocation > 0 && giv < numTotalGivers && usedCoreQuota > 0; ++giv) + { + SchedulerProxy * pGivingProxy = m_ppGivingProxies[giv]->m_pProxy; + if (pGivingProxy->GetNumAllocatedCores() > m_ppGivingProxies[giv]->m_suggestedAllocation) + { + SchedulerNode * pNodes = pGivingProxy->GetAllocatedNodes(); + SchedulerNode * pGivingNode = &pNodes[nodeIndex]; + if (pGivingNode->GetNumMigratableCores() > 0) + { + ASSERT((m_ppGivingProxies[giv]->m_pProxy->GetNumAllocatedCores() - m_ppGivingProxies[giv]->m_suggestedAllocation) == + (m_ppGivingProxies[giv]->m_borrowedIdleCoresToMigrate + m_ppGivingProxies[giv]->m_borrowedInUseCoresToMigrate + + m_ppGivingProxies[giv]->m_ownedCoresToMigrate)); + + // Find the number of cores we will take from this proxy to satisfy an allocation on this node. This is the minimum of + // - the remaining quota. + // - the number of migratable cores of the right type (borrowed or owned) the proxy has on this node + // - the number of cores the proxy is able to give up (as suggested by hill climbing) + // - the remaining requirement + + // Calculate the number of cores that actually correspond to the numbers of borrowed and owned cores we are allowed + // to migrate from the giving scheduler. For instance, if this node has 3 available owned cores, but + // m_ppGivingProxies[giv]->m_ownedCoresToMigrate is 1, we cannot migrate the remaining 2 owned cores. + unsigned int numMigratableCores = min(pGivingNode->GetNumBorrowedIdleCores(), m_ppGivingProxies[giv]->m_borrowedIdleCoresToMigrate) + + min(pGivingNode->GetNumBorrowedInUseCores(), m_ppGivingProxies[giv]->m_borrowedInUseCoresToMigrate) + + min(pGivingNode->GetNumOwnedMigratableCores(), m_ppGivingProxies[giv]->m_ownedCoresToMigrate); + + if (numMigratableCores > 0) + { + ASSERT(pGivingNode->m_numBorrowedCores >= pGivingNode->m_numDRMBorrowedIdle); + ASSERT(numMigratableCores <= m_ppGivingProxies[giv]->m_pProxy->GetNumAllocatedCores() - m_ppGivingProxies[giv]->m_suggestedAllocation); + + unsigned int coresToTransfer = min(min(usedCoreQuota, numMigratableCores), satisfiedAllocation); + + ASSERT(coresToTransfer > 0); + DynamicMigrateCores(m_ppGivingProxies[giv], pReceivingProxyData->m_pProxy, nodeIndex, coresToTransfer); + + ASSERT(usedCoreQuota >= coresToTransfer); + ASSERT(satisfiedAllocation >= coresToTransfer); + + usedCoreQuota -= coresToTransfer; + satisfiedAllocation -= coresToTransfer; + } + } + } + } + ASSERT(satisfiedAllocation == 0); + } + + // Move the startingNodeIndex up by 1, and push the node we have just populated back, so that we do not consider it + // during the next iteration (if any). + unsigned int tempIndex = pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex]; + pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex] = pSortedNodeOrder[bestFitNodeIndex]; + pSortedNodeOrder[bestFitNodeIndex] = tempIndex; + + ++pReceivingProxyData->m_startingNodeIndex; + + ASSERT(pReceivingProxyData->m_startingNodeIndex <= m_nodeCount); + ASSERT(pReceivingProxyData->m_startingNodeIndex < m_nodeCount || pReceivingProxyData->m_allocation == 0); + + pReceivingProxyData->m_fExactFitAllocation = true; + } + else + { + ASSERT(exactFit); + pReceivingProxyData->m_fExactFitAllocation = false; + } + + return coresTransferred; + } + + /// + /// Distributes unused cores and cores from scheduler proxies that are willing to give up cores to scheduler proxies that + /// need cores. + /// + void ResourceManager::DistributeExclusiveCores(unsigned int totalCoresNeeded, + unsigned int unusedCoreQuota, + unsigned int usedCoreQuota, + unsigned int numReceivers, + unsigned int numGivers) + { + // The array of receiving proxies is arranged by partial nodes (min to max), In addition, in each proxy with partially filled + // nodes, the nodes are arranged with the most tightly packed nodes earlier in the sorted node array. + + // Go through the array of receivers, transferring one core at a time to a partially filled node on the scheduler proxy + // if possible. + bool foundPartialNode = false; + + do + { + foundPartialNode = false; + for (unsigned int rec = 0; rec < numReceivers; ++rec) + { + // Allocate one core to each receiver at a time, to ensure some fairness among receivers if multiple receivers + // have the same node partially filled. + if ((m_ppReceivingProxies[rec]->m_allocation > 0) && + (m_ppReceivingProxies[rec]->m_numPartiallyFilledNodes > m_ppReceivingProxies[rec]->m_startingNodeIndex)) + { + foundPartialNode = true; + + if (FindCoreForPartiallyFilledNode(unusedCoreQuota, /* passed by reference */ + usedCoreQuota, /* passed by reference */ + m_ppReceivingProxies[rec], + numGivers)) + { + --totalCoresNeeded; + } + } + } + } + while (foundPartialNode); + + if (totalCoresNeeded > 0) + { + unsigned int remainingReceivers = numReceivers; + // Sort the array of receivers by number of cores needed first, highest first. + for (unsigned int i = 0; i < numReceivers; ++i) + { + unsigned int maxIndex = i; + for (unsigned int j = i + 1; j < numReceivers; ++j) + { + if (m_ppReceivingProxies[j]->m_allocation > m_ppReceivingProxies[maxIndex]->m_allocation) + { + maxIndex = j; + } + } + if (i != maxIndex) + { + DynamicAllocationData * pTemp = m_ppReceivingProxies[i]; + m_ppReceivingProxies[i] = m_ppReceivingProxies[maxIndex]; + m_ppReceivingProxies[maxIndex] = pTemp; + } + if (m_ppReceivingProxies[i]->m_allocation == 0) + { + // We can stop looking, since all receivers after this point have 'allocation' equal to 0. + remainingReceivers = i; + break; + } + } + + numReceivers = remainingReceivers; + ASSERT(numReceivers > 0); + // Now for each receiver, try to satisfy cores on an unallocated node. + do + { + // Go through the remaining receivers and try to satisfy as many cores on an unallocated node as possible. + for (unsigned int rec = 0; rec < numReceivers; ++rec) + { + DynamicAllocationData * pReceivingProxyData = m_ppReceivingProxies[rec]; + if (pReceivingProxyData->m_allocation > 0) + { + totalCoresNeeded -= FindBestFitExclusiveAllocation(unusedCoreQuota, /* passed by reference */ + usedCoreQuota, /* passed by reference */ + pReceivingProxyData, + remainingReceivers, + numGivers); + + if (pReceivingProxyData->m_allocation == 0) + { + --remainingReceivers; + } + } + } + } + while (totalCoresNeeded > 0); + + ASSERT(remainingReceivers == 0); + } + } + + /// + /// Attempts to assign cores to a receiver on a single empty node, using idle cores. + /// + unsigned int ResourceManager::FindBestFitIdleAllocation(unsigned int idleCoresAvailable, DynamicAllocationData * pReceivingProxyData, unsigned int remainingReceivers) + { + SchedulerNode * pAllocatedNodes = pReceivingProxyData->m_pProxy->GetAllocatedNodes(); + unsigned int * pSortedNodeOrder = pReceivingProxyData->m_pProxy->GetSortedNodeOrder(); + + // Unless only one receiver is present, we first look for an exact fit while satisfying an allocation. + // For instance if we find a node with 3 cores available, but the current scheduler proxy needs only 2, + // we do not allocate out of that node just yet, in case a different scheduler down the line needs + // exactly 3, and we can satisfy those cores out of the node we found. The next time around, we + // will allocate out of the node that has the most cores available and so on. + bool exactFit = (remainingReceivers == 1) ? false : pReceivingProxyData->m_fExactFitAllocation; + + unsigned int coresTransferred = 0; + + unsigned int bestFitNodeIndex = static_cast(-1); + unsigned int bestFitAllocation = 0; + + // Go through all nodes, starting at startingNodeIndex. The nodes before that node have already been considered. + for (unsigned int i = pReceivingProxyData->m_startingNodeIndex; i < m_nodeCount; ++i) + { + unsigned int nodeIndex = pSortedNodeOrder[i]; + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + ASSERT(pReceivingNode->m_allocatedCores == 0 || pReceivingNode->m_allocatedCores == pReceivingNode->m_coreCount); + + if (pReceivingNode->m_allocatedCores == 0) + { + unsigned int currentAllocation = min (pReceivingProxyData->m_allocation, pReceivingNode->m_coreCount); + + // We're going to try to satisfy 'currentAllocation' at this iteration. Find the + // best fit node that will satisfy currentAllocation. + unsigned int foundAllocation = 0; + + if (m_pGlobalNodes[nodeIndex].m_idleCores > 0) + { + foundAllocation = min(idleCoresAvailable, m_pGlobalNodes[nodeIndex].m_idleCores); + } + + if ((exactFit && (foundAllocation == currentAllocation)) + || + (!exactFit && (foundAllocation > bestFitAllocation))) + { + bestFitNodeIndex = i; + bestFitAllocation = foundAllocation; + + if (exactFit) + { + // We can immediately satisfy this request. + break; + } + } + } + } + + if (bestFitNodeIndex != -1) + { + // Satisfy the allocation at this node + unsigned int nodeIndex = pSortedNodeOrder[bestFitNodeIndex]; + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + ASSERT(pReceivingNode->m_allocatedCores == 0); + ASSERT(bestFitAllocation <= pReceivingNode->m_coreCount); + + coresTransferred = min(pReceivingProxyData->m_allocation, bestFitAllocation); + ASSERT(coresTransferred > 0); + + ASSERT (m_pGlobalNodes[nodeIndex].m_idleCores >= coresTransferred); + + DynamicAssignCores(pReceivingProxyData->m_pProxy, nodeIndex, coresTransferred, true); + + ASSERT(pReceivingProxyData->m_allocation >= coresTransferred); + pReceivingProxyData->m_allocation -= coresTransferred; + + // Move the startingNodeIndex up by 1, and push the node we have just populated back, so that we do not consider it + // during the next iteration (if any). + unsigned int tempIndex = pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex]; + pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex] = pSortedNodeOrder[bestFitNodeIndex]; + pSortedNodeOrder[bestFitNodeIndex] = tempIndex; + + ++pReceivingProxyData->m_startingNodeIndex; + + ASSERT(pReceivingProxyData->m_startingNodeIndex <= m_nodeCount); + ASSERT(pReceivingProxyData->m_startingNodeIndex < m_nodeCount || pReceivingProxyData->m_allocation == 0); + + pReceivingProxyData->m_fExactFitAllocation = true; + } + else + { + ASSERT(exactFit); + pReceivingProxyData->m_fExactFitAllocation = false; + } + + return coresTransferred; + } + + /// + /// Distributes idle cores to scheduler proxies that need cores. + /// + void ResourceManager::DistributeIdleCores(unsigned int totalCoresNeeded, unsigned int numReceivers) + { + // The array of receiving proxies is arranged by partial nodes (min to max), In addition, in each proxy with partially filled + // nodes, the nodes are arranged with the most tightly packed nodes earlier in the sorted node array. + + // Go through the array of receivers, transferring one core at a time to a partially filled node on the scheduler proxy + // if possible. + bool foundPartialNode = false; + + do + { + foundPartialNode = false; + for (unsigned int rec = 0; rec < numReceivers && totalCoresNeeded > 0; ++rec) + { + DynamicAllocationData * pReceivingProxyData = m_ppReceivingProxies[rec]; + // Allocate one core to each receiver at a time, to ensure some fairness among receivers if multiple receivers + // have the same node partially filled. + if ((pReceivingProxyData->m_allocation > 0) && + (pReceivingProxyData->m_numPartiallyFilledNodes > pReceivingProxyData->m_startingNodeIndex)) + { + foundPartialNode = true; + + unsigned int * pSortedNodeOrder = pReceivingProxyData->m_pProxy->GetSortedNodeOrder(); + unsigned int nodeIndex = pSortedNodeOrder[pReceivingProxyData->m_startingNodeIndex]; + + SchedulerNode * pAllocatedNodes = pReceivingProxyData->m_pProxy->GetAllocatedNodes(); + SchedulerNode * pReceivingNode = &(pAllocatedNodes[nodeIndex]); + + // The first sorted node should be a partially filled node + ASSERT(pReceivingNode->m_allocatedCores > 0 && pReceivingNode->m_allocatedCores < pReceivingNode->m_coreCount); + + if (m_pGlobalNodes[nodeIndex].m_idleCores > 0) + { + // There are idle cores available in this node. + DynamicAssignCores(pReceivingProxyData->m_pProxy, nodeIndex, 1, true); + + // If the node is fully allocated, move the starting node index along. + if (pReceivingNode->m_allocatedCores == pReceivingNode->m_coreCount) + { + ++pReceivingProxyData->m_startingNodeIndex; + } + pReceivingProxyData->m_allocation -= 1; + --totalCoresNeeded; + } + else + { + // We couldn't find any cores for this receiver in the partially filled node in the node we're looking at. + // Move the starting node index along so that we look at the next partially filled node, if any, during + // the next iteration. + ++pReceivingProxyData->m_startingNodeIndex; + } + } + } + } + while (foundPartialNode); + + if (totalCoresNeeded > 0) + { + unsigned int remainingReceivers = numReceivers; + + // Sort the array of receivers by number of cores needed first, highest first. + for (unsigned int i = 0; i < numReceivers; ++i) + { + unsigned int maxIndex = i; + for (unsigned int j = i + 1; j < numReceivers; ++j) + { + if (m_ppReceivingProxies[j]->m_allocation > m_ppReceivingProxies[maxIndex]->m_allocation) + { + maxIndex = j; + } + } + if (i != maxIndex) + { + DynamicAllocationData * pTemp = m_ppReceivingProxies[i]; + m_ppReceivingProxies[i] = m_ppReceivingProxies[maxIndex]; + m_ppReceivingProxies[maxIndex] = pTemp; + } + if (m_ppReceivingProxies[i]->m_allocation == 0) + { + // We can stop looking, since all receivers after this point have 'allocation' equal to 0. + remainingReceivers = i; + break; + } + } + + numReceivers = remainingReceivers; + ASSERT(numReceivers > 0); + // Now for each receiver, try to satisfy cores on an unallocated node. + do + { + for (unsigned int rec = 0; rec < numReceivers && totalCoresNeeded > 0; ++rec) + { + DynamicAllocationData * pReceivingProxyData = m_ppReceivingProxies[rec]; + if (pReceivingProxyData->m_allocation > 0) + { + totalCoresNeeded -= FindBestFitIdleAllocation(totalCoresNeeded, + pReceivingProxyData, + remainingReceivers); + if (pReceivingProxyData->m_allocation == 0) + { + --remainingReceivers; + } + } + } + } + while (totalCoresNeeded > 0); + ASSERT(remainingReceivers == 0); + } + } + + /// + /// Does a dynamic resource allocation based on feedback from hill climbing. + /// + void ResourceManager::DoCoreMigration() + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"---------------------------------------------------------------------------\n"); + + // Capture data needed for dynamic allocation for all existing schedulers. This includes gathering statistics + // and invoking a per scheduler hill climbing instance to get a suggested future allocation. + PopulateDynamicAllocationData(); + + // Handle a subset of idle, borrowed and shared cores up front. + PreProcessDynamicAllocationData(); + + // Exclusive cores are cores that other schedulers can give up (not-shared) or cores that are unused by any scheduler. + unsigned int exclusiveCoresAvailable = 0; + // Used cores are cores that are assigned to other schedulers, but are up for grabs, because hill climbing or idle core + // information has indicated to us that those schedulers can do without them. + unsigned int usedCoresAvailable = 0; + unsigned int numGivers = 0; + + // Find schedulers that are able to give up cores. + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + DynamicAllocationData * pDynamicData = static_cast(m_ppProxyData[index]); + // For all priorities, get the schedulers that we can take cores away from. + if (pDynamicData->m_pProxy->GetNumAllocatedCores() > pDynamicData->m_suggestedAllocation) + { + // Borrowed cores can be migrated as well. Clearly if the owning scheduler was using the borrowed core, the scheduler + // would not still have it. Therefore, the owning scheduler is idle on the core, and if a borrowed core is migrated + // the receiver also marks it as 'borrowed'. This also means that the same core can be migrated twice - if two schedulers + // have borrowed that core. + m_ppGivingProxies[numGivers++] = pDynamicData; + usedCoresAvailable += pDynamicData->m_pProxy->GetNumAllocatedCores() - pDynamicData->m_suggestedAllocation; + + // Find out how many borrowed cores and owned cores this scheduler should give. We first prefer to transfer + // borrowed cores before transferring owned cores. Note that all borrowed idle cores should be migrated. + ASSERT(pDynamicData->m_numBorrowedIdleCores <= pDynamicData->m_pProxy->GetNumBorrowedCores()); + pDynamicData->m_borrowedIdleCoresToMigrate = min(pDynamicData->m_numBorrowedIdleCores, + pDynamicData->m_pProxy->GetNumAllocatedCores() - pDynamicData->m_suggestedAllocation); + + pDynamicData->m_borrowedInUseCoresToMigrate = min(pDynamicData->m_pProxy->GetNumBorrowedCores() - pDynamicData->m_numBorrowedIdleCores, + pDynamicData->m_pProxy->GetNumAllocatedCores() - pDynamicData->m_suggestedAllocation - + pDynamicData->m_borrowedIdleCoresToMigrate); + ASSERT(pDynamicData->m_borrowedIdleCoresToMigrate + pDynamicData->m_borrowedInUseCoresToMigrate <= pDynamicData->m_pProxy->GetNumBorrowedCores()); + + pDynamicData->m_ownedCoresToMigrate = pDynamicData->m_pProxy->GetNumAllocatedCores() - pDynamicData->m_suggestedAllocation - + pDynamicData->m_borrowedIdleCoresToMigrate - pDynamicData->m_borrowedInUseCoresToMigrate; + ASSERT(pDynamicData->m_pProxy->GetNumOwnedCores() - pDynamicData->m_ownedCoresToMigrate >= pDynamicData->m_pProxy->MinHWThreads()); + } + else + { + ASSERT(pDynamicData->m_numBorrowedIdleCores == 0); + } + } + + // Find available cores (cores not assigned to any scheduler), and mark them as reserved. + unsigned int unusedCoresAvailable = 0; + + // Find cores that are idle, i.e, all schedulers that have that core assigned are not using them at present. + // We are able to temporarily share these cores with schedulers that indicate that they need cores. + m_dynamicIdleCoresAvailable = 0; + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + GlobalNode * pGlobalNode = &m_pGlobalNodes[nodeIndex]; + for (unsigned int coreIndex = 0; coreIndex < pGlobalNode->m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &pGlobalNode->m_pCores[coreIndex]; + if (pGlobalCore->m_useCount == 0) + { + pGlobalCore->m_coreState = ProcessorCore::Available; + ++pGlobalNode->m_availableCores; + ++unusedCoresAvailable; + } + else if (pGlobalCore->m_useCount == pGlobalCore->m_idleSchedulers) + { + pGlobalCore->m_coreState = ProcessorCore::Idle; + ++pGlobalNode->m_idleCores; + // Calculate the total number of idle cores up front. This number could change as we transfer cores between schedulers, + // and will be updated as we go along. + ++m_dynamicIdleCoresAvailable; + } + } + } + + exclusiveCoresAvailable = usedCoresAvailable + unusedCoresAvailable; + + // Perform two rounds of allocation/migration. + // Round 1 : Only consider receivers whose suggested allocation (as given by hill climbing) is higher than their allocated + // number of cores. After we have exhausted all such receivers, find fully loaded schedulers, and raise their suggested allocation to + // their desired. + // Round 2 : If cores are still available do a second round of migration to the new receivers if any. + for (m_allocationRound = 0; (exclusiveCoresAvailable > 0 || m_dynamicIdleCoresAvailable > 0) && m_allocationRound < 2; ++m_allocationRound) + { + if (m_allocationRound == 1) + { + // This is the second round of allocation. We have already satisfied the increases that hill climbing recommended. + // Now we try to find other schedulers who may benefit from resources - since we have some available to give. + IncreaseFullyLoadedSchedulerAllocations(); + } + + unsigned int numReceivers = 0; + unsigned int coresNeeded = 0; + + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + // Check if there are schedulers that we need to give resources to. + DynamicAllocationData * pDynamicData = static_cast(m_ppProxyData[index]); + if (pDynamicData->m_pProxy->GetNumAllocatedCores() < pDynamicData->m_suggestedAllocation) + { + m_ppReceivingProxies[numReceivers++] = pDynamicData; + coresNeeded += pDynamicData->m_suggestedAllocation - pDynamicData->m_pProxy->GetNumAllocatedCores(); + } + } + + if (numReceivers > 0) + { + ASSERT(coresNeeded > 0); + + // First check for unused cores and cores we can steal from other schedulers. We differentiate between exclusive cores + // and idle cores because we first want to satisfy requests using either unused cores or cores other schedulers can give up. + if (exclusiveCoresAvailable > 0) + { + // AdjustDynamicAllocation populates the 'allocation' field of the dynamic data that represents the additional cores we + // must give the scheduler. It is guaranteed that we can satisfy all allocations since they will be reduced if the + // sum of requested allocations was greater than what was available. + unsigned int coresToTransfer = AdjustDynamicAllocation(exclusiveCoresAvailable, coresNeeded, numReceivers); + + // Find the number of receivers that will still be granted cores (the AdjustDynamicAllocation API above could've reduced + // suggested allocations for some receivers), and sort the receivers by number of partially filled nodes. + unsigned int exclusiveCoreReceivers = PrepareReceiversForCoreTransfer(numReceivers); + + // 'coresTransferred' is the total number of cores we are about to distribute among the receivers in the receiving proxy + // array. The order in which we give cores is important. We must first give receivers unused cores, then cores taken from + // other schedulers, and finally, idle cores. + + unsigned int unusedCoreQuota = 0; + unsigned int usedCoreQuota = 0; + unsigned int coresDistributed = 0; + + coresDistributed = unusedCoreQuota = min(unusedCoresAvailable, coresToTransfer); + + ASSERT(unusedCoresAvailable >= unusedCoreQuota); + unusedCoresAvailable -= unusedCoreQuota; + + if (coresDistributed < coresToTransfer) + { + unsigned int remainingCores = coresToTransfer - coresDistributed; + + usedCoreQuota = min(remainingCores, usedCoresAvailable); + coresDistributed += usedCoreQuota; + usedCoresAvailable -= usedCoreQuota; + } + ASSERT(coresDistributed == coresToTransfer); + + DistributeExclusiveCores(coresToTransfer, unusedCoreQuota, usedCoreQuota, exclusiveCoreReceivers, numGivers); + + ASSERT(exclusiveCoresAvailable >= coresToTransfer); + exclusiveCoresAvailable -= coresToTransfer; + + ASSERT(coresNeeded >= coresToTransfer); + coresNeeded -= coresToTransfer; + } // end of if (exclusiveCoresAvailable > 0) + + // Now check if any more requests need to be satisfied. The reason we do this in two stages, (first unused and stolen + // cores, followed by idle cores), is that we want to distribute idle cores evenly, since we're temporarily oversubscribing them, and + // they could easy be taken away at the next iteration, if the schedulers that were not using the cores start using them. + + if (coresNeeded > 0 && m_dynamicIdleCoresAvailable > 0) + { + ASSERT(unusedCoresAvailable == 0); + ASSERT(usedCoresAvailable == 0); + ValidateDRMSchedulerState(); + + // AdjustDynamicAllocation populates the 'allocation' field of the dynamic data that represents the additional cores we + // must give the scheduler. It is guaranteed that we can satisfy all allocations since they will be reduced if the + // sum of requested allocations was greater than what was available. + unsigned int coresToTransfer = AdjustDynamicAllocation(m_dynamicIdleCoresAvailable, coresNeeded, numReceivers); + + // Find the number of receivers that will still be granted cores (the AdjustDynamicAllocation API above could've reduced + // suggested allocations for some receivers), and sort the receivers by number of partially filled nodes. + unsigned int idleCoreReceivers = PrepareReceiversForCoreTransfer(numReceivers); + + DistributeIdleCores(coresToTransfer, idleCoreReceivers); + + ASSERT(m_dynamicIdleCoresAvailable >= coresToTransfer && coresNeeded >= coresToTransfer); + + ValidateDRMSchedulerState(); + m_dynamicIdleCoresAvailable -= coresToTransfer; + coresNeeded -= coresToTransfer; + } // end of if (coresNeeded > 0 && m_dynamicIdleCoresAvailable > 0) + } // end of if (numReceivers > 0) + } + + // Undo any global state we initialized for dynamic core migration. + ResetGlobalAllocationData(); + +#if defined(_DEBUG) + // Ensure that allocations are between min and max for all schedulers after a core migration pass + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + SchedulerProxy * pSchedulerProxy = m_ppProxyData[index]->m_pProxy; + ASSERT(pSchedulerProxy->GetNumOwnedCores() >= pSchedulerProxy->MinHWThreads()); + ASSERT(pSchedulerProxy->GetNumAllocatedCores() <= pSchedulerProxy->DesiredHWThreads()); + } +#endif + +#if defined(CONCRT_TRACING) + + for (unsigned int index = 0; index < m_numSchedulers; ++index) + { + DynamicAllocationData * pDynamicData = static_cast(m_ppProxyData[index]); + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Scheduler %d[min=%d, max=%d]: Final values - Allocated: %d, Suggested: %d, Idle: %d, Borrowed: %d", + pDynamicData->m_pProxy->GetId(), pDynamicData->m_pProxy->MinHWThreads(), pDynamicData->m_pProxy->DesiredHWThreads(), + pDynamicData->m_pProxy->GetNumAllocatedCores(), pDynamicData->m_suggestedAllocation, pDynamicData->m_numIdleCores, + pDynamicData->m_pProxy->GetNumBorrowedCores()); + } + +#endif + + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"DRM:Remaining unused: %d, Remaining idle %d", unusedCoresAvailable, m_dynamicIdleCoresAvailable); + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"---------------------------------------------------------------------------\n"); + } + + /// + /// Returns the global subscription level of the underlying core. + /// + unsigned int ResourceManager::CurrentSubscriptionLevel(unsigned int nodeId, unsigned int coreIndex) + { + unsigned int currentGlobalSubscription = 0; + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + // Walk the collection of schedulers and capture subscription information. + for (SchedulerProxy * pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + SchedulerCore * pAllocatedCore = &pAllocatedNodes[nodeId].m_pCores[coreIndex]; + currentGlobalSubscription += pAllocatedCore->m_subscriptionLevel; + } + } // end locked region + + return currentGlobalSubscription; + } + + /// + /// Sends NotifyResourcesExternallyIdle/NotifyResourcesExternallyBusy notifications to the schedulers that + /// qualify for them, to let them know that the hardware resources allocated to them are in use or out of use + /// by other schedulers that share those resources. + /// + /// + /// The newly allocated scheduler proxy, if one was just allocated. + /// + void ResourceManager::SendResourceNotifications(SchedulerProxy * pNewlyAllocatedProxy) + { + // We need to do this in two stages. First capture local subscription data for each scheduler and calculate + // the global subscription data per core. Then send notifications, if needed. + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + for (unsigned int coreIndex = 0; coreIndex < m_pGlobalNodes[nodeIndex].m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &m_pGlobalNodes[nodeIndex].m_pCores[coreIndex]; + pGlobalCore->m_previousSubscriptionLevel = pGlobalCore->m_currentSubscriptionLevel; + pGlobalCore->m_currentSubscriptionLevel = 0; + + // Walk the collection of schedulers and capture subscription information. + for (SchedulerProxy * pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + SchedulerCore * pAllocatedCore = &pAllocatedNodes[nodeIndex].m_pCores[coreIndex]; + pAllocatedCore->m_previousSubscriptionLevel = pAllocatedCore->m_currentSubscriptionLevel; + pAllocatedCore->m_currentSubscriptionLevel = pAllocatedCore->m_subscriptionLevel; + pGlobalCore->m_currentSubscriptionLevel += pAllocatedCore->m_currentSubscriptionLevel; + } + } + } + + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + for (unsigned int coreIndex = 0; coreIndex < m_pGlobalNodes[nodeIndex].m_coreCount; ++coreIndex) + { + GlobalCore * pGlobalCore = &m_pGlobalNodes[nodeIndex].m_pCores[coreIndex]; + + ULONG previousGlobal = pGlobalCore->m_previousSubscriptionLevel; + ULONG currentGlobal = pGlobalCore->m_currentSubscriptionLevel; + + // Walk the collection of schedulers and send notifications if applicable. + for (SchedulerProxy * pSchedulerProxy = m_schedulers.First(); pSchedulerProxy != NULL; pSchedulerProxy = m_schedulers.Next(pSchedulerProxy)) + { + if (pSchedulerProxy->ShouldReceiveNotifications()) + { + SchedulerNode * pAllocatedNodes = pSchedulerProxy->GetAllocatedNodes(); + SchedulerCore * pAllocatedCore = &pAllocatedNodes[nodeIndex].m_pCores[coreIndex]; + ULONG previousLocal = pAllocatedCore->m_previousSubscriptionLevel; + ULONG currentLocal = pAllocatedCore->m_currentSubscriptionLevel; + ASSERT(previousGlobal >= previousLocal); + ASSERT(currentGlobal >= currentLocal); + + if (pAllocatedCore->m_numAssignedThreads > 0) + { + if (pSchedulerProxy == pNewlyAllocatedProxy) + { + if (currentGlobal > currentLocal) + { + // Ther are other scheduler proxies using this core. + pSchedulerProxy->SendCoreNotification(pAllocatedCore, true /* isBusy */); + } + else + { + // No one else is using this core at present. + pSchedulerProxy->SendCoreNotification(pAllocatedCore, false /* isIdle */); + } + } + else + { + if (previousGlobal == previousLocal && currentGlobal > currentLocal) + { + // If this scheduler proxy WAS the only thing running on this core, AND + // there is another scheduler proxy that IS contributing to the current number, + // THEN: Notify that the resources underneath virtual processors are now busy. + pSchedulerProxy->SendCoreNotification(pAllocatedCore, true /* isBusy */); + } + else if (currentGlobal == currentLocal && previousGlobal > previousLocal) + { + // If this scheduler proxy IS the only thing running on this core, AND + // it WAS sharing the core with another scheduler proxy, + // THEN: Notify that the resources underneath virtual processors are now idle. + pSchedulerProxy->SendCoreNotification(pAllocatedCore, false /* isIdle */); + } + } + } // if (pAllocatedCore->m_numAssignedThreads > 0) + } + } // end of for (.. scheduler proxy.. + } // end of for (.. core..) + } // end of for (.. node..) + } + + /// + /// Routine that performs dynamic resource management among existing schedulers at fixed time intervals. + /// + void ResourceManager::DynamicResourceManager() + { + const DWORD DynamicRMTimeInterval = 100; + DWORD timeout = DynamicRMTimeInterval; + + // The dynamic RM thread waits on an event with a fixed timeout. It can be woken up from the wait for one of the following + // reasons: + // 1) TIMEOUT - the DRM thread should perform core migration and send any pending notifications. + // 2) Number of schedulers just went from 1 to 2. The state is expected to be set to 'LoadBalance'. The DRM thread may have just been + // created, or woken up from a long wait. It needs to discard existing scheduler statistics, and set the next time interval + // appropriately. + // 3) Number of schedulers just went from 2 to 1. The state is expected to be set to 'Standby'. The DRM thread should go into a infinite + // wait. Before this, it redistributes cores to the surviving scheduler if that scheduler doesn't already have all the cores it wants. + // 4) An activation or a deactivation occurred that could warrant core idle/busy notifications for existing schedulers. The state could + // be either standby or LoadBalance. If it is 'Standby', we likely raced with the last scheduler leaving. Since we cannot differentiate + // this from 2), we do exactly the same as 2). If the state is 'LoadBalance', someone signaled us to send notifications. + // 5) RM is exiting and the DRM thread needs to quit. + + // We've just entered the function, simulate a longish wait by subtracting from the current tick count. + ULONGLONG oldTickCount = (platform::__GetTickCount64() - (ULONGLONG)500); + ULONGLONG newTickCount = 0; + + while (m_dynamicRMWorkerState != Exit) + { + DWORD retVal = WaitForSingleObjectEx(m_hDynamicRMEvent, timeout, FALSE); + + { // begin locked region + _NonReentrantBlockingLock::_Scoped_lock lock(m_lock); + + // The DRM thread event is signaled for one of 4 reasons. + // The RM is shutting down, and the thread needs to exit - handled above + // The thread needs to go into standby. + // The thread needs to start load balancing at fixed intervals. + // The thread needs to send notifications + switch (m_dynamicRMWorkerState) + { + case Standby: + { + // We're holding the lock, and the state is Standby. There should be only one + // scheduler the RM knows about at this time. + ASSERT(m_numSchedulers <= 1); + if (DistributeCoresToSurvivingScheduler()) + { + timeout = INFINITE; + } + else + { + // We might fail distributing cores to a scheduler if + // it has yet to be retired vprocs on cores that were + // removed previously. Since there is no DRM, we need + // to retry until the scheduler has the desired number + // of hardware threads. + timeout = DynamicRMTimeInterval; + } + break; + } + + case LoadBalance: + { + if (retVal == WAIT_TIMEOUT) + { + DoCoreMigration(); + if (SchedulersNeedNotifications()) + { + SendResourceNotifications(); + } + // The old tick count needs to be snapped each time we go back to wait with the original timeout value. + // That way, if we are woken up in between to deliver notifications, we can go back to wait for the remainder + // of the timeout. + oldTickCount = platform::__GetTickCount64(); + timeout = DynamicRMTimeInterval; + } + else + { + newTickCount = platform::__GetTickCount64(); + DWORD tickDifference = (DWORD) (newTickCount - oldTickCount); + if (tickDifference > DynamicRMTimeInterval) + { + // We're holding the lock, and the state is LoadBalance. There should be at least two + // schedulers the RM knows about at this time. + ASSERT(m_numSchedulers > 1); + if (tickDifference > DynamicRMTimeInterval + 30) + { + // Since GetTickCount is accurate upto 10-15ms, do not throw away statistics, + // unless we've waited for a 'long' time. + DiscardExistingSchedulerStatistics(); + } + else if (SchedulersNeedNotifications()) + { + SendResourceNotifications(); + } + + oldTickCount = platform::__GetTickCount64(); + timeout = DynamicRMTimeInterval; + } + else + { + // We were woken up within the 100 ms interval - most likely so that we could send notifications. + if (SchedulersNeedNotifications()) + { + SendResourceNotifications(); + } + timeout = DynamicRMTimeInterval - tickDifference; + } + } + break; + } + case Exit: + default: + { + ASSERT(m_dynamicRMWorkerState == Exit); + + // We are shutting down + break; + } + + }; // end switch (m_dynamicRMWorkerState) + } // end locked region + } + } + + /// + /// Main thread procedure for the dynamic RM worker thread. + /// + /// + /// Resource manager pointer passed to the worker thread. + /// + /// + /// Status on thread exit. + /// + DWORD CALLBACK ResourceManager::DynamicRMThreadProc(LPVOID lpParameter) + { + ResourceManager * pResourceManager = (ResourceManager *) lpParameter; + pResourceManager->DynamicResourceManager(); + FreeLibraryAndDestroyThread(0); + return 0; + } + + /// + /// The API returns after ensuring that all store buffers on processors that are running threads from this process, + /// are flushed. It does this by either calling a Win32 API that explicitly does this on versions of Windows that + /// support the functionality, or by changing the protection on a page using VirtualProtect. + /// + /// NOTE: We use the same mechanism the CLR uses for flushing write buffers in absence of the FlushProcessWriteBuffers API, + /// and most of the comments below are taken directly from the CLR vm code. + /// + void ResourceManager::FlushStoreBuffers() + { + FlushProcessWriteBuffers(); + } + + ResourceManager::~ResourceManager() + { + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + delete [] m_pGlobalNodes[i].m_pCores; + } + delete [] m_pGlobalNodes; + +#if !defined(_ONECORE) + if (m_pPageVirtualProtect != NULL) + { + VirtualFree(m_pPageVirtualProtect, 0, MEM_RELEASE); + } +#endif // !defined(_ONECORE) + +#if defined(_DEBUG) + ASSERT(m_schedulers.Empty()); +#endif + + ASSERT(m_hDynamicRMEvent != NULL); + CloseHandle(m_hDynamicRMEvent); + + delete [] m_ppProxyData; + + if (m_hDynamicRMThreadHandle != NULL) + { + platform::__CloseThreadHandle(m_hDynamicRMThreadHandle); + + delete [] m_ppGivingProxies; + delete [] m_ppReceivingProxies; + } + +#if defined(CONCRT_TRACING) + delete [] m_drmInitialState; +#endif + } + + /// + /// Returns an interface to the next node in enumeration order. + /// + /// + /// An interface to the next node in enumeration order. If there are no more nodes in enumeration order of the system topology, this method + /// will return NULL. + /// + /// + /// + /**/ + ITopologyNode *GlobalNode::TopologyObject::GetNext() const + { + GlobalNode *pNode = m_pNode->m_pRM->GetNextGlobalNode(m_pNode); + return pNode ? pNode->m_pTopologyObject : NULL; + } + + /// + /// Returns an interface to the next execution resource in enumeration order. + /// + /// + /// An interface to the next execution resource in enumeration order. If there are no more nodes in enumeration order of the node to which + /// this execution resource belongs, this method will return NULL. + /// + /// + /// + /**/ + ITopologyExecutionResource *GlobalCore::TopologyObject::GetNext() const + { + GlobalCore *pCore = m_pCore->m_pOwningNode->GetNextGlobalCore(m_pCore); + return pCore ? pCore->m_pTopologyObject : NULL; + } + +} // namespace details +} // namespace Concurrency + +#pragma warning(pop) diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.h new file mode 100644 index 0000000000000000000000000000000000000000..2a87d2a54cd1005abeea356c8f78728137774124 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.h @@ -0,0 +1,826 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ResourceManager.h +// +// Implementation of IResourceManager. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + #pragma warning(push) + #pragma warning(disable: 4265) // non-virtual destructor in base class + class ResourceManager final : public ::Concurrency::IResourceManager + { + public: + /// + /// Increments the reference count on a resource manager. + /// + /// + /// Returns the resulting reference count. + /// + virtual unsigned int Reference(); + + /// + /// Decrements the reference count on a resource manager. + /// + /// + /// Returns the resulting reference count. + /// + virtual unsigned int Release(); + + /// + /// Associates an IScheduler with the ISchedulerProxy that represents the part + /// of IResourceManager associated with the IScheduler. + /// + /// + /// The scheduler to be associated. + /// + /// + /// The version of the RM<->Scheduler communication channel that is being utilized. + /// + virtual ISchedulerProxy * RegisterScheduler(IScheduler *pScheduler, unsigned int version); + + /// + /// Returns the number of nodes available to the Resource Manager. + /// + /// + /// The number of nodes available to the Resource Manager. + /// + /**/ + virtual unsigned int GetAvailableNodeCount() const + { + // TRANSITION: At some point when RM honors process affinity, etc..., go back and ensure that this is the correct value to return! + return m_nodeCount; + } + + /// + /// Returns the first node in enumeration order as defined by the Resource Manager. + /// + /// + /// The first node in enumeration order as defined by the Resource Manager. + /// + /// + /**/ + virtual ITopologyNode* GetFirstNode() const + { + return m_pGlobalNodes->m_pTopologyObject; + } + + /// + /// Creates an instance of the resource manager. + /// + static ResourceManager* CreateSingleton(); + + /// + /// Returns the OS version. + /// + static IResourceManager::OSVersion Version(); + + /// + /// Returns the number of nodes (processor packages or NUMA nodes) + /// + static unsigned int GetNodeCount(); + + /// + /// Returns the number of cores. + /// + static unsigned int GetCoreCount(); + + /// + /// Returns a pointer to the manager of factories for thread proxies. + /// + ThreadProxyFactoryManager * GetThreadProxyFactoryManager() { return &m_threadProxyFactoryManager; } + + /// + /// These APIs return unique identifiers for use by schedulers, execution contexts and thread proxies. + /// + static unsigned int GetSchedulerId() { return InterlockedIncrement(&s_schedulerIdCount); } + static unsigned int GetExecutionContextId() { return InterlockedIncrement(&s_executionContextIdCount); } + static unsigned int GetThreadProxyId() { return InterlockedIncrement(&s_threadProxyIdCount); } + + /// + /// These APIs restrict the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified. + /// + static void SetTaskExecutionResources(DWORD_PTR dwAffinityMask); + static void SetTaskExecutionResources(USHORT count, PGROUP_AFFINITY pGroupAffinity); + + /// + /// The main allocation routine that allocates cores for a newly created scheduler proxy. + /// + ExecutionResource * PerformAllocation(SchedulerProxy *pSchedulerProxy, bool fInitialAllocation, bool fSubscribeCurrentThread); + + /// + /// This API registers the current thread with the resource manager, associating it with this scheduler proxy, + /// and returns an instance of IExecutionResource back to the scheduler, for bookkeeping and maintenance. + /// + ExecutionResource * SubscribeCurrentThread(SchedulerProxy *pSchedulerProxy); + + /// + /// The allocation routine that allocates a single core for a newly registered external thread. + /// + ExecutionResource * PerformExternalThreadAllocation(SchedulerProxy *pSchedulerProxy); + + /// + /// Removes an execution resource that was created for an external thread. + /// + void RemoveExecutionResource(ExecutionResource * pExecutionResource); + + /// + /// Called in order to notify the resource manager that the given scheduler is shutting down. This + /// will cause the resource manager to immediately reclaim all resources granted to the scheduler. + /// + void Shutdown(SchedulerProxy *pProxy); + + /// + /// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request + /// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request + /// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to + /// IScheduler::AddVirtualProcessors. + /// + /// + /// The scheduler proxy that is making the allocation request. + /// + /// + /// Whether to subscribe the current thread and account for it during resource allocation. + /// + /// + /// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise. + /// + IExecutionResource * RequestInitialVirtualProcessors(SchedulerProxy *pProxy, bool doSubscribeCurrentThread); + + /// + /// Debug CRT test hook to create artificial topologies. With the retail CRT, this API simply returns. + /// + virtual void CreateNodeTopology(unsigned int nodeCount, unsigned int *pCoreCount, unsigned int **pNodeDistance, unsigned int *pProcessorGroups); + + /// + /// The API returns after ensuring that all store buffers on processors that are running threads from this process, + /// are flushed. It does this by either calling a Win32 API that explicitly does this on versions of Windows that + /// support the functionality, or by changing the protection on a page that is locked into the working set, forcing + /// a TB flush on all processors in question. + /// + void FlushStoreBuffers(); + + /// + /// Returns the TLS slot where information about an execution resource is supposed to be stored. + /// + /// + /// Used to check whether SubscribeCurrentThread already has an execution resource on which it is running. + /// + DWORD GetExecutionResourceTls() const + { + return m_threadProxyFactoryManager.GetExecutionResourceTls(); + } + + /// + /// Decrements the use count on a particular global core. Used for removal of external threads. + /// + void DecrementCoreUseCount(unsigned int nodeId, unsigned int coreIndex) + { + // NOTE: Caller is responsible for holding the RM lock! + GlobalCore * pGlobalCore = &(m_pGlobalNodes[nodeId].m_pCores[coreIndex]); + pGlobalCore->m_useCount--; + } + + /// + /// Returns the current thread's node id and core id (relative to that node). + /// + unsigned int GetCurrentNodeAndCore(unsigned int * pCore); + + /// + /// Returns the global subscription level of the underlying core. + /// + unsigned int CurrentSubscriptionLevel(unsigned int nodeId, unsigned int coreIndex); + + /// + /// Returns true if there are any schedulers in the RM that need notifications sent, false, otherwise. + /// + bool SchedulersNeedNotifications() + { + return (m_numSchedulersNeedingNotifications > 0); + } + + /// + /// Returns the number of schedulers that need core busy/idle notifications. + /// + unsigned int GetNumSchedulersForNotifications() + { + return m_numSchedulersNeedingNotifications; + } + + /// + /// Wakes up the dynamic RM worker from a wait state. + /// + void WakeupDynamicRMWorker() + { + SetEvent(m_hDynamicRMEvent); + } + + /// + /// Sends NotifyResourcesExternallyIdle/NotifyResourcesExternallyBusy notifications to the schedulers that + /// qualify for them, to let them know that the hardware resources allocated to them are in use or out of use + /// by other schedulers that share those resources. + /// + /// + /// The newly allocated scheduler proxy, if one was just allocated. + /// + void SendResourceNotifications(SchedulerProxy * pNewlyAllocatedProxy = NULL); + + /// + /// Allocates and initializes the data structure that will represent the allocated nodes for a scheduler proxy. + /// This function is called the first time a scheduler proxy requests an allocation. + /// + SchedulerNode * CreateAllocatedNodeData(); + + /// + /// Destroys the data structures representing nodes/cores allocated to a scheduler proxy when the proxy has + /// shutdown. + /// + void DestroyAllocatedNodeData(SchedulerNode * pAllocatedNodes); + + /// + /// Gets the next node in enumeration order. + /// + GlobalNode *GetNextGlobalNode(const GlobalNode *pNode) + { + unsigned int idx = (unsigned int)((pNode - m_pGlobalNodes) + 1); + return ((idx < m_nodeCount) ? &m_pGlobalNodes[idx] : NULL); + } + + private: + + // State that controls what the dynamic RM worker thread does. + enum DynamicRMWorkerState + { + Standby, + LoadBalance, + Exit + }; + + struct AffinityRestriction + { + AffinityRestriction() : + m_count(0), + m_pGroupAffinity(NULL) + { + } + + AffinityRestriction(USHORT count, HardwareAffinity * pGroupAffinity) : + m_count(count), + m_pGroupAffinity(pGroupAffinity) + { + } + + ~AffinityRestriction() + { + delete m_pGroupAffinity; + } + + HardwareAffinity * FindGroupAffinity(USHORT group) + { + for (USHORT i = 0; i < m_count; ++i) + { + if (m_pGroupAffinity[i].GetGroup() == group) + { + return &m_pGroupAffinity[i]; + } + } + return NULL; + } + + void ApplyAffinityLimits(PGROUP_AFFINITY pGroupAffinity) + { + HardwareAffinity * pAffinity = FindGroupAffinity(pGroupAffinity->Group); + if (pAffinity != NULL) + { + pGroupAffinity->Mask &= pAffinity->GetMask(); + } + else + { + // The user has not asked for this group to be included. + pGroupAffinity->Mask = 0; + } + } + + USHORT GetCount() + { + return m_count; + } + + private: + USHORT m_count; + HardwareAffinity * m_pGroupAffinity; + }; + +#if defined(CONCRT_TRACING) + + struct GlobalCoreData + { + unsigned char m_nodeIndex; + unsigned char m_coreIndex; + unsigned char m_useCount; + unsigned char m_idleSchedulers; + }; + + // Maintains a trace for every core removed during preprocessing. + struct PreProcessingTraceData + { + SchedulerProxy * m_pProxy; + unsigned char m_nodeIndex; + unsigned char m_coreIndex; + bool m_fMarkedAsOwned : 1; + bool m_fBorrowedCoreRemoved : 1; + bool m_fSharedCoreRemoved : 1; + bool m_fIdleCore : 1; + }; + + // Maintains a trace for each core allocation + struct DynamicAllocationTraceData + { + SchedulerProxy * m_pGiver; // this is null if the core was unused or idle + SchedulerProxy * m_pReceiver; + unsigned char m_round; + unsigned char m_nodeIndex; + unsigned char m_coreIndex; + bool m_fUnusedCoreMigration : 1; + bool m_fIdleCoreSharing : 1; + bool m_fBorrowedByGiver : 1; + bool m_fIdleOnGiver : 1; + }; + +#endif + + // + // Private data + // + + // The singleton resource manager instance. + static ResourceManager *s_pResourceManager; + + // System and process affinities, either when the RM is created or an affinity limitation is specified. Note that this is limited to 64 cores on + // >64 core systems; by default the OS puts a process in a single group. For processes on a >64 core system, the system affinity mask reflects the + // affinity of the process in that group. + static DWORD_PTR s_processAffinityMask; + static DWORD_PTR s_systemAffinityMask; + + // Pointer to a data structure that is initialized if the task execution affinity for ConcRT is limited via the API SetTaskExecutionResources. + static AffinityRestriction * s_pUserAffinityRestriction; + // Pointer to a data structure that is initialized if the process affinity is different from the system affinity at the time the topology is created. + static AffinityRestriction * s_pProcessAffinityRestriction; + + // A lock that protects setting of the singleton instance. + static _StaticLock s_lock; + + // The total number of hardware threads available to the RM. + static unsigned int s_coreCount; + + // The number of nodes that hardware threads are grouped into. + static unsigned int s_nodeCount; + + // Operating system characteristics. + static IResourceManager::OSVersion s_version; + + // Termination indicator + static volatile LONG s_terminating; + + // Static counters to generate unique identifiers. + static volatile LONG s_schedulerIdCount; + static volatile LONG s_executionContextIdCount; + static volatile LONG s_threadProxyIdCount; + + // Variables used to obtain information about the topology of the system. + static DWORD s_logicalProcessorInformationLength; + static PSYSTEM_LOGICAL_PROCESSOR_INFORMATION s_pSysInfo; + + // Constants that are used as parameters to the ReleaseSchedulerResources API + static const unsigned int ReleaseCoresDownToMin = static_cast(-1); + static const unsigned int ReleaseOnlyBorrowedCores = static_cast(-2); + + // RM instance reference count + volatile LONG m_referenceCount; + + // Number of schedulers currently using resources granted by the RM. + unsigned int m_numSchedulers; + + // The maximum number of schedulers the dynamic RM worker has resources to handle, at any time. This can + // change during the lifetime of the process. + unsigned int m_maxSchedulers; + + // Number of schedulers in the RM that need resource notifications. + unsigned int m_numSchedulersNeedingNotifications; + + // The number of processor packages or NUMA nodes (whichever is greater) on the system. This is a mirror of s_nodeCount above. + unsigned int m_nodeCount; + + // The number of HW threads on the machine. This is a mirror of s_coreCount above. + unsigned int m_coreCount; + + // A field used during core migration to keep track of the number of idle cores - cores such that + // all schedulers they are assigned to are not using them. + unsigned int m_dynamicIdleCoresAvailable; + + // Keeps track of the allocation round during dynamic core migration. Used for tracing. + unsigned int m_allocationRound; + + // A state variable that is used to control how the dynamic worker behaves. + volatile DynamicRMWorkerState m_dynamicRMWorkerState; + + // A lock that protects resource allocation and deallocation. + _NonReentrantBlockingLock m_lock; + + // The global allocation map for all schedulers - array of processor nodes. + GlobalNode * m_pGlobalNodes; + + // Handle to the dynamic RM worker thread. + HANDLE m_hDynamicRMThreadHandle; + + // An event that is used to control the dynamic RM worker thread. + HANDLE m_hDynamicRMEvent; + + // Data used for static and/or dynamic allocation. + AllocationData ** m_ppProxyData; + DynamicAllocationData ** m_ppGivingProxies; + DynamicAllocationData ** m_ppReceivingProxies; + + // Lists to hold scheduler proxies. + List m_schedulers; + + // A collection of thread proxy factories + ThreadProxyFactoryManager m_threadProxyFactoryManager; + + // A pointer to a page that is used to flush write buffers on versions of Windows < 6000. + char* m_pPageVirtualProtect; + +#if defined(CONCRT_TRACING) + + // Captures the initial global state during the DRM phase. + GlobalCoreData * m_drmInitialState; + unsigned int m_numTotalCores; + + // Maintains a trace for every core removed during preprocessing. + PreProcessingTraceData m_preProcessTraces[100]; + unsigned int m_preProcessTraceIndex; + + // Maintains a trace for each core allocation + DynamicAllocationTraceData m_dynAllocationTraces[100]; + unsigned int m_dynAllocationTraceIndex; +#endif + + // + // Private methods + // + + // Private constructor. + ResourceManager(); + + // Private destructor. + ~ResourceManager(); + + /// + /// Initializes static variables related to the operating system version. + /// + static void RetrieveSystemVersionInformation(); + + /// + /// Captures the process affinity if it is not equal to the system affinity. + /// + static void CaptureProcessAffinity(); + + /// + /// Modify the passed in affinity based on any user or process affinity restrictions. + /// + static void ApplyAffinityRestrictions(PGROUP_AFFINITY pGroupAffinity); + static void ApplyAffinityRestrictions(PULONG_PTR pProcessorMask); + + /// + /// Retrieves a buffer from the operating system that contains topology information. + /// + static void GetTopologyInformation(LOGICAL_PROCESSOR_RELATIONSHIP relationship); + + /// + /// Cleans up the variables that store operating system topology information. + /// + static void CleanupTopologyInformation(); + + /// + /// Initializes static information related to the operating system and machine topology. + /// + static void InitializeSystemInformation(bool fSaveTopologyInfo = false); + + /// + /// Creates a scheduler proxy for an IScheduler that registers with the RM. + /// + SchedulerProxy* CreateSchedulerProxy(IScheduler *pScheduler); + + /// + /// Increments the reference count to RM but does not allow a 0 to 1 transition. + /// + /// + /// True if the RM was referenced; false, if the reference count was 0. + /// + bool SafeReference(); + + /// + /// Creates a structure of nodes and cores based on the machine topology. + /// + void DetermineTopology(); + + /// + /// Instructs existing schedulers to release cores. Then tries to allocate available cores for the new scheduler. + /// The parameter 'numberToFree' can have a couple of special values: + /// ReleaseCoresDownToMin - scheduler should release all cores above its minimum. Preference is giving to releasing borrowed cores. + /// ReleaseOnlyBorrowedCores - scheduler should release all its borrowed cores. + /// If the parameter is not a special value, a call should have previously been made for this scheduler with the value ReleaseOnlyBorrowedCores. + /// i.e., the scheduler should not have any borrowed cores to release. + /// + unsigned int ReleaseCoresOnExistingSchedulers(SchedulerProxy * pNewProxy, unsigned int request, unsigned int numberToFree); + + /// + /// Tries to redistribute cores allocated to all schedulers, proportional to each schedulers value for 'DesiredHardwareThreads', + /// and allocates any freed cores to the new scheduler. + /// + unsigned int RedistributeCoresAmongAll(SchedulerProxy* pSchedulerProxy, unsigned int allocated, unsigned int minimum, unsigned int desired); + + /// + /// Reserves cores for the new scheduler at higher use counts - this is used only to satisfy MinHWThreads. + /// + unsigned int ReserveAtHigherUseCounts(SchedulerProxy * pSchedulerProxy, unsigned int request); + + /// + /// Worker routine that does actual core reservation, using the supplied use count. It tries to + /// pack reserved cores onto nodes by preferring nodes where more free cores are available. + /// + unsigned int ReserveCores(SchedulerProxy * pSchedulerProxy, unsigned int request, unsigned int useCount); + + /// + /// Instructs a scheduler proxy to free up a fixed number of resources. This is only a temporary release of resources. The + /// use count on the global core is decremented and the scheduler proxy remembers the core as temporarily released. At a later + /// point, the release is either confirmed or rolled back, depending on whether the released core was used to satisfy a + /// different scheduler's allocation. + /// + /// + /// The scheduler proxy for which the cores are being stolen - this is the proxy that is being currently allocated to. + /// + /// + /// The scheduler proxy that needs to free up resources. + /// + /// + /// The number of resources to free. This parameter can have a couple of special values: + /// ReleaseCoresDownToMin - scheduler should release all cores above its minimum. Preference is giving to releasing borrowed cores. + /// ReleaseOnlyBorrowedCores - scheduler should release all its borrowed cores. + /// If the parameter is not a special value, a call should have previously been made for this scheduler with the value ReleaseOnlyBorrowedCores. + /// i.e., the scheduler should not have any borrowed cores to release. + /// + bool ReleaseSchedulerResources(SchedulerProxy * pReceivingProxy, SchedulerProxy *pGivingProxy, unsigned int numberToFree); + + /// + /// Called to claim back any previously released cores that were not allocated to a different scheduler. If released + /// cores were allocated (stolen), the proxy needs to notify its scheduler to give up the related virtual processor + /// roots. + /// + void CommitStolenCores(SchedulerProxy * pSchedulerProxy); + + /// + /// Starts up the dynamic RM worker thread if it is on standby, or creates a thread if one is not already created. + /// The worker thread wakes up at fixed intervals and load balances resources among schedulers, until it it put on standby. + /// + void CreateDynamicRMWorker(); + + /// + /// Routine that performs dynamic resource management among existing schedulers at fixed time intervals. + /// + void DynamicResourceManager(); + + /// + /// Performs a dynamic resource allocation based on feedback from hill climbing. + /// + void DoCoreMigration(); + + /// + /// When the number of schedulers in the RM goes from 2 to 1, this routine is invoked to make sure the remaining scheduler + /// has its desired number of cores, before putting the dynamic RM worker on standby. It is also called when there is just + /// one scheduler with external subscribed threads that it removes -> there is a chance that this move may allow us to allocate + /// more vprocs. + /// + bool DistributeCoresToSurvivingScheduler(); + + /// + /// This API is called by the dynamic RM worker thread when it starts up, and right after its state changed to + /// LoadBalance after being on Standby for a while. We need to find the existing schedulers, and discard the + /// statistics they have collected so far if any. Either we've never collected statistics for this scheduler before, + /// or too much/too little time has passed since we last collected statistics, and this information cannot be trusted. + /// + void DiscardExistingSchedulerStatistics(); + + /// + /// Ensures that the memory buffers needed for static and dynamic RM are of the right size, and initializes them. + /// + void InitializeRMBuffers(); + + /// + /// Populates data needed for allocation (static or dynamic). + /// + void PopulateCommonAllocationData(unsigned int index, SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData); + + /// + /// Captures data needed for static allocation, for all existing schedulers. This includes determining which + /// cores on a scheduler are idle. + /// A number of preprocessing steps are are also preformed before we are ready to allocate cores for a new scheduler. + /// + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed any more. + /// + void SetupStaticAllocationData(SchedulerProxy * pNewProxy, bool fSubscribeCurrentThread); + + /// + /// Captures data needed for dynamic allocation for all existing schedulers. This includes gathering statistics + /// and invoking a per scheduler hill climbing instance, to get a suggested future allocation. Also, determines how may + /// idle cores a scheduler has. + /// + void PopulateDynamicAllocationData(); + + /// + /// Undo global state that was initialized to perform static allocation or dynamic core migration. + /// + void ResetGlobalAllocationData(); + + /// + /// Resets state that was set on the global cores during static or dynamic allocation. + /// + void ResetGlobalState(); + + /// + /// Toggles the idle state on a core and updates tracking counts. + /// + void ToggleRMIdleState(SchedulerNode * pAllocatedNode, SchedulerCore * pAllocatedCore, + GlobalNode * pGlobalNode, GlobalCore * pGlobalCore, AllocationData * pDRMData); + + /// + /// A number of preprocessing steps are performed before we are ready to allocate cores. They include handling of borrowed and idle, + /// cores, as follows: + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore. + /// + void PreProcessStaticAllocationData(); + + /// + /// A number of preprocessing steps are preformed before we are ready to migrate cores. They include handling of borrowed, idle, + /// and shared cores, as follows: + /// + /// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away. + /// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore. + /// - If hill climbing has suggested an allocation increase for a scheduler that has idle cores, or an allocation decrease that + /// does not take away all its idle cores, the RM overrides it, setting the suggested allocation for that scheduler to + /// max(minCores, allocatedCores - idleCores). + /// + /// The new value of suggested allocation is used for the following: + /// - If the suggested allocation is less than the current allocation for a scheduler that has shared cores (cores oversubscribed + /// with a different scheduler), those cores are taken away here, since we want to minimize sharing. + /// + void PreProcessDynamicAllocationData(); + + /// + /// Preprocessing steps for borrowed cores - both static and dynamic allocation start out with a call to this API. + /// + void HandleBorrowedCores(SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData); + + /// + /// Preprocessing steps for shared cores - this is used during dynamic core migration. + /// + void HandleSharedCores(SchedulerProxy * pSchedulerProxy, DynamicAllocationData * pAllocationData); + + /// + /// This routine increases the suggested allocation to desired, for schedulers with the following characteristics: + /// 1) Hill climbing has *not* recommended an allocation decrease. + /// 2) They are using all the cores allocated to them (no idle cores). + /// In the second round of core migration, we try to satisfy these schedulers' desired allocation. + /// + void IncreaseFullyLoadedSchedulerAllocations(); + + /// + /// Decides on the number of additional cores to give a set of schedulers, given what the schedulers need and what is available. + /// + unsigned int AdjustDynamicAllocation(unsigned int coresAvailable, unsigned int coresNeeded, unsigned int numReceivers); + + /// + /// Initializes receiving proxy data in preparation for core transfer. Calculates the number of partially filled nodes + /// for schedulers that are receiving cores, and sorts the receiving proxy data in increasing order of partial nodes. + /// + /// + /// Number of receivers that still need cores (allocation field of the receiving proxy data > 0). + /// + unsigned int PrepareReceiversForCoreTransfer(unsigned int numReceivers); + + /// + /// Assigns one core at a time to a partially filled node on a receiving scheduler proxy, if possible + /// + bool FindCoreForPartiallyFilledNode(unsigned int& unusedCoreQuota, + unsigned int& usedCoreQuota, + DynamicAllocationData * pReceivingProxyData, + unsigned int numGivers); + + /// + /// Attempts to assign cores to a receiver on a single empty node, taking cores from multiple givers if necessary. + /// + unsigned int FindBestFitExclusiveAllocation(unsigned int& unusedCoreQuota, + unsigned int& usedCoreQuota, + DynamicAllocationData * pReceivingProxyData, + unsigned int remainingReceivers, + unsigned int numGivers); + + /// + /// Distributes unused cores and cores from scheduler proxies that are willing to give up cores to scheduler proxies that + /// need cores. + /// + void DistributeExclusiveCores(unsigned int totalCoresNeeded, + unsigned int unusedCoreQuota, + unsigned int usedCoreQuota, + unsigned int numReceivers, + unsigned int numGivers); + + /// + /// Attempts to assign cores to a receiver on a single empty node, using idle cores. + /// + unsigned int FindBestFitIdleAllocation(unsigned int idleCoresAvailable, DynamicAllocationData * pReceivingProxyData, unsigned int remainingReceivers); + + /// + /// Distributes idle cores to scheduler proxies that need cores. + /// + void DistributeIdleCores(unsigned int totalCoresAvailable, unsigned int numReceivers); + + /// + /// Assigns a fixed number of unused or idle cores to a scheduler from a given node. + /// + void DynamicAssignCores(SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToMigrate, bool fIdle); + + /// + /// Transfers a fixed number of cores from one scheduler to another. + /// + void DynamicMigrateCores(DynamicAllocationData * pGivingProxyData, SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToMigrate); + +#if defined (CONCRT_TRACING) + + /// + /// Captures the initial state of the global map at the beginning of core migration, each cycle. + /// + void TraceInitialDRMState(); + + /// + /// Captures data relating to an action during DRM preprocessing. + /// + void TracePreProcessingAction(SchedulerProxy * pProxy, unsigned int nodeIndex, unsigned int coreIndex, + bool fMarkedAsOwned, bool fBorrowedCoreRemoved, bool fSharedCoreRemoved, bool fIdleCore); + + /// + /// Captures data relating to an action during DRM core migration. + /// + void TraceCoreMigrationAction(SchedulerProxy * pGiver, SchedulerProxy * pReceiver, unsigned int round, unsigned int nodeIndex, + unsigned int coreIndex, bool fUnusedCoreMigration, bool fIdleCoreSharing, bool fBorrowedByGiver, + bool fIdleOnGiver); + +#endif + /// + /// Performs borrowed core validation. A core can be borrowed by only one scheduler at a time. + /// + void ValidateBorrowedCores(); + + /// + /// Performs state validations during dynamic core migration. + /// + void ValidateDRMSchedulerState(); + + /// + /// Performs state validations during static allocation. + /// + void ValidateStaticSchedulerState(SchedulerProxy * pSchedulerProxy); + + /// + /// Main thread procedure for the dynamic RM worker thread. + /// + /// + /// Resource manager pointer passed to the worker thread. + /// + /// + /// Status on thread exit. + /// + static DWORD CALLBACK DynamicRMThreadProc(LPVOID lpParameter); + + /// + /// Given a set of scaled floating point allocations that add up to nSum, rounds them to integers. + /// + static void RoundUpScaledAllocations(AllocationData ** ppData, unsigned int count, unsigned int nSum); + }; + + #pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8de73284a0090c73422b52d496fffc60b494249b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.cpp @@ -0,0 +1,870 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ScheduleGroupBase.cpp +// +// Implementation file for ScheduleGroupBase. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs a schedule group with an initial reference count of 1. + /// + ScheduleGroupBase::ScheduleGroupBase(SchedulerBase *pScheduler, location* pGroupPlacement) : + m_pScheduler(pScheduler), + m_pAffineSegments(NULL), + m_pNonAffineSegments(NULL), + m_refCount(0) + { + Initialize(pGroupPlacement); + m_id = m_pScheduler->GetNewScheduleGroupId(); + } + + /// + /// Performs initialization (or reinitialization) of a schedule group. + /// + void ScheduleGroupBase::Initialize(location* pGroupPlacement) + { + ASSERT(m_refCount == 0); + m_refCount = 1; + m_groupPlacement = *pGroupPlacement; + + OMTRACE(MTRACE_EVT_INITIALIZED, this, NULL, NULL, 0); + } + + /// + /// Constructs a new schedule group segment with a specific affinity in the specified ring. + /// + /// + /// The group to which this segment belongs. + /// + /// + /// The ring in which this segment is contained. + /// + /// + /// The affinity of this segment. + /// + ScheduleGroupSegmentBase::ScheduleGroupSegmentBase(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) : + m_mailedTasks(pOwningGroup->GetScheduler(), pOwningGroup->GetScheduler()->GetBitSet(&m_affinity)), + m_workQueues(pOwningGroup->GetScheduler(), 256, 64), + m_detachedWorkQueues(pOwningGroup->GetScheduler(), 256, ListArray< ListArrayInlineLink >::DeletionThresholdInfinite), // No deletion + m_lastServiceTime(0) + { + Initialize(pOwningGroup, pOwningRing, pSegmentAffinity); + } + + /// + /// Initializes a schedule group segment. + /// + /// + /// The group to which this segment belongs. + /// + /// + /// The ring in which this segment is contained. + /// + /// + /// The affinity of this segment. + /// + void ScheduleGroupSegmentBase::Initialize(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location *pSegmentAffinity) + { + m_pOwningGroup = pOwningGroup; + m_pRing = pOwningRing; + m_affinity = *pSegmentAffinity; + m_priorityServiceLink.m_type = BoostedObject::BoostTypeScheduleGroupSegment; + m_priorityServiceLink.m_boostState = BoostedObject::BoostStateUnboosted; + + m_affinitySet = pOwningGroup->GetScheduler()->GetBitSet(pSegmentAffinity); + if (pSegmentAffinity->_GetType() == location::_ExecutionResource) + { + m_maskIdIf = pOwningGroup->GetScheduler()->GetResourceMaskId(pSegmentAffinity->_GetId()); + } + m_mailedTasks.Initialize(m_affinitySet); + } + + /// + /// Creates a new segment with the specified affinity within the specified ring. + /// + /// + /// The affinity of the segment. + /// + /// + /// The ring into which the new segment will be placed. Some aspect of pSegmentAffinity must overlap with the node to which this ring + /// belongs. + /// + /// + /// A new segment with the specified affinity within the specified ring. + /// + ScheduleGroupSegmentBase *ScheduleGroupBase::CreateSegment(location* pSegmentAffinity, SchedulingRing *pOwningRing) + { + ScheduleGroupSegmentBase **pSegmentList = pSegmentAffinity->_Is_system() ? &m_pNonAffineSegments : &m_pAffineSegments; + + // + // At the moment, there is no point in free listing segments -- they are bound to the lifetime of the group. There should never be + // anything on the free list except at destruct time. + // + ScheduleGroupSegmentBase *pSegment = NULL; + + if (pSegmentAffinity->_Is_system()) + { + pSegment = pOwningRing->m_nonAffineSegments.PullFromFreePool(); + } + else + { + pSegment = pOwningRing->m_affineSegments.PullFromFreePool(); + } + + if (pSegment == NULL) + { + pSegment = AllocateSegment(pOwningRing, pSegmentAffinity); + } + else + { + pSegment->Initialize(this, pOwningRing, pSegmentAffinity); + } + + pSegment->m_pNext = *pSegmentList; + *pSegmentList = pSegment; + + // + // If this ring is not active yet, make it active. This would happen for a ring which we have no virtual processors / nodes in but which + // we've created a segment in. We would do this if we knew a-priori that we were running on a thread / virtual processor affine to that node + // and scheduled work to this scheduler from there despite this scheduler not having any virtual processors from that node. There are two ways + // in which this might happen: + // + // 1: We decide that location::current can return specific locations from an external thread. Today this is not done. + // 2: We might be running on scheduler A / node X and schedule work to scheduler B from there. We're on node X even though scheduler B doesn't + // *currently* have any virtual processors there. + // + // In either of these cases, we'll still fork the group (create a new segment) within the node/ring even though we have no virtual processors there. + // After all, we never know when dynamic RM will kick in and change that. + // + // Note that this does *NOT* necessarily mean that the work is strongly affine to a non-existent node/ring! + // + if (!pOwningRing->IsActive()) + { + pOwningRing->Activate(); + } + + if (pSegmentAffinity->_Is_system()) + { + pOwningRing->m_nonAffineSegments.Add(pSegment); + } + else + { + pOwningRing->m_affineSegments.Add(pSegment); + } + + OMTRACE(MTRACE_EVT_CREATESEGMENT, this, NULL, NULL, pSegment); + + return pSegment; + } + + /// + /// Internal routine which finds an appropriate segment for a task placement. + /// + /// + /// A segment with this affinity will be located. + /// + /// + /// A segment with pSegmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order + /// to keep work local. + /// + /// + /// A segment with the specified affinity close to the specified location. + /// + ScheduleGroupSegmentBase *ScheduleGroupBase::FindSegment(location* pSegmentAffinity, SchedulingRing *pRing) + { + ScheduleGroupSegmentBase **pSegmentList = pSegmentAffinity->_Is_system() ? &m_pNonAffineSegments : &m_pAffineSegments; + ScheduleGroupSegmentBase *pSegment = *pSegmentList; + + location origin = pRing->GetOwningNode()->GetLocation(); + + // + // @TODO: + // + // At some point, it might be beneficial to hash segments within the group instead of looking them up. There will be M * N segments + // within a group where M is the number of different locations utilized and N is the number of nodes which those locations span. + // + while (pSegment != NULL) + { + if (pSegment->GetAffinity() == *pSegmentAffinity && pSegment->GetSchedulingRing() == pRing) + { + break; + } + + pSegment = pSegment->m_pNext; + } + + return pSegment; + } + + /// + /// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement + /// and the origin of the thread making the call. + /// + /// + /// A segment with affinity to this particular location will be located. + /// + /// + /// A location representing the origin of the search. The scheduler will tend to fork a given pSegmentAffinity into segments by node in order + /// to keep locally scheduled work with the same affinity local. + /// + /// + /// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is + /// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found. + /// + /// + /// A segment appropriate for scheduling work with affinity to pSegmentAffinity from code executing at pOrigin. Note that NULL may be returned + /// if fCreateNew is specified as false and no appropriate segment yet exists for the group. + /// + ScheduleGroupSegmentBase *ScheduleGroupBase::LocateSegment(location* pSegmentAffinity, bool fCreateNew) + { + // + // In general, we wish to find a segment local to our origin (the node where the current context is executing) that has a placement + // of pSegmentAffinity, or create a new segment should one not yet exist within the group. + // + // In practice, a segment will only be created specific to the current ring, if the current ring's affinity is "within" pSegmentAffinity. + // Otherwise, someone creating a group and saying something like: + // + // pGroup->ScheduleTask(..., N0); + // (..., N1); + // (..., N2); + // (..., Nn); + // + // might wind up creating n^2 segments within the group for no good reason. + // + // This will also allow unbiased work to fork per node and work on local portions. This is exactly the kind of separation we want. + // + // Note that it is possible that we cannot place the current thread (or the scheduler chooses not to) and FindCurrentNode will return NULL. It's also + // possible that the pSegmentAffinity to locate does not intersect our origin (even if the scheduler could place the current thread). In either of these + // cases, we revert back to previous behavior and round robin an appropriate ring. The ring's affinity must intersect pSegmentAffinity in some way! + + // + SchedulingNode * pNode = m_pScheduler->FindCurrentNode(); + SchedulingRing *pRing = (pNode != NULL) ? pNode->GetSchedulingRing() : m_pScheduler->GetNextSchedulingRing(); + + // + // Make sure pRing's affinity intersects pSegmentAffinity (or find a ring which does in round robin order). + // + location ringAffinity = pRing->GetOwningNode()->GetLocation(); + location unbiased; + SchedulingRing * pFirstRing = pRing; + + while (!ringAffinity._FastNodeIntersects(*pSegmentAffinity)) + { + pRing = m_pScheduler->GetNextSchedulingRing(NULL, pRing); + ringAffinity = pRing->GetOwningNode()->GetLocation(); + + // If we've looped through all the SchedulingRings and haven't found an intersection, back off + // to an unbiased system-wide location. This can occur on certain machines that have NUMA + // nodes with no processors, thus they have valid node locations with no ring created by the + // scheduler since they can do no work. + if (pRing == pFirstRing) + { + ASSERT(pSegmentAffinity->_GetType() == location::_NumaNode); + pSegmentAffinity = &unbiased; + } + } + + // + // Do not hold a lock unless we need to create the segment. This operation should be as inexpensive as possible in the majority case where + // the appropriate segment already exists. + // + ScheduleGroupSegmentBase *pSegment = FindSegment(pSegmentAffinity, pRing); + if (pSegment == NULL && fCreateNew) + { + m_segmentLock._Acquire(); + pSegment = FindSegment(pSegmentAffinity, pRing); + if (pSegment == NULL) + { + pSegment = CreateSegment(pSegmentAffinity, pRing); + } + m_segmentLock._Release(); + } + + ASSERT(!pSegment || pSegment->GetSchedulingRing()->IsActive()); + return pSegment; + } + + /// + /// Removes all schedule group segments from the group. + /// + void ScheduleGroupBase::RemoveSegments() + { + ScheduleGroupSegmentBase *pSegment = m_pNonAffineSegments; + ScheduleGroupSegmentBase *pNext = NULL; + + while(pSegment) + { + pNext = pSegment->m_pNext; + pSegment->Remove(); + pSegment = pNext; + } + + pSegment = m_pAffineSegments; + while(pSegment) + { + pNext = pSegment->m_pNext; + pSegment->Remove(); + pSegment = pNext; + } + + m_pNonAffineSegments = NULL; + m_pAffineSegments = NULL; + } + + /// + /// Schedules a light-weight task within the schedule group. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// Calling the ScheduleTask method implicitly places a reference count on the schedule group which is removed by the runtime + /// at an appropriate time after the task executes. + /// + /// + void ScheduleGroupBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data) + { + ScheduleGroupSegmentBase *pSegment = LocateSegment(&m_groupPlacement, true); + pSegment->ScheduleTask(proc, data); + } + + /// + /// Schedules a light-weight task within the schedule group. The light-weight task will also be biased towards executing at the specified location. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// A reference to a location where the light-weight task will be biased towards executing at. + /// + /// + /// Calling the ScheduleTask method implicitly places a reference count on the schedule group which is removed by the runtime + /// at an appropriate time after the task executes. + /// + /// + /// + void ScheduleGroupBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void * data, location& placement) + { + ScheduleGroupSegmentBase *pSegment = LocateSegment(&placement, true); + pSegment->ScheduleTask(proc, data); + } + + /// + /// Adds runnable context to the schedule group. This is usually a previously blocked context that + /// was subsequently unblocked, but it could also be an internal context executing chores on behalf + /// of an external context. + /// + void ScheduleGroupSegmentBase::AddRunnableContext(InternalContextBase* pContext, location bias) + { + ASSERT(pContext->GetScheduleGroupSegment() == this); + // + // If the current context does not belong to this group, the caller is not guaranteed to have a reference to the + // schedule group. We call CrossGroupRunnable() to make sure that scheduler and schedule group are kept around long + // enough, that we can attempt to startup the virtual processor without fear of the scheduler being finalized, or the + // schedule group being destroyed. + // + ContextBase* pCurrentContext = SchedulerBase::FastCurrentContext(); + + if ((pCurrentContext == NULL) || (pCurrentContext->GetScheduleGroupSegment() != this)) + { + // Set this flag to allow the calling thread to use 'this' safely once the context is pushed onto runnables. + // Note that this call does not need a fence because it is fenced by push to the runnable contexts collection. + pContext->CrossGroupRunnable(TRUE); + } + + // + // If there is an "inactive pending thread" virtual processor, this runnable should be shoved to it instead of going through the normal + // wake path. There is *NO REASON* to require an SFW context to immediately switch to this. + // + SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler(); + if (!(pScheduler->HasVirtualProcessorPendingThreadCreate() && pScheduler->PushRunnableToInactive(pContext, bias))) + { + // Add it to the actual collection. + AddToRunnablesCollection(pContext); + + if (!m_affinity._Is_system() && bias == m_affinity) + { + NotifyAffinitizedWork(); + } + + if (pScheduler->HasVirtualProcessorAvailable()) + { + pScheduler->StartupIdleVirtualProcessor(this, bias); + } + } + + // Reset the flag, if it was set, since we're done with touching scheduler/context data. + // This flag is not fenced. This means the reader could end up spinning a little longer until the data is + // propagated by the cache coherency mechanism. + pContext->CrossGroupRunnable(FALSE); + // NOTE: It is not safe to touch 'this' after this point, if this was a cross group runnable. + } + + /// + /// Steals an unrealized chore from a workqueue in the schedule group. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + _UnrealizedChore* ScheduleGroupSegmentBase::StealUnrealizedChore(bool fForceStealLocalized) + { + // + // When we fail to steal from a work queue that's detached, it's an indication that the work queue + // is finally empty and can be retired. + // + + _UnrealizedChore *pChore; + + bool killEmptyQueues = false; + int maxIndex = m_workQueues.MaxIndex(); + if (maxIndex > 0) + { + int skippedCount = 0; + const int maxSkippedCount = 16; + int skippedState[maxSkippedCount]; + bool fEntered = false; + + for (int j = 0; j < maxIndex; j++) + { + WorkQueue *pQueue = m_workQueues[j]; + if (pQueue != NULL) + { + if ( !pQueue->IsEmpty()) + { + if ((pChore = pQueue->TryToSteal(fForceStealLocalized, fEntered)) != NULL) + return pChore; + else if ( !fEntered) + { + if (skippedCount < maxSkippedCount-1) + { + skippedState[skippedCount++] = j; + continue; + } + else if ((pChore = pQueue->Steal(fForceStealLocalized)) != NULL) + return pChore; + } + + killEmptyQueues |= (pQueue->IsDetached() && pQueue->IsEmpty()); + } + else + killEmptyQueues |= pQueue->IsDetached(); + } + } + + if (skippedCount > 0) + { + for (int j = 0; j < skippedCount; j++) + { + WorkQueue *pQueue = m_workQueues[skippedState[j]]; + if (pQueue != NULL) + { + if ( !pQueue->IsEmpty() && (pChore = pQueue->Steal(fForceStealLocalized)) != NULL) + return pChore; + else + killEmptyQueues |= (pQueue->IsDetached() && pQueue->IsEmpty()); + } + } + } + } + + if (m_mailedTasks.Dequeue(&pChore)) + { + // The chore may not be from a detached workqueue, but since it is dequeued from a mailbox, we set it as detached + // which will add the stealing context to a list in the task collection instead of the owning contexts stealer collection. + pChore->_SetDetached(true); + return pChore; + } + + int numDetachedArrays = m_detachedWorkQueues.MaxIndex(); + if (numDetachedArrays > 0 && killEmptyQueues) + { + for (int i = 0; i < m_workQueues.MaxIndex(); i++) + { + WorkQueue *pQueue = m_workQueues[i]; + if (pQueue != NULL) + { + if (pQueue->IsDetached() && pQueue->IsUnstructuredEmpty()) + { + SafelyDeleteDetachedWorkQueue(pQueue); + } + } + } + } + + return NULL; + } + + /// + /// Returns true if the group has any realized chores. + /// This is used during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + bool ScheduleGroupSegmentBase::HasRealizedChores() const + { + return !m_realizedChores.Empty(); + } + + /// + /// Returns the first work queue in the schedule group that has unrealized chores. + /// This is only stable during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + WorkQueue *ScheduleGroupSegmentBase::LocateUnrealizedChores() + { + for (int i = 0; i < m_workQueues.MaxIndex(); i++) + { + WorkQueue *pQueue = m_workQueues[i]; + if (pQueue != NULL) + { + if (!pQueue->IsStructuredEmpty() || !pQueue->IsUnstructuredEmpty()) + { + return pQueue; + } + else if (pQueue->IsDetached()) + { + SafelyDeleteDetachedWorkQueue(pQueue); + } + } + } + + if (!m_mailedTasks.IsEmpty()) + return MAILBOX_LOCATION; + + return NULL; + } + + /// + /// Returns true if any of the workqueues in the schedule group has unrealized chores. + /// This is only stable during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + bool ScheduleGroupSegmentBase::HasUnrealizedChores() + { + return LocateUnrealizedChores() != NULL; + } + + /// + /// Called to safely delete a detached work queue -- this is lock free and utilizes safe points to perform + /// the deletion and dereference. It can be called during the normal SFW or during the finalization sweep + /// safely. + /// + bool ScheduleGroupSegmentBase::SafelyDeleteDetachedWorkQueue(WorkQueue *pQueue) + { + // + // The way in which we resolve race conditions between this and queue reattachment is by who is able to remove the + // element from the detached list array. We cannot kill the work queue until it's gone out of that list array. + // + if (m_detachedWorkQueues.Remove(&pQueue->m_detachment, false)) + { + // + // There's always the possibility of a very subtle race where we check IsDetached and IsUnstructuredEmpty and then + // are preempted, the queue is reattached, work is added, and it's detached again in the same spot with work. We + // cannot free the queue in such circumstance. Only if it is empty AFTER removal from m_detachedWorkQueues are + // we safe. + // + if (pQueue->IsUnstructuredEmpty()) + { + // + // Each detached work queue holds a reference on the group. It is referenced + // in ScheduleGroupBase::DetachActiveWorkQueue(). Since we are removing this + // empty work queue, we need to release the reference. + // + // There's an unfortunate reality here -- this work queue might be the LAST thing holding reference onto + // the schedule group. It's entirely possible that someone just stole and hasn't yet gotten to the point + // where a reference is added to the schedule group. If we arbitrarily release this reference, we might delete + // (or reuse) an active schedule group. This could cause all sorts of problems. + // + // Instead of trying to release that reference here, we will wait until the next safe point to do so. We + // are guaranteed no one is in the middle of stealing from this schedule group at that time. + // + // Note that this means that the stealer **MUST** stay within a critical region until after the WorkItem::TransferReferences + // call. + // + pQueue->RetireAtSafePoint(this); + return true; + } + else + { + CONCRT_COREASSERT(!m_pOwningGroup->GetScheduler()->InFinalizationSweep()); + + // + // The queue is not empty and we need to roll back. Since we never removed the queue from m_workQueues, the work will + // still be found by the scheduler without undue futzing around sleep states. The queue must, however, be placed + // back in m_detachedWorkQueues in a detached state. + // + // There's an unfortunate reality here too -- the slot used for the queue within the detached queues list might already + // be gone. Adding back to the detached queues might trigger a heap allocation. Given that this might be in SFW, a heap allocation + // triggering UMS would be bad. Hence -- if we need to roll back (unlikely), we must do this at a safe point. + // + pQueue->RedetachFromScheduleGroupAtSafePoint(this); + } + } + + return false; + } + + /// + /// Creates a realized (non workstealing) chore in the schedule group. Used to schedule light-weight + /// tasks and agents. + /// + void ScheduleGroupSegmentBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data) + { + if (proc == NULL) + { + throw std::invalid_argument("proc"); + } + + SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler(); + RealizedChore *pChore = pScheduler->GetRealizedChore(proc, data); + TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::ScheduleTask(sgroup=%d,ring=0x%p,chore=0x%p)\n", Id(), m_pRing, pChore); + + // Every task takes a reference on its schedule group. This is to ensure a schedule group has a ref count > 0 if + // no contexts are working on it, but queued tasks are present. The reference count is transferred to the context + // that eventually executes the task. + m_pOwningGroup->InternalReference(); + + m_realizedChores.Enqueue(pChore); + + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + + if (pCurrentContext == NULL || pCurrentContext->GetScheduler() != pScheduler) + { + // + // This is a thread that is in no way tracked in ConcRT (no context assigned to it) or it is a context foreign to + // this scheduler, so we cannot have statistics directly associated with its context. Instead, there is an entry in + // the TLS section PER scheduler that points to the external statistics mapping. From that information, we can know + // whether we have seen this thread before and whether it was ever scheduling tasks on the current scheduler. + // + ExternalStatistics * externalStatistics = (ExternalStatistics *) platform::__TlsGetValue(pScheduler->m_dwExternalStatisticsIndex); + + if (externalStatistics == NULL) + { + // + // This is the first piece of statistical data for this thread on this scheduler, so + // create a statistics class, add it to the list array of statistics on this scheduler and + // save it in the TLS slot reserved for statistics on this scheduler. + // + externalStatistics = _concrt_new ExternalStatistics(); + pScheduler->AddExternalStatistics(externalStatistics); + platform::__TlsSetValue(pScheduler->m_dwExternalStatisticsIndex, externalStatistics); + } + else + { + // + // We already have some statistical data for this thread on this scheduler. + // + ASSERT(pScheduler->m_externalThreadStatistics.MaxIndex() > 0); + } + + ASSERT(externalStatistics != NULL); + externalStatistics->IncrementEnqueuedTaskCounter(); + } + else if (pCurrentContext->IsExternal()) + { + static_cast(pCurrentContext)->IncrementEnqueuedTaskCounter(); + } + else + { + static_cast(pCurrentContext)->IncrementEnqueuedTaskCounter(); + } + + // + // If there is explicit affinity placed on this new task, make sure to tell the scheduler so that it can send messages to any virtual + // processors as necessary to snap them back to affine work. + // + if (!m_affinity._Is_system()) + { + NotifyAffinitizedWork(); + } + + // In most cases this if check will fail. To avoid the function call overhead in the common case, we check + // for virtual processors beforehand. + if (pScheduler->HasVirtualProcessorAvailableForNewWork()) + { + pScheduler->StartupNewVirtualProcessor(this, m_affinity); + } + + } + + + /// + /// Places a work queue in the detached queue. This will cause the work queue to remain eligible for stealing + /// while the queue can be detached from a context. The work queue will be recycled and handed back to a + /// context executing within the schedule group that needs a queue. If the queue is not recycled, it will be + /// abandoned and freed when it becomes empty (a steal on it while in detached mode fails). + /// + void ScheduleGroupSegmentBase::DetachActiveWorkQueue(WorkQueue *pWorkQueue) + { + m_pOwningGroup->InternalReference(); + + // + // Note: there is a distinct lack of relative atomicity between the flag set and the queue add. The worst thing that + // happens here is that we ask the list array to remove an element at an invalid index. It is prepared to handle + // that anyway. + // + pWorkQueue->SetDetached(true); + m_detachedWorkQueues.Add(&pWorkQueue->m_detachment); + } + + /// + /// Called by a work queue in order to roll back an attempted kill that could not be committed due to reuse. + /// + void ScheduleGroupSegmentBase::RedetachQueue(WorkQueue *pWorkQueue) + { + // + // Roll back by reinserting into m_detachedWorkQueues. We detect the error before setting detached state to false or releasing + // reference, so this is the only operation which needs to happen. It just cannot happen during the steal due to the fact that + // there is a **SLIGHT** chance that the call will perform a heap allocation. + // + m_detachedWorkQueues.Add(&pWorkQueue->m_detachment); + } + + /// + /// Attempts to acquire a detached work queue from the schedule group. If such a work queue is found, it + /// is removed from detached queue and returned. This allows recycling of work queues that are detached + /// yet still have unstructured work. + /// + WorkQueue *ScheduleGroupSegmentBase::GetDetachedWorkQueue() + { + int maxIdx = m_detachedWorkQueues.MaxIndex(); + for (int i = 0; i < maxIdx; i++) + { + ListArrayInlineLink *pLink = m_detachedWorkQueues[i]; + + // + // No code below this may dereference pLink unless it is removed from the list array. There is no guarantee + // of safety as this can be called from an external context or multiple internal contexts. + // + if (pLink != NULL && m_detachedWorkQueues.Remove(pLink, i, false)) + { + WorkQueue *pWorkQueue = pLink->m_pObject; + + pWorkQueue->SetDetached(false); + + // + // This removed detached work queue incremented the reference count + // in ScheduleGroupBase::DetachActiveWorkQueue(). Release it now. + // + // This is safe because we are inside the schedule group getting a work queue. This means that there is already + // some context with a reference on the schedule group and it won't disappear out from underneath us by removing + // the detach reference. + // + m_pOwningGroup->InternalRelease(); + + return pWorkQueue; + } + } + + return NULL; + } + + /// + /// Called by a work queue in order to retire itself at a safe point. + /// + void ScheduleGroupSegmentBase::RetireDetachedQueue(WorkQueue *pWorkQueue) + { + CONCRT_VERIFY(m_workQueues.Remove(pWorkQueue)); + + // + // This removed detached work queue incremented the reference count + // in ScheduleGroupBase::DetachActiveWorkQueue(). Release it now. + // + m_pOwningGroup->InternalRelease(); + } + + RealizedChore * ScheduleGroupSegmentBase::GetRealizedChore() + { + if (m_realizedChores.Empty()) + return NULL; + + RealizedChore *pChore = m_realizedChores.Dequeue(); + TRACE(TRACE_SCHEDULER, L"ScheduleGroup::GetRealizedChore(sgroup=%d,ring=0x%p,chore=0x%p)\n", Id(), m_pRing, pChore); + return pChore; + } + + /// + /// Gets an internal context from either the idle pool or a newly allocated one and prepares it for + /// execution. A NULL return value from the routine is considered fatal (out of memory). This is the + /// API that should be used to obtain an internal context for execution. The context is associated + // with this schedule group. + /// + InternalContextBase * ScheduleGroupSegmentBase::GetInternalContext(_Chore *pChore, bool choreStolen) + { + // Get an internal context from the idle pool + InternalContextBase* pContext = m_pOwningGroup->GetScheduler()->GetInternalContext(); + + if (pContext != NULL) + { + // Associate it with this schedule group + pContext->PrepareForUse(this, pChore, choreStolen); + } + + return pContext; + } + + /// + /// Releases an internal context after execution into the idle pool. If the idle pool + /// is full, it could be freed. + /// + void ScheduleGroupSegmentBase::ReleaseInternalContext(InternalContextBase *pContext) + { + pContext->RemoveFromUse(); + m_pOwningGroup->GetScheduler()->ReleaseInternalContext(pContext); + } + + /// + /// Destroys a schedule group segment. + /// + ScheduleGroupSegmentBase::~ScheduleGroupSegmentBase() + { + // + // Make CERTAIN that the quick cache is cleared if this segment is contained within it. + // + if (m_affinity._GetType() == location::_ExecutionResource) + { + m_pOwningGroup->GetScheduler()->ClearQuickCacheSlotIf(m_maskIdIf, this); + } + + // There shall be no work queues (detached or otherwise) when a schedule group segment + // is deleted. This assumption is made in our safe point mechanism. If one + // of the workqueues in a schedule group segment requests a safe point invocation after + // the one for schedule group deletion, the workqueues would be deleted before + // its callback is invoked. + ASSERT(m_workQueues.IsEmptyAtSafePoint()); + ASSERT(m_detachedWorkQueues.IsEmptyAtSafePoint()); + } + + /// + /// Removes the segment. + /// + void ScheduleGroupSegmentBase::Remove() + { + OMTRACE(MTRACE_EVT_DESTROYSEGMENT, m_pOwningGroup, NULL, NULL, this); + // The order of operations here is important. Removing from the list array should be the last operation we perform on + // the segment. + m_pOwningGroup->m_pScheduler->RemovePrioritizedObject(&m_priorityServiceLink); + m_pRing->RemoveScheduleGroupSegment(this); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.h new file mode 100644 index 0000000000000000000000000000000000000000..b80c75cef2d7c87e2a64ae570bc074d94fc38a73 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.h @@ -0,0 +1,654 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ScheduleGroupBase.h +// +// Header file containing ScheduleGroup related declarations. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +#define MAILBOX_LOCATION (reinterpret_cast(1)) + +namespace Concurrency +{ +namespace details +{ + // + // A ScheduleGroupBase* object represents a schedule group as defined in the public API set. It is a container of work which is related + // and benefits from temporally and spatially close scheduling. + // + // A ScheduleGroupSegmentBase* object represents a segment of a schedule group with affinity to a particular location -- in this case affinity + // to a particular scheduling node. + // + + class ScheduleGroupBase; + + /// + /// A piece of a schedule group which is uniquely assigned to a given scheduling node/ring. + /// + class ScheduleGroupSegmentBase + { + public: + + /// + /// Called by a work queue in order to retire itself at a safe point. + /// + void RetireDetachedQueue(WorkQueue *pWorkQueue); + + /// + /// Called by a work queue in order to roll back an attempted kill that could not be committed due to reuse. + /// + void RedetachQueue(WorkQueue *pWorkQueue); + + /// + /// Destroys a schedule group segment. + /// + virtual ~ScheduleGroupSegmentBase(); + + /// + /// Returns the group to which this segment belongs. + /// + ScheduleGroupBase *GetGroup() const + { + return m_pOwningGroup; + } + + /// + /// Returns the scheduling ring to which this segment belongs. + /// + SchedulingRing *GetSchedulingRing() const + { + return m_pRing; + } + + /// + /// Schedules a realized (non workstealing) chore in the schedule group segment. Used to schedule light-weight + /// tasks and agents. + /// + void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data); + + /// + /// Marks the segment as serviced at a particular time mark. + /// + void ServiceMark(ULONGLONG markTime) + { + // + // Avoid cache contention on this by only writing the service time every so often. We only care about this on granularities of something + // like 1/2 seconds anyway -- it's effectively the priority boost time granularity that we care about. + // + if (TimeSinceServicing(markTime) > 100) + { + OMTRACE(MTRACE_EVT_MARK, this, NULL, NULL, markTime); + m_lastServiceTime = markTime; + } + } + + /// + /// Returns the time delta between the last service time and the passed service time. + /// + ULONG TimeSinceServicing(ULONGLONG markTime) + { + return (ULONG) (markTime - m_lastServiceTime); + } + + /// + /// Returns a segment from its internal list entry. + /// + static ScheduleGroupSegmentBase* FromBoostEntry(BoostedObject *pEntry) + { + return CONTAINING_RECORD(pEntry, ScheduleGroupSegmentBase, m_priorityServiceLink); + } + + /// + /// Notifies virtual processors that work affinitized to them has become available in the schedule group segment. + /// + virtual void NotifyAffinitizedWork() =0; + + protected: + + // + // Private methods + // + + /// + /// Constructs a new schedule group segment with a specific affinity in the specified ring. + /// + /// + /// The group to which this segment belongs. + /// + /// + /// The ring in which this segment is contained. + /// + /// + /// The affinity of this segment. + /// + ScheduleGroupSegmentBase(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity); + + /// + /// Initializes a schedule group segment. + /// + /// + /// The group to which this segment belongs. + /// + /// + /// The ring in which this segment is contained. + /// + /// + /// The affinity of this segment. + /// + void Initialize(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location *pSegmentAffinity); + + /// + /// Adds runnable context to the schedule group. This is usually a previously blocked context that + /// was subsequently unblocked, but it could also be an internal context executing chores on behalf + /// of an external context. + /// + void AddRunnableContext(InternalContextBase *pContext, location bias = location()); + + /// + /// Puts a runnable context into the runnables collection in the schedule group. + /// + virtual void AddToRunnablesCollection(InternalContextBase *pContext) =0; + + virtual InternalContextBase *GetRunnableContext() = 0; + + /// + /// Returns true if the group has any realized chores. + /// This is used during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + bool HasRealizedChores() const; + + /// + /// Returns the first work queue in the schedule group that has unrealized chores. + /// This is only stable during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + /// + /// This method either returns a special constant MAILBOX_LOCATION if work was found in the mailbox or + /// a work queue in which an unrealized chore was found. + /// + WorkQueue *LocateUnrealizedChores(); + + /// + /// Returns true if any of the workqueues in the schedule group has unrealized chores. + /// This is only stable during scheduler finalization when only one thread is active in the scheduler. + /// At any other time, this information is stale since new work could get added to the scheduler. + /// + bool HasUnrealizedChores(); + + /// + /// Returns a realized chore if one exists in the queue. + /// + RealizedChore *GetRealizedChore(); + + /// + /// Acquires an internal context for execution + /// + InternalContextBase* GetInternalContext(_Chore *pChore = NULL, bool choreStolen = false); + + /// + /// Releases an internal context after execution + /// + void ReleaseInternalContext(InternalContextBase *pContext); + + /// + /// Steals an unrealized chore from a workqueue in the schedule group. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + _UnrealizedChore* StealUnrealizedChore(bool fForceStealLocalized = false); + + /// + /// Attempts to acquire a detached work queue from the schedule group. If such a work queue is found, it + /// is removed from detached queue and returned. This allows recycling of work queues that are detached + /// yet still have unstructured work. + /// + WorkQueue *GetDetachedWorkQueue(); + + /// + /// Places a work queue in the detached queue. This will cause the work queue to remain eligible for stealing + /// while the queue can be detached from a context. The work queue will be recycled and handed back to a + /// context executing within the schedule group that needs + /// a queue. If the queue is not recycled, it will be abandoned and freed when it becomes empty (a steal on it + /// while in detached mode fails). + /// + void DetachActiveWorkQueue(WorkQueue *pWorkQueue); + + /// + /// Called to safely delete a detached work queue -- this is lock free and utilizes safe points to perform + /// the deletion and dereference. It can be called during the normal SFW or during the finalization sweep + /// safely. + /// + bool SafelyDeleteDetachedWorkQueue(WorkQueue *pQueue); + + /// + /// Returns a location representing the affinity of this segment. Note that if the location returned is the system location, + /// the segment has no specific placement affinity. It may still have a weaker natural affinity to a particular node by + /// nature of the fact that a segment is contained within a ring. + /// + const location& GetAffinity() const + { + return m_affinity; + } + + /// + /// Returns our cached affinity set. + /// + const QuickBitSet& GetAffinitySet() const + { + return m_affinitySet; + } + + /// + /// Removes the segment. + /// + void Remove(); + + // + // Private data + // + + // Owning ring. + SchedulingRing *m_pRing; + + // A location representing the affinity of this segment. + location m_affinity; + + // The bitset representing m_affinity for quick masking. + QuickBitSet m_affinitySet; + + // Quickly stashed maskId if the location for this segment is a core. + unsigned int m_maskIdIf; + + // Each schedule group has three stores of work. It has a collection of runnable contexts (in the derived classes), + // a FIFO queue of realized chores and a list of workqueues that hold unrealized chores. + + // A queue of realized chores. + SafeSQueue m_realizedChores; + + // The list of tasks which were mailed to this segment. + Mailbox<_UnrealizedChore> m_mailedTasks; + + // A list array of all unrealized chore queues that are owned by contexts in this schedule group, + // protected by a r/w lock. + ListArray m_workQueues; + + // A list array of work queues which still contain work within the schedule group but have become detached + // from their parent context (e.g.: a chore queues unstructured work and does not wait upon it before + // exiting). This is the first level "free list". Any context needing a work queue can grab one from + // here assuming it's executing the same schedule group. + ListArray< ListArrayInlineLink > m_detachedWorkQueues; + + // The index that this schedule group is at in its containing ListArray + int m_listArrayIndex; + + // Unique identifier + unsigned int m_id; + + // The group to which this segment belongs + ScheduleGroupBase *m_pOwningGroup; + + // The next segment within the group + ScheduleGroupSegmentBase * volatile m_pNext; + + // The last time this segment was serviced. + ULONGLONG m_lastServiceTime; + + // + // TRANSITION: This is a temporary patch on livelock until we can tie into priority for livelock prevention. + // + BoostedObject m_priorityServiceLink; + + private: + + friend class SchedulerBase; + friend class ScheduleGroupBase; + friend class ContextBase; + friend class ExternalContextBase; + friend class InternalContextBase; + friend class ThreadInternalContext; + friend class SchedulingNode; + friend class SchedulingRing; + friend class VirtualProcessor; + friend class WorkItem; + friend class WorkSearchContext; + template friend class ListArray; + + // Intrusive links for list array. + SLIST_ENTRY m_listArrayFreeLink; + }; + +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class ScheduleGroupBase : public ScheduleGroup + { + public: + // + // Public Methods + // + + /// + /// Constructs a schedule group. + /// + ScheduleGroupBase(SchedulerBase *pScheduler, location* pGroupPlacement); + + /// + /// Virtual destructor + /// + virtual ~ScheduleGroupBase() + { + } + + /// + /// Performs initialization (or reinitialization) of a schedule group. + /// + void Initialize(location* pGroupPlacement); + + /// + /// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement + /// and the origin of the thread making the call. + /// + /// + /// A segment with affinity to this particular location will be located. + /// + /// + /// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is + /// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found. + /// + /// + /// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned + /// if fCreateNew is specified as false and no appropriate segment yet exists for the group. + /// + virtual ScheduleGroupSegmentBase *LocateSegment(location* pSegmentAffinity, bool fCreateNew); + + /// + /// Returns a pointer to the scheduler this group belongs to. + /// + SchedulerBase * GetScheduler() { return m_pScheduler; } + + // *************************************************************************** + // + // Public Interface Derivations: + // + + /// + /// Returns a unique identifier to the schedule group. + /// + unsigned int Id() const + { + return m_id; + } + + /// + /// Increments the reference count of a schedule group. A reference count is held for + /// - every unstarted or incomplete realized chore that is part of the schedule group + /// - every context that is executing a chore that was stolen from an unrealized chore queue + /// within the schedule group + /// - every external context attached to the scheduler instance, IFF this is the anonymous + /// schedule group for the scheduler instance, + /// - an external caller, IFF this schedule group was created using one of the public task + /// creation APIs. + /// + /// + /// Returns the resulting reference count. + /// + virtual unsigned int Reference() + { + return (unsigned int)InternalReference(); + } + + /// + /// Decrements the reference count of a schedule group. Used for composition. + /// + /// + /// Returns the resulting reference count. + /// + virtual unsigned int Release() + { + return (unsigned int)InternalRelease(); + } + + /// + /// Schedules a light-weight task within the schedule group. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// Calling the ScheduleTask method implicitly places a reference count on the schedule group which is removed by the runtime + /// at an appropriate time after the task executes. + /// + /// + virtual void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data); + // + // End of Public Interface Derivations: + // + // *************************************************************************** + + /// + /// Schedules a light-weight task within the schedule group. The light-weight task will also be biased towards executing at the specified location. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// A reference to a location where the light-weight task will be biased towards executing at. + /// + /// + /// Calling the ScheduleTask method implicitly places a reference count on the schedule group which is removed by the runtime + /// at an appropriate time after the task executes. + /// + /// + /// + void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void * data, location& placement); + + /// + /// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified + /// location. + /// + /// + /// The chore to mail. + /// + /// + /// A pointer to a location where the chore will be mailed. + /// + /// + /// The mailbox slot into which the chore was placed. + /// + /// + /// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body + /// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method. + /// + virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore, + location * pPlacement, + ScheduleGroupSegmentBase ** ppDestinationSegment) =0; + + /// + /// Gets the first schedule group segment within the group that is either affine or non-affine as specified by fAffine. + /// + ScheduleGroupSegmentBase *GetFirstScheduleGroupSegment(bool fAffine) + { + return fAffine ? m_pAffineSegments : m_pNonAffineSegments; + } + + /// + /// Gets the next schedule group segment within the group. This will return only affine or non-affine segments depending + /// on how GetFirstScheduleGroupSegment was called. + /// + ScheduleGroupSegmentBase *GetNextScheduleGroupSegment(ScheduleGroupSegmentBase *pSegment) + { + return pSegment->m_pNext; + } + + protected: + friend class ScheduleGroupSegmentBase; + + friend class SchedulerBase; + friend class ContextBase; + friend class ExternalContextBase; + friend class InternalContextBase; + friend class ThreadInternalContext; + friend class SchedulingNode; + friend class SchedulingRing; + friend class VirtualProcessor; + friend class WorkItem; + friend class WorkSearchContext; + template friend class ListArray; + + enum { + CacheLocalScheduling = 1, + FairScheduling = 2, + AnonymousScheduleGroup = 4 + }; + + // + // Private data + // + + // Owning scheduler + SchedulerBase *m_pScheduler; + + // The lock which guards creation of segments. + _NonReentrantLock m_segmentLock; + + // A linked list of explicitly affine segments within this group + ScheduleGroupSegmentBase *m_pAffineSegments; + + // A linked list of segments which are not explicitly affine. + ScheduleGroupSegmentBase *m_pNonAffineSegments; + + // Reference count for the schedule group + volatile long m_refCount; + + // The index that this schedule group is at in its containing ListArray + int m_listArrayIndex; + + // Unique identifier + unsigned int m_id; + + // The location that the group schedules to by default. A non-biased group will contain the system location. + location m_groupPlacement; + + // flag indicating schedule group kind + BYTE m_kind; + + // + // Private methods + // + + /// + /// Removes all schedule group segments from the group. + /// + virtual void RemoveSegments(); + + /// + /// Non-virtual function that increments the reference count of a schedule group. + /// + LONG InternalReference() + { + if ((m_kind & AnonymousScheduleGroup) == 0) + { + ASSERT(m_refCount >= 0); + TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::InternalReference(rc=%d)\n", m_refCount+1); + LONG val = InterlockedIncrement(&m_refCount); + + OMTRACE(MTRACE_EVT_REFERENCE, this, NULL, NULL, val); + + return val; + } + return 0; + } + + /// + /// Non-virtual function that decrements the reference count of a schedule group. + /// + LONG InternalRelease() + { + if ((m_kind & AnonymousScheduleGroup) == 0) + { + ASSERT(m_refCount > 0); + TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::InternalRelease(rc=%d)\n", m_refCount-1); + LONG newValue = InterlockedDecrement(&m_refCount); + + OMTRACE(MTRACE_EVT_DEREFERENCE, this, NULL, NULL, newValue); + + if (newValue == 0) + { + RemoveSegments(); + m_pScheduler->RemoveScheduleGroup(this); + } + return newValue; + } + return 0; + } + + bool IsFairScheduleGroup() const { return (m_kind & FairScheduling) != 0; } + + /// + /// Allocates a new cache local schedule group segment within the specified group and ring with the specified affinity. + /// + /// + /// The affinity for the segment. + /// + /// + /// The scheduling ring to which the newly allocated segment will belong. + /// + /// + /// A new cache local schedule group within the specified group and ring with the specified affinity. + /// + virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity) = 0; + + /// + /// Creates a new segment with the specified affinity within the specified ring. + /// + /// + /// The affinity of the segment. + /// + /// + /// The ring into which the new segment will be placed. Some aspect of segmentAffinity must overlap with the node to which this ring + /// belongs. + /// + /// + /// A new segment with the specified affinity within the specified ring. + /// + ScheduleGroupSegmentBase *CreateSegment(location* pSegmentAffinity, SchedulingRing *pOwningRing); + + /// + /// Internal routine which finds an appropriate segment for a task placement. + /// + /// + /// A segment with this affinity will be located. + /// + /// + /// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order + /// to keep work local. + /// + /// + /// A segment with the specified affinity close to the specified location. + /// + virtual ScheduleGroupSegmentBase *FindSegment(location* pSegmentAffinity, SchedulingRing *pRing); + + private: + + // Intrusive links for list array. + SLIST_ENTRY m_listArrayFreeLink; + }; +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c217a5550ed0531b85d8b438096c4aeb4416be13 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.cpp @@ -0,0 +1,3423 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulerBase.cpp +// +// Implementation file of the metaphor for a concrt scheduler +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +namespace Concurrency +{ +/// +/// Creates a scheduler that only manages internal contexts. Implicitly calls Reference. +/// If Attach is called, the scheduler is no longer anonymous because it is also managing the external +/// context where Attach was called. To destroy an anonymous scheduler, Release needs to be called. +/// +/// +/// A const reference to the scheduler policy. +/// +/// +/// A pointer to the new scheduler +/// +Scheduler* Scheduler::Create(const SchedulerPolicy& policy) +{ + ::Concurrency::details::SchedulerBase *pScheduler = ::Concurrency::details::SchedulerBase::Create(policy); + pScheduler->Reference(); + return pScheduler; +} + +/// +/// Allows a user defined policy to be used to create the default scheduler. It is only valid to call this API when no default +/// scheduler exists. Once a default policy is set, it remains in effect until the next valid call to the API. +/// +/// +/// The policy to be set as the default. The runtime will make a copy of the policy for its use, and the user +/// is responsible for the lifetime of the policy that is passed in. +/// +void Scheduler::SetDefaultSchedulerPolicy(const SchedulerPolicy & _Policy) +{ + ::Concurrency::details::SchedulerBase::SetDefaultSchedulerPolicy(_Policy); +} + +/// +/// Resets the default scheduler policy, and the next time a default scheduler is created, it will use the runtime's default policy settings. +/// +void Scheduler::ResetDefaultSchedulerPolicy() +{ + ::Concurrency::details::SchedulerBase::ResetDefaultSchedulerPolicy(); +} + +// +// Internal bit mask definitions for the shutdown gate. +// +#define SHUTDOWN_INITIATED_FLAG 0x80000000 +#define SUSPEND_GATE_FLAG 0x40000000 +#define SHUTDOWN_COMPLETED_FLAG 0x20000000 +#define GATE_COUNT_MASK 0x1FFFFFFF +#define GATE_FLAGS_MASK 0xE0000000 + +namespace details +{ + + // The default scheduler lock protects access to both the default scheduler as well as the + // default scheduler policy. + SchedulerBase *SchedulerBase::s_pDefaultScheduler = NULL; + SchedulerPolicy *SchedulerBase::s_pDefaultSchedulerPolicy = NULL; + + LONG SchedulerBase::s_initializedCount = 0; + LONG SchedulerBase::s_oneShotInitializationState = ONESHOT_NOT_INITIALIZED; + volatile LONG SchedulerBase::s_workQueueIdCounter = 0; + DWORD SchedulerBase::t_dwContextIndex; + + // Number of suballocators for use by external contexts that are active in the process. + volatile LONG SchedulerBase::s_numExternalAllocators = 0; + + // The max number of external contexts that could have suballocators at any given time. + const int SchedulerBase::s_maxExternalAllocators = 32; + + // The maximum depth of the free pool of allocators. + const int SchedulerBase::s_allocatorFreePoolLimit = 16; + + /// + /// Constructor for SchedulerBase. + /// + SchedulerBase::SchedulerBase(_In_ const ::Concurrency::SchedulerPolicy& policy) + : m_policy(policy) + , m_scheduleGroups(NULL, 256, 64) + , m_externalThreadStatistics(NULL, 256, ListArray::DeletionThresholdInfinite) + , m_contextIdCounter(-1) + , m_scheduleGroupIdCounter(-1) + , m_safePointDataVersion(0) + , m_safePointCommitVersion(0) + , m_safePointPendingVersion(0) + , m_id(static_cast(-1)) + , m_nextSchedulingRingIndex(0) + , m_refCount(0) + , m_attachCount(0) + , m_internalContextCountPlusOne(1) + , m_initialReference(0) + , m_boundContextCount(0) + , m_vprocShutdownGate(0) + , m_fSweepWithoutActualWork(FALSE) + , m_lastServiceScan(0) + , m_pResourceManager(NULL) + , m_activeVProcCount(0) + , m_virtualProcessorsPendingThreadCreate(0) + , m_enqueuedTaskCounter(0) + , m_dequeuedTaskCounter(0) + , m_enqueuedTaskCheckpoint(0) + , m_dequeuedTaskCheckpoint(0) + , m_lastThrottledCreateTime(0) + , m_pendingDeferredCreates(0) + { + // + // @TODO: Ugly... + // + m_scheduleGroups.SetScheduler(this); + + m_schedulerKind = (::Concurrency::SchedulerType) policy.GetPolicyValue(::Concurrency::SchedulerKind); + m_localContextCacheSize = (unsigned short) policy.GetPolicyValue(::Concurrency::LocalContextCacheSize); + m_schedulingProtocol = (::Concurrency::SchedulingProtocolType) policy.GetPolicyValue(::Concurrency::SchedulingProtocol); + + // + // This is a count before which we will **NOT** perform any throttling. In the event of repeated latent blocking, we will reach + // this number of threads rapidly. By default, we choose this number to be 4x the number of cores. Because MaxConcurrency is utilized + // as a "preferred concurrency level", if a client has specified a ManConcurrency value that implies a greater number of vprocs than this, + // we will adjust the throttling limit upwards to MaxConcurrency. This may result in poorer overall throttling performance; + // however -- one would expect that most clients aren't requesting > 4x oversubscription. + // + m_threadsBeforeThrottling = max(::Concurrency::GetProcessorCount() * 4, policy.GetPolicyValue(::Concurrency::MaxConcurrency)); + + // Allocate a TLS slot to track statistics for threads alien to this scheduler + m_dwExternalStatisticsIndex = platform::__TlsAlloc(); // VSO#459907 + + if ((m_hThrottlingTimer = RegisterAsyncTimerAndLoadLibrary(PSEUDOINFINITE, SchedulerBase::ThrottlerDispatchBridge, this, true)) == nullptr) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); // VSO#459907 + } + } + + SchedulerBase::~SchedulerBase() + { + Cleanup(); + } + + void SchedulerBase::Cleanup() + { + for (int idx = 0; idx < m_nodeCount; ++idx) + delete m_nodes[idx]; + + for (int idx = 0; idx < m_nodeCount; ++idx) + delete m_rings[idx]; + + delete [] m_pCoreAffinityQuickCache; + delete [] m_nodes; + delete [] m_rings; + delete [] m_numaInformation; + + // Cleanup a TLS slot and allow a reuse + platform::__TlsFree(m_dwExternalStatisticsIndex); + m_dwExternalStatisticsIndex = 0; + + m_pResourceManager->Release(); + SchedulerBase::StaticDestruction(); + + } + + // race is fine -- only for inputting work + SchedulingRing *SchedulerBase::GetNextSchedulingRing() + { + SchedulingRing *pRing = m_rings[m_nextSchedulingRingIndex]; + ASSERT(pRing != NULL); + m_nextSchedulingRingIndex = GetNextValidSchedulingRingIndex(m_nextSchedulingRingIndex); + return pRing; + } + + int SchedulerBase::GetValidSchedulingRingIndex(int idx) + { + ASSERT(idx >= 0 && idx <= m_nodeCount); + ASSERT(m_rings[idx] != NULL); + if (!m_rings[idx]->IsActive()) + return GetNextValidSchedulingRingIndex(idx); + return idx; + } + + int SchedulerBase::GetNextValidSchedulingRingIndex(int idx) + { + ASSERT(idx >= 0 && idx <= m_nodeCount); + do + { + idx = (idx+1) % m_nodeCount; + ASSERT(m_rings[idx] != NULL); + } while (!m_rings[idx]->IsActive()); + return idx; + } + + SchedulingRing *SchedulerBase::GetNextSchedulingRing(const SchedulingRing *pOwningRing, SchedulingRing *pCurrentRing) + { + ASSERT(pCurrentRing != NULL); + + SchedulingRing *pRing = m_rings[GetNextValidSchedulingRingIndex(pCurrentRing->Id())]; + ASSERT(pRing != NULL); + if (pRing == pOwningRing) + pRing = NULL; + return pRing; + } + + void SchedulerBase::SetNextSchedulingRing(SchedulingRing *pRing) + { + ASSERT(pRing != NULL); + + if (m_schedulingProtocol == ::Concurrency::EnhanceForwardProgress) + m_nextSchedulingRingIndex = GetNextValidSchedulingRingIndex(pRing->Id()); + } + + /// + /// Creates a scheduler instance + /// + /// + /// [in] A const reference to the scheduler policy. + /// + /// + /// A pointer to the new scheduler An exception is thrown if an error occurs. + /// + _Ret_writes_(1) SchedulerBase* SchedulerBase::Create(_In_ const SchedulerPolicy& policy) + { + SchedulerBase *pScheduler = CreateWithoutInitializing(policy); + // Obtain hardware threads, initialize virtual processors, etc. + pScheduler->Initialize(); + + return pScheduler; + } + + /// + /// Creates a scheduler instance + /// + /// + /// [in] A const pointer to the scheduler policy. + /// + /// + /// A pointer to the new scheduler An exception is thrown if an error occurs. + /// + _Ret_writes_(1) SchedulerBase* SchedulerBase::CreateWithoutInitializing(_In_ const SchedulerPolicy& policy) + { + policy._ValidateConcRTPolicy(); + CheckStaticConstruction(); + + SchedulerBase *pScheduler = ThreadScheduler::Create(policy); + return pScheduler; + } + + /// + /// Generates a unique identifier for a context. + /// + unsigned int SchedulerBase::GetNewContextId() + { + return (unsigned int) InterlockedIncrement(&m_contextIdCounter); + } + + /// + /// Generates a unique identifier for a schedule group. + /// + unsigned int SchedulerBase::GetNewScheduleGroupId() + { + return (unsigned int) InterlockedIncrement(&m_scheduleGroupIdCounter); + } + + /// + /// Generates a unique identifier for a work queue (across scheduler instances in the process). + /// + unsigned int SchedulerBase::GetNewWorkQueueId() + { + return (unsigned int) InterlockedIncrement(&s_workQueueIdCounter); + } + + /// + /// Anything which requires a one shot pattern of initialization with no destruction until termination goes here. + /// + void SchedulerBase::OneShotStaticConstruction() + { + _SpinCount::_Initialize(); + + // + // The TLS indicies must be one-shot as they are used outside the domain of guaranteed scheduler presence. We cannot free them + // until process-exit/CRT-unload or we'll have races with scheduler teardown/creation and outside APIs which require the TLS indicies. + // + + t_dwContextIndex = platform::__TlsAlloc(); + } + + /// + /// Anything which requires a pattern of demand initialization upon first scheduler creation and destruction upon last + /// scheduler destruction goes here. + /// + void SchedulerBase::StaticConstruction() + { + // + // Register ConcRT as an ETW trace provider + // + if (g_pEtw == NULL) + { + ::Concurrency::details::_RegisterConcRTEventTracing(); + } + } + + /// + /// Called to ensure static construction is performed upon creation of a scheduler. + /// + void SchedulerBase::CheckStaticConstruction() + { + // + // The reason a lock is taken here (rather than InterlockedIncrement of s_initializedCount) is that we want to ensure + // the entire construction is complete from the 0->1 transition before any other schedulers proceed past this point. + // + _StaticLock::_Scoped_lock lockHolder(s_schedulerLock); + + if (++s_initializedCount == 1) + { + // + // all static initialization here + // + StaticConstruction(); + + #pragma warning(suppress: 28112) // False positive warning, VSO-1807048 + if ((s_oneShotInitializationState & ONESHOT_INITIALIZED_FLAG) == 0) + { + OneShotStaticConstruction(); + + // + // This both guarantees a full fence and protects against simultaneous manipulation of the reference count stored within the lower + // 31 bits of s_oneShotInitializationState. + // + InterlockedOr(&s_oneShotInitializationState, ONESHOT_INITIALIZED_FLAG); + } + } + } + + /// + /// Performs one shot static destruction (at unload/process exit). + /// + void SchedulerBase::OneShotStaticDestruction() + { + platform::__TlsFree(t_dwContextIndex); + t_dwContextIndex = 0; + } + + /// + /// Called at unload/process exit to perform cleanup of one-shot initialization items. + /// + void SchedulerBase::CheckOneShotStaticDestruction() + { + // + // This might happen at unload time and does not need to be governed by lock. Further, at the time of calling in such circumstance, + // all static and globals should already have destructed -- it would be bad form to touch s_schedulerLock even if it is presently + // a wrapper around a POD type. Note that a background thread might come through here but would never get past the InterlockedDecrement + // unless we were at unload time. + // + LONG val = DereferenceStaticOneShot(); + if (val == ONESHOT_INITIALIZED_FLAG) // ref==0 + { + // + // Here, we are at unload time. + // + OneShotStaticDestruction(); + + val = InterlockedAnd(&s_oneShotInitializationState, ~ONESHOT_INITIALIZED_FLAG); + ASSERT(val == ONESHOT_INITIALIZED_FLAG); + } + } + + void SchedulerBase::StaticDestruction() + { + // + // The reason a lock is taken here (rather than InterlockedDecrement of s_initializedCount) is that we want to ensure + // the entire destruction is complete from the 1->0 transition before any other schedulers try construction. + // + _StaticLock::_Scoped_lock lockHolder(s_schedulerLock); + + if (--s_initializedCount == 0) + { + // + // all static destruction here + // + + // + // Unregister ConcRT as an ETW trace provider + // + ::Concurrency::details::_UnregisterConcRTEventTracing(); + + // We have exclusive access to the free pool, and therefore can use unsafe APIs. + SubAllocator* pAllocator = s_subAllocatorFreePool.Pop(); + while (pAllocator != NULL) + { + delete pAllocator; + pAllocator = s_subAllocatorFreePool.Pop(); + } + } + } + + /// + /// Initialize variables and request execution resources from the Resource Manager. + /// + void SchedulerBase::Initialize() + { + m_virtualProcessorAvailableCount = 0; + m_virtualProcessorCount = 0; + m_nodeCount = 0; + + m_pResourceManager = Concurrency::CreateResourceManager(); + m_id = Concurrency::GetSchedulerId(); + + // Get the number of nodes on the machine so we can create a fixed array for scheduling nodes and + // scheduling rings - obviating the need for locking these collections when we traverse them. + m_nodeCount = GetProcessorNodeCount(); + + ULONG highestNodeNumber = platform::__GetNumaHighestNodeNumber(); + m_numaCount = highestNodeNumber + 1; + m_numaInformation = _concrt_new NumaInformation[m_numaCount]; + + m_rings = _concrt_new SchedulingRing*[m_nodeCount]; + m_nodes = _concrt_new SchedulingNode*[m_nodeCount]; + memset(m_rings, 0, sizeof(SchedulingRing*) * m_nodeCount); + memset(m_nodes, 0, sizeof(SchedulingNode*) * m_nodeCount); + + m_pAnonymousScheduleGroup = static_cast(CreateScheduleGroup()); + m_pAnonymousScheduleGroup->m_kind |= ScheduleGroupBase::AnonymousScheduleGroup; + + // Assigns a bitmask id to each execution resource. + unsigned int ridCounter = 0; + + // + // Build a complete understanding of the system topology *WITHIN* the scheduler as well as maps for resource IDs, etc... + // + unsigned int procCount = GetProcessorCount(); + + for (int index = 0; index < m_numaCount; ++index) + { + // Not all NUMA nodes may be present in the RM's topology. Initialize the bit sets here so all + // operations work as expected. + m_numaInformation[index].m_nodeMask.Grow(m_nodeCount); + m_numaInformation[index].m_resourceMask.Grow(procCount); + } + + ITopologyNode *pCurNode = m_pResourceManager->GetFirstNode(); + while (pCurNode != NULL) + { + QuickBitSet nodeMask(procCount); + unsigned int nodeId = pCurNode->GetId(); + + DWORD numaNodeNumber = pCurNode->GetNumaNode(); + m_numaInformation[numaNodeNumber].m_nodeMask.Set(nodeId); + + unsigned int ridBase = ridCounter; + + ITopologyExecutionResource *pFirstResource = pCurNode->GetFirstExecutionResource(); + ITopologyExecutionResource *pCurResource = pFirstResource; + while (pCurResource != NULL) + { + // + // The resource ID is arbitrary from the resource manager. Assign a position in the bitmask for the resource ID and place + // that in a hash table for quick lookups and masking with affinity. + // + unsigned int resourceId = pCurResource->GetId(); + m_resourceNodeMap.Insert(resourceId, nodeId); + m_resourceBitMap.Insert(resourceId, ridCounter); + nodeMask.Set(ridCounter); + m_numaInformation[numaNodeNumber].m_resourceMask.Set(ridCounter); + ++ridCounter; + + pCurResource = pCurResource->GetNext(); + } + + SchedulingRing *pRing = _concrt_new SchedulingRing(this, nodeId); + SchedulingNode *pNode = _concrt_new SchedulingNode(nodeMask, numaNodeNumber, pRing); + pRing->SetOwningNode(pNode); + + pCurResource = pFirstResource; + while (pCurResource != NULL) + { + pNode->NotifyResource(pCurResource->GetId(), ridBase++); + pCurResource = pCurResource->GetNext(); + } + + m_rings[nodeId] = pRing; + m_nodes[nodeId] = pNode; + + pCurNode = pCurNode->GetNext(); + } + + ASSERT(ridCounter <= ::Concurrency::GetProcessorCount()); + + m_idleSearch.Grow(ridCounter); + m_nonAffineResourceListeners.Grow(ridCounter); + m_affinityMessages.Grow(ridCounter); + m_activeSet.Grow(ridCounter); + + m_pCoreAffinityQuickCache = _concrt_new ScheduleGroupSegmentBase* [static_cast(ridCounter) << QUICKCACHEPAD_SHIFT]; + for (unsigned int i = 0; i < ridCounter << QUICKCACHEPAD_SHIFT; ++i) + m_pCoreAffinityQuickCache[i] = 0; + + // The RequestInitialVirtualProcessors API will invoke a scheduler callback to add new virtual processors to + // the scheduler during the course of the API call. If this API succeeds, we can assume that scheduling + // nodes have been populated with virtual processors representing resources allocated by the RM based on + // values specified in the scheduler's policy. + m_pSchedulerProxy = m_pResourceManager->RegisterScheduler(GetIScheduler(), CONCRT_RM_VERSION_1); + m_pSchedulerProxy->RequestInitialVirtualProcessors(false); + + m_nextSchedulingRingIndex = GetValidSchedulingRingIndex(0); + + m_hSchedulerShutdownSync = CreateSemaphoreExW(NULL, 0, 0x7FFFFFFF, NULL, 0, SEMAPHORE_ALL_ACCESS); + + if (m_hSchedulerShutdownSync == NULL) + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); // the RM process should probably die here + + InitializeSchedulerEventHandlers(); + + TraceSchedulerEvent(CONCRT_EVENT_START, TRACE_LEVEL_INFORMATION, m_id); + } + + /// + /// Create a context from the default scheduler (possibly create the default too). + /// + ContextBase* SchedulerBase::CreateContextFromDefaultScheduler() + { + // If the context TLS value is NULL, the current thread is not attached to a scheduler. Find the + // default scheduler and attach to it. + + SchedulerBase* pDefaultScheduler = GetDefaultScheduler(); + // Creating an external context on the current thread attaches the scheduler. + ContextBase *pContext = pDefaultScheduler->AttachExternalContext(false); + + ASSERT((ContextBase*) platform::__TlsGetValue(t_dwContextIndex) == pContext); + + // GetDefaultScheduler takes a reference which is safe to release after the attach. + pDefaultScheduler->Release(); + + return pContext; + } + + /// + /// Returns the ConcRT context attached to the current OS execution context. If one does not exist NULL is returned + /// + ContextBase *SchedulerBase::SafeFastCurrentContext() + { + return IsOneShotInitialized() ? (ContextBase*) platform::__TlsGetValue(t_dwContextIndex) : NULL; + } + + /// + /// Returns the ConcRT context attached to the current OS execution context. If one does not exist NULL is returned + /// This is only callable if you know a-priori that all statics have been initialized. + /// + ContextBase *SchedulerBase::FastCurrentContext() + { + CONCRT_COREASSERT(IsOneShotInitialized()); + return (ContextBase*) platform::__TlsGetValue(t_dwContextIndex); + } + + /// + /// Returns a pointer to the ConcRT scheduler attached to the current thread. If one does not exist, it creates + /// a context and attaches it to the default scheduler. + /// + SchedulerBase* SchedulerBase::CurrentScheduler() + { + return CurrentContext()->GetScheduler(); + } + + /// + /// Returns a pointer to the current scheduler, if the current thread is attached to a ConcRT scheduler, null otherwise. + /// This is only callable if you know a-priori that all statics have been initialized. + /// + SchedulerBase *SchedulerBase::FastCurrentScheduler() + { + ContextBase * pContext = FastCurrentContext(); + return (pContext != NULL) ? pContext->GetScheduler() : NULL; + } + + /// + /// Returns a pointer to the current scheduler, if the current thread is attached to a ConcRT scheduler, null otherwise. + /// + SchedulerBase *SchedulerBase::SafeFastCurrentScheduler() + { + ContextBase * pContext = SafeFastCurrentContext(); + return (pContext != NULL) ? pContext->GetScheduler() : NULL; + } + + /// + /// Returns a pointer to the default scheduler. Creates one if it doesn't exist and tries to make it the default. + /// NOTE: The API takes an reference on the scheduler which must be released by the caller appropriately. + /// + SchedulerBase *SchedulerBase::GetDefaultScheduler() + { + // Acquire the lock in order to take a safe reference on the default scheduler. + _StaticLock::_Scoped_lock _lock(s_defaultSchedulerLock); + + // If the default scheduler is non-null, try to reference it safely. If the reference fails, + // we've encountered a scheduler that is in the middle of finalization => the thread finalizing + // the scheduler will attempt to clear the value under write mode. + if ((s_pDefaultScheduler == NULL) || !s_pDefaultScheduler->SafeReference()) + { + SchedulerPolicy policy(0); + + // Note that the default scheduler policy is protected by the default scheduler lock. + SchedulerPolicy * pDefaultPolicy = s_pDefaultSchedulerPolicy; + if (pDefaultPolicy != NULL) + { + policy = *pDefaultPolicy; + } + + // Either the default scheduler was null, or we found a scheduler that was in the middle of being finalized. + // Create a scheduler and set it as the default. + s_pDefaultScheduler = SchedulerBase::CreateWithoutInitializing(policy); + + // Obtain hardware threads, initialize virtual processors, etc. + s_pDefaultScheduler->Initialize(); + + // Create returns a scheduler with a reference count of 0. We need to reference the scheduler before releasing the lock. + // to prevent a different thread from assuming this scheduler is shutting down because the ref count is 0. + // The caller is responsible for decrementing it after attaching to the scheduler. + s_pDefaultScheduler->Reference(); + } + + // We're holding on to a reference, so it is safe to return this scheduler. + ASSERT(s_pDefaultScheduler != NULL); + return s_pDefaultScheduler; + } + + /// + /// Allows a user defined policy to be used to create the default scheduler. It is only valid to call this API when no default + /// scheduler exists, unless the parameter is NULL. Once a default policy is set, it remains in effect until the next valid call + /// to the API. + /// + /// + /// [in] A pointer to the policy to be set as the default. The runtime will make a copy of the policy + /// for its use, and the user is responsible for the lifetime of the policy that is passed in. An argument of NULL will reset + /// the default scheduler policy, and the next time a default scheduler is created, it will use the runtime's default policy settings. + /// + void SchedulerBase::SetDefaultSchedulerPolicy(_In_ const SchedulerPolicy & _Policy) + { + _Policy._ValidateConcRTPolicy(); + + bool fSetDefault = false; + + if (s_pDefaultScheduler == NULL) + { + // We can only set a non-null default policy if the default scheduler does not exist. + + _StaticLock::_Scoped_lock _lock(s_defaultSchedulerLock); + + // It's possible the default scheduler exists but is on its way out, i.e. its ref count is 0, and a different thread is about + // acquire the write lock and set the value to null. We ignore this case, and allow the API to fail. + if (s_pDefaultScheduler == NULL) + { + delete s_pDefaultSchedulerPolicy; + s_pDefaultSchedulerPolicy = _concrt_new SchedulerPolicy(_Policy); + fSetDefault = true; + } + } + + if (!fSetDefault) + { + throw default_scheduler_exists(); + } + } + + /// + /// Resets the default scheduler policy, and the next time a default scheduler is created, it will use the runtime's default policy settings. + /// + void SchedulerBase::ResetDefaultSchedulerPolicy() + { + _StaticLock::_Scoped_lock _lock(s_defaultSchedulerLock); + + if (s_pDefaultSchedulerPolicy != NULL) + { + delete s_pDefaultSchedulerPolicy; + s_pDefaultSchedulerPolicy = NULL; + } + } + + /// + /// Increments the reference count to the scheduler but does not allow a 0 to 1 transition. This API should + /// be used to safely access a scheduler when the scheduler is not 'owned' by the caller. + /// + /// + /// True if the scheduler was referenced, false, if the reference count was 0. + /// + bool SchedulerBase::SafeReference() + { + return SafeInterlockedIncrement(&m_refCount); + } + + /// + /// Start up a virtual processor in the scheduler, if one is found. The virtual processor must have the specified availability + /// characteristics. + /// + bool SchedulerBase::StartupVirtualProcessor(ScheduleGroupSegmentBase *pSegment, + location bias, + ULONG type) + { + // + // We **MUST** be in a hyper-critical region during this period. There is an interesting scenario on UMS that makes this so: + // + // - [VP A] can't find work and is in its search for work loop + // - [VP A] makes itself available + // - [VP B] running context alpha adds a new work item and does a StartupIdleVirtualProcessor + // - [VP B] does a FindAvailableVirtualProcessor and claims VP A + // - [VP B] page faults / blocks + // - [VP A] finds context alpha in its final SFW pass + // - [VP A] tries to claim ownership of its virtual processor + // - [VP A] can't claim exclusive ownership because context alpha already did + // - [VP A] calls deactivate to wait for the corresponding activation. + // - [VP A] deadlocks with context alpha. Since it is about to execute alpha, no one else can grab it. Similarly, + // it's waiting on an activate which will only come from context alpha. + // + // Since this code runs on the primary anyway during completion list moves, hyper-crit should be safe. This does mean that + // this code must be extraordinarily careful about what it calls / does. There can be NO MEMORY ALLOCATION or other arbitrary + // Win32 calls in the UMS variant of this path. + // + bool foundVProc = false; + ContextBase::StaticEnterHyperCriticalRegion(); + + // + // The callers of this API MUST check that that the available virtual processor count in the scheduler + // is non-zero before calling the API. We avoid putting that check here since it would evaluate to false + // most of the time, and it saves the function call overhead on fast paths (chore push) + // + VirtualProcessor::ClaimTicket ticket; + if (FoundAvailableVirtualProcessor(ticket, bias, type)) + { + ticket.Exercise(pSegment); + foundVProc = true; + } + + ContextBase::StaticExitHyperCriticalRegion(); + return foundVProc; + } + + /// + /// Looks for an available virtual processor in the scheduler, and returns it. + /// + bool SchedulerBase::FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket, + location bias, + ULONG type) + { + // Direct or indirect callers of this API MUST check that that the available virtual processor count in the scheduler + // is non-zero before calling the API. We avoid putting that check here since it would evaluate to false + // most of the time, and it saves the function call overhead on fast paths (chore push) + + // + // Bias first towards the given virtual processor, secondly to its node, and thirdly to everyone else in order. + // + switch(bias._GetType()) + { + case location::_NumaNode: + { + NumaInformation *pNumaInfo = m_numaInformation + bias._GetId(); + for (int i = 0; i < m_nodeCount; ++i) + { + if (pNumaInfo->m_nodeMask.IsSet((unsigned int)i)) + { + if (m_nodes[i]->FoundAvailableVirtualProcessor(ticket, bias, type)) + return true; + } + } + + break; + } + case location::_SchedulingNode: + case location::_ExecutionResource: + { + SchedulingNode *pBiasNode = FindNodeByLocation(&bias); + if (pBiasNode && pBiasNode->FoundAvailableVirtualProcessor(ticket, bias, type)) + return true; + + break; + } + + default: + break; + } + + for (int idx = 0; idx < m_nodeCount; ++idx) + { + SchedulingNode *pNode = m_nodes[idx]; + if (pNode != NULL) + { + // Perform a quick check of the processor count to avoid the function call overhead + // on some fast paths (chore push operations) on a system with many nodes. + if (pNode->HasVirtualProcessorAvailable()) + { + if (pNode->FoundAvailableVirtualProcessor(ticket, location(), type)) + return true; + } + } + } + + return false; + + } + + /// + /// Attempts to push a runnable to an inactive virtual processor. If successful, true is returned. + /// + bool SchedulerBase::PushRunnableToInactive(InternalContextBase *pRunnableContext, location bias) + { + bool fPushed = false; + + // + // Affinitization requires a spin wait on the blocked flag. We cannot push ourselves to another virtual processor for startup! + // + if (SchedulerBase::FastCurrentContext() != pRunnableContext) + { + ContextBase::StaticEnterHyperCriticalRegion(); + + // + // The callers of this API MUST check that that the available virtual processor count in the scheduler + // is non-zero before calling the API. We avoid putting that check here since it would evaluate to false + // most of the time, and it saves the function call overhead on fast paths (chore push) + // + VirtualProcessor::ClaimTicket ticket; + if (FoundAvailableVirtualProcessor(ticket, bias, VirtualProcessor::AvailabilityInactive | VirtualProcessor::AvailabilityInactivePendingThread)) + { + ticket.ExerciseWith(pRunnableContext); + fPushed = true; + } + + ContextBase::StaticExitHyperCriticalRegion(); + } + + return fPushed; + } + + /// + /// Steals a local runnable contexts from nodes in the scheduler other than the skip node provided. + /// + InternalContextBase *SchedulerBase::StealForeignLocalRunnableContext(SchedulingNode *pSkipNode) + { + ASSERT(pSkipNode != NULL); + + for (int i = 0; i < m_nodeCount; ++i) + { + if (m_nodes[i] != NULL && m_nodes[i] != pSkipNode) + { + ASSERT(m_nodes[i]->m_id == i); + InternalContextBase *pContext = m_nodes[i]->StealLocalRunnableContext(); + if (pContext != NULL) + return pContext; + } + } + + return NULL; + } + + /// + /// Determines how long in milliseconds until the next set of threads is allowed to be created. + /// + ULONG SchedulerBase::ThrottlingTime(ULONG stepWidth) + { + ULONG boundContextCount = GetNumberOfBoundContexts(); + if (boundContextCount < m_threadsBeforeThrottling) + return 0; + + ULONG overage = (boundContextCount - m_threadsBeforeThrottling); + + // + // We can instantly shoot up to m_threadsBeforeThrottling. For all below notes, K is the stair-step width. Note that we are + // hard limited to 8K threads on Win7 UMS currently. This should have hefty gradient to reach the thousands especially since this is per-scheduler + // and we can have multiple schedulers in the process! + // + // After that, the next 100 threads will take approximately (1) seconds to create. // 100 threads + // , the next 200 threads will take approximately (8) seconds to create. // 300 threads + // , the next 300 threads will take approximately (20) seconds to create. // 600 threads + // , the next 900 threads will take approximately (6.5) minutes to create. // 1.5K threads (2.5m: 600-1000) + // , the next 1000 threads will take approximately (20) minutes to create. // 2.5K threads + // , the next 1500 threads will take approximately (1.5) hours to create. // 4K threads + // , the next 4000 threads will take approximately (12) hours to create. // 8K threads + // , we run out of resources. Hopefully, we aren't repeatedly waiting on operations with multi-hour latency in a parallel loop. + // + ULONG delay = 0; + + if (overage < 100) + delay = 5 + (overage / 10); + else if (overage < 300) + delay = 15 + 0 + (overage / 8); + else if (overage < 600) + delay = 53 + 7 + (overage / 5); + else if (overage < 1500) + delay = 180 + 0 + (overage / 4); + else if (overage < 2500) + delay = 555 + 0 + (overage / 3); + else if (overage < 4000) + delay = 1388 + 1112 + (overage / 3); + else + delay = 3833 + 4367 + (overage / 2); + + return (delay * stepWidth); + } + + /// + /// Acquires a new internal context of the appropriate type and notifies the scheduler when it is available. The scheduler can + /// choose what to do with said internal context. This creation happens in a deferred manner subject to throttling constraints. + /// + void SchedulerBase::DeferredGetInternalContext() + { + OMTRACE(MTRACE_EVT_DEFERREDCONTEXT, this, NULL, NULL, NULL); + + // + // This routine must be UMS safe and must schedule the deferred task in a UMS safe way. + // + if (InterlockedIncrement(&m_pendingDeferredCreates) == 1) + { + // Directly invoke the throttle dispatch + SchedulerBase::ThrottlerTrampoline(this, true); + } + } + + /// + /// Changes the due time for dispatching new threads + /// + void SchedulerBase::ChangeThrottlingTimer(ULONG dueTime) + { + FILETIME time = {0}; + // Convert 100 ns unit into 1 ms unit. + // Negative here means FILETIME is a time span (instead of time point). + reinterpret_cast(time) = -static_cast(dueTime) * 10000; + + SetThreadpoolTimer(static_cast(m_hThrottlingTimer), &time, PSEUDOINFINITE, 0); + } + + /// + /// Acts as a trampoline between the event wait and the timer wait as we cannot queue the timer in DeferredGetInternalContext + /// due to limitations on what Win32 APIs can be called from a UMS primary. + /// + void SchedulerBase::ThrottlerTrampoline(PVOID pData, BOOLEAN) + { + SchedulerBase *pScheduler = reinterpret_cast(pData); + + ULONG delay = pScheduler->ThrottlingTime(1); + ULONG delta = pScheduler->ThrottlingDelta(); + + // + // If we don't need a timer (or we decide that the due time is too "soon"), just invoke the dispatcher. Otherwise, reschedule it for + // a later time. Minimize the number of background threads we're utilizing here. + // + if (delta < delay) + { + OMTRACE(MTRACE_EVT_SCHEDULEDTHROTTLER, pScheduler, SchedulerBase::FastCurrentContext(), NULL, delay - delta); + + pScheduler->ChangeThrottlingTimer(delay-delta); + } + else + pScheduler->ThrottlerDispatch(); + } + + /// + /// Creates new contexts. + /// + void SchedulerBase::ThrottlerDispatch() + { + OMTRACE(MTRACE_EVT_THROTTLERDISPATCH, this, NULL, NULL, platform::__GetTickCount64()); + + // + // The throttler will be spuriously awakened at 49-day intervals due to a timer limitation on pre-Vista operating systems. Just ignore + // the spurious awakening in these cases. + // + if (m_pendingDeferredCreates > 0) + { + bool fAwokeVProc = false; + bool fFailedThreadCreate = false; + bool fReschedule = false; + + + // + // It is entirely possible that m_pendingDeferredCreates is a number much larger than is strictly speaking necessary. A context + // may go through SFW, require a thread, block, get awoken because of a context, switch to it, block, go through SFW, and require + // a thread again all in between two throttling ticks. + // + for(;;) + { + InternalContextBase *pContext = GetInternalContext(false); + if (pContext == NULL) + { + fFailedThreadCreate = true; + break; + } + + OMTRACE(MTRACE_EVT_CREATEDTHROTTLEDCONTEXT, this, pContext, NULL, platform::__GetTickCount64()); + + fAwokeVProc |= NotifyThrottledContext(pContext); + + if (!HasVirtualProcessorPendingThreadCreate() || ThrottlingTime(1) > 0) + { + break; + } + } + + // + // The timer should be rescheduled under the following circumstances only: + // - If we are not in scheduler shutdown and either there are still virtual processors in need of threads *OR* our observation of pending + // requests changed. + // - If we are in scheduler shutdown, were unable to create a new thread and all available virtual processors are pending threads (i.e, we + // are unable to wake up an idle virtual processor). + // + + if (!m_fSweepWithoutActualWork && (fFailedThreadCreate || HasVirtualProcessorPendingThreadCreate())) + { + fReschedule = true; + InterlockedExchange(&m_pendingDeferredCreates, 1); + } + else + { + LONG pendingDeferredCreates = m_pendingDeferredCreates; + ASSERT(m_pendingDeferredCreates >= pendingDeferredCreates); + fReschedule = InterlockedExchangeAdd(&m_pendingDeferredCreates, -pendingDeferredCreates) != pendingDeferredCreates; + + if (!fReschedule && m_fSweepWithoutActualWork && !fAwokeVProc) + { + // + // At least one vproc needs to be activated since pending requests blocks scheduler shutdown. Activate a vproc after + // clearing the pending request count to restart scheduler shutdown. If such a vproc cannot be found because all virtual processors + // are pending thread create, we need to reschedule the timer. + // + fAwokeVProc = StartupIdleVirtualProcessor(GetAnonymousScheduleGroupSegment()); + if (!fAwokeVProc) + { + fReschedule = true; + InterlockedExchange(&m_pendingDeferredCreates, 1); + } + } + } + + if (fReschedule) + { + ASSERT(m_pendingDeferredCreates > 0); + + // + // There is absolutely no reason to trampoline here. We are within an arbitrary thread context and not a primary. Just reset + // the timer. + // + ULONG delay = ThrottlingTime(1); + ULONG delta = ThrottlingDelta(); + + delay = (delta < delay) ? delay - delta : 0; + OMTRACE(MTRACE_EVT_SCHEDULEDTHROTTLER, this, NULL, NULL, delay); + + // + // If for some reason, the throttler could not get a thread (we hit the system-wide cap on threads) and the failure wasn't due to + // some other exception, we push back throttling so that nothing will get tried again for at least another 500 mS) + // + if (fFailedThreadCreate && delay < 500) + delay = 500; + ChangeThrottlingTimer(delay); + } + } + } + + /// + /// Called to notify the scheduler that a context is available from the throttling manager / background creation. + /// + bool SchedulerBase::NotifyThrottledContext(InternalContextBase *pContext) + { + VirtualProcessor::ClaimTicket ticket; + + if (FoundAvailableVirtualProcessor(ticket, + location(), + VirtualProcessor::AvailabilityInactivePendingThread | VirtualProcessor::AvailabilityIdlePendingThread)) + { + OMTRACE(MTRACE_EVT_NOTIFYTHROTTLEDCONTEXT, this, pContext, NULL, TRUE); + + if (!ticket.ExerciseWakesExisting()) + ticket.ExerciseWith(pContext); + else + { + m_reservedContexts.Push(pContext); + ticket.Exercise(); + } + + return true; + } + else + { + OMTRACE(MTRACE_EVT_NOTIFYTHROTTLEDCONTEXT, this, pContext, NULL, FALSE); + m_reservedContexts.Push(pContext); + } + + return false; + } + + /// + /// Acquires a new internal context of the appropriate type and returns it. This can come from either + /// a free list within the scheduler, or be one newly allocated from the heap. This method may return NULL if the thread cannot be + /// created due to a resource limitation. + /// + /// + /// An indication as to whether the creation should be throttled. + /// + InternalContextBase *SchedulerBase::GetInternalContext(bool fThrottled) + { + OMTRACE(MTRACE_EVT_GETINTERNALCONTEXT, this, SchedulerBase::FastCurrentContext(), NULL, m_boundContextCount); + + // + // For some schedulers, the reserved context pool is just a list of unused contexts that are pooled due to races. For others (e.g.: UMS), + // it is a pool of contexts to be used in certain circumstances (e.g.: where contexts can't be created) and shouldn't be pulled from for + // general fetch. + // + if (fThrottled && AllowGeneralFetchOfReservedContexts()) + { + InternalContextBase *pContext = GetReservedContext(); + if (pContext != NULL) + return pContext; + } + + // + // m_internalContextPool contains unbound contexts. The act of binding a context is what, in particular, needs to be throttled. + // + if (fThrottled) + { + ULONG delay = ThrottlingTime(1); + if (delay > 0) + { + if (ThrottlingDelta() < delay) + { + // + // The caller is responsible for notifying the background thread. After all -- there may be other runnable contexts + // that can be switched to before notification that we absolutely need a thread created at the point of throttling. + // + return NULL; + } + + // + // It has been sufficiently long since the last thread creation. Let this one go through here. Yes, it is possible that + // the background thread decides this at the same time and both create a thread without the exact throttling ramp. Since + // this is largely heuristic, it doesn't matter. + // + fThrottled = false; + } + } + + // + // *** READ THIS ***: + // + // The increment of m_boundContextCount (which is what the throttler uses to make a determination of whether/how much to throttle) + // must happen between the point of throttling decision and ** ANY LOCK ACQUISITION ** in the below code. Otherwise, on the UMS scheduler, + // N threads may come in here, decide not to throttle, block, switch to another N threads which also decide not to throttle since the count is not + // incremented yet and block on the same lock. + // + // This can lead to a side-stepping of the throttler and exponential thread growth. + // + // Note: If we ever delay bind contexts, this needs to change. + // + InterlockedIncrement(&m_boundContextCount); + + if (!fThrottled) + { + // + // This is unprotected and unfenced. It is entirely possible this thread and the background thread compete and both set + // this. Throttling does not need to be exact. + // + StampThrottledCreate(); + } + + // + // Thread creation failure due to the CreateThread* call failing is not considered to be a fatal exception. Any other + // resource failure (e.g.: out of memory) is still considered fatal to the runtime. + // + InternalContextBase *pContext = pContext = m_internalContextPool.Pop(); + + if (pContext == NULL) + { + pContext = CreateInternalContext(); + AddContext(pContext); + + + // The internal reference count on the scheduler *must* be incremented by the creator of the context. + // The reference count will be released when the context is canceled. If the context is executing on + // a thread proxy at the time it is canceled, it will decrement its own reference count before + // leaving the dispatch loop for the final time. If it is on the idle pool - the thread/context + // that cancels it is responsible for decrementing the reference count. + IncrementInternalContextCount(); + } + + // + // IMPORTANT NOTE: It is possible that there is a thread proxy still in the process of executing this + // context's dispatch loop. This is because on going idle, contexts add themselves to the idle pool, + // and proceed to leave their dispatch loops - they could be picked up and re-initialized before they + // have actually left the routine. + // + // We must be careful *not* to re-initialize any variables the context uses after the point at which it + // adds itself to the idle list, until the time it has left the dispatch routine. + // + CONCRT_COREASSERT(pContext != NULL); + + // + // Note also that there are other fields which need to be touched until m_blockedState is set. When we reuse a context, we must spin until + // that bit is set. Newly created contexts are started blocked. + // + pContext->SpinUntilBlocked(); + + // Context shall be marked as idle. + CONCRT_COREASSERT(pContext->IsIdle()); + + // Bind a thread proxy to the context + pContext->m_pThreadProxy = NULL; + + try + { + // NOTE: This is one of the places in the core scheduler where we catch an internal exception. This means that + // the code from this point down, including code in the Resource Manager layer must be exception safe wrt the + // scheduler_worker_creation_error exception being thrown. + GetSchedulerProxy()->BindContext(pContext); + } + catch (const scheduler_worker_creation_error&) + { + ReleaseInternalContext(pContext); + pContext = NULL; + } + //__faststorefence(); + + if (pContext != NULL) + { + + CMTRACE(MTRACE_EVT_CONTEXT_ACQUIRED, pContext, NULL, NULL); + +#if defined(_DEBUG) + pContext->NotifyAcquired(); +#endif // _DEBUG + + pContext->ClearCriticalRegion(); + + } + + return pContext; + } + + /// + /// Enqueues a context into m_allContexts + /// + void SchedulerBase::AddContext(InternalContextBase * pContext) + { + ContextNode *pNode = _concrt_new ContextNode(pContext); + m_allContexts.Push(pNode); + } + + /// + /// Releases an internal context of the appropriate to the scheduler's idle pool. + /// + void SchedulerBase::ReleaseInternalContext(InternalContextBase *pContext, bool fUnbind) + { + if (fUnbind) + m_pSchedulerProxy->UnbindContext(pContext); + +#if defined(_DEBUG) + pContext->m_fEverRecycled = true; + pContext->SetDebugBits(CTX_DEBUGBIT_RELEASED); +#endif // _DEBUG + + InterlockedDecrement(&m_boundContextCount); + + // Context shall be marked as idle. + CONCRT_COREASSERT(fUnbind || pContext->IsIdle()); + + // We keep all contexts created by the scheduler. Deleting/canceling these contexts would required us to + // remove it from the list of 'all contexts' (m_allContexts), which we use during finalization to detect + // blocked contexts, and would require an additional level of synchronization there. Since idle contexts + // do not have backing thread proxies, this is not a problem. + m_internalContextPool.Push(pContext); + } + + /// + /// Gets a realized chore from the idle pool, creating a new one if the idle pool is empty. + /// + RealizedChore * SchedulerBase::GetRealizedChore(TaskProc pFunction, void * pParameters) + { + RealizedChore * pChore = m_realizedChorePool.Pop(); + + if (pChore == NULL) + { + pChore = _concrt_new RealizedChore(pFunction, pParameters); + } + else + { + pChore->Initialize(pFunction, pParameters); + } + return pChore; + } + + /// + /// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full. + /// + void SchedulerBase::ReleaseRealizedChore(RealizedChore * pChore) + { + // Try to maintain the max size of the free pool somewhere close to num vprocs * 32. It is + // not an exact upper limit. + if (m_realizedChorePool.Count() < (m_virtualProcessorCount << 5)) + { + m_realizedChorePool.Push(pChore); + } + else + { + delete pChore; + } + } + + /// + /// Returns a copy of the policy this scheduler is using. No error state. + /// + SchedulerPolicy SchedulerBase::GetPolicy() const + { + return m_policy; + } + + /// + /// Increments a reference count to this scheduler to manage lifetimes over composition. + /// This reference count is known as the scheduler reference count. + /// + /// + /// The resulting reference count is returned. No error state. + /// + unsigned int SchedulerBase::Reference() + { + ASSERT(m_internalContextCountPlusOne > 0); + LONG val = InterlockedIncrement(&m_refCount); + if (val == 1) + { + // + // This could be an initial reference upon the scheduler from a creation path or it could be + // the case that an unblocked context from a scheduler decided to attach the scheduler somewhere. + // In the second case, we need to resurrect the scheduler and halt the shutdown attempt. + // + if (m_initialReference > 0) + { + // + // This should only come from an **INTERNAL** context on this scheduler; otherwise, the client is + // being very bad and racing with shutdown for a nice big crash. + // + ContextBase* pCurrentContext = SchedulerBase::FastCurrentContext(); + + if ((pCurrentContext == NULL ) || (pCurrentContext->IsExternal()) || (pCurrentContext->GetScheduler() != this)) + { + throw improper_scheduler_reference(); + } + + Resurrect(); + } + else + { + InterlockedExchange(&m_initialReference, 1); + } + + } + return (unsigned int)val; + } + + /// + /// Decrements this scheduler's reference count to manage lifetimes over composition. + /// A scheduler starts the shutdown protocol when the scheduler reference count goes to zero. + /// + unsigned int SchedulerBase::Release() + { + LONG val = InterlockedDecrement(&m_refCount); + if (val == 0) + { + PhaseOneShutdown(); + } + + return (unsigned int)val; + } + + /// + /// Causes the OS event object 'eventObject' to be set when the scheduler shuts down and destroys itself. + /// + /// + /// [in] A valid event object. + /// + void SchedulerBase::RegisterShutdownEvent(_In_ HANDLE eventObject) + { + if (eventObject == NULL || eventObject == INVALID_HANDLE_VALUE) + { + throw std::invalid_argument("eventObject"); + } + + HANDLE hEvent = NULL; + + if (!DuplicateHandle(GetCurrentProcess(), + eventObject, + GetCurrentProcess(), + &hEvent, + 0, + FALSE, + DUPLICATE_SAME_ACCESS)) + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + else + { + WaitNode *pNode = _concrt_new WaitNode; + pNode->m_hEvent = hEvent; + m_finalEvents.AddTail(pNode); + } + } + + /// + /// Attaches this scheduler to the calling thread. Implicitly calls Reference. After this function is called, + /// the calling thread is then managed by the scheduler and the scheduler becomes the current scheduler. + /// + void SchedulerBase::Attach() + { + const SchedulerBase* pCurrentScheduler = FastCurrentScheduler(); + + // A context is not allowed to re-attach to its current scheduler. + if (pCurrentScheduler == this) + throw improper_scheduler_attach(); + + // Attaching to the scheduler involves incrementing reference counts on the scheduler and creating a context data structure + // corresponding to the new scheduler for the current thread. + ASSERT(m_internalContextCountPlusOne > 0); + + // External context creation will reference the scheduler, create the context data structure and store the context and + // scheduler values in TLS. + AttachExternalContext(true); + + TraceSchedulerEvent(CONCRT_EVENT_ATTACH, TRACE_LEVEL_INFORMATION, m_id); + } + + /// + /// Detaches the current scheduler from the calling thread and restores the previously attached scheduler as the + /// current scheduler. Implicitly calls Release(). After this function is called, the calling thread is then managed + /// by the scheduler that was previously activated via Create() or Attach(). + /// + void SchedulerBase::Detach() + { + ContextBase* pContext = SchedulerBase::FastCurrentContext(); + + ASSERT(pContext != NULL); + if (!pContext->IsExternal()) + { + throw improper_scheduler_detach(); + } + + ExternalContextBase* pExternalContext = static_cast(pContext); + + if (!pExternalContext->WasExplicitlyAttached()) + { + // Only contexts that attached explicitly either via the attach api, or the current scheduler creation api + // are allowed to detach. + + throw improper_scheduler_detach(); + } + + unsigned int schedulerId = m_id; + + // External context detachment will release references on the scheduler, and remove the context from TLS on explicit detaches. + DetachExternalContext(pExternalContext, true); + + // It is *UNSAFE* to touch 'this', after the DetachExternalContext call, since the caller does not have a reference on the + // scheduler and it could get deleted in the meantime. + TraceSchedulerEvent(CONCRT_EVENT_DETACH, TRACE_LEVEL_INFORMATION, schedulerId); + } + + /// + /// Creates an external context and attaches it to the calling thread. Called when a thread attaches to a scheduler. + /// + ExternalContextBase * SchedulerBase::AttachExternalContext(bool explicitAttach) + { + ContextBase * pCurrentContext = SchedulerBase::FastCurrentContext(); + + if (pCurrentContext != NULL) + { + ASSERT(explicitAttach); + + if (pCurrentContext->m_pScheduler == this) + { + // A context is not allowed to re-attach to its own scheduler. + throw improper_scheduler_attach(); + } + // Check if this is an internal context. If so, it is presumably consuming a virtual processor + // on a different scheduler (the parent scheduler). Since a new ConcRT context will be + // associated with the OS context during this API, the parent scheduler should get its virtual processor back. + if (!pCurrentContext->IsExternal()) + { + // + // If the underlying previous context was a UMS thread, the LeaveScheduler call will result in a + // SwitchTo(..., Nesting) to the RM which will immediately transmogrify the UMS thread into a "virtual"-thread. + // From the perspective of the scheduler, it will behave identically to a thread. There's more overhead in this, + // but the functionality is identical. + // + static_cast(pCurrentContext)->LeaveScheduler(); + } + // We also clear out the context/scheduler TLS values here. Since we've saved the current context, + // we remember it as the parent context of the new context we're about to create. The reason for + // clearing TLS, is that if code that executes between this point and the point at which the new + // TLS values are setup, relies on the current context in TLS, it might behave non-deterministically. + // e.g. Creating an external context looks at the anonymous schedule group - since the current + // context is an internal context on the previous scheduler, we don't get what we expect.. + pCurrentContext->ClearContextTls(); + } + // Take reference counts on the scheduler. + ReferenceForAttach(); + + ExternalContextBase * pContext = GetExternalContext(explicitAttach); + + // Save the new context into the TLS slot reserved for the same. + pContext->PushContextToTls(pCurrentContext); + + // The thread continues to run. It does not need to wait to be scheduled on a virtual processor. + return pContext; + } + + /// + /// Detaches an external context from the scheduler. On implicit detach we assume + /// that this routine (and any function it calls) is short and non-blocking. See + /// ExternalContextBase::ImplicitDetachHandler for details + /// + /// + /// The external context being detached. + /// + /// + /// Whether this was the result of an explicit detach or the thread exiting. + /// + void SchedulerBase::DetachExternalContext(ExternalContextBase * pContext, bool explicitDetach) + { + // External context destruction will remove the values from TLS and cleanup the context data structure + ContextBase * pParentContext = NULL; + + if (explicitDetach) + pParentContext = pContext->PopContextFromTls(); + + ReleaseExternalContext(pContext); + + // Release reference counts on the scheduler. + ReleaseForDetach(); + + // The this pointer is *cannot be dereferenced* after the Release call. + + if ((pParentContext != NULL) && (!pParentContext->IsExternal())) + { + ASSERT(explicitDetach); + // An internal parent context must be rescheduled on its scheduler. + static_cast(pParentContext)->RejoinScheduler(); + } + } + + /// + /// Gets an external context from the idle pool, creating a new one if the idle pool is empty + /// + ExternalContextBase * SchedulerBase::GetExternalContext(bool explicitAttach) + { + ExternalContextBase * pContext = m_externalContextPool.Pop(); + + if (pContext == NULL) + { + pContext = _concrt_new ExternalContextBase(this, explicitAttach); + } + else + { + pContext->PrepareForUse(explicitAttach); + } + return pContext; + } + + /// + /// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full. + /// + void SchedulerBase::ReleaseExternalContext(ExternalContextBase * pContext) + { + // Try to maintain the max size of the free pool somewhere close to m_virtualProcessorCount. It is + // not an exact upper limit. + if (m_externalContextPool.Count() < m_virtualProcessorCount) + { + pContext->RemoveFromUse(); + m_externalContextPool.Push(pContext); + } + else + { + _InternalDeleteHelper(pContext); + } + } + + /// + /// References a segment in the anonymous schedule group and returns a pointer to it. The segment returned will be close to the specified + /// source location. + /// + /// + /// The returned segment will be close to this location. + /// + /// + /// A segment in the anonymous schedule group located close to srcLocation. + /// + ScheduleGroupSegmentBase *SchedulerBase::GetAnonymousScheduleGroupSegment() + { + return GetNextSchedulingRing()->GetAnonymousScheduleGroupSegment(); + } + + /// + /// Create a schedule group within this scheduler. + /// + /// + /// A pointer to a location where tasks within the schedule group will be biased towards executing at. + /// + /// + /// A reference to a new ScheduleGroup. + /// + ScheduleGroup* SchedulerBase::InternalCreateScheduleGroup(location* pPlacement) + { + ScheduleGroupBase *pGroup = m_scheduleGroups.PullFromFreePool(); + if (m_schedulingProtocol == ::Concurrency::EnhanceScheduleGroupLocality) + { + if (pGroup == NULL) + { + pGroup = _concrt_new CacheLocalScheduleGroup(this, pPlacement); + } + else + { + pGroup->Initialize(pPlacement); + } + } + else + { + // + // Fair schedule groups completely ignore any hint of placement. We are directed to round robin through groups anyway! + // + location unbiased; + if (pGroup == NULL) + { + pGroup = _concrt_new FairScheduleGroup(this, &unbiased); + } + else + { + pGroup->Initialize(&unbiased); + } + } + m_scheduleGroups.Add(pGroup); + ASSERT(pGroup->m_refCount >= 0); + return pGroup; + } + + /// + /// Removes an unreferenced schedule group from the scheduler's list of groups. + /// + void SchedulerBase::RemoveScheduleGroup(ScheduleGroupBase *pGroup) + { + // + // Essentially m_refCount is the refcount of how many contexts reference this schedule group. + // m_refCount is incremented whenever a schedule group is associated with a context, decremented + // when a context is switched out to another context. When workstealing happens the context that + // steals from this schedule group increments m_refCount and decrements after it is done with this + // schedule group, whether by stealing from another or by switching out and going back on the + // freelist. When m_refCount hits 0, then the schedule group is taken out of m_scheduleGroups and hence + // is not searched for runnables or stolen chores. + // + ASSERT(pGroup != NULL && pGroup->m_refCount == 0); + + // It is still in the circular list, but other apis that are traversing the list will move over + // it, since it will not have any runnable contexts or chores to steal. + + m_scheduleGroups.Remove(pGroup); + } + + /// + /// Schedules a light-weight task within the scheduler. The light-weight task will be placed within a schedule group of + /// the runtime's choosing. + /// + /// + /// A pointer to the main function of a task. + /// + /// + /// A void pointer to the data that will be passed in to the task. + /// + void SchedulerBase::ScheduleTask(TaskProc proc, void *data) + { + ScheduleGroupBase *pGroup = NULL; + + // + // If we are currently executing in the context of a particular schedule group, the work should go there instead of in an anonymous schedule group. + // We should not easily create cross-group dependencies. + // + // Note that it is entirely possible that the current context is on a DIFFERENT scheduler (e.g.: we're scheduling work on scheduler 2 within a thread + // bound to scheduler 1). In this case, we do **NOT** want to look at the current group -- we just pick an **appropriate** anonymous group within + // scheduler 1. + // + ContextBase *pCurrentContext = FastCurrentContext(); + if (pCurrentContext != NULL && pCurrentContext->GetScheduler() == this) + { + pGroup = pCurrentContext->GetScheduleGroup(); + ASSERT(pGroup != NULL); + } + else + { + // + // This task does not have an associated schedule group, assign it to the anonymous + // schedule group for the scheduler + // + pGroup = GetAnonymousScheduleGroup(); + } + pGroup->ScheduleTask(proc, data); + } + + /// + /// Schedules a light-weight task within the scheduler. The light-weight task will be scheduled at the specified priority and placed within + /// a schedule group of the runtime's choosing. It will also be biased towards executing at the specified location. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// A reference to a location where the light-weight task will be biased towards executing at. + /// + void SchedulerBase::ScheduleTask(TaskProc proc, void * data, location& placement) + { + ScheduleGroupBase *pGroup = NULL; + + // + // If we are currently executing in the context of a particular schedule group, the work should go there instead of in an anonymous schedule group. + // We should not easily create cross-group dependencies. + // + // Note that it is entirely possible that the current context is on a DIFFERENT scheduler (e.g.: we're scheduling work on scheduler 2 within a thread + // bound to scheduler 1). In this case, we do **NOT** want to look at the current group -- we just pick an **appropriate** anonymous group within + // scheduler 1. + // + ContextBase *pCurrentContext = FastCurrentContext(); + if (pCurrentContext != NULL && pCurrentContext->GetScheduler() == this) + { + pGroup = pCurrentContext->GetScheduleGroup(); + ASSERT(pGroup != NULL); + } + else + { + // + // This task does not have an associated schedule group, assign it to the anonymous + // schedule group for the scheduler + // + pGroup = GetAnonymousScheduleGroup(); + } + pGroup->ScheduleTask(proc, data, placement); + } + + /// + /// Determines whether a given location is available on the scheduler. + /// + /// + /// A reference to the location to query the scheduler about. + /// + /// + /// An indication of whether or not the location specified by the argument is available on the scheduler. + /// + /// + /// Note that the return value is an instantaneous sampling of whether the given location is available. In the presence of multiple + /// schedulers, dynamic resource management may add or take away resources from schedulers at any point. Should this happen, the given + /// location may change availability. + /// + bool SchedulerBase::IsAvailableLocation(const location& _Placement) const + { + // @TODO: The const_cast shouldn't be here. We need to propagate const to more places (here & collections, etc...) + QuickBitSet set = const_cast(this)->GetBitSet(&_Placement); + return set.Intersects(m_activeSet); + } + + /// + /// Initialize event handlers or background threads + /// + void SchedulerBase::InitializeSchedulerEventHandlers() + { + // + // The utilization of the thread-pool for background throttling needs reference on the scheduler as an "event-handler". It will go away + // at the time event handlers are destroyed. + // + IncrementInternalContextCount(); + + } + + /// + /// Destroy event handlers or background threads + /// + void SchedulerBase::DestroySchedulerEventHandlers() + { + DeleteAsyncTimerAndUnloadLibrary(static_cast(m_hThrottlingTimer)); + + OMTRACE(MTRACE_EVT_EVENTHANDLERSDESTROYED, this, NULL, NULL, NULL); + + // + // The UnregisterWait and DeleteTimerQueueTimer should give us the guarantees we need to make this safe. + // + DecrementInternalContextCount(); + } + + // Finalization: + // + // The active vproc count and idle vproc count are encoded into the vproc shutdown gate, in addition to the SHUTDOWN and SUSPEND flags. + // + // SHUTDOWN_INITIATED_FLAG (0x80000000) + // | + // | + // | <----- 29 bit gate count ------> + // +---+---+---+------------------------------+ + // | i | g | c | encoded active/idle count | + // +---+---+---+------------------------------+ + // | | + // | | + // | SHUTDOWN_COMPLETED_FLAG (0x20000000) + // | + // SUSPEND_GATE_FLAG (0x40000000) + // + // The gate count is 29 bits that encodes both the active and idle vproc counts. NOTE: If we have more than half a billion vprocs, + // this needs to change. Somehow, I'm doubting that, but it's a hard limit of the way this gate functions. + // + // Once the SHUTDOWN_INITIATED bit on the shutdown gate is set (all external references to the scheduler are released), + // the scheduler proceeds into a 'sweep' phase iff all active virtual processors in the scheduler are idle (gate count is 0). The + // sweep suspends all virtual processors and looks for blocked contexts in the scheduler. If any are found, finalization is rolled + // back and virtual processors are unsuspended and allowed to proceed. In addition, virtual processor transitions from active to idle + // and active to inactive, that bring the gate count to 0, also trigger a sweep and can lead to finalization. + // + // A virtual processor notifies the scheduler that it is ACTIVE when it is started up by the scheduler in response to incoming work. + // From the ACTIVE state it could transition to IDLE and back to ACTIVE several times before either the scheduler shuts down or the + // in the individual virtual processor is asked to retire. At that point it moves from ACTIVE to INACTIVE. + // + // VirtualProcessorActive(true) VirtualProcessorIdle(true) + // | | + // | | + // ------------> -------------> + // INACTIVE ACTIVE IDLE + // <------------ <------------- + // | | + // | | + // VirtualProcessorActive(false) VirtualProcessorIdle(false) + // + // + // The figure below shows how a single virtual processor affects the gate count value(GC) as it changes state. + // + // + // VirtualProcessorActive(false) VirtualProcessorActive(true) + // | | + // | | + // <-------- ---------> + // GC-1 GC GC+1 + // <-------- ---------> + // | | + // | | + // VirtualProcessorIdle(true) VirtualProcessorIdle(false) + // + // Virtual processors should never be able to produce a gate count of -1 if they transition through valid states. + // Therefore the increment/decrement operations can be done simply using InterlockedIncrement/InterlockedDecrement + // without fear of underflowing the 29 bit count into the flag area. (This is all assuming there are not > 1/2 billion + // vprocs, of course). + // + // When the number of active vprocs is equal to the number of idle vprocs the gate count is 0. + + /// + /// Called to initiate shutdown of the scheduler. This may directly proceed to phase two of shutdown (actively + /// shutting down internal contexts) or it may wait for additional events (e.g.: all work to complete) before + /// proceeding to phase two. + /// +#pragma warning(push) +#pragma warning(disable: 4702) // unreachable code + void SchedulerBase::PhaseOneShutdown() + { + OMTRACE(MTRACE_EVT_PHASEONESHUTDOWN, this, NULL, NULL, NULL); + + // If this scheduler is the default scheduler, it should be cleared here, since we do not want any external contexts attaching + // to it via the CurrentScheduler interface. In the meantime, all calls to GetDefaultScheduler will perform a safe reference which + // will fail. + if (s_pDefaultScheduler == this) + { + _StaticLock::_Scoped_lock lockHolder(s_defaultSchedulerLock); + + if (s_pDefaultScheduler == this) + { + s_pDefaultScheduler = NULL; + } + } + + ASSERT(m_internalContextCountPlusOne >= 1); + + // Check if the internal reference count is greater than 1. This is an optimistic check - it could go down to 1 immediately + // after the check - this just means we will attempt to shutdown virtual processors even though there may be none left by the + // time we try. Note, that with our implementation today this will not happen, if virtual processors were started up previously, + // the contexts that executed on them retain their internal references on the scheduler, keeping m_internalContextCountPlusOne > 1, + // until a finalization sweep completes successfully. However, even if the implementation changes, this optimistic check, at worst, + // causes us to do slightly more work here. Could it increase after the check if we found it to be 1? Not without a bug + // in user code, and we're not hardening ourself against these. (The external facing reference count is 0 at this point, and we + // have the only reference to the scheduler.) + // + // The reason we don't decrement the value m_internalContextCountPlusOne, and check if the result is non-zero, to detect that + // there are contexts/virtual processors out there, is that the moment we do that, the scheduler could disappear out + // from under us. Consider the case where we decremented the internal count from 5 to 4, then proceeded to set the SHUTDOWN_INITIATED_FLAG + // bit, and noticed that the gate count was 0. Now there is nothing stopping a virtual processor from becoming active + // while the SHUTDOWN_INITIATED_FLAG bit is set. If it quickly became inactive (bringing the Gate count to zero once again), + // we could have two callers simultaneously executing AttemptSchedulerSweep. One would win, and go on to the sweep and finalize + // the scheduler, the other could be left touching garbage memory. This is why decrementing the ref count m_internalContextCountPlusOne + // is the last thing we should do in this function - this keeps the scheduler alive as long as we're executing PhaseOneShutdown. + // + + if (m_internalContextCountPlusOne > 1) + { + // + // Signal a start of shutdown. + // + // At this point, we cannot finalize the scheduler. Instead, we need to wait for all work to complete + // before performing such finalization. This means any realized chores, blocked contexts, etc... We do + // this by waiting for all virtual processors to become idle (no more unblocked work) and then suspending + // all the virtual processors (they're idle anyway) and sweeping the scheduler looking for blocked contexts. + // If none are found, the scheduler can be finalized. + // + LONG oldVal = m_vprocShutdownGate; + LONG xchgVal = 0; + + for(;;) + { + xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, oldVal | SHUTDOWN_INITIATED_FLAG, oldVal); + if (xchgVal == oldVal) + break; + + oldVal = xchgVal; + } + + ASSERT((oldVal & GATE_FLAGS_MASK) == 0); + + if ((oldVal & GATE_COUNT_MASK) == 0) + { + AttemptSchedulerSweep(); + } + } + + // There is an 'extra' internal context count per scheduler that must be released by every call to PhaseOneShutdown on the scheduler. + // Resurrecting a scheduler must resurrect this count as well. + DecrementInternalContextCount(); + } +#pragma warning(pop) + + /// + /// Invoked when the Gate Count goes to zero as a result of virtual processor state transitions, while the + /// scheduler has been marked for shutdown. It proceeds to sweep the scheduler if it can set the suspend flag + /// on the shutdown gate while the gate count is still 0 and the scheduler is marked for shutdown. + /// + void SchedulerBase::AttemptSchedulerSweep() + { + // + // If we're actively in a shutdown semantic, start a handshake to ensure that no virtual processor + // comes out of idle until we've swept the scheduler. + // + LONG oldVal = SHUTDOWN_INITIATED_FLAG; // Gate Count was found to be 0 and suspend bit cannot be set. + + LONG xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, oldVal | SUSPEND_GATE_FLAG, oldVal); + if (xchgVal == oldVal) + { + // + // At this point no vprocs can become active even if they found work - they will stall on + // the suspend gate when they make the transition from idle -> active. + // + SweepSchedulerForFinalize(); + // + // NOTE: After this point, the *this* pointer is no longer valid and must not be dereferenced. + // + } + else + { + // + // One of three things could've happened here: + // - One of the idle vprocs became active before we could set the suspend gate flag + // - The scheduler was resurrected and vproc resurrecting the scheduler managed to become idle again. + // - There was a concurrent call to AttemptSchedulerSweep (see comments in PhaseOneShutdown) which + // succeeded in setting the suspend bit before we did, and probably completed finalization as well. + // + ASSERT(((xchgVal & GATE_COUNT_MASK) != 0) || ((xchgVal & GATE_FLAGS_MASK) == 0) || + ((xchgVal & GATE_FLAGS_MASK) == (SHUTDOWN_INITIATED_FLAG | SUSPEND_GATE_FLAG)) || + ((xchgVal & GATE_FLAGS_MASK) == (SHUTDOWN_INITIATED_FLAG | SHUTDOWN_COMPLETED_FLAG))); + } + } + + /// + /// Called during scheduler finalization, to check if any chores exist in the scheduler. + /// + /// + /// A boolean value indicating whether any unstarted chores (realized or unrealized) were found. + /// + bool SchedulerBase::FoundUnstartedChores() + { + ASSERT((m_vprocShutdownGate & SHUTDOWN_INITIATED_FLAG) != 0); + ASSERT((m_vprocShutdownGate & SUSPEND_GATE_FLAG) != 0); + + bool choresFound = false; + + for (int idx = 0; idx < m_nodeCount; ++idx) + { + SchedulingRing *pRing = m_rings[idx]; + // For each ring, go through all schedule groups + + if (pRing != NULL) + { + for (int i = 0; i < pRing->m_affineSegments.MaxIndex(); i++) + { + ScheduleGroupSegmentBase *pSegment = pRing->m_affineSegments[i]; + if (pSegment != NULL) + { + if (pSegment->HasRealizedChores() || pSegment->HasUnrealizedChores()) + { + choresFound = true; + break; + } + } + } + + if (choresFound) + break; + + for(int i = 0; i < pRing->m_nonAffineSegments.MaxIndex(); i++) + { + ScheduleGroupSegmentBase *pSegment = pRing->m_nonAffineSegments[i]; + if (pSegment != NULL) + { + if (pSegment->HasRealizedChores() || pSegment->HasUnrealizedChores()) + { + choresFound = true; + break; + } + } + } + } + } + return choresFound; + } + + /// + /// Called during scheduler finalization, to check if any blocked contexts exist in the scheduler. + /// + /// + /// A boolean value indicating whether any blocked contexts were found. + /// + bool SchedulerBase::FoundBlockedContexts() + { + ASSERT((m_vprocShutdownGate & SHUTDOWN_INITIATED_FLAG) != 0); + ASSERT((m_vprocShutdownGate & SUSPEND_GATE_FLAG) != 0); + + bool blockedContextsFound = false; + + // + // No new contexts shall be added to the m_allContexts list at this point. Since + // all the vprocs are guaranteed to be idle, there should be no one executing on + // a vproc (even though there could be contexts that are blocked). Any background + // thread in the scheduler that adds a context needs to synchronize with sweep to + // ensure that contexts are not added while the sweep is in progress. For example, + // the UT creation thread in UMS fails the sweep if there are pending requests to + // add new reserved contexts. + // + ContextNode *pNode = m_allContexts.Unsafe_Top(); + while (pNode != NULL) + { + // + // Work consists of active contexts that are blocked. + // + if ((!pNode->m_pContext->IsIdle()) && pNode->m_pContext->IsBlocked()) + { + ASSERT(pNode->m_pContext->IsBlocked()); + blockedContextsFound = true; + break; + } + + pNode = LockFreePushStack::Next(pNode); + } + + return blockedContextsFound; + } + + /// + /// Determines if there is pending work such as blocked context/unstarted chores etc in the + /// scheduler. If there is no pending work, the scheduler will attempt to shutdown. + /// + SchedulerBase::PendingWorkType SchedulerBase::TypeOfWorkPending() + { + if (FoundBlockedContexts() || FoundUnstartedChores()) + return UserWork; + + // + // Deferred creates from the throttler count as work pending so that it does not race with finalization. + // + if (m_pendingDeferredCreates > 0) + return OnlyAncillaryWork; + + return NoWork; + } + + /// + /// Releases the list of reserved contexts to the idle pool. The thread proxy + /// is released before returning the contexts to the idle pool. + /// + void SchedulerBase::ReleaseReservedContexts() + { + InternalContextBase *pContext = m_reservedContexts.Pop(); + + while (pContext != NULL) + { + GetSchedulerProxy()->UnbindContext(pContext); + ReleaseInternalContext(pContext); + + pContext = m_reservedContexts.Pop(); + } + } + + /// + /// Cancel all the internal contexts. + /// + void SchedulerBase::CancelAllContexts() + { + // + // We need to be in a hypercritical region (this code path shall not rely + // on another UT to be scheduled). + // + ContextBase::StaticEnterHyperCriticalRegion(); + ReleaseReservedContexts(); + ContextBase::StaticExitHyperCriticalRegion(); + + ContextNode *pNode = m_allContexts.Unsafe_Top(); + while ( pNode != NULL) + { + pNode->m_pContext->Cancel(); + pNode = LockFreePushStack::Next(pNode); + } + } + + /// + /// Once all virtual processors are idle, the scheduler calls this routine which performs a full sweep through all + /// schedule groups looking for work. If work is found (even a blocked context), the scheduler backs off finalization; + /// otherwise, it proceeds with phase two of shutdown, which cancels all contexts running in their dispatch loops, + /// as well as any background threads that exist. + /// + void SchedulerBase::SweepSchedulerForFinalize() + { + OMTRACE(MTRACE_EVT_SCHEDULERSWEEP, this, NULL, NULL, m_vprocShutdownGate); + + ASSERT((m_vprocShutdownGate & SHUTDOWN_INITIATED_FLAG) != 0); + ASSERT((m_vprocShutdownGate & SUSPEND_GATE_FLAG) != 0); + + ContextBase *pContext = FastCurrentContext(); + bool fExternal = true; + + if ((pContext != NULL) && (!pContext->IsExternal())) + { + fExternal = false; + pContext->EnterCriticalRegion(); + } + + // + // Once we get in the sweep, and the SUSPEND_GATE_FLAG is set, no virtual processor can start searching for work, + // without being gated by us. At this point we expect all virtual processors (except this one, if this is a context + // running on a virtual processor) to be deactivated via (vproot->Deactivate). Even if work was added and one of + // these was activated again (via vproot->Activate), they would have to reduce the idle count (via VirtualProcessorIdle(false)), + // before they actually searched the scheduler queues for work. If they did, they would be suspended on the shutdown + // gate semaphore. We need to make one final pass for blocked contexts and chores before deciding whether the scheduler + // can be finalized. If either is found, we need to roll back. + // + PendingWorkType workType = TypeOfWorkPending(); + if (workType == NoWork) + { + // + // If there are no blocked contexts and no chores, we can safely proceed to PhaseTwoShutdown. + // + PhaseTwoShutdown(); + } + else + { + if (workType == OnlyAncillaryWork && !m_fSweepWithoutActualWork) + { + // + // Make sure the throttler doesn't dawdle forever by indicating the lack of actual work. + // + InterlockedExchange(&m_fSweepWithoutActualWork, TRUE); + } + + // + // There's work, we need to let everyone go and try again on the next active to idle transition, or + // the next active to inactive transition. + // + LONG xchgVal = m_vprocShutdownGate; + LONG oldVal = xchgVal; + + do + { + oldVal = xchgVal; + xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, oldVal & ~SUSPEND_GATE_FLAG, oldVal); + } + while (xchgVal != oldVal); + + // + // Some virtual processors may have tried to transition from idle to active and been suspended by the gate. + // The number of these vprocs should be the value of the gate count at the time we clear the suspend flag. + // The flag was set at a time the gate count was 0, and from there, it could only have transitioned to a + // positive value. (+1 for each vproc that tried to go idle -> active and was suspended on the gate). + // This is how many virtual processors we need to wake up from suspend. + // + ReleaseSuspendedVirtualProcessors(xchgVal & GATE_COUNT_MASK); + } + + if (!fExternal) pContext->ExitCriticalRegion(); + } + + /// + /// Releases virtual processors that were suspended on the shutdown gate, while trying to go from IDLE to + /// ACTIVE when the finalization sweep was in progress. + /// + /// + /// Number of virtual processors that need to be released. + /// + void SchedulerBase::ReleaseSuspendedVirtualProcessors(LONG releaseCount) + { + if (releaseCount > 0) + { + ReleaseSemaphore(m_hSchedulerShutdownSync, releaseCount, NULL); + } + } + + /// + /// Called when a virtual processor becomes active (before it does) or becomes inactive (before it does). + /// + /// + /// True if a virtual processor is going from INACTIVE to ACTIVE, and false if it is going from ACTIVE to INACTIVE. + /// + /// + /// For activation, the function returns true if the virtual processor was successfully activated, and false + /// if it could not be activated because the scheduler was shutting down. For inactivation, it always returns true. + /// + bool SchedulerBase::VirtualProcessorActive(bool fActive) + { + OMTRACE(MTRACE_EVT_VPROCACTIVE, this, NULL, NULL, fActive); + + // + // It is possible for a virtual processor to become active while the finalization sweep is in progress. A thread external + // to the scheduler could unblock a scheduler context, and activate a virtual processor, if one is found to be available. + // + // However, it is not possible for a virtual processor to become inactive during the sweep. This is because the active + // and idle vproc counts were equal at the time the bit was set (gate count was 0), and there are no external contexts + // attached to the scheduler. To become inactive, a virtual processor would first have to go idle -> active, and would + // block on the suspend gate. + // + + // + // A virtual processor increments the shutdown gate count on going from inactive to active, and decrements it + // on going from active to inactive. + // It also updates the active count - the gate count is used to synchronize with finalization, but the active count + // is needed when the finalization code needs to suspend virtual processors. + // + if (fActive) + { + // We need to spin while the suspend bit is set, if the scheduler is in the sweep phase. If the scheduler finds a blocked + // context, it will rollback finalization and allow us to proceed. If it enters phase two shutdown, it will set a bit + // indicating that shutdown is complete and we should fail this call. We are guaranteed that the scheduler will not + // be deleted, in that we are safe in accessing its data members during this call, since every path that calls this API + // and does not already have a reference on the scheduler, employs a different means of synchronization to ensure the + // scheduler stays around. An example of this is the AddRunnableContext API in CacheLocalScheduleGroup. + // + // We also need to increment the shutdown gate while ensuring that the suspend bit is not set, therefore we use a + // compare exchange instead of an interlocked increment. + LONG xchgVal = m_vprocShutdownGate; + LONG oldVal = xchgVal; + + do + { + oldVal = xchgVal; + + if ((oldVal & SUSPEND_GATE_FLAG) != 0) + { + // If the suspend bit was set in the meantime, we need to spin again until it is unset. Same logic as above applies; + // a blocked context exists, and the scheduler will roll back finalization. + oldVal = SpinUntilBitsReset(&m_vprocShutdownGate, SUSPEND_GATE_FLAG); + } + if ((oldVal & SHUTDOWN_COMPLETED_FLAG) != 0) + { + // Scheduler has shutdown and we cannot activate virtual processors anymore. + OMTRACE(MTRACE_EVT_VPROCACTIVE, this, NULL, NULL, 2); + return false; + } + + xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, oldVal + 1, oldVal); + } + while (xchgVal != oldVal); + + ASSERT((oldVal & SUSPEND_GATE_FLAG) == 0); + ASSERT((oldVal & SHUTDOWN_COMPLETED_FLAG) == 0); + + LONG activeCount = InterlockedIncrement(&m_activeVProcCount); + VirtualProcessorActiveNotification(fActive, activeCount); + } + else + { + ASSERT((m_vprocShutdownGate & SUSPEND_GATE_FLAG) == 0); + ASSERT((m_activeVProcCount != 0) && ((m_vprocShutdownGate & GATE_COUNT_MASK) != 0)); + + LONG activeCount = InterlockedDecrement(&m_activeVProcCount); + VirtualProcessorActiveNotification(fActive, activeCount); + + LONG val = InterlockedDecrement(&m_vprocShutdownGate); + // + // The act of going inactive could potentially make the active and idle vproc counts equal and should try initiate finalization + // if the shutdown initiated flag is set. + // + if (((val & GATE_COUNT_MASK) == 0) && ((val & SHUTDOWN_INITIATED_FLAG) != 0)) + { + // The suspend flag should not bet set. + ASSERT(val == SHUTDOWN_INITIATED_FLAG); + AttemptSchedulerSweep(); + } + } + + return true; + } + + /// + /// Internal contexts call the scheduler right before they deactivate their virtual processors and sleep indefinitely + /// until more work enters the scheduler, in order to allow things that happen on scheduler idle to happen (e.g.: sweeping + /// for phase two shutdown). + /// + /// They also call the scheduler when they transition out of idle before starting to search the scheduler for work, if + /// they underlying virtual processor was re-activated as a result of new work entering. This may halt scheduler shutdown + /// or it may coordinate with scheduler shutdown depending on the current phase of shutdown. + /// + /// This call *MUST* be made from a scheduler critical region. + /// + void SchedulerBase::VirtualProcessorIdle(bool fIdle) + { + OMTRACE(MTRACE_EVT_VPROCIDLE, this, NULL, NULL, fIdle); + + // + // There shall be no blocking operations during SchedulerSweep. If they do and we are forced to make a scheduling decision (such as + // in UMS), it is a recipe for deadlock. (Scheduling decision => activate idle virtual processor => wait for sweep to complete => deadlock). + // We will enter a hypercritical region to enforce it. Any blocking operation that require another thread to be scheduled will immediately + // deadlock. + // + ContextBase::StaticEnterHyperCriticalRegion(); + + // + // A virtual processor decrements the shutdown gate count when it goes from active to idle and increments it + // when it goes from idle to active. + // + if (fIdle) + { + ASSERT((m_vprocShutdownGate & SUSPEND_GATE_FLAG) == 0); + ASSERT((m_vprocShutdownGate & GATE_COUNT_MASK) != 0); + LONG val = InterlockedDecrement(&m_vprocShutdownGate); + // + // The act of going idle could potentially make the active and idle vproc counts equal and should try initiate finalization + // if the shutdown in progress bit flag is set. + // + if (((val & GATE_COUNT_MASK) == 0) && ((val & SHUTDOWN_INITIATED_FLAG) != 0)) + { + // The suspend flag should not bet set. + ASSERT(val == SHUTDOWN_INITIATED_FLAG); + AttemptSchedulerSweep(); + } + } + else + { + LONG val = InterlockedIncrement(&m_vprocShutdownGate); + // + // If a virtual processor is trying to go from idle to active while a scheduler sweep is in progress, it must be + // forcefully suspended until the scheduler has decided whether it needs to rollback or continue with finalization. + // + if ((val & SUSPEND_GATE_FLAG) != 0) + { + // + // For UMS, this will trigger return to primary. We're in a critical section, so we won't + // be able to observe it. + // + WaitForSingleObjectEx(m_hSchedulerShutdownSync, INFINITE, FALSE); + } + } + + ContextBase::StaticExitHyperCriticalRegion(); + } + + /// + /// Called to perform a resurrection of the scheduler. When the scheduler reference count has fallen to zero, + /// it's possible there's still work on the scheduler and that one of those work items will perform an action + /// leading to additional reference. Such bringing of the reference count from zero to non-zero is only legal + /// on an *INTERNAL* context and immediately halts shutdown. + /// + void SchedulerBase::Resurrect() + { + // + // If we got here, someone is going to flag shutdown triggering a whole slew of stuff. We need to ensure + // that that guy progresses to the point where the shutdown_initiated_flag gets set and *THEN* clear it. Hence, + // spin for a while waiting for the thread which released to finish setting the flag. Subsequently, + // we clear it. The original thread will not sweep (as there's a non idle vproc by definition if we + // get here). + // + + LONG val = SpinUntilBitsSet(&m_vprocShutdownGate, SHUTDOWN_INITIATED_FLAG); + ASSERT((val & SHUTDOWN_INITIATED_FLAG) != 0); + + while(true) + { + LONG xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, val & ~SHUTDOWN_INITIATED_FLAG, val); + if (xchgVal == val) + break; + + val = xchgVal; + } + + // + // As this had to have happened from an internal context, that fact alone should guarantee that we weren't in the + // middle of a sweep or moving forward finalization. Further, it also makes this guaranteed safe -- our context + // still holds one reference on the scheduler. This cannot have dropped to zero yet. + // + IncrementInternalContextCount(); + } + + /// + /// Actively informs all internal contexts to exit and breaks them out of their dispatch loops. When the last + /// internal context dies, finalization will occur and we move to SchedulerBase::Finalize(). + /// + void SchedulerBase::PhaseTwoShutdown() + { + OMTRACE(MTRACE_EVT_PHASETWOSHUTDOWN, this, NULL, NULL, NULL); + + ContextBase * pContext = SchedulerBase::FastCurrentContext(); + bool fExternal = (pContext == NULL || pContext->IsExternal() || (pContext->GetScheduler() != this)); + + // If this is not an internal context belonging to this scheduler, we need to take a reference here to be safe. + // In the course of phase two shutdown, we may end up canceling all contexts, which may bring the reference + // count to zero and finalize the scheduler while we're still releasing a lock or something. + if (fExternal) + IncrementInternalContextCount(); + + // + // Fully commit all safe points. + // + CommitToVersion(0); + + // + // Cancel all contexts. For contexts that are running atop virtual processors, we must activate the virtual processors, + // so that the contexts can exit their dispatch loops. For the remaining contexts, we must perform a certain amount of + // cleanup, such as decrementing the reference counts they hold on the scheduler. + // + // Contexts *must* be canceled before the suspend bit is reset. This is so that any calls to VirtualProcessorIdle(false) + // by contexts in their dispatch loops are blocked on the suspend gate until *after* the context is canceled. That way, + // when they are un-suspended, they will immediately exit their dispatch loop, as we intend for them to. Calls to + // VirtualProcessorIdle(false) could result as a race between adding a work item to the scheduler (and subsequently + // trying to activate a virtual processor), and the scheduler shutting down due to a different virtual processor finding + // and executing that work item and subsequently going idle. + // + CancelAllContexts(); + + // + // PhaseTwoShutdown is executed when the scheduler has confirmed that no work, in the form of blocked contexts, exists, and that + // all active virtual processors are idle. However, it is possible that a foreign thread is trying to activate a virtual processor + // in this scheduler. This could be due to a race while adding runnable contexts. We need to mark the scheduler such that the + // vproc addition apis can fail gracefully. Atomically clear the suspend bit and set the shutdown completed bit. + // + // This needs to be done in a loop, since changes to the gate count from calls to VirtualProcessorIdle(false) are possible. + // + LONG xchgVal = m_vprocShutdownGate; + LONG oldVal = 0; + + do + { + oldVal = xchgVal; + ASSERT((oldVal & SHUTDOWN_INITIATED_FLAG) != 0); + ASSERT((oldVal & SUSPEND_GATE_FLAG) != 0); + + xchgVal = InterlockedCompareExchange(&m_vprocShutdownGate, (oldVal | SHUTDOWN_COMPLETED_FLAG) & ~SUSPEND_GATE_FLAG, oldVal); + } + while (xchgVal != oldVal); + + // + // Some virtual processors may have tried to transition from idle to active and been suspended by the gate. + // The number of these vprocs should be the value of the gate count at the time we clear the suspend flag. + // The flag was set at a time the gate count was 0, and from there, it could only have transitioned to a + // positive value. (+1 for each vproc that tried to go idle -> active and was suspended on the gate). + // This is how many virtual processors we need to wake up from suspend. + // + ReleaseSuspendedVirtualProcessors(xchgVal & GATE_COUNT_MASK); + + // + // Cancel all background event handlers + // + DestroySchedulerEventHandlers(); + + if (fExternal) DecrementInternalContextCount(); + } + + /// + /// Returns true if the scheduler has gone past a certain point in PhaseTwoShutdown (when it sets the shutdown completed flag). + /// This function is mainly used for debug asserts. + /// + bool SchedulerBase::HasCompletedShutdown() + { + LONG shutdownFlags = SHUTDOWN_INITIATED_FLAG | SHUTDOWN_COMPLETED_FLAG; + return ((m_vprocShutdownGate & shutdownFlags) == shutdownFlags); + } + + /// + /// Returns true if the scheduler is in the finalization sweep, i.e, the SUSPEND_GATE_FLAG is set. + /// This function is mainly used for debug asserts. + /// + bool SchedulerBase::InFinalizationSweep() + { + LONG shutdownFlags = SHUTDOWN_INITIATED_FLAG | SUSPEND_GATE_FLAG; + return ((m_vprocShutdownGate & shutdownFlags) == shutdownFlags); + } + + /// + /// Called to finalize the scheduler. + /// + void SchedulerBase::Finalize() + { + OMTRACE(MTRACE_EVT_FINALIZATION, this, NULL, NULL, NULL); + + // The scheduler resources should be given back to RM before setting the + // shutdown events. Waiters should be able to create a new scheduler and + // get the resources this scheduler released. + // + // Note that this should happen prior to deleting contexts. We might be + // on a UMS thread finalizing which might need to perform lock validation + // of other UMS related things which require m_pContext not to be toasted + // underneath the UMS thread. + // + m_pSchedulerProxy->Shutdown(); + CloseHandle(m_hSchedulerShutdownSync); + + // Delete all the internal contexts + ContextNode *pNode = m_allContexts.Flush(); + while ( pNode != NULL) + { + ContextNode *pNextNode = LockFreePushStack::Next(pNode); + _InternalDeleteHelper(pNode->m_pContext); + delete pNode; + pNode = pNextNode; + } + + ExternalContextBase *pContext = m_externalContextPool.Flush(); + while (pContext != NULL) + { + ExternalContextBase *pNextContext = LockFreeStack::Next(pContext); + _InternalDeleteHelper(pContext); + pContext = pNextContext; + } + + RealizedChore *pChore = m_realizedChorePool.Flush(); + while (pChore != NULL) + { + RealizedChore *pNextChore = LockFreeStack::Next(pChore); + delete pChore; + pChore = pNextChore; + } + + // Trace event to signal scheduler shutdown + TraceSchedulerEvent(CONCRT_EVENT_END, TRACE_LEVEL_INFORMATION, m_id); + + // Signal threads waiting on scheduler shutdown + while ( !m_finalEvents.Empty()) + { + WaitNode *pNode = m_finalEvents.RemoveHead(); + SetEvent(pNode->m_hEvent); + CloseHandle(pNode->m_hEvent); + delete pNode; + } + + delete this; + } + + /// + /// Increments the reference counts required by a scheduler attach. + /// + void SchedulerBase::ReferenceForAttach() + { + InterlockedIncrement(&m_attachCount); + Reference(); + } + + /// + /// Decrements the reference counts incremented for scheduler attach. + /// + void SchedulerBase::ReleaseForDetach() + { + InterlockedDecrement(&m_attachCount); + Release(); + } + + /// + /// Internal contexts call this when created and utilized inside this scheduler. + /// + void SchedulerBase::IncrementInternalContextCount() + { + InterlockedIncrement(&m_internalContextCountPlusOne); + } + + /// + /// Internal contexts call this function in order to notify that they are out of dispatch. The last internal context + /// to call this will trigger scheduler finalization. + /// + void SchedulerBase::DecrementInternalContextCount() + { + LONG val = InterlockedDecrement(&m_internalContextCountPlusOne); + ASSERT(val >= 0); + if (val == 0) Finalize(); + } + + /// + /// Send a scheduler ETW event. + /// + void SchedulerBase::ThrowSchedulerEvent(ConcRT_EventType eventType, UCHAR level, unsigned int schedulerId) + { + if (g_pEtw != NULL) + { + CONCRT_TRACE_EVENT_HEADER_COMMON concrtHeader = {0}; + + concrtHeader.header.Size = sizeof concrtHeader; + concrtHeader.header.Flags = WNODE_FLAG_TRACED_GUID; + concrtHeader.header.Class.Type = (UCHAR)eventType; + concrtHeader.header.Class.Level = level; + concrtHeader.header.Guid = SchedulerEventGuid; + + concrtHeader.SchedulerID = schedulerId; + + g_pEtw->Trace(g_ConcRTSessionHandle, &concrtHeader.header); + } + } + + /// + /// Called when the resource manager is giving virtual processors to a particular scheduler. The virtual processors are + /// identified by an array of IVirtualProcessorRoot interfaces. This call is made to grant virtual processor roots + /// at initial allocation during the course of ISchedulerProxy::RequestInitialVirtualProcessors, and during dynamic + /// core migration. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors being added to the scheduler. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + void SchedulerBase::AddVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count) + { + if (ppVirtualProcessorRoots == NULL) + throw std::invalid_argument("ppVirtualProcessorRoots"); + + if (count < 1) + throw std::invalid_argument("count"); + + for (unsigned int i = 0; i < count; ++i) + { + IVirtualProcessorRoot * pVProcRoot = ppVirtualProcessorRoots[i]; + + // IMPORTANT: This API is called for each virtual processor added at the time of scheduler creation, and + // later when dynamic RM adds cores to this scheduler. We do not need to synchronize between concurrent + // invocations of this API, as the RM guarantees for now that only one thread is calling this API at a time. + int nodeId = pVProcRoot->GetNodeId(); + + ASSERT(nodeId >= 0 && nodeId < m_nodeCount && m_nodes[nodeId] != NULL && m_rings[nodeId] != NULL); + if (!m_rings[nodeId]->IsActive()) + { + m_rings[nodeId]->Activate(); + } + + m_nodes[nodeId]->AddVirtualProcessor(pVProcRoot); + + // This count should be incremented after adding the virtual processor. The SchedulingNode::AddVirtualProcessor + // API called above tests if the count is 0, to infer that this virtual processor is the first one added to the + // scheduler during the initial thread request. + InterlockedIncrement(&m_virtualProcessorCount); + + // The total count on the scheduler is not incremented for oversubscribed virtual processors. (adding an oversubscribed + // virtual processor doesn't go through this code path). Querying for the number of virtual processors assigned to a scheduler + // does not take into account oversubscribed virtual processors, since technically these virtual processors are in place + // to compensate for other virtual processors that may be blocked, and therefore are not available to perform work for + // the scheduler. + } + } + + /// + /// Called when the resource manager is taking away virtual processors from a particular scheduler. The scheduler should + /// mark the supplied virtual processors such that they are removed asynchronously and return immediately. Note that + /// the scheduler should make every attempt to remove the virtual processors as quickly as possible as the resource manager + /// will reaffinitize threads executing upon them to other resources. Delaying stopping the virtual processors may result + /// in unintentional oversubscription within the scheduler. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors which are to be removed. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + void SchedulerBase::RemoveVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count) + { + if (ppVirtualProcessorRoots == NULL) + throw std::invalid_argument("ppVirtualProcessorRoots"); + + if (count < 1) + throw std::invalid_argument("count"); + + for (unsigned int i = 0; i < count; ++i) + { + IVirtualProcessorRoot * pVProcRoot = ppVirtualProcessorRoots[i]; + VirtualProcessor * pVirtualProcessor = m_nodes[pVProcRoot->GetNodeId()]->FindMatchingVirtualProcessor(pVProcRoot); + + while (pVirtualProcessor == NULL) + { + // If the virtual processor was not found the first time around, it must because it is an oversubscribed virtual processor + // and we are racing with the call to Oversubscribe(true). Once the virtual processor root has been created in the RM + // (for the oversubscribed vproc), we can receive a RemoveVirtualProcessor call for that root at any time. Only the thread + // scheduler creates oversubscribed vprocs. + ASSERT(m_policy.GetPolicyValue(::Concurrency::SchedulerKind) == ::Concurrency::ThreadScheduler); + + _SpinWaitBackoffNone spinWait; + while (spinWait._SpinOnce()) + { + // _YieldProcessor is called inside _SpinOnce + } + + platform::__SwitchToThread(); + pVirtualProcessor = m_nodes[pVProcRoot->GetNodeId()]->FindMatchingVirtualProcessor(pVProcRoot); + ASSERT(pVirtualProcessor == NULL || pVirtualProcessor->m_fOversubscribed); + } + + if (pVirtualProcessor->m_fOversubscribed) + { + // We must synchronize with a potential RemoveVirtualProcessor for this virtual processor due to the RM taking the underlying + // core away. The winner of the interlocked exchange gets to retire the virtual processor. + ASSERT(pVirtualProcessor->m_pOversubscribingContext != NULL); + pVirtualProcessor = pVirtualProcessor->m_pOversubscribingContext->GetAndResetOversubscribedVProc(pVirtualProcessor); + + ASSERT(pVirtualProcessor == NULL || pVirtualProcessor->GetOwningRoot() == pVProcRoot); + // Even if we lose the race, we are safe to touch the virtual processor here, since the context retiring the virtual processor + // is guaranteed to not get past the call to the RM (in VirtualProcessor::Retire), that removes the virtual processor. + } + + if (pVirtualProcessor != NULL) + { + pVirtualProcessor->MarkForRetirement(); + } + } + } + + /// + /// Collect all the statistical information about this scheduler, which include arrival and completion + /// rates, from which the total number of tasks is deduced. + /// + void SchedulerBase::Statistics(unsigned int *pTaskCompletionRate, unsigned int *pTaskArrivalRate, unsigned int *pNumberOfTasksEnqueued) + { + // + // Collect all the virtual processor statistics. All internal contexts own a virtual processor when they + // run a task, so they also own the statistical information at that point and are free to update it without + // racing with other internal contexts (it is done without interlocked operation). Now we simply collect that + // information that aggregated on each virtual processor and add it to our total. We do it non-interlocked + // fully aware that the numbers might be slightly off, for example due to store-buffer not being flushed. + // + + for (int index = 0; index < m_nodeCount; index++) + { + SchedulingNode * pNode = m_nodes[index]; + + if (pNode != NULL) + { + for (int i = 0; i < pNode->m_virtualProcessors.MaxIndex(); i++) + { + VirtualProcessor * pVirtualProcessor = pNode->m_virtualProcessors[i]; + + // + // We collect the data and reset it so that next time around we would get the numbers as of + // last update. This allows us to get the rate of change and avoid overflow in most cases. + // + if (pVirtualProcessor != NULL) + { + unsigned int arrivalRate = pVirtualProcessor->GetEnqueuedTaskCount(); + unsigned int completionRate = pVirtualProcessor->GetDequeuedTaskCount(); + + *pTaskArrivalRate += arrivalRate; + *pTaskCompletionRate += completionRate; + *pNumberOfTasksEnqueued += (arrivalRate - completionRate); + } + } + } + } + + // + // Collect data from the retired virtual processors, saved on the scheduler itself. Note that there is + // a race here between virtual processor retiring and statistics being collected. Since we do not lock + // any structure that we are reading from we can either count the statistics twice, or miss them completely. + // This will cause a spike in statistics, but hopefully it will be rare enough that after collecting + // several datapoints it can be discarded. + // + { + unsigned int arrivalRate = GetEnqueuedTaskCount(); + unsigned int completionRate = GetDequeuedTaskCount(); + + *pTaskArrivalRate += arrivalRate; + *pTaskCompletionRate += completionRate; + *pNumberOfTasksEnqueued += (arrivalRate - completionRate); + } + + // + // Collect all the external context and free thread statistics. All external contexts and alien threads (not + // bound to our scheduler) are registered in a list array that is kept on a scheduler. They own a slot in the + // list array of external statistics, and they update that particular external statistics. Because they own a unique + // ExternalStatistics class there is no contention or races. Now we simply collect that information per external context + // or free thread and add it to our total. Again, we are fully aware that numbers might not be fully accurate. + // + for (int i = 0; i < m_externalThreadStatistics.MaxIndex(); i++) + { + ExternalStatistics * externalStatistics = m_externalThreadStatistics[i]; + + // + // We collect the data and reset it so that next time around we would get the numbers as of + // last update. This allows us to get the rate of change. + // + if (externalStatistics != NULL) + { + unsigned int arrivalRate = externalStatistics->GetEnqueuedTaskCount(); + unsigned int completionRate = externalStatistics->GetDequeuedTaskCount(); + + *pTaskArrivalRate += arrivalRate; + *pTaskCompletionRate += completionRate; + *pNumberOfTasksEnqueued += (arrivalRate - completionRate); + + // If external statistics class is no longer useful, remove it. Note that we could have left the external + // statistics alone because when scheduler finalizes it destroys the ListArray, which + // will also destruct all external statistics stored in it. However, this way we allow for slot reuse in + // the ListArray in case we have a huge amount of external context joining and leaving. + if (!externalStatistics->IsActive()) + { + // We can safely remove this statistics from our list. To see why look at comments in IsActive(). + m_externalThreadStatistics.Remove(externalStatistics, false); + delete externalStatistics; + } + } + } + } + + /// + /// Returns a suballocator from the pool of suballocators in the process, or creates a new one. The RM only allows + /// a fixed number of allocators for external contexts in the process, whereas every virtual processor that requests + /// an allocator will get one. + /// + /// + /// Specifies whether the allocator is being requested for an external context. If this is 'true' the RM will return + /// NULL if it has reached its limit of suballocators for external contexts. If this is 'false', the caller is requesting + /// the suballocator for a virtual processor, and the RM *must* allocate one (resources permitting). + /// + SubAllocator* SchedulerBase::GetSubAllocator(bool fExternalAllocator) + { + if (fExternalAllocator) + { + #pragma warning(suppress: 28112) // False positive warning, VSO-1807048 + if (s_numExternalAllocators >= s_maxExternalAllocators) + { + return NULL; + } + InterlockedIncrement(&s_numExternalAllocators); + } + + SubAllocator* pAllocator = s_subAllocatorFreePool.Pop(); + if (pAllocator == NULL) + { + pAllocator = _concrt_new SubAllocator(); + } + + ASSERT(pAllocator != NULL); + pAllocator->SetExternalAllocatorFlag(fExternalAllocator); + + return pAllocator; + } + + /// + /// Returns a suballocator back to the pool in the RM. + /// The RM caches a fixed number of suballocators and will destroy the rest. + /// + void SchedulerBase::ReturnSubAllocator(SubAllocator* pAllocator) + { + if (pAllocator->IsExternalAllocator()) + { + LONG retVal = InterlockedDecrement(&s_numExternalAllocators); + ASSERT(retVal >= 0); + } + + if (s_subAllocatorFreePool.Count() < s_allocatorFreePoolLimit) + { + s_subAllocatorFreePool.Push(pAllocator); + } + else + { + delete pAllocator; + } + } + + /// + /// Called to perform a commit of safe-point registrations up to **AND INCLUDING** a particular version. + /// + /// + /// The data version that we commit to. A version of zero indicates a full commit. + /// + void SchedulerBase::CommitToVersion(ULONG commitVersion) + { + // + // For UMS, this has to be lock free (more accurately, UMS trigger free -- meaning no blocking or yielding operations). + // We store this as a pure-spin-lock (hyper critical) protected queue. There should be very low contention on this lock. + // + + SQueue pCommits; + + m_safePointInvocations.Acquire(); + for(;;) + { + SafePointInvocation *pCur = m_safePointInvocations.Current(); + + // + // We do not attempt to commit across the wrap-around boundary. We commit up to the boundary and then recommit afterward. This prevents + // wrap-around issues. + // + if (pCur != NULL && (commitVersion == 0 || (IsVisibleVersion(pCur->m_safePointVersion) && pCur->m_safePointVersion <= commitVersion))) + { + pCur = m_safePointInvocations.SQueue::Dequeue(); + pCommits.Enqueue(pCur); + } + else + { + break; + } + } + m_safePointInvocations.Release(); + + // + // Perform every safe point invocation. + // These must be invoked in the order they were enqueued to m_safePointInvocations. There is an ordering constraint because + // ListArrays of workqueues are in ScheduleGroups, which are in ListArrays themselves. Deleting a workqueue after deleting + // its enclosing ScheduleGroup will cause an AV. + // + while (!pCommits.Empty()) + { + SafePointInvocation *pCur = pCommits.Dequeue(); + pCur->Invoke(); + } + } + + /// + /// Returns the commit version for safe points within the scheduler. + /// + ULONG SchedulerBase::ComputeSafePointCommitVersion() + { + bool fVersioned = false; + ULONG commitVersion = 0; + + for (int index = 0; index < m_nodeCount; index++) + { + SchedulingNode *pNode = m_nodes[index]; + + if (pNode != NULL) + { + for (int i = 0; i < pNode->m_virtualProcessors.MaxIndex(); i++) + { + VirtualProcessor *pVirtualProcessor = pNode->m_virtualProcessors[i]; + if (pVirtualProcessor != NULL) + { + ULONG localCommit = ObservedVersion(pVirtualProcessor->m_safePointMarker.m_lastObservedVersion); + + if (fVersioned) + { + // + // We can only commit to the lowest version that every virtual processor has observed. + // + if (commitVersion > localCommit) + commitVersion = localCommit; + } + else + { + commitVersion = localCommit; + fVersioned = true; + } + } + } + } + } + + return commitVersion; + } + + /// + /// Updates and returns the pending version for safe point commits. + /// If there are no commits pending, 0 is returned. + /// + ULONG SchedulerBase::UpdatePendingVersion() + { + ULONG commitVersion = ComputeSafePointCommitVersion(); + + if (commitVersion <= m_safePointPendingVersion) + { + // It has either been comitted or is pending in some vproc. + return 0; + } + + if (m_safePointPendingVersion == m_safePointCommitVersion) + { + // Update pending version. This routine is called with the lock + // held. This compare and set operation needs to be atomic. + m_safePointPendingVersion = commitVersion; + return commitVersion; + } + else + { + // Just update the pending version. The vproc that snapped the list + // will notice this update and resnap the new entries + m_safePointPendingVersion = commitVersion; + return 0; + } + } + + /// + /// Updates the commit version to the given version and returns + /// the pending commit version. If there are no commits pending, 0 is returned. + /// + /// + /// The version up to which safe points have been committed. + /// + ULONG SchedulerBase::UpdateCommitVersion(ULONG commitVersion) + { + ASSERT(commitVersion != 0); + + if (commitVersion == ULONG_MAX) + { + // Handle overflow + ASSERT(commitVersion == m_safePointPendingVersion); + m_safePointCommitVersion = 0; + + // Handle safepoints above the wrap around point + m_safePointPendingVersion = ComputeSafePointCommitVersion(); + } + else + { + // Update the committed version + m_safePointCommitVersion = commitVersion; + } + + if (m_safePointCommitVersion != m_safePointPendingVersion) + { + // Found pending commits + ASSERT(m_safePointPendingVersion > m_safePointCommitVersion); + return m_safePointPendingVersion; + } + + return 0; + } + + /// + /// Called to make a determination of what version of data we can commit up to. This is the minimum data version that all virtual + /// processors have observed. + /// + void SchedulerBase::CommitSafePoints() + { + ULONG commitVersion = 0; + + // Update the version we are about to commit. + m_safePointInvocations.Acquire(); + commitVersion = UpdatePendingVersion(); + m_safePointInvocations.Release(); + + + // Note that a commitVersion of 0 here indicates that there are no safe points + // to commit. + while (commitVersion != 0) + { + CommitToVersion(commitVersion); + + // Publish the committed version and check for any pending commits + m_safePointInvocations.Acquire(); + commitVersion = UpdateCommitVersion(commitVersion); + m_safePointInvocations.Release(); + } + } + + /// + /// Called when a particular virtual processor reaches a safe point. This function does very little unless there has + /// been a change in the version number of the safe point. + /// + /// + /// The safe point marker for a given virtual processor. This is the virtual processor reaching a safe point. + /// + /// + /// An indication of whether a commit should take place. If this is true, the caller should call CommitSafePoints when possible. + /// Note that this is a return value so that things like UMS virtual processors can exit critical regions before performing + /// the commit (to avoid, for instance, heap locks in critical regions). + /// + bool SchedulerBase::MarkSafePoint(SafePointMarker *pMarker) + { + // + // If there has been no change in observation version, there's nothing to mark off and nothing to worry about. Only if there + // has been a change need we go down the path of checking how far we can commit. + // + if (pMarker->m_lastObservedVersion != m_safePointDataVersion) + { + pMarker->m_lastObservedVersion = m_safePointDataVersion; + return true; + } + + return false; + } + + /// + /// The routine is used to trigger a safe point commit on all the vprocs by + /// updating the data version. This routine shall not trigger synchronous UMS blocking + /// + void SchedulerBase::TriggerCommitSafePoints(SafePointMarker *pMarker) + { + m_safePointInvocations.Acquire(); + + // + // We check for a change with the lock held to avoid triggering + // a commit check on all vprocs unnecessarily. + // + if (pMarker->m_lastObservedVersion != m_safePointDataVersion) + { + // + // Publishing a new data version would cause all vprocs + // to attempt a commit + // + PublishNewDataVersion(); + } + + m_safePointInvocations.Release(); + } + + /// + /// Called to register an object to invoke upon reaching the next safe point after this call. + /// + /// + /// The invocation object which contains information about what to call. + /// + void SchedulerBase::InvokeOnSafePoint(SafePointInvocation *pInvocation) + { + // + // *READ THIS CAREFULLY*: + // + // Due to the places in which this is likely to be invoked, this routine must not trigger UMS. That means it must be lock-free (or at least + // block/yield free). Doing any UMS trigger operation will wreak havoc on the UMS scheduler. + // + // Note that in order to vastly simplify this code, I am utilizing a pure spin lock protected queue. There should be low enough contention + // on this that it should not matter and there are potential truly lock-free algorithms which might be used for more efficiency (though hugely + // more complex). + // + + // + // Note that we assume that everything is enqueued in data version order (FIFO) in order to simplify the code and prevent having to always + // scan the entire list. In order to guarantee this, the increment and the list addition must be atomic with respect to each other. Right + // now, this is guarded via the spinlock on this list. + // + m_safePointInvocations.Acquire(); + + pInvocation->m_safePointVersion = PublishNewDataVersion(); + m_safePointInvocations.SQueue::Enqueue(pInvocation); + + m_safePointInvocations.Release(); + + // + // pInvocation is must not be dereferenced after this point: + // + + } + + /// + /// Registers a particular function to be called with particular data when a given scheduler reaches the next safe point + /// after the call is made. This is an intrusive invocation with the current SafePointInvocation class incurring no heap + /// allocations. + /// + /// + /// The function which will be invoked at the next safe point + /// + /// + /// User specified data. + /// + /// + /// The scheduler on which to wait for a safe point to invoke pInvocationFunction. + /// + void SafePointInvocation::InvokeAtNextSafePoint(InvocationFunction pInvocationFunction, void *pData, SchedulerBase *pScheduler) + { + // + // If the shutdown completed flag is set, all scheduler operations are serialized to one thread for finalization. It is perfectly safe to + // perform the action right now rather than defer it. This is cleanup! + // + if (pScheduler->m_vprocShutdownGate & SHUTDOWN_COMPLETED_FLAG) + { + pInvocationFunction(pData); + } + else + { + m_pInvocation = pInvocationFunction; + m_pData = pData; + + pScheduler->InvokeOnSafePoint(this); + } + } + + /// + /// Finds the node associated with the calling thread, if any. This method only returns a node if the current context is an internal context + /// in this scheduler. + /// + SchedulingNode *SchedulerBase::FindCurrentNode() + { + SchedulingNode * pCurrentNode = NULL; + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + if (pCurrentContext != NULL && pCurrentContext->m_pScheduler == this && !pCurrentContext->IsExternal()) + { + InternalContextBase *pInternalContext = static_cast(pCurrentContext); + pInternalContext->EnterCriticalRegion(); + pCurrentNode = pInternalContext->m_pVirtualProcessor->GetOwningNode(); + pInternalContext->ExitCriticalRegion(); + } + + return pCurrentNode; + } + + /// + /// Returns the scheduling node which srcLocation is a member of. Note that if srcLocation and this node's location do not intersect, + /// this will return NULL. + /// + SchedulingNode *SchedulerBase::FindNodeByLocation(location* pSrcLocation) + { + SchedulingNode *pNode = NULL; + + switch(pSrcLocation->_GetType()) + { + case location::_ExecutionResource: + { + unsigned int nodeId; + if (m_resourceNodeMap.Find(pSrcLocation->_GetId(), &nodeId)) + pNode = m_nodes[nodeId]; + + break; + } + + case location::_SchedulingNode: + pNode = m_nodes[pSrcLocation->_GetId()]; + break; + + case location::_NumaNode: + // + // This should be handled at a different level. There is no single node which maps here. + // + ASSERT(false); + + default: + break; + } + + return pNode; + } + + /// + /// Returns a bit set for a given location to perform quick masking. + /// + QuickBitSet SchedulerBase::GetBitSet(const location* pLoc) + { + QuickBitSet set(GetMaskIdCount()); + + switch(pLoc->_GetType()) + { + case location::_System: + { + set.Fill(); + break; + } + case location::_NumaNode: + { + set = m_numaInformation[pLoc->_GetId()].m_resourceMask; + break; + } + case location::_SchedulingNode: + { + set = m_nodes[pLoc->_GetId()]->GetResourceSet(); + break; + } + case location::_ExecutionResource: + { + unsigned int maskId; + Hash::ListNode *pHashNode = m_resourceBitMap.Find(pLoc->_GetId(), &maskId); + ASSERT(pHashNode != NULL); + set.Set(maskId); + break; + } + + default: + break; + } + + return set; + } + + // + // @TODO: This needs to go with real priority. + // + BoostedObject *SchedulerBase::GetNextPriorityObject() + { + m_priorityObjects.AcquireWrite(); + BoostedObject *pEntry = m_priorityObjects.UnlockedRemoveHead(); + + if (pEntry) + { + // m_boostState must be set under the lock + ASSERT(pEntry->m_boostState == BoostedObject::BoostStateBoosted); + pEntry->m_boostState = BoostedObject::BoostStateUnboosted; + } + m_priorityObjects.ReleaseWrite(); + + return pEntry; + } + + /// + /// Performs the scheduler service scan. + /// + void SchedulerBase::PerformServiceScan(ULONGLONG serviceTime) + { + // + // Only one person should enter the service loop. It should also only be entered every period defined by how often we want to + // do priority boosting, etc... + // + for(;;) + { + ULONGLONG readServiceTime = m_lastServiceScan; + + if ((ULONGLONG)InterlockedCompareExchange64(reinterpret_cast(&m_lastServiceScan), + serviceTime, + readServiceTime) == readServiceTime) + { + + OMTRACE(MTRACE_EVT_PERIODICSCAN, this, NULL, NULL, serviceTime); + + // + // Take the lock and perform the scan. + // @TODO: This part needs to change. + // + + m_priorityObjects.AcquireWrite(); + + for (int idx = 0; idx < m_nodeCount; ++idx) + { + SchedulingRing *pRing = m_rings[idx]; + SchedulingNode *pNode = m_nodes[idx]; + + int sIdx; + ScheduleGroupSegmentBase *pSegment = pRing->GetFirstAffineScheduleGroupSegment(&sIdx); + while (pSegment != NULL) + { + if (pSegment->TimeSinceServicing(serviceTime) > 2000 && + pSegment->m_priorityServiceLink.m_boostState == BoostedObject::BoostStateUnboosted) + { + OMTRACE(MTRACE_EVT_PERIODICSCANNED, pSegment, NULL, NULL, 1); + OMTRACE(MTRACE_EVT_PRIORITYBOOST, pSegment, NULL, NULL, serviceTime); + + pSegment->m_priorityServiceLink.m_boostState = BoostedObject::BoostStateBoosted; + m_priorityObjects.UnlockedAddHead(&pSegment->m_priorityServiceLink); + } + else + { + OMTRACE(MTRACE_EVT_PERIODICSCANNED, pSegment, NULL, NULL, 0); + } + + pSegment = pRing->GetNextAffineScheduleGroupSegment(&sIdx); + } + + pSegment = pRing->GetFirstNonAffineScheduleGroupSegment(&sIdx); + while (pSegment != NULL) + { + if (pSegment->TimeSinceServicing(serviceTime) > 2000 && + pSegment->m_priorityServiceLink.m_boostState == BoostedObject::BoostStateUnboosted) + { + OMTRACE(MTRACE_EVT_PRIORITYBOOST, pSegment, NULL, NULL, serviceTime); + + pSegment->m_priorityServiceLink.m_boostState = BoostedObject::BoostStateBoosted; + m_priorityObjects.UnlockedAddHead(&pSegment->m_priorityServiceLink); + } + else + { + OMTRACE(MTRACE_EVT_PERIODICSCANNED, pSegment, NULL, NULL, 0); + } + + pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&sIdx); + } + + int vIdx; + VirtualProcessor *pVProc = pNode->GetFirstVirtualProcessor(&vIdx); + while (pVProc != NULL) + { + if (pVProc->TimeSinceServicing(serviceTime) > 2000 && + pVProc->m_priorityServiceLink.m_boostState == BoostedObject::BoostStateUnboosted) + { + pVProc->m_priorityServiceLink.m_boostState = BoostedObject::BoostStateBoosted; + m_priorityObjects.UnlockedAddHead(&pVProc->m_priorityServiceLink); + } + pVProc = pNode->GetNextVirtualProcessor(&vIdx); + } + } + + m_priorityObjects.ReleaseWrite(); + + break; + } + } + } + + void SchedulerBase::RemovePrioritizedObject(BoostedObject *pObject) + { + m_priorityObjects.AcquireWrite(); + if (pObject->m_boostState == BoostedObject::BoostStateBoosted) + { + m_priorityObjects.UnlockedRemove(pObject); + } + pObject->m_boostState = BoostedObject::BoostStateDisallowed; + m_priorityObjects.ReleaseWrite(); + } + + unsigned int _Scheduler::_Reference() + { + return _M_pScheduler->Reference(); + } + + unsigned int _Scheduler::_Release() + { + return _M_pScheduler->Release(); + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.h new file mode 100644 index 0000000000000000000000000000000000000000..0ecb5d10111c0d40c6056b4ce1063093a449d23a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.h @@ -0,0 +1,1691 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulerBase.h +// +// Header file containing the metaphor for a concrt scheduler +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +// +// Defines how many (1 << x) pointers worth of padding there will be in between quick cache slots. +// +#ifdef _WIN64 +// +// 64 bit: +// 1 << 4 == 8 pointers * 8 == 64 bytes (assumed cache pad) +// +#define QUICKCACHEPAD_SHIFT 4 +#else // !_WIN64 +// +// 32 bit: +// 1 << 5 == 16 pointers * 4 == 64 bytes (assumed cache pad) +// +#define QUICKCACHEPAD_SHIFT 5 +#endif // _WIN64 + +namespace Concurrency +{ +namespace details +{ + // The base class that implements a scheduler instance + + class SchedulerBase : public Scheduler + { + private: + + // + // NESTED CLASSES: + // + + /// + /// Represents information about the NUMA nodes on the machine. + /// + struct NumaInformation + { + QuickBitSet m_nodeMask; + QuickBitSet m_resourceMask; + }; + + /// + /// An intrusive node type for context tracking outside of the normal placement of contexts upon + /// free/runnable lists. + /// + class ContextNode + { + public: + + ContextNode(InternalContextBase *pContext) : m_pContext(pContext) + { + } + + SLIST_ENTRY m_slNext{}; + InternalContextBase *m_pContext; + }; + + /// + /// A node that tracks events needing to be signaled at finalization time. + /// + class WaitNode + { + public: + + WaitNode *m_pNext, *m_pPrev; + HANDLE m_hEvent; + }; + + /// + /// A class that the scheduler uses to manage external context exit events for implicitly attached + /// external contexts. + /// + class ContextExitEventHandler + { + public: + + bool m_fCanceled; + // Count of handles the event handler is waiting on at any time. + unsigned short m_handleCount; + // Modified to reflect the new handle count after adding handles to the wait array and before notifying the + // watch dog of handle addition. + unsigned short m_newHandleCount; + // Event handle used to notify the event handler of certain events (new handle addition, shutdown). + HANDLE m_hWakeEventHandler; + SchedulerBase *m_pScheduler; + // prev, next pointers for the list of all handlers in the scheduler. + ContextExitEventHandler *m_pNext, *m_pPrev; + // list entry for a list of handlers with available slots for context handles. The scheduler uses this + // list when registering contexts. + ListEntry m_availableChain; + // The array of wait handles each thread waits on. Of these one is an event handle for notification + // and the rest are handles to OS contexts. + HANDLE m_waitHandleArray[MAXIMUM_WAIT_OBJECTS]; + }; + + public: + + /// + /// Creates a scheduler that only manages internal contexts. Implicitly calls Reference. + /// If Attach is called, the scheduler is no longer anonymous because it is also managing the external + /// context where Attach was called. To destroy an anonymous scheduler, Release needs to be called. + /// + /// + /// [in] A const reference to the scheduler policy. + /// + /// + /// A pointer to the new scheduler (never null) + /// + static _Ret_writes_(1) SchedulerBase* Create(_In_ const SchedulerPolicy& policy); + static _Ret_writes_(1) SchedulerBase* CreateWithoutInitializing(_In_ const SchedulerPolicy& policy); + + // Constructor + SchedulerBase(_In_ const ::Concurrency::SchedulerPolicy& policy); + + // dtor + virtual ~SchedulerBase(); + + public: // Public Scheduler interface + /// + /// Returns a unique identifier for this scheduler. No error state. + /// + virtual unsigned int Id() const { return m_id; } + + /// + /// Returns a current number of virtual processors for this scheduler. No error state. + /// + virtual unsigned int GetNumberOfVirtualProcessors() const { return m_virtualProcessorCount; }; + + /// + /// Returns a copy of the policy this scheduler is using. No error state. + /// + virtual SchedulerPolicy GetPolicy() const; + + /// + /// Increments a reference count to this scheduler to manage lifetimes over composition. + /// This reference count is known as the scheduler reference count. + /// + /// + /// The resulting reference count is returned. No error state. + /// + virtual unsigned int Reference(); + + /// + /// Decrements this scheduler's reference count to manage lifetimes over composition. + /// A scheduler starts the shutdown protocol when the scheduler reference count goes to zero. + /// + /// + /// The resulting reference count is returned. No error state. + /// + virtual unsigned int Release(); + + /// + /// Causes the OS event object 'event' to be set when the scheduler shuts down and destroys itself. + /// + /// + /// [in] A handle to avalid event object + /// + virtual void RegisterShutdownEvent(_In_ HANDLE event); + + /// + /// Attaches this scheduler to the calling thread. Implicitly calls Reference. + /// After this function is called, the calling thread is then managed by the scheduler and the scheduler becomes the current scheduler. + /// It is illegal for an internal context to call Attach on its current scheduler. + /// + virtual void Attach(); + + /// + /// Allows a user defined policy to be used to create the default scheduler. It is only valid to call this API when no default + /// scheduler exists. Once a default policy is set, it remains in effect until the next time the API is called (in the absence + /// of a default scheduler). + /// + /// + /// [in] A pointer to the policy to be set as the default. The runtime will make a copy of the policy + /// for its use, and the user is responsible for the lifetime of the policy that is passed in. + /// + static void SetDefaultSchedulerPolicy(_In_ const SchedulerPolicy & _Policy); + + /// + /// Resets the default scheduler policy, and the next time a default scheduler is created, it will use the runtime's default policy settings. + /// + static void ResetDefaultSchedulerPolicy(); + + /// + /// Creates a new schedule group within the scheduler associated with the calling context. + /// + /// + /// A pointer to the newly created schedule group. This ScheduleGroup object has an initial reference count placed on it. + /// + /// + /// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no + /// scheduler currently associated with the calling context. + /// You must invoke the Release method on a schedule group when you are + /// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed. + /// Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before + /// you release your reference on the scheduler, via detaching the current context from it. + /// + /// + /// + /// + virtual ScheduleGroup* CreateScheduleGroup() + { + location unbiased; + return InternalCreateScheduleGroup(&unbiased); + } + + /// + /// Creates a new schedule group within the scheduler associated with the calling context. Tasks scheduled within the newly created + /// schedule group will be biased towards executing at the specified location. + /// + /// + /// A reference to a location where the tasks within the schedule group will biased towards executing at. + /// + /// + /// A pointer to the newly created schedule group. This ScheduleGroup object has an initial reference count placed on it. + /// + /// + /// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no + /// scheduler currently associated with the calling context. + /// You must invoke the Release method on a schedule group when you are + /// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed. + /// Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before + /// you release your reference on the scheduler, via detaching the current context from it. + /// + /// + /// + /// + /// + virtual ScheduleGroup * CreateScheduleGroup(location& _Placement) + { + return InternalCreateScheduleGroup(&_Placement); + } + + /// + /// Schedules a light-weight task within the scheduler. The light-weight task will be placed in a schedule group of the runtime's choosing. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// + virtual void ScheduleTask(TaskProc proc, void *data); + + /// + /// Schedules a light-weight task within the scheduler. The light-weight task will be placed + /// within a schedule group of the runtime's choosing. It will also be biased towards executing at the specified location. + /// + /// + /// A pointer to the function to execute to perform the body of the light-weight task. + /// + /// + /// A void pointer to the data that will be passed as a parameter to the body of the task. + /// + /// + /// A reference to a location where the light-weight task will be biased towards executing at. + /// + /// + /// + /// + virtual void ScheduleTask(TaskProc proc, void * data, location& placement); + + /// + /// Determines whether a given location is available on the scheduler. + /// + /// + /// A reference to the location to query the scheduler about. + /// + /// + /// An indication of whether or not the location specified by the argument is available on the scheduler. + /// + /// + /// Note that the return value is an instantaneous sampling of whether the given location is available. In the presence of multiple + /// schedulers, dynamic resource management may add or take away resources from schedulers at any point. Should this happen, the given + /// location may change availability. + /// + virtual bool IsAvailableLocation(const location& _Placement) const; + + public: // Internal stuff + + enum + { + // + // One shot starts with a single reference count placed implicitly by the module in which ConcRT is contained. + // + ONESHOT_NOT_INITIALIZED = 1, + ONESHOT_INITIALIZED_FLAG = 0x80000000 + }; + + /// + /// Returns whether or not the scheduler has performed one shot static construction. + /// + static bool IsOneShotInitialized() { return ((s_oneShotInitializationState & ONESHOT_INITIALIZED_FLAG) != 0); } + + /// + /// Detaches this scheduler from the current thread. It is required that the current scheduler on the thread be the same as 'this' + /// + void Detach(); + + /// + /// Generates a unique identifier for a context. + /// + unsigned int GetNewContextId(); + + /// + /// Generates a unique identifier for a schedule group. + /// + unsigned int GetNewScheduleGroupId(); + + /// + /// Generates a unique identifier for a work queue across schedulers. + /// + static unsigned int GetNewWorkQueueId(); + + /// + /// Gets a reserved context off the free list. This is lock-free and safe to use at any point in the scheduler. If a context + /// is returned, it is a pre-bound and unstarted context. + /// + InternalContextBase *GetReservedContext() + { + return m_reservedContexts.Pop(); + } + + /// + /// Releases the list of reserved contexts to the idle pool. The thread proxy + /// is released before returning the contexts to the idle pool. + /// + void ReleaseReservedContexts(); + + /// + /// Acquires a new internal context of the appropriate type and returns it. This can come from either + /// a free list within the scheduler, or be one newly allocated from the heap. + /// + /// + /// An indication as to whether the creation should be throttled. + /// + InternalContextBase *GetInternalContext(bool fThrottled = true); + + /// + /// Acquires a new internal context of the appropriate type and notifies the scheduler when it is available. The scheduler can + /// choose what to do with said internal context. This creation happens in a deferred manner subject to throttling constraints. + /// + void DeferredGetInternalContext(); + + /// + /// Releases an internal context to the scheduler's idle pool. + /// + void ReleaseInternalContext(InternalContextBase *pContext, bool fUnbind = false); + + /// + /// Gets a realized chore from the idle pool, creating a new one if the idle pool is empty. + /// + RealizedChore *GetRealizedChore(TaskProc pFunction, void* pParameters); + + /// + /// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full. + /// + void ReleaseRealizedChore(RealizedChore *pChore); + + /// + /// References the anonymous schedule group, creating it if it doesn't exists, and returns a pointer to it. + /// + ScheduleGroupBase* GetAnonymousScheduleGroup() + { + return m_pAnonymousScheduleGroup; + } + + /// + /// References a segment in the anonymous schedule group and returns a pointer to it. + /// + /// + /// A segment in the anonymous schedule group. + /// + ScheduleGroupSegmentBase *GetAnonymousScheduleGroupSegment(); + + static SchedulerBase* CurrentScheduler(); + static SchedulerBase* FastCurrentScheduler(); + static SchedulerBase* SafeFastCurrentScheduler(); + static ContextBase* FastCurrentContext(); + static ContextBase* SafeFastCurrentContext(); + static ContextBase* CreateContextFromDefaultScheduler(); + static ContextBase* CurrentContext() + { + if ( !IsOneShotInitialized()) + return CreateContextFromDefaultScheduler(); + ContextBase *pContext = (ContextBase*) platform::__TlsGetValue(t_dwContextIndex); + if (pContext == NULL) + return CreateContextFromDefaultScheduler(); + return pContext; + } + + /// + /// Gets an IScheduler pointer for use in communication with the resource manager. + /// + virtual IScheduler* GetIScheduler() = 0; + + /// + /// Gets an IResourceManager pointer for use in communication with the resource manager. + /// + IResourceManager *GetResourceManager() const + { + return m_pResourceManager; + } + + /// + /// Gets an ISchedulerProxy pointer for use in communication with the resource manager. + /// + ISchedulerProxy *GetSchedulerProxy() const + { + return m_pSchedulerProxy; + } + + /// + /// Find an available virtual processor in the scheduler. + /// + bool FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket, + location bias = location(), + ULONG type = VirtualProcessor::AvailabilityAny); + + /// + /// Try to steal from foreign nodes. + /// + InternalContextBase *StealForeignLocalRunnableContext(SchedulingNode *pSkipNode); + + /// + /// Start up a virtual processor in the scheduler, if one is found. The virtual processor must have the specified availability + /// characteristics. + /// + bool StartupVirtualProcessor(ScheduleGroupSegmentBase *pSegment, + location bias = location(), + ULONG type = VirtualProcessor::AvailabilityAny); + + /// + /// Start up an idle virtual processor in the scheduler. This can be any virtual processor except one that is inactive due to + /// waiting for a thread creation. + /// + bool StartupIdleVirtualProcessor(ScheduleGroupSegmentBase *pSegment, location bias = location()) + { + // + // If the vproc is inactive pending thread -- there's no point in performing a general wake up. The general wake up will require an SFW + // context which will simply put it back to sleep and violate our concurrency constraints. Either an incoming runnable must push to the + // context or the throttler must wake it up. + // + return StartupVirtualProcessor(pSegment, bias, VirtualProcessor::AvailabilityAny & ~VirtualProcessor::AvailabilityInactivePendingThread); + } + + /// + /// Start up an new virtual processor in the scheduler. New virtual processor refers + /// to any vproc that either has never been activated or has been deactivated due to lack + /// of work (wait for work). + /// + virtual void StartupNewVirtualProcessor(ScheduleGroupSegmentBase *pSegment, location bias = location()) + { + StartupVirtualProcessor(pSegment, bias, (VirtualProcessor::AvailabilityType)(VirtualProcessor::AvailabilityIdle | VirtualProcessor::AvailabilityInactive)); + } + + /// + /// Attempts to push a runnable to an inactive virtual processor. If successful, true is returned. + /// + virtual bool PushRunnableToInactive(InternalContextBase *pRunnableContext, location bias = location()); + + /// + /// Called when a virtual processor becomes active (before it does) or becomes inactive (before it does). + /// + /// + /// True if a virtual processor is going from INACTIVE to ACTIVE, and false if it is going from ACTIVE to INACTIVE. + /// + /// + /// For activation, the function returns true if the virtual processor was successfully activated, and false + /// if it could not be activated because the scheduler was shutting down. For inactivation, it always returns true. + /// + bool VirtualProcessorActive(bool fActive); + + /// + /// Internal contexts and background threads call this when created and used inside the scheduler. + /// + void IncrementInternalContextCount(); + + /// + /// Internal contexts and background threads call this function in order to notify that they are about to exit. + /// The last caller will trigger scheduler finalization. + /// + void DecrementInternalContextCount(); + + /// + /// Returns the scheduling protocol policy element value this scheduler was created with. + /// + ::Concurrency::SchedulingProtocolType GetSchedulingProtocol() { return m_schedulingProtocol; } + + /// + /// Returns a pointer to the 'next' scheduling ring in a round-robin manner + /// + SchedulingRing *GetNextSchedulingRing(); + + // Specifying pOwningNode produces an order of scheduling rings, ordered by node distance. + // pCurrentNode is the current position in said order. + SchedulingRing *GetNextSchedulingRing(const SchedulingRing *pOwningRing, SchedulingRing *pCurrentRing); + + /// + /// Sets the 'next' scheduling ring in a round-robin manner + /// + void SetNextSchedulingRing(SchedulingRing *pRing); + + /// + /// Returns true if the scheduler has gone past a certain point in PhaseTwoShutdown (when it sets the shutdown completed flag). + /// This function is mainly used for debug asserts. + /// + bool HasCompletedShutdown(); + + /// + /// Returns true if the scheduler is in the finalization sweep, i.e, the SUSPEND_GATE_FLAG is set. + /// This function is mainly used for debug asserts. + /// + bool InFinalizationSweep(); + + /// + /// Internal contexts call the scheduler when they go idle for a specified amount of time in order to allow + /// things that happen on scheduler idle to happen (e.g.: sweeping for phase two shutdown). + /// They must also call the scheduler when they transition out of idle before executing a work item or performing + /// a context switch. This may halt scheduler shutdown or it may coordinate with scheduler shutdown depending on + /// the current phase of shutdown. + /// + /// This call *MUST* be made from a scheduler critical region. + /// + /// + /// Specifies whether the processor is going idle or non-idle. + /// + void VirtualProcessorIdle(bool fIdle); + + /// + /// Adds a new statistics class to track. + /// + /// + /// The statistics we are adding to the scheduler's ListArray for tracking. + /// + void AddExternalStatistics(ExternalStatistics * pStats) + { + m_externalThreadStatistics.Add(pStats); + } + + /// + /// Saves the statistical information from the retiring virtual processor. + /// + /// + /// The virtual processor that is retiring and whose statistics we are trying to preserve. + /// + /// + /// The reason we use interlocked operation here is because multiple virtual processors can + /// be retiring at the same time and the error can be much greater than on a simple increment. + /// + void SaveRetiredVirtualProcessorStatistics(VirtualProcessor * pVProc) + { + InterlockedExchangeAdd((volatile long *) &m_enqueuedTaskCounter, pVProc->GetEnqueuedTaskCount()); + InterlockedExchangeAdd((volatile long *) &m_dequeuedTaskCounter, pVProc->GetDequeuedTaskCount()); + } + + /// + /// Resets the count of work coming in. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetEnqueuedTaskCount() + { + ULONG currentValue = m_enqueuedTaskCounter; + unsigned int retVal = (unsigned int) (currentValue - m_enqueuedTaskCheckpoint); + + // Update the checkpoint value with the current value + m_enqueuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Resets the count of work being done. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetDequeuedTaskCount() + { + ULONG currentValue = m_dequeuedTaskCounter; + unsigned int retVal = (unsigned int) (currentValue - m_dequeuedTaskCheckpoint); + + // Update the checkpoint value with the current value + m_dequeuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Returns a suballocator from the pool of suballocators in the process, or creates a new one. The RM only allows + /// a fixed number of allocators for external contexts in the process, whereas every virtual processor that requests + /// an allocator will get one. + /// + /// + /// Specifies whether the allocator is being requested for an external context. If this is 'true' the RM will return + /// NULL if it has reached its limit of suballocators for external contexts. If this is 'false', the caller is requesting + /// the suballocator for a virtual processor, and the RM *must* allocate one (resources permitting). + /// + static SubAllocator* GetSubAllocator(bool fExternalAllocator); + + /// + /// Returns a suballocator back to the pool in the RM. The RM caches a fixed number of suballocators and will destroy the + /// rest. + /// + static void ReturnSubAllocator(SubAllocator* pAllocator); + + /// + /// Enqueues a context into m_allContexts + /// + void AddContext(InternalContextBase * pContext); + + /// + /// Returns the first scheduling node. + /// + /// + /// The iterator position of the returned scheduling node will be placed here. This can only be + /// utilized as the pIdx parameter or the idxStart parameter of a GetNextSchedulingNode. + /// + SchedulingNode *GetFirstSchedulingNode(int *pIdx) + { + *pIdx = 0; + return GetNextSchedulingNode(pIdx, -1); + } + + /// + /// Returns the next scheduling node in an iteration. + /// + SchedulingNode *GetNextSchedulingNode(int *pIdx, int idxStart = 0) + { + int base = *pIdx + (idxStart == -1 ? 0 : 1); + int size = m_nodeCount; + for (int i = 0; i < size; i++) + { + int index = (i + base) % size; + if (index == idxStart) + return NULL; + + SchedulingNode *pNode = m_nodes[index]; + if (pNode != NULL) + { + *pIdx = index; + return pNode; + } + } + + return NULL; + } + + /// + /// Performs a reference on one shot static items. The caller should CheckOneShotStaticDestruction to remove + /// the reference count. + /// + static LONG ReferenceStaticOneShot() + { + return InterlockedIncrement(&s_oneShotInitializationState); + } + + /// + /// Removes a previous reference on one shot static items. + /// + static LONG DereferenceStaticOneShot() + { + return InterlockedDecrement(&s_oneShotInitializationState); + } + + /// + /// Called at unload/process exit to perform cleanup of one-shot initialization items. + /// + static void CheckOneShotStaticDestruction(); + + /// + /// Called when a particular virtual processor reaches a safe point. This function does very little unless there has + /// been a change in the version number of the safe point. + /// + /// + /// The safe point marker for a given virtual processor. This is the virtual processor reaching a safe point. + /// + /// + /// An indication of whether a commit should take place. If this is true, the caller should call CommitSafePoints when possible. + /// Note that this is a return value so that things like UMS virtual processors can exit critical regions before performing + /// the commit (to avoid, for instance, heap locks in critical regions). + /// + bool MarkSafePoint(SafePointMarker *pMarker); + + /// + /// Called to make a determination of what version of data we can commit up to. This is the minimum data version that all virtual + /// processors have observed. + /// + void CommitSafePoints(); + + /// + /// The routine is used to trigger a safe point commit on all the vprocs by + /// updating the data version. + /// + void TriggerCommitSafePoints(SafePointMarker *pMarker); + + /// + /// Determines how long in milliseconds until the next set of threads is allowed to be created. + /// + ULONG ThrottlingTime(ULONG stepWidth); + + /// + /// Returns the delay before the next thread can be created. + /// + ULONG ThrottlingDelta() + { + ULONGLONG curTime = platform::__GetTickCount64(); + ULONG delta = (ULONG)(curTime - m_lastThrottledCreateTime); + + return delta; + } + + /// + /// Puts a timestamp on the last time a throttled thread was created. + /// + void StampThrottledCreate() + { + m_lastThrottledCreateTime = platform::__GetTickCount64(); + } + + /// + /// Returns whether a virtual processor is available. + /// + bool HasVirtualProcessorAvailable() const + { + return m_virtualProcessorAvailableCount > 0; + } + + /// + /// Returns whether a virtual processor is waiting for throttling. + /// + bool HasVirtualProcessorPendingThreadCreate() const + { + return m_virtualProcessorsPendingThreadCreate > 0; + } + + /// + /// Returns whether a virtual processor is available to execute new work. + /// + bool HasVirtualProcessorAvailableForNewWork() const + { + // + // The observational race (lack of atomicity between the two reads) should not matter. If it does in some obscure + // case, a new atomic counter can be added. + // + return (m_virtualProcessorAvailableCount - m_virtualProcessorsPendingThreadCreate) > 0; + } + + /// + /// Removes an unreferenced schedule group from the scheduler's list of groups. + /// + void RemoveScheduleGroup(ScheduleGroupBase *pGroup); + + /// + /// Returns the scheduling node associated with the calling thread, if any. This method only returns a node if the current + /// context is an internal context. + /// + SchedulingNode * FindCurrentNode(); + + /// + /// Returns the scheduling node which pSrcLocation is a member of. Note that if srcLocation and this node's location do not intersect, + /// this will return NULL. + /// + SchedulingNode * FindNodeByLocation(location* pSrcLocation); + + /// + /// Returns whether or not a location has a tight binding to an object on this scheduler. + /// + bool IsLocationBound(const location* pLoc) const + { + return (pLoc->_GetBindingId() == m_id); + } + + /// + /// Returns a bit set for a given location to perform quick masking. + /// + QuickBitSet GetBitSet(const location* pLoc); + + /// + /// Notifies the scheduler that a given virtual processor is listening for affinity events pertaining to its underlying + /// resource. Note that this is a reference counted API. + /// + /// + /// The mask id assigned for a given resource. + /// + void ListenAffinity(unsigned int maskId) + { + m_nonAffineResourceListeners.InterlockedSet(maskId); + OMTRACE(MTRACE_EVT_LISTENINGTRUE, this, NULL, NULL, maskId); + ClearQuickCacheSlot(maskId); + } + + /// + /// Notifies the scheduler that a given virtual processor is ignoring messages for affinity events pertaining to its underlying + /// resource. Note that this is a reference counted API. + /// + /// + /// The mask id assigned for a given resource. + /// + void IgnoreAffinity(unsigned int maskId) + { + m_nonAffineResourceListeners.InterlockedClear(maskId); + OMTRACE(MTRACE_EVT_LISTENINGFALSE, this, NULL, NULL, maskId); + } + + /// + /// Called when affine work comes into the scheduler, this posts any required notifications to virtual processors which are executing + /// non-affine work that they need to stop working on their current group and search for affine work again. + /// + void PostAffinityMessage(const QuickBitSet& srcMask) + { + if (srcMask.Intersects(m_nonAffineResourceListeners)) + { + OMTRACE(MTRACE_EVT_POSTAFFINITYMESSAGE, this, NULL, NULL, srcMask.DbgAcquireBits(0)); + m_affinityMessages.InterlockedSet(srcMask & m_nonAffineResourceListeners); + } + } + + /// + /// Returns whether a given resource id has a message for affinity and, if so, acknowledges it. + /// + bool AcknowledgedAffinityMessage(unsigned int maskId) + { + bool hasMessage = m_affinityMessages.IsSet(maskId); + if (hasMessage) + m_affinityMessages.InterlockedClear(maskId); + + return hasMessage; + } + + /// + /// Returns the mask id for a given resource id. + /// + unsigned int GetResourceMaskId(unsigned int resourceId) + { + unsigned int val; + Hash::ListNode *pNode = m_resourceBitMap.Find(resourceId, &val); + ASSERT(pNode != NULL); + return val; + } + + /// + /// Returns the number of mask ids associated with the scheduler. + /// + unsigned int GetMaskIdCount() const + { + return ::Concurrency::GetProcessorCount(); + } + + /// + /// Acquires the quick cache slot. + /// + ScheduleGroupSegmentBase *AcquireQuickCacheSlot(unsigned int maskId) + { + // + // Make **SURE** this is short, sweet, and inlines. + // + if (m_pCoreAffinityQuickCache[static_cast(maskId) << QUICKCACHEPAD_SHIFT] > reinterpret_cast(1)) + { + return ActualGetQuickCacheSlot(maskId); + } + + return NULL; + } + + /// + /// Clears the quick cache slot. + /// + void ClearQuickCacheSlot(unsigned int maskId) + { + if (m_pCoreAffinityQuickCache[static_cast(maskId) << QUICKCACHEPAD_SHIFT] == reinterpret_cast(1)) + { + InterlockedCompareExchangePointer(reinterpret_cast (m_pCoreAffinityQuickCache + (static_cast(maskId) << QUICKCACHEPAD_SHIFT)), + reinterpret_cast (NULL), + reinterpret_cast (1)); + } + } + + /// + /// Clears a given quick cache slot if the slot contains a specific value. + /// + void ClearQuickCacheSlotIf(unsigned int maskId, ScheduleGroupSegmentBase *pSegment) + { + if (m_pCoreAffinityQuickCache[static_cast(maskId) << QUICKCACHEPAD_SHIFT] == pSegment) + { + InterlockedCompareExchangePointer(reinterpret_cast (m_pCoreAffinityQuickCache + (static_cast(maskId) << QUICKCACHEPAD_SHIFT)), + reinterpret_cast (NULL), + reinterpret_cast (pSegment)); + } + } + + /// + /// Sets a given quick cache slot. Each execution resource (by mask id) gets a quick cache slot. When a work item arrives that is specifically + /// affinitized to a given execution resource, the segment containing that work item is stashed in the quick cache slot for the corresponding + /// execution resource. This is a fast check which is made repeatedly during search-for-work. This allows a virtual processor which is idle + /// searching for work or which is executing non-affine work to quickly snap back to an affine segment without the need for a search. This allows + /// more rapid virtual processor spin-up for certain affinity scenarios. + /// + void SetQuickCacheSlot(unsigned int maskId, ScheduleGroupSegmentBase *pSegment) + { + if (m_pCoreAffinityQuickCache[static_cast(maskId) << QUICKCACHEPAD_SHIFT] == NULL) + { + InterlockedCompareExchangePointer(reinterpret_cast (m_pCoreAffinityQuickCache + (static_cast(maskId) << QUICKCACHEPAD_SHIFT)), + reinterpret_cast (pSegment), + reinterpret_cast (NULL)); + } + } + + /// + /// Notifies the scheduler that a thread serving a virtual processor with the given mask id is actively searching for work. This + /// will prevent other virtual processors from picking up work which is affine to maskId but not affine to the other virtual processor. + /// + void NotifySearching(unsigned int maskId, bool fSearching) + { + if (fSearching) + { + m_idleSearch.InterlockedSet(maskId); + OMTRACE(MTRACE_EVT_SEARCHINGTRUE, this, NULL, NULL, maskId); + ClearQuickCacheSlot(maskId); + } + else + { + m_idleSearch.InterlockedClear(maskId); + OMTRACE(MTRACE_EVT_SEARCHINGFALSE, this, NULL, NULL, maskId); + + } + } + + /// + /// Returns whether or not any of the set of virtual processors represented by bitSet is searching for work. + /// + bool HasSearchers(const QuickBitSet& bitSet) const + { + return m_idleSearch.Intersects(bitSet); + } + + /// + /// Checks whether a periodic scan is necessary, and if so, performs it. + /// + void PeriodicScan(ULONGLONG serviceTime) + { + // + // Right now, we only perform livelock service scan every 2 seconds. + // + if (serviceTime - m_lastServiceScan > 2000) + PerformServiceScan(serviceTime); + } + + /// + /// Increments the count of active resources by a given resource's mask id. + /// + void IncrementActiveResourcesByMask(unsigned int maskId) + { + m_activeSet.InterlockedSet(maskId); + } + + /// + /// Decrements the count of active resources by a given resource's mask id. + /// + void DecrementActiveResourcesByMask(unsigned int maskId) + { + m_activeSet.InterlockedClear(maskId); + } + + //************************************************** + // + // TRANSITION: This is temporary until such time as we can hook into priority to solve livelock issues. + // + + bool HasPriorityObjects() const + { + return !m_priorityObjects.Empty(); + } + + BoostedObject *GetNextPriorityObject(); + + void RemovePrioritizedObject(BoostedObject *pEntry); + + // + // TRANSITION: End of temporary section + // + //************************************************** + + + protected: + + SchedulerPolicy m_policy; + + // scheduler policy fields + ::Concurrency::SchedulerType m_schedulerKind; + ::Concurrency::SchedulingProtocolType m_schedulingProtocol; + unsigned short m_localContextCacheSize; + + // The total number of virtual processors in the scheduler, not including oversubscribed virtual processors. + // This number is adjusted as dynamic RM adds and removes cores. + volatile LONG m_virtualProcessorCount{}; + + // The default scheduler + static SchedulerBase* s_pDefaultScheduler; + static _StaticLock s_defaultSchedulerLock; + + // The default scheduler policy + static SchedulerPolicy* s_pDefaultSchedulerPolicy; + + // TLS data + static DWORD t_dwContextIndex; + DWORD m_dwExternalStatisticsIndex; + + // + // NOTE: Must cleanup up m_nodes before m_rings + // + NumaInformation* m_numaInformation{}; + SchedulingNode** m_nodes{}; + SchedulingRing** m_rings{}; + int m_numaCount{}; + int m_nodeCount{}; + + // + // The active set of virtual processors on this scheduler. + // + ReferenceCountedQuickBitSet m_activeSet; + + // + // Tracking for virtual processors which need messages of notification for affine work scheduling, etc... + // + ReferenceCountedQuickBitSet m_idleSearch; + ReferenceCountedQuickBitSet m_nonAffineResourceListeners; + QuickBitSet m_affinityMessages; + + // + // Quick cache for core affine tasks. + // + ScheduleGroupSegmentBase* volatile * m_pCoreAffinityQuickCache{}; + + // The list of schedule groups within the scheduler. Note that while groups are owned by the scheduler, a group is merely + // a collection of segments where the individual segments are owned by scheduling rings. This allows groups with affinity applied + // as well as separation of work within a group by which node scheduled it. + ListArray m_scheduleGroups; + + // The single anonymous schedule group for the scheduler. The anonymous schedule group will have one segment per ring. + ScheduleGroupBase *m_pAnonymousScheduleGroup{}; + + // Lock free list of all internal contexts in the scheduler + LockFreePushStack m_allContexts; + + SafeRWList m_finalEvents; + + // A list array that keeps statistical information for all non-internal contexts + ListArray m_externalThreadStatistics; + + // Lock that guards the data structures for tracking context exit events. + _NonReentrantBlockingLock m_listArrayDeletionLock; + + /// + /// Activate the given virtual processor + /// + void ActivateVirtualProcessor(VirtualProcessor *pVirtualProcessor, ScheduleGroupBase *pGroup); + + /// + /// Returns a newly constructed internal context appropriate to the given type of scheduler. + /// + virtual InternalContextBase *CreateInternalContext() =0; + + /// + /// Increments the reference counts required by a scheduler attach. + /// + void ReferenceForAttach(); + + /// + /// Decrements the reference counts incremented for scheduler attach. + /// + void ReleaseForDetach(); + + /// + /// Returns a current number of active virtual processors for this scheduler + /// + /// + /// Returns a current number of active virtual processors for this scheduler. No error state. + /// + unsigned int GetNumberOfActiveVirtualProcessors() const { return m_activeVProcCount; }; + + /// + /// Notification after a virtual processor goes from INACTIVE to ACTIVE or ACTIVE to INACTIVE + /// + /// + /// True if a virtual processor is going from INACTIVE to ACTIVE, and false if it is going from ACTIVE to INACTIVE. + /// + /// + /// Active virtual processor count after the transition + /// + virtual void VirtualProcessorActiveNotification(bool fActive, LONG activeCount) + { + (fActive); (activeCount); + } + + /// + /// Indicates the type of work which exists within the scheduler. + /// + enum PendingWorkType + { + /// + /// No work exists within the scheduler. + /// + NoWork, + + /// + /// There is user work within the scheduler (chores, tasks, blocked contexts, etc...). There may or may not + /// be ancillary work. + /// + UserWork, + + /// + /// There is ancillary work related to the scheduler (e.g.: queued timers for throttling, etc...) + /// + OnlyAncillaryWork + }; + + /// + /// Determines if there is pending work such as blocked context/unstarted chores etc in the + /// scheduler. If there is no pending work, the scheduler will attempt to shutdown. + /// + virtual PendingWorkType TypeOfWorkPending(); + + /// + /// Initialize scheduler event handlers/background threads + /// + virtual void InitializeSchedulerEventHandlers(); + + /// + /// Destroy scheduler event handlers/background threads + /// + virtual void DestroySchedulerEventHandlers(); + + /// + /// Cancel all the internal contexts. + /// + virtual void CancelAllContexts(); + + /// + /// Returns the count of bound contexts on the scheduler. + /// + ULONG GetNumberOfBoundContexts() const + { + return (ULONG)m_boundContextCount; + } + + // Implementation for IScheduler interface APIs that is shared between to all derived classes. + + /// + /// Called by the resource manager in order to gather statistics for a given scheduler. The statistics gathered here + /// will be used to drive dynamic feedback with the scheduler to determine when it is appropriate to assign more resources + /// or take resources away. Note that these counts can be optimistic and do not necessarily have to reflect the current + /// count with 100% synchronized accuracy. + /// + /// + /// The number of tasks which have been completed by the scheduler since the last call to the Statistics method. + /// + /// + /// The number of tasks that have arrived in the scheduler since the last call to the Statistics method. + /// + /// + /// The total number of tasks in all scheduler queues. + /// + void Statistics(unsigned int *pTaskCompletionRate, unsigned int *pTaskArrivalRate, unsigned int *pNumberOfTasksEnqueued); + + /// + /// Called when the resource manager is giving virtual processors to a particular scheduler. The virtual processors are + /// identified by an array of IVirtualProcessorRoot interfaces. This call is made to grant virtual processor roots + /// at initial allocation during the course of ISchedulerProxy::RequestInitialVirtualProcessors, and during dynamic + /// core migration. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors being added to the scheduler. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + void AddVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count); + + /// + /// Called when the resource manager is taking away virtual processors from a particular scheduler. The scheduler should + /// mark the supplied virtual processors such that they are removed asynchronously and return immediately. Note that + /// the scheduler should make every attempt to remove the virtual processors as quickly as possible as the resource manager + /// will reaffinitize threads executing upon them to other resources. Delaying stopping the virtual processors may result + /// in unintentional oversubscription within the scheduler. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors which are to be removed. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + void RemoveVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count); + + /// + /// Invoked when the Gate Count goes to zero as a result of virtual processor state transitions, while the + /// scheduler has been marked for shutdown. It proceeds to sweep the scheduler if it can set the suspend flag + /// on the shutdown gate while the gate count is still 0 and the scheduler is marked for shutdown. + /// + void AttemptSchedulerSweep(); + + /// + /// Returns whether the reserved context pool can be utilized to fetch contexts to bypass throttling. + /// + virtual bool AllowGeneralFetchOfReservedContexts() + { + return true; + } + + private: + + friend class ContextBase; + friend class ::Concurrency::CurrentScheduler; + friend class ScheduleGroupBase; + friend class ScheduleGroupSegmentBase; + friend class FairScheduleGroup; + friend class CacheLocalScheduleGroup; + friend class InternalContextBase; + friend class ExternalContextBase; + friend class VirtualProcessor; + friend class SchedulingRing; + friend class SchedulingNode; + friend class SafePointInvocation; + + // + // TRANSITION: This is a temporary patch for livelock prevention until we can hook into priority. + // TRANSITION: This **MUST** have a hyper lock on it. + // + SafeRWList m_priorityObjects; + + // The list of invocations for safe point registrations. + SafeSQueue m_safePointInvocations; + + // Counter used to assign unique identifiers to contexts. + volatile LONG m_contextIdCounter; + + // Counter used to assign unique identifiers to schedule groups. + volatile LONG m_scheduleGroupIdCounter; + + // Counter used to assign unique identifiers to work queues. + static volatile LONG s_workQueueIdCounter; + + // The current safe point version for data. This indicates the newest data requiring observation by all virtual processors + volatile ULONG m_safePointDataVersion; + + // The current safe point commit version. This indicates the newest data that has been observed by all virtual processors + volatile ULONG m_safePointCommitVersion; + + // The pending version that is being committed by one of the vprocs. + volatile ULONG m_safePointPendingVersion; + + // Hash tables for conversion + Hash m_resourceNodeMap; + Hash m_resourceBitMap; + + // scheduler id + unsigned int m_id; + + // Round-robin index for scheduling ring. + unsigned int m_nextSchedulingRingIndex; + + // Handle to a semaphore used to synchronize during scheduler finalization. + HANDLE m_hSchedulerShutdownSync{}; + + // + // Reference counts: + // + // m_refCount -- The externally visible reference count on the scheduler. Incremented for attachment + // and for explicit calls to Reference. When this reference count falls to zero, the + // scheduler initiates shutdown. When m_internalContextCount falls to zero, the + // scheduler finalizes. + // + // m_attachCount -- The count of external contexts to which this scheduler is attached. This is primarily + // present for debugging purposes. + // + // m_internalContextCountPlusOne -- The count of internal contexts on the scheduler plus one. Note that + // it's +1 to explicitly handle any possibility of scheduler shutdown + // before internal contexts are created. + // + // m_boundContextCount -- The count of internal contexts which are currently bound. This affects how the scheduler + // throttles thread creation. + // + volatile LONG m_refCount; + volatile LONG m_attachCount; + volatile LONG m_internalContextCountPlusOne; + volatile LONG m_initialReference; + volatile LONG m_boundContextCount; + + // + // The virtual processor shutdown gate. This is used to implement scheduler shutdown, by ensuring a handshake + // when all virtual processors go idle. When such happens, no virtual processor may go active again without + // handshaking. During the period between handshakes, the scheduler is free to sweep schedule groups + // to detect whether finalization is yet appropriate. + // + // Layout: + // 31 - SHUTDOWN_INITIATED_FLAG -- indicates that the external reference count on the scheduler has fallen to zero, + // and the scheduler should be able to finalize when all work queued to it has + // completed. This flag may be reset at a later point if an internal context + // ends up resurrecting the scheduler. + // 30 - SUSPEND_GATE_FLAG -- indicates a suspend phase while the scheduler is trying to evaluate whether + // it is ready to finalize. A scheduler may find blocked contexts during this + // phase and back off from finalization, resetting the flag. No contexts are allowed + // to execute work during this phase, and no new virtual processors may be added + // to the scheduler while this bit is set. + // 29 - SHUTDOWN_COMPLETED_FLAG -- indicates that the scheduler has completed shutdown. This is the point of no + // return, for this scheduler. At this point no work should exist in the scheduler, + // and attempts to add any new virtual processors will fail, since the scheduler + // is about to be destroyed. + // + volatile LONG m_vprocShutdownGate; + + // An indication of whether we have done a sweep without actual work. + volatile LONG m_fSweepWithoutActualWork; + + // An indication of how long it has been since the last sweep for livelocked segments. + volatile ULONGLONG m_lastServiceScan; + + static _StaticLock s_schedulerLock; + static LONG s_initializedCount; + + // + // The one shot initialization state has two parts, a reference count occupying the lower 31 bits and a flag indicating whether + // one shot initialization was performed in the top bit. + // + static LONG s_oneShotInitializationState; + + IResourceManager *m_pResourceManager; + ISchedulerProxy *m_pSchedulerProxy{}; + + // The count of virtual processors active in the scheduler. + volatile LONG m_activeVProcCount; + + // The number of virtual processors available to schedule more work. + // This does *NOT* take into account those virtual processors which are *inactive pending thread* + volatile LONG m_virtualProcessorAvailableCount{}; + + // The number of virtual processors available pending a thread creation. + volatile LONG m_virtualProcessorsPendingThreadCreate; + + // Statistics data counters + volatile ULONG m_enqueuedTaskCounter; + volatile ULONG m_dequeuedTaskCounter; + + // Statistics data checkpoints + ULONG m_enqueuedTaskCheckpoint; + ULONG m_dequeuedTaskCheckpoint; + + // + // Throttling information: + // + ULONG m_threadsBeforeThrottling; + ULONGLONG m_lastThrottledCreateTime; + + HANDLE m_hThrottlingTimer; + volatile LONG m_pendingDeferredCreates; + + // Free list of internal contexts. + LockFreeStack m_internalContextPool; + + // Free list of external contexts. + LockFreeStack m_externalContextPool; + + // Free list of realized chores. + LockFreeStack m_realizedChorePool; + + // List of reserved contexts + LockFreeStack m_reservedContexts; + + // A stack that holds free suballocators. + static LockFreeStack s_subAllocatorFreePool; + + // Number of suballocators for use by external contexts that are active in the process. + static volatile LONG s_numExternalAllocators; + + // The max number of external contexts that could have suballocators at any given time. + static const int s_maxExternalAllocators; + + // The maximum depth of the free pool of allocators. + static const int s_allocatorFreePoolLimit; + + static void CheckStaticConstruction(); + static void StaticConstruction(); + static void StaticDestruction(); + static void OneShotStaticConstruction(); + static void OneShotStaticDestruction(); + + void Initialize(); + void Cleanup(); + + int GetValidSchedulingRingIndex(int idx); + int GetNextValidSchedulingRingIndex(int idx); + + /// + /// Creates the correct type of virtual processor. + /// + virtual VirtualProcessor *CreateVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot) = 0; + + /// + /// Creates an external context and attaches it to the calling thread. Called when a thread attaches to a scheduler. + /// + ExternalContextBase *AttachExternalContext(bool explicitAttach); + + /// + /// Detaches an external context from the scheduler it is attached to. Called when an external context actively detaches + /// from a scheduler, or when the underlying thread for an implicitly attached external context exits. + /// + /// + /// The external context being detached. + /// + /// + /// Whether this was the result of an explicit detach or the thread exiting. + /// + void DetachExternalContext(ExternalContextBase* pContext, bool explicitDetach); + + /// + /// Gets an external context from the idle pool, creating a new one if the idle pool is empty. + /// + ExternalContextBase *GetExternalContext(bool explicitAttach); + + /// + /// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full. + /// + void ReleaseExternalContext(ExternalContextBase *pContext); + + /// + /// Increments the reference count to the scheduler but does not allow a 0 to 1 transition. This API should + /// be used to safely access a scheduler when the scheduler is not 'owned' by the caller. + /// + /// + /// True if the scheduler was referenced, false, if the reference count was 0. + /// + bool SafeReference(); + + /// + /// Returns the default scheduler creating one if it doesn't exist. + /// + /// + /// A pointer to the default scheduler + /// + static SchedulerBase* GetDefaultScheduler(); + + // + // Finalization: + // + + /// + /// Called to initiate shutdown of the scheduler. This may directly proceed to phase two of shutdown (actively + /// shutting down internal contexts) or it may wait for additional events (e.g.: all work to complete) before + /// proceeding to phase two. + /// + void PhaseOneShutdown(); + + /// + /// Actively informs all internal contexts to exit and breaks them out of their dispatch loops. When the last + /// internal context dies, finalization will occur and we move to SchedulerBase::Finalize(). + /// + void PhaseTwoShutdown(); + + /// + /// Performs finalization of the scheduler deleting all structures, etc... This will also notify any listeners + /// that the scheduler has actively shut down. + /// + void Finalize(); + + /// + /// Once all virtual processors are idle, the scheduler calls this routine which performs a full sweep through all + /// schedule groups looking for work. If work is found (even a blocked context), the scheduler backs off finalization; + /// otherwise, it proceeds by asking all virtual processors for final check-in. + /// + void SweepSchedulerForFinalize(); + + /// + /// Releases virtual processors that were suspended on the shutdown gate, while trying to go from IDLE to + /// ACTIVE when the finalization sweep was in progress. + /// + /// + /// Number of virtual processors that need to be released. + /// + void ReleaseSuspendedVirtualProcessors(LONG releaseCount); + + /// + /// Called during scheduler finalization, after all virtual processors are suspended to check if any chores still + /// exist in the scheduler. The calling thread is the only thread active in the scheduler at the time the function + /// is called. + /// + /// + /// A boolean value indicating whether any unstarted chores (realized or unrealized) were found. + /// + bool FoundUnstartedChores(); + + /// + /// Called during scheduler finalization, before all virtual processors are suspended to check if any blocked + /// contexts exist in the scheduler. + /// + /// + /// A boolean value indicating whether any blocked contexts were found. + /// + bool FoundBlockedContexts(); + + /// + /// Called to perform a resurrection of the scheduler. When the scheduler reference count has fallen to zero, + /// it's possible there's still work on the scheduler and that one of those work items will perform an action + /// leading to additional reference. Such bringing of the reference count from zero to non-zero is only legal + /// on an *INTERNAL* context and immediately halts shutdown. + /// + void Resurrect(); + + /// + /// Called to perform a commit of safe-point registrations up to **AND INCLUDING** a particular version. + /// + /// + /// The data version that we commit to. A version of zero indicates a full commit. + /// + void CommitToVersion(ULONG commitVersion); + + /// + /// Returns the commit version for safe points within the scheduler. + /// + ULONG ComputeSafePointCommitVersion(); + + /// + /// Updates and returns the pending version for safe point commits. + /// If there are no commits pending, 0 is returned. + /// + ULONG UpdatePendingVersion(); + + /// + /// Updates the commit version to the given version and returns + /// the pending commit version. If there are no commits pending, 0 is returned. + /// + /// + /// The version up to which safe points have been committed. + /// + ULONG UpdateCommitVersion(ULONG commitVersion); + + /// + /// Returns whether a particular version number is visible to us yet. Versions at the wrap-around point + /// are not visible until we commit the wrap. + /// + bool IsVisibleVersion(ULONG version) + { + return (version >= m_safePointCommitVersion); + } + + /// + /// Returns the version we are allowed to see from an observation. This handles wrap around. + /// + ULONG ObservedVersion(ULONG version) + { + return (IsVisibleVersion(version) ? version : ULONG_MAX); + } + + /// + /// Publishes a new data version and returns the version number. + /// + ULONG PublishNewDataVersion() + { + ULONG dataVersion = InterlockedIncrement(reinterpret_cast(&m_safePointDataVersion)); + + // + // Zero and ULONG_MAX are special keys used to handle wrap-around in the version counters. The commit counter may never be either of these values due + // to a data version being them. + // + while (dataVersion == 0 || dataVersion == ULONG_MAX) + dataVersion = InterlockedIncrement(reinterpret_cast(&m_safePointDataVersion)); + + return dataVersion; + } + + /// + /// Registers a callback at the next safe point after this function call. This should never be directly used by clients. + /// SafePointInvocation::Register(...) should be used instead. + /// + /// + /// The invocation object which is being registered. + /// + void InvokeOnSafePoint(SafePointInvocation *pInvocation); + + /// + /// Send a scheduler ETW event + /// + void TraceSchedulerEvent(ConcRT_EventType eventType, UCHAR level, unsigned int schedulerId) + { + if (g_TraceInfo._IsEnabled(level, SchedulerEventFlag)) + ThrowSchedulerEvent(eventType, level, schedulerId); + } + + /// + /// Changes the due time for dispatching new threads + /// + void ChangeThrottlingTimer(ULONG dueTime); + + /// + /// Acts as a trampoline between the event wait and the timer wait as we cannot queue the timer in DeferredGetInternalContext + /// due to limitations on what Win32 APIs can be called from a UMS primary. + /// + static void CALLBACK ThrottlerTrampoline(PVOID pData, BOOLEAN waitOrTimerFired); + + /// + /// Creates new contexts. + /// + void ThrottlerDispatch(); + + /// + /// Called to notify the scheduler that a context is available from the throttling manager / background creation. + /// + /// + /// An indication of whether a virtual processor was awoken due to the context being utilized. + /// + bool NotifyThrottledContext(InternalContextBase *pContext); + + /// + /// Create a schedule group within this scheduler. + /// + /// + /// A pointer to a location where tasks within the schedule group will be biased towards executing at. + /// + /// + /// A pointer to a newly created schedule group. + /// + ScheduleGroup* InternalCreateScheduleGroup(location* pPlacement); + + /// + /// Internal claim of a quick cache slot. + /// + ScheduleGroupSegmentBase *ActualGetQuickCacheSlot(unsigned int maskId) + { + ScheduleGroupSegmentBase *pSegment = m_pCoreAffinityQuickCache[static_cast(maskId) << QUICKCACHEPAD_SHIFT]; + + if (pSegment > reinterpret_cast(1)) + { + ScheduleGroupSegmentBase *pXchgSegment = reinterpret_cast ( + InterlockedCompareExchangePointer(reinterpret_cast (m_pCoreAffinityQuickCache + (static_cast(maskId) << QUICKCACHEPAD_SHIFT)), + reinterpret_cast (1), + reinterpret_cast (pSegment)) + ); + + if (pSegment == pXchgSegment) + return pSegment; + } + + return NULL; + } + + /// + /// Performs the scheduler service scan. + /// + void PerformServiceScan(ULONGLONG serviceTime); + + /// + /// A simple bridge to ThrottlerDispatch. This bridge is used for Vista and up (except MSDK) + /// + static void CALLBACK ThrottlerDispatchBridge(PTP_CALLBACK_INSTANCE, void * pContext, PTP_TIMER) + { + ThrottlerDispatchBridgeXP(pContext, true); + } + + /// + /// A simple bridge to ThrottlerDispatch. This bridge is used for XP and MSDK + /// + static void CALLBACK ThrottlerDispatchBridgeXP(PVOID pScheduler, BOOLEAN) + { + reinterpret_cast(pScheduler)->ThrottlerDispatch(); + } + + static void ThrowSchedulerEvent(ConcRT_EventType eventType, UCHAR level, unsigned int schedulerId); + + // Hide assignment operator and copy constructor + SchedulerBase const &operator =(SchedulerBase const &); + SchedulerBase(SchedulerBase const &); + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerPolicyBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerPolicyBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32a05a84891a281696d39a7944e654165c4d151b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerPolicyBase.cpp @@ -0,0 +1,437 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulerPolicyBase.cpp +// +// Scheduler policy implementation +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Internal list of scheduler policy defaults. + /// + const unsigned int PolicyDefaults[] = + { + ::Concurrency::ThreadScheduler, // SchedulerKind + MaxExecutionResources, // MaxConcurrency + 1, // MinConcurrency + 1, // TargetOversubscriptionFactor + 8, // LocalContextCacheSize + 0, // ContextStackSize + THREAD_PRIORITY_NORMAL, // ContextPriority + EnhanceScheduleGroupLocality, // SchedulingProtocol + ProgressFeedbackEnabled, // DynamicProgressFeedback + InitializeWinRTAsMTA, // WinRTInitialization + }; + + /// + /// Internal map from policy keys to descriptive strings. + /// + const char* const PolicyElementKeyStrings[] = + { + "SchedulerKind", + "MaxConcurrency", + "MinConcurrency", + "TargetOversubscriptionFactor", + "LocalContextCacheSize", + "ContextStackSize", + "ContextPriority", + "SchedulingProtocol", + "DynamicProgressFeedback", + "WinRTInitialization", + "MaxPolicyElementKey" + }; +} + + /// + /// Creates a new default scheduler policy. + /// + SchedulerPolicy::SchedulerPolicy() + { + _Initialize(0, NULL); + } + + /// + /// Creates a new scheduler policy that uses a named-parameter style of initialization. Unnamed parameters take defaults described above. + /// + SchedulerPolicy::SchedulerPolicy(size_t _PolicyKeyCount, ...) + { + va_list args; + va_start(args, _PolicyKeyCount); + _Initialize(_PolicyKeyCount, &args); + } + + /// + /// Initializes the scheduler policy. + /// + void SchedulerPolicy::_Initialize(size_t _PolicyKeyCount, va_list *_PArgs) + { + size_t bagSize = sizeof(unsigned int) * Concurrency::MaxPolicyElementKey; + _PolicyBag *pPolicyBag = _concrt_new _PolicyBag; + _M_pPolicyBag = pPolicyBag; + + try + { + memcpy(pPolicyBag->_M_values._M_pPolicyBag, PolicyDefaults, bagSize); + + for (size_t i = 0; i < _PolicyKeyCount; i++) + { + PolicyElementKey key = va_arg(*_PArgs, PolicyElementKey); + unsigned int value = va_arg(*_PArgs, unsigned int); + + if ( !_ValidPolicyKey(key)) + throw invalid_scheduler_policy_key(_StringFromPolicyKey(key)); + + if ( !_ValidPolicyValue(key, value)) + throw invalid_scheduler_policy_value(_StringFromPolicyKey(key)); + + pPolicyBag->_M_values._M_pPolicyBag[key] = value; + } + + if (!_AreConcurrencyLimitsValid()) + { + throw invalid_scheduler_policy_thread_specification(); + } + + if (!_ArePolicyCombinationsValid()) + { + throw invalid_scheduler_policy_value(); + } + + _ResolvePolicyValues(); + + } + catch (...) + { + delete pPolicyBag; + throw; + } + } + + /// + /// The most convenient way to define a new scheduler policy is to copy + /// an existing policy and modify it. The copy constructor is also needed + /// for all the usual reasons. + /// + SchedulerPolicy::SchedulerPolicy(const SchedulerPolicy &srcPolicy) + { + _M_pPolicyBag = _concrt_new _PolicyBag; + _Assign(srcPolicy); + } + + /// + /// The most convenient way to define a new scheduler policy is to copy + /// an existing policy and modify it. The copy constructor is also needed + /// for all the usual reasons. + /// + SchedulerPolicy& SchedulerPolicy::operator=(const SchedulerPolicy &rhsPolicy) + { + _Assign(rhsPolicy); + return *this; + } + + /// + /// Make this policy a copy of the source policy. + /// + void SchedulerPolicy::_Assign(const SchedulerPolicy &rhsPolicy) + { + size_t bagSize = sizeof(unsigned int) * Concurrency::MaxPolicyElementKey; + memcpy(_M_pPolicyBag->_M_values._M_pPolicyBag, rhsPolicy._M_pPolicyBag->_M_values._M_pPolicyBag, bagSize); + } + + /// + /// Destroys a scheduler policy. + /// + SchedulerPolicy::~SchedulerPolicy() + { + delete _M_pPolicyBag; + } + + /// + /// Retrieve the value of the supplied policy key. + /// + /// + /// [in] The policy key. + /// + /// + /// The policy key value for the key, if is a supported key. + /// + /// + /// The function will throw "invalid_scheduler_policy_key" for any key that is not supported. + /// + unsigned int SchedulerPolicy::GetPolicyValue(PolicyElementKey key) const + { + if (!_ValidPolicyKey(key)) + { + throw invalid_scheduler_policy_key(_StringFromPolicyKey(key)); + } + + return _M_pPolicyBag->_M_values._M_pPolicyBag[key]; + } + + /// + /// Set the value of the supplied policy key and return the old value. + /// + /// + /// [in] The policy key. + /// + /// + /// [in] The value for the policy key. + /// + /// + /// The old policy key value for the key, if is a supported key. + /// + /// + /// The function will throw "invalid_scheduler_policy_key" for any key that is not supported, + /// and "invalid_scheduler_policy_value" for a value that is not supported for a valid key. + /// + unsigned int SchedulerPolicy::SetPolicyValue(PolicyElementKey key, unsigned int value) + { + if (!_ValidPolicyKey(key) + || key == ::Concurrency::MinConcurrency + || key == ::Concurrency::MaxConcurrency) + { + throw invalid_scheduler_policy_key(_StringFromPolicyKey(key)); + } + + if (!_ValidPolicyValue(key, value)) + { + throw invalid_scheduler_policy_value(_StringFromPolicyKey(key)); + } + + unsigned int oldValue = GetPolicyValue(key); + _M_pPolicyBag->_M_values._M_pPolicyBag[key] = value; + + _ResolvePolicyValues(); + return oldValue; + } + + /// + /// Set the value of the supplied policy key and return the old value. + /// + /// + /// The value for MinConcurrency. + /// + /// + /// The value for MaxConcurrency. + /// + /// + /// The function will throw "invalid_scheduler_policy_value" if: + /// _MaxConcurrency != MaxExecutionResources && _MinConcurrency > _MaxConcurrency + /// + void SchedulerPolicy::SetConcurrencyLimits(unsigned int _MinConcurrency, unsigned int _MaxConcurrency) + { + if (!_ValidPolicyValue(::Concurrency::MaxConcurrency, _MaxConcurrency)) + throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MaxConcurrency)); + + if (!_ValidPolicyValue(::Concurrency::MinConcurrency, _MinConcurrency)) + throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MinConcurrency)); + + if (!_AreConcurrencyLimitsValid(_MinConcurrency, _MaxConcurrency)) + throw invalid_scheduler_policy_thread_specification(); + + if (!_ArePolicyCombinationsValid()) + throw invalid_scheduler_policy_value(); + + _M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::MaxConcurrency] = _MaxConcurrency; + _M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::MinConcurrency] = _MinConcurrency; + + _ResolvePolicyValues(); + } + + /// + /// Resolves some of the policy keys that are set to defaults, based on the characteristics of the underlying system. + /// + void SchedulerPolicy::_ResolvePolicyValues() + { + // Resolve the SchedulerKind policy key value. + _M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::SchedulerKind] = ::Concurrency::ThreadScheduler; + + // Resolve MinConcurrency and MaxConcurrency, if either of them are set to the special value MaxExecutionResources. + unsigned int coreCount = ::Concurrency::GetProcessorCount(); + ASSERT((coreCount > 0) && (coreCount <= INT_MAX)); + + if (_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] == MaxExecutionResources) + { + if (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] == MaxExecutionResources) + { + // [1] Both the keys are set to MaxExecutionResources. + _M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] = _M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] = coreCount; + } + else + { + // [2] MinConcurrency is set to MaxExecutionResources. + _M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] = (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] < coreCount) ? + _M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] : coreCount; + } + } + else if (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] == MaxExecutionResources) + { + // [3] MaxConcurrency is set to MaxExecutionResources. + _M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] = (_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] > coreCount) ? + _M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] : coreCount; + } + + ASSERT(_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] >= _M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency]); + } + + + const char* SchedulerPolicy::_StringFromPolicyKey(unsigned int index) + { + if (index > ::Concurrency::MaxPolicyElementKey) + index = ::Concurrency::MaxPolicyElementKey; + + return PolicyElementKeyStrings[index]; + } + + bool SchedulerPolicy::_ValidPolicyKey(PolicyElementKey key) + { + return (key >= SchedulerKind && key < MaxPolicyElementKey); + } + + bool SchedulerPolicy::_ValidPolicyValue(PolicyElementKey key, unsigned int value) + { + bool valid = true; + + switch (key) + { + case ::Concurrency::SchedulerKind: + if ( value != ::Concurrency::ThreadScheduler ) + { + valid = false; + } + break; + case ::Concurrency::ContextPriority: + { + int priority = (int)value; + // + // The win32 api accepts values [-7, 7), 15 and -15 for threads other than the current thread. + // In addition, we define a special value INHERIT_THREAD_PRIORITY, whereby the internal contexts + // inherit the priority of the thread creating the scheduler + // + if ( !(priority >= -7 && priority < 7 + || priority == 15 + || priority == -15 + || priority == INHERIT_THREAD_PRIORITY)) + { + valid = false; + } + } + break; + case ::Concurrency::SchedulingProtocol: + if ( !(value == ::Concurrency::EnhanceScheduleGroupLocality + || value == ::Concurrency::EnhanceForwardProgress)) + { + valid = false; + } + break; + case ::Concurrency::MaxConcurrency: + if ( !((value > 0 && value <= INT_MAX) || value == MaxExecutionResources)) + { + valid = false; + } + break; + case ::Concurrency::MinConcurrency: + if ( !((value <= INT_MAX) || value == MaxExecutionResources)) + { + valid = false; + } + break; + case ::Concurrency::LocalContextCacheSize: + case ::Concurrency::ContextStackSize: + if ( !(value <= INT_MAX)) + { + valid = false; + } + break; + case ::Concurrency::TargetOversubscriptionFactor: + if ( !(value > 0 && value <= INT_MAX)) + { + valid = false; + } + break; + + case ::Concurrency::DynamicProgressFeedback: + if ( !(value == ::Concurrency::ProgressFeedbackEnabled || value == ::Concurrency::ProgressFeedbackDisabled)) + { + valid = false; + } + break; + + case ::Concurrency::WinRTInitialization: + if ( !(value == ::Concurrency::InitializeWinRTAsMTA || value == ::Concurrency::DoNotInitializeWinRT)) + { + valid = false; + } + break; + + case ::Concurrency::MaxPolicyElementKey: + default: + terminate(); + } + + return valid; + } + + void SchedulerPolicy::_ValidateConcRTPolicy() const + { + unsigned int minConcurrency = GetPolicyValue(::Concurrency::MinConcurrency); + if (minConcurrency == 0) + { + throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MinConcurrency)); + } + + ::Concurrency::DynamicProgressFeedbackType dynamicProgress = + (::Concurrency::DynamicProgressFeedbackType) GetPolicyValue(::Concurrency::DynamicProgressFeedback); + + if (dynamicProgress == ProgressFeedbackDisabled) + { + throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::DynamicProgressFeedback)); + } + } + + /// + /// Test a policy's concurrency limits. + /// + bool SchedulerPolicy::_AreConcurrencyLimitsValid(unsigned int _MinConcurrency, unsigned int _MaxConcurrency) + { + // For concurrency limits that are != MaxExecutionResource, plug into the equation: _MinConcurrency <= _MaxConcurrency, + // and return false, if it does not hold. + + // Validate Max + if ((_MaxConcurrency != MaxExecutionResources) + && (_MinConcurrency != MaxExecutionResources) && (_MaxConcurrency < _MinConcurrency)) + { + return false; + } + + return true; + } + + /// + /// Test a policy's concurrency limits. + /// + bool SchedulerPolicy::_AreConcurrencyLimitsValid() const + { + return _AreConcurrencyLimitsValid(GetPolicyValue(::Concurrency::MinConcurrency), + GetPolicyValue(::Concurrency::MaxConcurrency)); + } + + /// + /// Test a policy's concurrency limits. + /// + bool SchedulerPolicy::_ArePolicyCombinationsValid() const + { + return true; + } +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49ffba1b3b00cd0b61e9cb9fa51bb82d743f9a86 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.cpp @@ -0,0 +1,1237 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulerProxy.cpp +// +// RM proxy for a scheduler instance +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ +#pragma warning (push) +#pragma warning (disable : 4702) + /// + /// Constructs a scheduler proxy. + /// + SchedulerProxy::SchedulerProxy(IScheduler * pScheduler, ResourceManager * pResourceManager, const SchedulerPolicy &policy) + : m_pThreadProxyFactory(nullptr) + , m_pResourceManager(pResourceManager) + , m_pHillClimbing(nullptr) + , m_staticData{} + , m_queueLength(0) + , m_currentConcurrency(0) + , m_numAllocatedCores(0) + , m_numBorrowedCores(0) + , m_numFixedCores(0) + , m_numAssignedThreads(0) + , m_numExternalThreads(0) + , m_numExternalThreadCores(0) + { + ASSERT(pScheduler != NULL); + + m_pScheduler = pScheduler; + + m_maxConcurrency = policy.GetPolicyValue(::Concurrency::MaxConcurrency); + m_minConcurrency = policy.GetPolicyValue(::Concurrency::MinConcurrency); + m_targetOversubscriptionFactor = policy.GetPolicyValue(::Concurrency::TargetOversubscriptionFactor); + m_contextStackSize = policy.GetPolicyValue(::Concurrency::ContextStackSize); + m_contextPriority = policy.GetPolicyValue(::Concurrency::ContextPriority); + m_fDoHillClimbing = policy.GetPolicyValue(::Concurrency::DynamicProgressFeedback) == ::Concurrency::ProgressFeedbackEnabled; + + if (m_contextPriority == INHERIT_THREAD_PRIORITY) + { + m_contextPriority = (char) platform::__GetThreadPriority(GetCurrentThread()); + } + + m_id = m_pScheduler->GetId(); + ASSERT(m_id != -1); + + unsigned int coreCount = m_pResourceManager->GetCoreCount(); + + m_coreCount = coreCount; + + ASSERT(coreCount > 0 && coreCount <= INT_MAX); + ASSERT(m_maxConcurrency > 0 && m_maxConcurrency >= m_minConcurrency); + + unsigned int originalTof = m_targetOversubscriptionFactor; + + // Find the minimum target oversubscription factor required to satisfy MaxConcurrency with the cores available. + unsigned int minTof = (m_maxConcurrency + coreCount - 1)/coreCount; + + if (originalTof < minTof) + { + // Adjust target oversubscription factor to ensure that we can satisfy MaxConcurrency with the cores on the system. + m_targetOversubscriptionFactor = minTof; + // The scheduler needs all the cores on the machine to satisfy max threads. Moreover we will need to oversubscribe + // more than the user indicated. + m_desiredHardwareThreads = coreCount; + } + else + { + m_desiredHardwareThreads = (m_maxConcurrency + originalTof - 1)/originalTof; + } + + // Now adjust target oversubscription factor to ensure that MaxConcurrency virtual processors are evenly distributed + // over the desired number of hardware threads (i.e each core gets either m_tof vprocs or m_tof - 1 vprocs). Also + // calculate how many of the assigned cores will get m_tof vprocs. + if ((m_maxConcurrency % m_desiredHardwareThreads) == 0) + { + // This is the common case. We have a simple distribution and every allocated core will get tof vprocs. + m_targetOversubscriptionFactor = m_maxConcurrency/m_desiredHardwareThreads; + m_numFullySubscribedCores = m_desiredHardwareThreads; + m_minimumHardwareThreads = (m_minConcurrency + m_targetOversubscriptionFactor - 1)/m_targetOversubscriptionFactor; + } + else + { + // We have an uneven distribution; some cores will get tof vprocs and some will get tof - 1. + ASSERT(m_targetOversubscriptionFactor > 1); + + m_targetOversubscriptionFactor = (m_maxConcurrency + m_desiredHardwareThreads - 1)/m_desiredHardwareThreads; + m_numFullySubscribedCores = m_desiredHardwareThreads - ((m_desiredHardwareThreads * m_targetOversubscriptionFactor) - m_maxConcurrency); + + // Calculate min hardware threads. We need to make sure that given the way vprocs are distributed to cores + // (where some cores could get tof vprocs and some could get tof - 1 vprocs), the scheduler proxy will never go below + // min concurrency if it is left with just the minimum number of cores (and all of those cores happen to have tof -1 + // vprocs assigned to them). + if (((m_desiredHardwareThreads - m_numFullySubscribedCores) * (m_targetOversubscriptionFactor - 1)) >= m_minConcurrency) + { + m_minimumHardwareThreads = (m_minConcurrency + m_targetOversubscriptionFactor - 2)/(m_targetOversubscriptionFactor - 1); + } + else + { + m_minimumHardwareThreads = (m_desiredHardwareThreads - m_numFullySubscribedCores); + + unsigned int remainingThreads = (m_minConcurrency - (m_minimumHardwareThreads * (m_targetOversubscriptionFactor - 1))); + ASSERT(remainingThreads < m_minConcurrency); + m_minimumHardwareThreads += (remainingThreads + m_targetOversubscriptionFactor - 1)/m_targetOversubscriptionFactor; + } + } + + ASSERT(m_maxConcurrency <= m_targetOversubscriptionFactor * m_desiredHardwareThreads); + ASSERT(m_numFullySubscribedCores <= m_desiredHardwareThreads); + ASSERT(m_targetOversubscriptionFactor > 1 || m_numFullySubscribedCores == m_desiredHardwareThreads); + + ASSERT(m_targetOversubscriptionFactor > 0 && m_targetOversubscriptionFactor <= INT_MAX); + ASSERT(m_desiredHardwareThreads > 0 && m_desiredHardwareThreads <= coreCount); + ASSERT(m_desiredHardwareThreads > 0 && m_minimumHardwareThreads <= m_desiredHardwareThreads); + + // Hold a reference to the resource manager. + int ref = m_pResourceManager->Reference(); + (ref); + CONCRT_COREASSERT(ref > 1); + + if (m_fDoHillClimbing) + { + m_pHillClimbing = _concrt_new HillClimbing(m_id, coreCount, this); + } + + m_nodeCount = GetProcessorNodeCount(); + // The allocated nodes structure is created when the first allocation is made for this scheduler proxy. We need to read global core + // state during this allocation, and therefore we need to perform it while holding the RM lock. + m_pAllocatedNodes = NULL; + + m_pSortedNodeOrder = _concrt_new unsigned int[m_nodeCount]; + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + m_pSortedNodeOrder[i] = i; + } + +#if defined(CONCRT_TRACING) + m_drmInitialState = NULL; +#endif + } +#pragma warning (pop) + + /// + /// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request + /// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request + /// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to + /// IScheduler::AddVirtualProcessors. + /// + /// + /// Whether to subscribe the current thread and account for it during resource allocation. + /// + /// + /// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise. + /// + IExecutionResource * SchedulerProxy::RequestInitialVirtualProcessors(bool doSubscribeCurrentThread) + { + return m_pResourceManager->RequestInitialVirtualProcessors(this, doSubscribeCurrentThread); + } + + /// + /// Called in order to notify the resource manager that the given scheduler is shutting down. This + /// will cause the resource manager to immediately reclaim all resources granted to the scheduler. + /// + void SchedulerProxy::Shutdown() + { + m_pResourceManager->Shutdown(this); + } + + /// + /// Gets a new thread proxy from the factory. + /// + IThreadProxy * SchedulerProxy::GetNewThreadProxy(IExecutionContext * pContext) + { + if (m_pThreadProxyFactory == NULL) + { + // Populate the cached pointer from the one in the RM + m_pThreadProxyFactory = GetResourceManager()->GetThreadProxyFactoryManager()->GetFreeThreadProxyFactory(); + } + + FreeThreadProxy * pProxy = static_cast(m_pThreadProxyFactory->RequestProxy(ContextStackSize(), ContextPriority())); + pProxy->AssociateExecutionContext(pContext); + + return pProxy; + } + + /// + /// Ensures that a context is bound to a thread proxy. This API should *NOT* be called in the vast majority of circumstances. + /// The IThreadProxy::SwitchTo will perform late binding to thread proxies as necessary. There are, however, circumstances + /// where it is necessary to pre-bind a context to ensure that the SwitchTo operation switches to an already bound context. This + /// is the case on a UMS scheduling context as it cannot call allocation APIs. + /// + /// + /// The context to bind. + /// + void SchedulerProxy::BindContext(IExecutionContext * pContext) + { + if (pContext == NULL) + { + throw std::invalid_argument("pContext"); + } + + // Find out if this context already has a thread proxy, if not we have to request one from the factory. + if (pContext->GetProxy() == NULL) + { + // Find a thread proxy from the pool that corresponds to the stack size and priority we need. + GetNewThreadProxy(pContext); + } + } + + /// + /// Returns an **unstarted** thread proxy attached to pContext, to the thread proxy factory. + /// Such a thread proxy **must** be unstarted. + /// This API should *NOT* be called in the vast majority of circumstances. + /// + /// + /// The context to unbind. + /// + void SchedulerProxy::UnbindContext(IExecutionContext * pContext) + { + if (pContext == NULL) + { + throw std::invalid_argument("pContext"); + } + + FreeThreadProxy * pProxy = static_cast (pContext->GetProxy()); + + ASSERT(pProxy != NULL); + pProxy->ReturnIdleProxy(); + } + + /// + /// This function retrieves the execution resource associated with this thread, if one exists + /// + /// + /// The ExecutionResource instance representing current thread in the runtime. + /// + ExecutionResource * SchedulerProxy::GetCurrentThreadExecutionResource() + { + ExecutionResource * pExecutionResource = NULL; + DWORD tlsSlot = GetResourceManager()->GetExecutionResourceTls(); + void * tlsPointer = platform::__TlsGetValue(tlsSlot); + size_t tlsValue = (size_t) tlsPointer; + + if ((tlsPointer != NULL) && ((tlsValue & TlsResourceBitMask) == TlsResourceInResource)) + { + pExecutionResource = (ExecutionResource *) tlsValue; + } + + return pExecutionResource; + } + + /// + /// This function retrieves the execution resource associated with this thread, if one exists, + /// and updates the reference count on it for better bookkeeping. + /// + /// + /// The ExecutionResource instance representing current thread in the runtime. + /// + ExecutionResource * SchedulerProxy::ReferenceCurrentThreadExecutionResource() + { + ExecutionResource * pExecutionResource = NULL; + DWORD tlsSlot = GetResourceManager()->GetExecutionResourceTls(); + void * tlsPointer = platform::__TlsGetValue(tlsSlot); + + if (tlsPointer != NULL) + { + size_t tlsValue = (size_t) tlsPointer; + + if ((tlsValue & TlsResourceBitMask) == TlsResourceInResource) + { + // The current thread was previously subscribed with the RM. + pExecutionResource = (ExecutionResource *) tlsValue; + + VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot(); + + // If this is a nested subscribe call then if there was a virtual processor root, + // it could not have been removed, because it would have been marked as "fixed". + ASSERT(pVPRoot == NULL || !pVPRoot->IsRootRemoved()); + pExecutionResource->IncrementUseCounts(); + } + else if ((tlsValue & TlsResourceBitMask) == TlsResourceInProxy) + { + // The current thread is a thread proxy. + FreeThreadProxy * pThreadProxy = (FreeThreadProxy *) (((size_t) tlsValue) & ~TlsResourceInProxy); + pExecutionResource = pThreadProxy->GetVirtualProcessorRoot()->GetExecutionResource(); + VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot(); + if (pVPRoot != NULL && pVPRoot->IsRootRemoved()) + { + // The virtual processor root that this thread is running on has been removed. We have to + // create a new execution resource abstraction for the current thread and perform an external + // thread allocation for this scheduler proxy. + pExecutionResource = NULL; + } + else + { + pExecutionResource->IncrementUseCounts(); + } + } + } + + if (pExecutionResource != NULL) + { + return GetResourceForNewSubscription(pExecutionResource); + } + + return pExecutionResource; + } + + /// + /// Creates or reuses an execution resource for the thread subscription + /// + ExecutionResource * SchedulerProxy::GetResourceForNewSubscription(ExecutionResource * pParentExecutionResource) + { + ExecutionResource * pExecutionResource = NULL; + + if (pParentExecutionResource->GetSchedulerProxy() != this) + { + pExecutionResource = _concrt_new ExecutionResource(this, pParentExecutionResource); + pExecutionResource->IncrementUseCounts(); + } + else + { + pExecutionResource = pParentExecutionResource; + } + + return pExecutionResource; + } + + /// + /// Registers that a call to SubscribeCurrentThread has occurred for this core, making this core immovable. + /// + void SchedulerProxy::IncrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread) + { + SchedulerCore * pCore = &m_pAllocatedNodes[nodeId].m_pCores[coreIndex]; + if (pCore->m_numFixedThreads++ == 0) + { + SchedulerNode * pNode = &m_pAllocatedNodes[nodeId]; + pNode->m_numFixedCores++; + m_numFixedCores++; + if (pCore->IsBorrowed()) + { + // When a core becomes fixed, we temporarily remove the borrowed flag on it, and restore it when it + // becomes movable again. + pCore->m_fPreviouslyBorrowed = true; + ToggleBorrowedState(pNode, coreIndex); + } + + // If this core has no virtual processors on it, count it as a core exclusively dedicated to external threads. + if (isExternalThread && m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_numAssignedThreads == 0) + { + ++m_numExternalThreadCores; + } + } + + // Increment the external thread count on the core, which helps account for all the resources running on that core. + if (isExternalThread) + { + m_numExternalThreads++; + pCore->m_numExternalThreads++; + } + } + + /// + /// Registers that a call to IExecutionResource::Release has occurred, potentially freeing this core. + /// + void SchedulerProxy::DecrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread) + { + SchedulerCore * pCore = &m_pAllocatedNodes[nodeId].m_pCores[coreIndex]; + // Decrement external thread count on the core which helps account for all the resources running on that core. + if (isExternalThread) + { + ASSERT(pCore->m_numExternalThreads > 0); + pCore->m_numExternalThreads--; + m_numExternalThreads--; + } + + ASSERT(pCore->m_numFixedThreads > 0); + if (--pCore->m_numFixedThreads == 0) + { + SchedulerNode * pNode = &m_pAllocatedNodes[nodeId]; + ASSERT(pCore->m_numExternalThreads == 0); + m_numFixedCores--; + pNode->m_numFixedCores--; + + if (pCore->m_fPreviouslyBorrowed) + { + // If this was a borrowed core convereted to fixed due to a subscription request, we restore the state + // back to borrowed, here. + ASSERT(!pCore->IsBorrowed()); + ToggleBorrowedState(pNode, coreIndex); + pCore->m_fPreviouslyBorrowed = false; + } + + // If this core was owned only due to an external thread being on it, then there is + // no more reason for it to be marked as such. + if (isExternalThread && m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_numAssignedThreads == 0) + { + m_numExternalThreadCores--; + } + } + } + + /// + /// This API registers the current thread with the resource manager associating it with this scheduler proxy, + /// and returns an instance of IExecutionResource back to the scheduler for bookkeeping and maintenance. + /// + /// + /// The IExecutionResource instance representing current thread in the runtime. + /// + IExecutionResource * SchedulerProxy::SubscribeCurrentThread() + { + return m_pResourceManager->SubscribeCurrentThread(this); + } + + /// + /// Creates a new execution resource for the external thread and registers it with the scheduler proxy. + /// + ExecutionResource * SchedulerProxy::CreateExternalThreadResource(SchedulerNode * pNode, unsigned int coreIndex) + { + ExecutionResource * pExecutionResource = _concrt_new ExecutionResource(this, pNode, coreIndex); + pExecutionResource->IncrementUseCounts(); + return pExecutionResource; + } + + /// + /// Adds the execution resource to the list of subscribed threads + /// + void SchedulerProxy::AddThreadSubscription(ExecutionResource * pExecutionResource) + { + m_threadSubscriptions.AddTail(pExecutionResource); + } + + /// + /// Removes the execution resource from the list of subscribed threads + /// + void SchedulerProxy::RemoveThreadSubscription(ExecutionResource * pExecutionResource) + { + m_threadSubscriptions.Remove(pExecutionResource); + delete pExecutionResource; + } + + /// + /// Called by the RM when it is done reserving cores for the scheduler proxy. The scheduler proxy allocates virtual processors + /// or standalone execution resources based on the cores that were reserved for it. + /// + ExecutionResource * SchedulerProxy::GrantAllocation(unsigned int numberReserved, bool fInitialAllocation, bool fSubscribeCurrentThread) + { + ASSERT(m_numAllocatedCores == 0 || !fInitialAllocation); + ASSERT(m_numExternalThreads == 0 || !fInitialAllocation); + + // The scheduler proxy's allocated node map contains 'numberReserved' cores that the RM has reserved in order to + // satisfy the proxy's request based on its request and the availability of resources. The cores are marked with + // ProcessorCore::Reserved, and will be converted to ProcessorCore::Allocated here. + + // Note that 'numberReserved' could have the value 0, if this is an allocation for an external thread. In this case, depending + // on whether the scheduler has more than its minimum, we will either oversubscribe a core, or remove virtual processors + // assigned to a core in order to accommodate the external thread. + unsigned int reservationsAllocated = 0; + ExecutionResource * pExecutionResource = NULL; + + ASSERT(!fInitialAllocation || m_minimumHardwareThreads == MinHWThreads()); + // Calculate the number of virtual processors we will give this scheduler based on the core allocation + // we received. Each core will be allocated either m_tof vprocs or m_tof - 1 vprocs, based on the + // desired hardware threads and the value for max concurrency. + + // The current thread subscription we are about to make does not contribute to MinHWThreads() at present. The external thread + // gets an exclusive core, if the remaining cores, allocated and reserved, can satisfy at least 1 more then the current minimum. + // Note that 'externalThreadCore' can be 1 even if no cores were reserved -> in this case we will have to remove vprocs from an allocated + // core and use it exclusively for the external thread. + unsigned int externalThreadCores = fSubscribeCurrentThread ? (m_numAllocatedCores + numberReserved > MinHWThreads() ? 1 : 0) : 0; + unsigned int vprocCores = (numberReserved > externalThreadCores) ? (numberReserved - externalThreadCores) : 0; + bool fRemoveVProcs = (externalThreadCores > 0 && numberReserved == 0); + bool fShareExternalThreadCore = (fSubscribeCurrentThread && externalThreadCores == 0); + + // These variables are used if a thread subscription is part of this allocation. For a thread subscription assignment to a core, + // there are 3 possibilities: + // 1. A Reserved core exists in the current allocation map exclusive for the thread subscription. + // 2. The thread subscription will share a core with virtual processors. + // 3. An existing allocated core will be assigned to the external thread after removing all vprocs that are currently allocated to it. + unsigned int externalThreadUseCount = (unsigned int) -1; + unsigned int externalThreadCoreIndex = (unsigned int) -1; + SchedulerNode * pExternalThreadNode = NULL; + unsigned int currentNodeIndex = fSubscribeCurrentThread ? m_pResourceManager->GetCurrentNodeAndCore(NULL) : (unsigned int) -1; + + ASSERT(!fRemoveVProcs || (m_numAllocatedCores > MinHWThreads())); + + unsigned int vprocCount = 0; + if (vprocCores > 0) + { + ASSERT(m_numFullySubscribedCores > 0 && m_numFullySubscribedCores <= m_desiredHardwareThreads); + if (vprocCores <= m_numFullySubscribedCores) + { + vprocCount = vprocCores * m_targetOversubscriptionFactor; + } + else + { + vprocCount = (m_numFullySubscribedCores * m_targetOversubscriptionFactor) + + ((vprocCores - m_numFullySubscribedCores) * (m_targetOversubscriptionFactor - 1)); + } + } + + ASSERT(!fInitialAllocation || (vprocCount >= m_minConcurrency && vprocCount <= m_maxConcurrency)); + + IVirtualProcessorRoot** vprocArray = (vprocCount > 0) ? _concrt_new IVirtualProcessorRoot *[vprocCount] : NULL; + unsigned int vprocIndex = 0; + bool externalThreadCoreFound= !fSubscribeCurrentThread; + + // We may not have a core reserved for the external thread, so we should loop until the external thread is assigned to an + // existing core, if thread subscription is requested. + for (unsigned int nodeIndex = 0; (reservationsAllocated < numberReserved || !externalThreadCoreFound) && + nodeIndex < m_nodeCount; ++nodeIndex) + { + // If the core is marked Reserved, we will either assign to it virtual processors, the external thread or both. Whether or not + // the external thread shares the core with virtual processors depends on the value of fShareExternalThreadCore. + + // If we find any cores marked Allocated, it implies that this is not the initial allocation, and all we're looking to do here + // is assign a core to the external thread. The external thread could either share a core with vprocs or displace vprocs, depending + // on the value of fRemoveVProcs. + + SchedulerNode * pNode = &m_pAllocatedNodes[nodeIndex]; + if (pNode->m_reservedCores > 0 || pNode->m_allocatedCores > 0) + { + for(unsigned int coreIndex = 0; (reservationsAllocated < numberReserved || !externalThreadCoreFound) && + coreIndex < pNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pCore = &pNode->m_pCores[coreIndex]; + if (pCore->m_coreState == ProcessorCore::Reserved) + { + bool assignExternalThread = (!externalThreadCoreFound && (reservationsAllocated == numberReserved - 1 || currentNodeIndex == nodeIndex)); + bool assignVProcs = (!assignExternalThread || externalThreadCores == 0); + + ASSERT(pCore->m_numAssignedThreads == 0 && pCore->m_numFixedThreads == 0); + pCore->m_coreState = ProcessorCore::Allocated; + ASSERT(pNode->m_allocatedCores < pNode->m_coreCount); + ++pNode->m_allocatedCores; + ++m_numAllocatedCores; + + // If the external thread also needs a core, first try to put it in a node whose affinity is a superset of the hardware thread + // it is currently running on. If not, reaffinitize it. + if (assignExternalThread) + { + // The execution resource is created right before returning from the function. + pExternalThreadNode = pNode; + externalThreadCoreIndex = coreIndex; + externalThreadCoreFound = true; + } + + if (assignVProcs) + { + ASSERT(!assignExternalThread || fShareExternalThreadCore); + // Create virtual processor roots in the scheduler proxy, corresponding to the node and core we're currently looking at. + unsigned int numVprocs = 0; + if (m_numFullySubscribedCores > 0) + { + numVprocs = m_targetOversubscriptionFactor; + // As we assign m_tof threads to a core, we decrement this value. This value is also updated in + // AddCore and RemoveCore. After the scheduler proxy has been given its initial allocation + // or resources, this variable keeps track of how many out of the remaining quota of cores the + // scheduler proxy could acquire (desired - allocated) would get tof threads per core if they + // were added to the scheduler during dynamic core migration. + --m_numFullySubscribedCores; + } + else + { + numVprocs = m_targetOversubscriptionFactor - 1; + } + pCore->m_numAssignedThreads += numVprocs; + m_numAssignedThreads += numVprocs; + + while (numVprocs-- > 0) + { + _Analysis_assume_(vprocIndex < vprocCount); + vprocArray[vprocIndex++] = CreateVirtualProcessorRoot(pNode, coreIndex); + } + ASSERT(vprocIndex <= vprocCount); + } + ++reservationsAllocated; + } + else if (pCore->m_coreState == ProcessorCore::Allocated) + { + // If we encounter allocated cores, this is a subsequent allocation for an external core. Determine if the external + // thread should share a core with existing vprocs and external threads, or displace some vprocs to get a core to itself. + + // Walk through all the allocated cores to find the right one to either oversubscribe or displace. For over + // subscription find the core with the least number of vprocs + external thread assigned to it (favouring the node + // where the current thread is running if there is more than one such core). + // For displacement, we need to find an unfixed core, favouring the node where the current thread is running. + if (fShareExternalThreadCore) + { + ASSERT(!fRemoveVProcs && externalThreadCores == 0); + + unsigned int useCount = pCore->m_numAssignedThreads + pCore->m_numExternalThreads; + if (useCount < externalThreadUseCount || (useCount == externalThreadUseCount && nodeIndex == currentNodeIndex)) + { + externalThreadUseCount = useCount; + pExternalThreadNode = pNode; + externalThreadCoreIndex = coreIndex; + + // We don't set externalThreadCoreFound here, since we want to examine all allocated cores. + } + } + else if (fRemoveVProcs) + { + ASSERT(externalThreadCores == 1); + if (!pCore->IsFixed() && (pExternalThreadNode == NULL || nodeIndex == currentNodeIndex)) + { + pExternalThreadNode = pNode; + externalThreadCoreIndex = coreIndex; + if (nodeIndex == currentNodeIndex) + { + // Stop looking if we find an unfixed core on the current node. + externalThreadCoreFound = true; + } + } + } + } + else + { + ASSERT(pCore->m_coreState == ProcessorCore::Unassigned); + } + } + pNode->m_reservedCores = 0; + } + } + + ASSERT(vprocIndex == vprocCount); + if (vprocCount > 0) + { + AddVirtualProcessorRoots(vprocArray, vprocCount); + delete [] vprocArray; + } + + if (fSubscribeCurrentThread) + { + ASSERT(pExternalThreadNode != NULL && externalThreadCoreIndex != (unsigned int) -1); + if (fShareExternalThreadCore) + { + ASSERT(externalThreadCores == 0); + } + else if (fRemoveVProcs) + { + ASSERT(externalThreadCores == 1); + ASSERT(m_numAllocatedCores > MinHWThreads()); + // Remove the core and replace with an external thread subscription. Note that the use count for this core + // stays the same, as we simply replace virtual processors with a thread subscription. + RemoveCore(pExternalThreadNode, externalThreadCoreIndex); + + pExternalThreadNode->m_pCores[externalThreadCoreIndex].m_coreState = ProcessorCore::Allocated; + ASSERT(pExternalThreadNode->m_allocatedCores < pExternalThreadNode->m_coreCount); + ++pExternalThreadNode->m_allocatedCores; + ++m_numAllocatedCores; + } + else + { + ASSERT(externalThreadCores == 1); + } + pExecutionResource = CreateExternalThreadResource(pExternalThreadNode, externalThreadCoreIndex); + } +#if defined(CONCRT_TRACING) + m_numTotalCores = m_nodeCount * m_pAllocatedNodes[0].m_coreCount; + m_drmInitialState = _concrt_new SchedulerCoreData[m_numTotalCores]; + memset(m_drmInitialState, 0, sizeof(SchedulerCoreData) * m_numTotalCores); +#endif + ASSERT(m_numAllocatedCores >= MinHWThreads() && m_numAllocatedCores <= DesiredHWThreads()); + return pExecutionResource; + } + + /// + /// Causes the resource manager to create a new virtual processor root running atop the same hardware thread as this + /// execution resource. Typically, this is used when a scheduler wishes to oversubscribe a particular hardware thread + /// for a limited amount of time. + /// + /// + /// The execution resource abstraction on which to oversubscribe. + /// + /// + /// A new virtual processor root running atop the same hardware thread as this execution resource. + /// + IVirtualProcessorRoot * SchedulerProxy::CreateOversubscriber(IExecutionResource * pExecutionResource) + { + // The scheduler proxy on the virtual processor root has to match 'this' + VirtualProcessorRoot * pOversubscribedRoot = NULL; + ExecutionResource * pResource = dynamic_cast(pExecutionResource); + bool isVprocRoot = false; + + // If dynamic cast failed then we must have a virtual processor root. + if (pResource == NULL) + { + pResource = static_cast(pExecutionResource)->GetExecutionResource(); + isVprocRoot = true; + } + + // Cannot verify the scheduler proxy for external threads because they can "live" on + // multiple schedulers at the same time (nested). + if (isVprocRoot && pResource->GetSchedulerProxy() != this) + { + throw std::invalid_argument("pExecutionResource"); + } + + // Synchronize with other concurrent calls that are adding/removing virtual processor roots. + { + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + // Use the scheduler proxy to clone this virtual processor root. + SchedulerNode * pNode = &m_pAllocatedNodes[pResource->GetNodeId()]; + unsigned int coreIndex = pResource->GetCoreIndex(); + + pOversubscribedRoot = CreateVirtualProcessorRoot(pNode, coreIndex); + + // We mark these vproc roots as oversubscribed to indicate that they do not contribute + // towards concurrency levels bounded by the policy + pOversubscribedRoot->MarkAsOversubscribed(); + pNode->m_pCores[coreIndex].m_resources.AddTail(pOversubscribedRoot->GetExecutionResource()); + } + + return pOversubscribedRoot; + } + + /// + /// Creates a virtual processor root and adds it to the scheduler proxys list of roots. + /// + VirtualProcessorRoot * SchedulerProxy::CreateVirtualProcessorRoot(SchedulerNode * pNode, unsigned int coreIndex) + { + return _concrt_new FreeVirtualProcessorRoot(this, pNode, coreIndex); + } + + /// + /// Notifies the scheduler associated with this proxy to adds the virtual processor roots provided. + /// Called by the RM during initial allocation and dynamic core migration. + /// + void SchedulerProxy::AddVirtualProcessorRoots(IVirtualProcessorRoot ** vprocRoots, unsigned int count) + { + // Note, that we are holding the global RM allocation lock when this API is called. + { + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + for (unsigned int i = 0; i < count; ++i) + { + VirtualProcessorRoot * pRoot = static_cast(vprocRoots[i]); + // Add the resources associated with the roots to the corresponding lists in the scheduler proxy. + unsigned int nodeId = pRoot->GetNodeId(); + unsigned int coreIndex = pRoot->GetCoreIndex(); + + m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_resources.AddTail(pRoot->GetExecutionResource()); + } + m_pScheduler->AddVirtualProcessors((IVirtualProcessorRoot **) vprocRoots, count); + + m_currentConcurrency += count; + } + } + + /// + /// Adds an execution resource to the list of resources that run on a particular core. + /// + void SchedulerProxy::AddExecutionResource(ExecutionResource * pExecutionResource) + { + { + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + + // Add the resource to the corresponding list in the scheduler proxy. + unsigned int nodeId = pExecutionResource->GetNodeId(); + unsigned int coreIndex = pExecutionResource->GetCoreIndex(); + + m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_resources.AddTail(pExecutionResource); + } + } + + /// + /// Toggles the state on a core from borrowed to owned (and vice versa), and updates necessary counts. + /// + void SchedulerProxy::ToggleBorrowedState(SchedulerNode * pNode, unsigned int coreIndex) + { + SchedulerCore * pCore = &pNode->m_pCores[coreIndex]; + + if (pCore->m_fBorrowed) + { + --m_numBorrowedCores; + --pNode->m_numBorrowedCores; + pCore->m_fBorrowed = false; + } + else + { + ++m_numBorrowedCores; + ++pNode->m_numBorrowedCores; + pCore->m_fBorrowed = true; + } + } + + /// + /// Adds an appropriate number of virtual processor roots to the scheduler associated with this proxy. + /// Called by the RM during core migration when the RM decides to give this scheduler an additional + /// core. + /// + void SchedulerProxy::AddCore(SchedulerNode * pNode, unsigned int coreIndex, bool fBorrowed) + { + // Note, that we are holding the global RM allocation lock when this API is called. + + // Decide how many virtual processors to give the scheduler on this core. Note that this value is required + // to be either m_tof or m_tof - 1. + + unsigned int numThreads = 0; + if (m_numFullySubscribedCores > 0) + { + numThreads = m_targetOversubscriptionFactor; + --m_numFullySubscribedCores; + } + else + { + numThreads = m_targetOversubscriptionFactor - 1; + } + + ASSERT(numThreads > 0 && numThreads <= INT_MAX); + + ASSERT(pNode->m_allocatedCores < pNode->m_coreCount); + ++pNode->m_allocatedCores; + ASSERT(m_numAllocatedCores < DesiredHWThreads()); + ++m_numAllocatedCores; + + SchedulerCore * pCore = &pNode->m_pCores[coreIndex]; + + ASSERT(pCore->m_coreState == ProcessorCore::Unassigned); + pCore->m_coreState = ProcessorCore::Allocated; + + ASSERT(pCore->m_numAssignedThreads == 0); + pCore->m_numAssignedThreads = numThreads; + m_numAssignedThreads += pCore->m_numAssignedThreads; + ASSERT(m_numAssignedThreads <= m_maxConcurrency); + + if (fBorrowed) + { + ASSERT(!pCore->IsBorrowed()); + ToggleBorrowedState(pNode, coreIndex); + } + + // Special case for when there is 1 vproc per core - this is likely to be the common case. + IVirtualProcessorRoot * pRoot; + IVirtualProcessorRoot ** pRootArray = (numThreads == 1) ? &pRoot : _concrt_new IVirtualProcessorRoot *[numThreads]; + + for (unsigned int i = 0; i < numThreads; ++i) + { + pRootArray[i] = CreateVirtualProcessorRoot(pNode, coreIndex); + } + + AddVirtualProcessorRoots(pRootArray, numThreads); + + if (pRootArray != &pRoot) + { + delete [] pRootArray; + } + } + + /// + /// Notifies the scheduler associated with this proxy to remove the virtual processor roots associated + /// with the core provided. Called by the RM during core migration. + /// + void SchedulerProxy::RemoveCore(SchedulerNode * pNode, unsigned int coreIndex) + { + // Note, that we are holding the global RM allocation lock when this API is called. + ASSERT(pNode->m_allocatedCores > 0 && pNode->m_allocatedCores <= pNode->m_coreCount); + --pNode->m_allocatedCores; + ASSERT(m_numAllocatedCores > MinVprocHWThreads()); + --m_numAllocatedCores; + + SchedulerCore * pCore = &pNode->m_pCores[coreIndex]; + + ASSERT(pCore->m_coreState == ProcessorCore::Allocated || pCore->m_coreState == ProcessorCore::Stolen); + pCore->m_coreState = ProcessorCore::Unassigned; + + ASSERT(pCore->m_numAssignedThreads == m_targetOversubscriptionFactor || + pCore->m_numAssignedThreads == m_targetOversubscriptionFactor - 1); + if (pCore->m_numAssignedThreads == m_targetOversubscriptionFactor) + { + ++m_numFullySubscribedCores; + } + + m_numAssignedThreads -= pCore->m_numAssignedThreads; + ASSERT(m_numAssignedThreads >= m_minConcurrency && m_numAssignedThreads < m_maxConcurrency); + pCore->m_numAssignedThreads = 0; + + if (pCore->m_fBorrowed) + { + ToggleBorrowedState(pNode, coreIndex); + } + + pCore->m_fIdleDuringDRM = false; + + ASSERT(GetNumOwnedCores() >= MinHWThreads()); + + // A lock is required around the iteration of nodes and the call to AddVirtualProcessors to synchronize with concurrent + // calls to DestroyVirtualProcessorRoot, which removes roots from the array and deletes them. + + { // begin locked region + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + ExecutionResource * pExecutionResource = pCore->m_resources.First(); + while (pExecutionResource != NULL) + { + // Remember the next root before hand, since a IVirtualProcessorRoot::Remove call could happen inline + // for the root we're removing, and by the time we get back, that root could be deleted. + ExecutionResource * pNextExecutionResource = pCore->m_resources.Next(pExecutionResource); + VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot(); + if (pVPRoot != NULL && !pVPRoot->IsRootRemoved()) + { + pVPRoot->MarkRootRemoved(); + IVirtualProcessorRoot * pIRoot = pVPRoot; + m_pScheduler->RemoveVirtualProcessors(&pIRoot, 1); + } + pExecutionResource = pNextExecutionResource; + } + } // end locked region + } + + /// + /// Called by the RM to instruct this scheduler proxy to notify its scheduler that this core is now + /// externally busy or externally idle. + /// + void SchedulerProxy::SendCoreNotification(SchedulerCore * pCore, bool isBusyNotification) + { + // Avoid a memory allocation under two locks if we have less than 8 roots per core - this is expected to be + // the common case. + IVirtualProcessorRoot * pRootArray[8]; + IVirtualProcessorRoot ** pRoots= NULL; + +#pragma warning(push) +#pragma warning(disable: 6385 6386) // TRANSITION, VSO-1807030 + // Note, that we are holding the global RM allocation lock when this API is called. + { // begin locked region + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + unsigned int numThreadsIndex = 0; + + if (pCore->m_resources.Count() > 8) + { + pRoots = _concrt_new IVirtualProcessorRoot * [pCore->m_resources.Count()]; + } + else + { + pRoots = pRootArray; + } + + ExecutionResource * pExecutionResource = pCore->m_resources.First(); + while (pExecutionResource != NULL) + { + ExecutionResource * pNextExecutionResource = pCore->m_resources.Next(pExecutionResource); + VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot(); + if (pVPRoot != NULL && !pVPRoot->IsRootRemoved()) + { + pRoots[numThreadsIndex++] = pVPRoot; + } + pExecutionResource = pNextExecutionResource; + } + ASSERT(numThreadsIndex <= (unsigned int) pCore->m_resources.Count()); + + // Now that the array is populated, send notifications for this core + if (isBusyNotification) + { + m_pScheduler->NotifyResourcesExternallyBusy(pRoots, numThreadsIndex); + } + else + { + m_pScheduler->NotifyResourcesExternallyIdle(pRoots, numThreadsIndex); + } + + } // end locked region +#pragma warning(pop) + + if (pRoots!= pRootArray) + { + delete [] pRoots; + } + } + /// + /// Removes a root from the scheduler proxy and destroys it. This API is called in response to a scheduler + /// informing the RM that it is done with a virtual processor root. + /// + void SchedulerProxy::DestroyVirtualProcessorRoot(VirtualProcessorRoot * pRoot) + { + // Synchronize with other concurrent calls that are adding/removing virtual processor roots. + { // begin locked region + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + SchedulerNode * pNode = &m_pAllocatedNodes[pRoot->GetNodeId()]; + ASSERT(pNode->m_id == pRoot->GetNodeId()); + + // NOTE: This API is called in response to a scheduler being done with a virtual processor root. + // The scheduler is expected not to invoke ISchedulerProxy::Shutdown, which destroys + // all remaining roots in the proxy, until all individual calls for removing virtual processor + // roots have completed. + + pNode->m_pCores[pRoot->GetCoreIndex()].m_resources.Remove(pRoot->GetExecutionResource()); + + if (!pRoot->IsOversubscribed()) + { + // Oversubscribed vprocs do not contribute towards concurrency level + ASSERT(m_currentConcurrency > 0); + --m_currentConcurrency; + } + + } // end locked region + + pRoot->DeleteThis(); + } + + /// + /// Removes an execution resource from the scheduler proxy, and destroys it. This API is called in response to a scheduler + /// informing the RM that it is done with an execution resource. + /// + void SchedulerProxy::DestroyExecutionResource(ExecutionResource * pExecutionResource) + { + // NOTE: This function should be called with the RM lock held. + SchedulerNode * pNode = &m_pAllocatedNodes[pExecutionResource->GetNodeId()]; + SchedulerCore * pCore = &pNode->m_pCores[pExecutionResource->GetCoreIndex()]; + ASSERT(pNode->m_id == pExecutionResource->GetNodeId()); + + // Mark this core as available to others if this was the last resource on it + // If this is the last running resource on this core then mark it as available again + if (pCore->m_numAssignedThreads + pCore->m_numExternalThreads == 0) + { + // If there are no vprocs or external threads, then core cannot be fixed + ASSERT(!pCore->IsFixed()); + ASSERT(pNode->m_allocatedCores > 0 && pNode->m_allocatedCores <= pNode->m_coreCount); + pNode->m_allocatedCores--; + ASSERT(m_numAllocatedCores > MinHWThreads()); + pCore->m_coreState = ProcessorCore::Unassigned; + m_numAllocatedCores--; + ASSERT(m_numAllocatedCores <= DesiredHWThreads()); + m_pResourceManager->DecrementCoreUseCount(pExecutionResource->GetNodeId(), pExecutionResource->GetCoreIndex()); + } + + // Synchronize with other concurrent calls that are adding/removing execution resources. + { // begin locked region + _ReentrantBlockingLock::_Scoped_lock lock(m_lock); + pCore->m_resources.Remove(pExecutionResource); + } // end locked region + + delete pExecutionResource; + } + + /// + /// Called to assist dynamic resource management in determining whether cores assigned to schedulers + /// are idle. An idle core is one whose subscription level is 0. + /// + void SchedulerProxy::IncrementCoreSubscription(ExecutionResource * pExecutionResource) + { + unsigned int nodeId = pExecutionResource->GetNodeId(); + unsigned int coreIndex = pExecutionResource->GetCoreIndex(); + + if ((InterlockedIncrement(&m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_subscriptionLevel) == 1) && + (m_pResourceManager->GetNumSchedulersForNotifications() > (ShouldReceiveNotifications() ? 1UL : 0UL))) + { + // We've incremented the local subscription from 0 to 1 -> this may warrant notifications. + // Note that the number of schedulers needing notifications may change right after we read it, but any + // missed notifications will be sent at the next Dynamic RM Poll. + + // We simply set the dynamic RM event here. Note -> there may not yet be a dynamic RM thread at this point. + // We clearly have 2 schedulers, but it could be that the second one is just being created. In that case, + // notifications will be sent when the dynamic RM starts up (right after the second scheduler has finished + // receiving all its resources). We may even race with shutdown for the penultimate scheduler. If the DRM + // thread wakes up and there is only one scheduler left, it will go back to waiting. + m_pResourceManager->WakeupDynamicRMWorker(); + } + } + + /// + /// Called to assist dynamic resource management in determining whether cores assigned to schedulers + /// are idle. An idle core is one whose subscription level is 0. + /// + void SchedulerProxy::DecrementCoreSubscription(ExecutionResource * pExecutionResource) + { + unsigned int nodeId = pExecutionResource->GetNodeId(); + unsigned int coreIndex = pExecutionResource->GetCoreIndex(); + + if ((InterlockedDecrement(&m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_subscriptionLevel) == 0) && + (m_pResourceManager->GetNumSchedulersForNotifications() > (ShouldReceiveNotifications() ? 1UL : 0UL))) + { + // We've decremented the local subscription from 1 to 0 -> this may warrant notifications. + // Note that the number of schedulers needing notifications may change right after we read it, but any + // missed notifications will be sent at the next Dynamic RM Poll. + + // We simply set the dynamic RM event here. Note -> there may not yet be a dynamic RM thread at this point. + // We clearly have 2 schedulers, but it could be that the second one is just being created. In that case, + // notifications will be sent when the dynamic RM starts up (right after the second scheduler has finished + // receiving all its resources). We may even race with shutdown for the penultimate scheduler. If the DRM + // thread wakes up and there is only one scheduler left, it will go back to waiting. + m_pResourceManager->WakeupDynamicRMWorker(); + } + } + + /// + /// Called to adjust the suggested allocation such that we do not exceed maxConcurrency. + /// This routine takes into account vprocs that are marked for removal but haven't yet been + /// retired by the scheduler. The suggested allocation would be decreased to account for such + /// vprocs. + /// + unsigned int SchedulerProxy::AdjustAllocationIncrease(unsigned int suggestedAllocation) const + { + ASSERT(suggestedAllocation >= GetNumAllocatedCores()); + ASSERT(suggestedAllocation <= DesiredHWThreads()); + + // Figure out the max number of new cores we can add + unsigned int newCores = 0; + + // Since we could be not holding the scheduler proxy lock the value in m_currentConcurrency could + // be changing. This is fine since a later DRM sweep will migrate appropriate number of cores. + if (m_maxConcurrency > m_currentConcurrency) + { + unsigned int remainingConcurrency = m_maxConcurrency - m_currentConcurrency; + + // Convert remaining concurrency to number of cores + unsigned int fullySubscribedConcurrency = m_numFullySubscribedCores * m_targetOversubscriptionFactor; + + if (fullySubscribedConcurrency >= remainingConcurrency) + { + newCores = remainingConcurrency / m_targetOversubscriptionFactor; + } + else + { + ASSERT(m_targetOversubscriptionFactor > 1); + newCores = m_numFullySubscribedCores; + newCores += ((remainingConcurrency - fullySubscribedConcurrency) / (m_targetOversubscriptionFactor - 1)); + } + } + + unsigned int maxAllocation = (GetNumAllocatedCores() + newCores); + + // Cores used exclusively by external threads are included in numAllocatedCores. As a result + // maxAllocation could go above desired. + maxAllocation = min(maxAllocation, DesiredHWThreads()); + +#if defined(CONCRT_TRACING) + if (maxAllocation < suggestedAllocation) + { + TRACE(CONCRT_TRACE_DYNAMIC_RM, L"Scheduler %d: Allocated: %d, Suggested: %d, Adjusted Suggested: %d", + GetId(), GetNumAllocatedCores(), suggestedAllocation, maxAllocation); + } +#endif + + return min(maxAllocation, suggestedAllocation); + } + + SchedulerProxy::~SchedulerProxy() + { + // + // Clean up anything which might be used during the asynchronous delete. + // + m_pResourceManager->DestroyAllocatedNodeData(m_pAllocatedNodes); + delete [] m_pSortedNodeOrder; + +#if defined(CONCRT_TRACING) + delete [] m_drmInitialState; +#endif + // + // Release the reference on the Resource manager + // + m_pResourceManager->Release(); + } + + /// + /// Called to shutdown a scheduler proxy. Derived classes can override shutdown behavior based on this. + /// + void SchedulerProxy::FinalShutdown() + { + Cleanup(); + DeleteThis(); + } + + /// + /// Cleans up resources associated with the scheduler. + /// + void SchedulerProxy::Cleanup() + { + // + // Delete vproc roots that exist in the allocated nodes at this time. The deletion here is a notification. It may happen asynchronously + // depending on the type of scheduler proxy. The data structures maintained for the scheduler proxy cannot go away until the deferred + // deletion happens. + // + for (unsigned int i = 0; i < m_nodeCount; ++i) + { + SchedulerNode * pNode = &m_pAllocatedNodes[i]; + + for (unsigned int j = 0; j < pNode->m_coreCount; ++j) + { + ExecutionResource * pExecutionResource = pNode->m_pCores[j].m_resources.First(); + + while (pExecutionResource != NULL) + { + ExecutionResource * pExecutionResourceToDelete = pExecutionResource; + pExecutionResource = pNode->m_pCores[j].m_resources.Next(pExecutionResource); + VirtualProcessorRoot * pVPRoot = pExecutionResourceToDelete->GetVirtualProcessorRoot(); + ASSERT(pVPRoot != NULL); + + // Since the root is going away, check if it contributes to the subscription count on the core, and + // fix up the count, if so. + pVPRoot->ResetSubscriptionLevel(); + pVPRoot->DeleteThis(); + } + } + } + + delete m_pHillClimbing; + } + +#if defined(CONCRT_TRACING) + + /// + /// Sets or clears a flag indicating that the RM needs to do an external thread allocation for this + /// scheduler proxy. + /// + void SchedulerProxy::TraceInitialDRMState() + { + int traceCoreIndex = 0; + for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex) + { + SchedulerNode * pAllocatedNode = &m_pAllocatedNodes[nodeIndex]; + for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex) + { + SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex]; + SchedulerCoreData * pCoreData = &m_drmInitialState[traceCoreIndex++]; + pCoreData->m_nodeIndex = (unsigned char)nodeIndex; + pCoreData->m_coreIndex = (unsigned char)coreIndex; + pCoreData->m_fAllocated = pAllocatedCore->m_coreState == ProcessorCore::Allocated; + pCoreData->m_fFixed = pAllocatedCore->IsFixed(); + pCoreData->m_fBorrowed = pAllocatedCore->IsBorrowed(); + pCoreData->m_fIdle = pAllocatedCore->IsIdle(); + } + } + } + +#endif +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.h new file mode 100644 index 0000000000000000000000000000000000000000..87faef108d29aebaa36067f37a9aab4a03399b01 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.h @@ -0,0 +1,647 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulerProxy.h +// +// RM proxy for a scheduler instance +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + #pragma warning(push) + #pragma warning(disable: 4265) // non-virtual destructor in base class + class SchedulerProxy : public ::Concurrency::ISchedulerProxy + { + public: + /// + /// Constructs a scheduler proxy. + /// + SchedulerProxy(IScheduler * pScheduler, ResourceManager * pResourceManager, const SchedulerPolicy &policy); + + /// + /// Called in order to notify the resource manager that the given scheduler is shutting down. This + /// will cause the resource manager to immediately reclaim all resources granted to the scheduler. + /// + virtual void Shutdown(); + + /// + /// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request + /// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request + /// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to + /// IScheduler::AddVirtualProcessors. + /// + /// + /// Whether to subscribe the current thread and account for it during resource allocation. + /// + /// + /// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise. + /// + virtual IExecutionResource * RequestInitialVirtualProcessors(bool doSubscribeCurrentThread); + + /// + /// Ensures that a context is bound to a thread proxy. This API should *NOT* be called in the vast majority of circumstances. + /// The IThreadProxy::SwitchTo will perform late binding to thread proxies as necessary. There are, however, circumstances + /// where it is necessary to pre-bind a context to ensure that the SwitchTo operation switches to an already bound context. This + /// is the case on a UMS scheduling context as it cannot call allocation APIs. + /// + /// + /// The context to bind. + /// + virtual void BindContext(IExecutionContext * pContext); + + /// + /// Returns an **unstarted** thread proxy attached to pContext, to the thread proxy factory. + /// Such a thread proxy **must** be unstarted. + /// This API should *NOT* be called in the vast majority of circumstances. + /// + /// + /// The context to unbind. + /// + virtual void UnbindContext(IExecutionContext * pContext); + + /// + /// This API registers the current thread with the resource manager associating it with this scheduler, + /// and returns an instance of IExecutionResource back to the scheduler, for bookkeeping and maintenance. + /// + /// + /// The IExecutionResource instance representing current thread in the runtime. + /// + virtual IExecutionResource * SubscribeCurrentThread(); + + /// + /// The unique identifier of the scheduler this proxy represents. + /// + unsigned int GetId() const + { + return m_id; + } + + /// + /// Causes the resource manager to create a new virtual processor root running atop the same hardware thread as this + /// execution resource. Typically, this is used when a scheduler wishes to oversubscribe a particular hardware thread + /// for a limited amount of time. + /// + /// + /// The execution resource abstraction on which to oversubscribe. + /// + /// + /// A new virtual processor root running atop the same hardware thread as this execution resource. + /// + virtual IVirtualProcessorRoot * CreateOversubscriber(IExecutionResource * pExecutionResource); + + /// + /// Getters for the various policy elements. + /// + unsigned int MaxConcurrency() const + { + return m_maxConcurrency; + } + unsigned int MinConcurrency() const + { + return m_minConcurrency; + } + unsigned int TargetOversubscriptionFactor() const + { + return m_targetOversubscriptionFactor; + } + int ContextStackSize () const + { + return m_contextStackSize; + } + int ContextPriority () const + { + return m_contextPriority; + } + + /// + /// Returns the minimum number of cores that must contain vprocs for this scheduler. These cores + /// may contain a subscribed thread in addition to virtual processors. + /// + unsigned int MinVprocHWThreads() const + { + // Compute number of cores used for virtual processors that are fixed + ASSERT(m_numFixedCores >= m_numExternalThreadCores); + unsigned int fixedVprocCores = m_numFixedCores - m_numExternalThreadCores; + // Compute maximum(t1, minimum set by policy) which is minimum of virtual processor cores + return max(fixedVprocCores, m_minimumHardwareThreads); + } + + unsigned int MinHWThreads() const + { + // The minimum needed number of hardware threads (cores) is equal to: + // - minimum needed vproc cores + minimum needed external thread cores + unsigned int minimumCores = MinVprocHWThreads() + m_numExternalThreadCores; + + ASSERT(minimumCores <= m_coreCount); + return minimumCores; + } + + unsigned int DesiredHWThreads() const + { + unsigned int desiredCores = min(m_coreCount, m_desiredHardwareThreads + m_numExternalThreadCores); + + ASSERT(m_numExternalThreads != 0 || desiredCores == m_desiredHardwareThreads); + return desiredCores; + } + + unsigned int ComputeMinHWThreadsWithExternalThread() const + { + unsigned int newMin = min(m_coreCount, MinHWThreads() + 1); + return newMin; + } + + unsigned int ComputeDesiredHWThreadsWithExternalThread() const + { + unsigned int newDesired = min(m_coreCount, DesiredHWThreads() + 1); + return newDesired; + } + + /// + /// Returns the number of external thread subscriptions + /// + unsigned int GetNumNestedThreadSubscriptions() + { + return m_threadSubscriptions.Count(); + } + + /// + /// Called to adjust the suggested allocation such that we do not exceed maxConcurrency. + /// This routine takes into account vprocs that are marked for removal but haven't yet been + /// retired by the scheduler. The suggested allocation would be decreased to account for such + /// vprocs. + /// + unsigned int AdjustAllocationIncrease(unsigned int suggestedAllocation) const; + + /// + /// Returns the number of cores allocated to the proxy at any time. + /// + unsigned int GetNumAllocatedCores() const + { + return m_numAllocatedCores; + } + + /// + /// Returns the number of borrowed cores. These are cores that were oversubscribed and temporarily + /// assigned to this scheduler during dynamic core migration as they were found to be unused + /// by the other scheduler(s) they were assigned to. The reason these cores were oversubscribed + /// instead of migrated was that they contributed to the minimum number of cores on the other + /// scheduler(s) and hence couldn't be taken away. + /// + unsigned int GetNumBorrowedCores() const + { + return m_numBorrowedCores; + } + + /// + /// Returns the number of owned cores. This is the total allocated cores minus the borrowed cores. + /// + unsigned int GetNumOwnedCores() const + { + return m_numAllocatedCores - m_numBorrowedCores; + } + + /// + /// Returns the number of fixed cores - cores that have a subscribed thread on them. These cores may + /// also have vprocs belonging to this scheduler. + /// + unsigned int GetNumFixedCores() const + { + return m_numFixedCores; + } + + /// + /// Toggles the state on a core from borrowed to owned (and vice versa), and updates necessary counts. + /// + void ToggleBorrowedState(SchedulerNode * pNode, unsigned int coreIndex); + + /// + /// Creates a new execution resource for the external thread and registers it with the scheduler proxy. + /// + ExecutionResource * CreateExternalThreadResource(SchedulerNode * pNode, unsigned int coreIndex); + + /// + /// Called by the RM when it is done reserving cores for the scheduler proxy. The scheduler proxy + /// allocates virtual processors or standalone execution resources based on the cores that were allocated + /// to it. + /// + ExecutionResource * GrantAllocation(unsigned int numberReserved, bool fInitialAllocation, bool fSubscribeCurrentThread); + + /// + /// Finds the core allocated by the RM on which a single subscribed external thread should run. + /// + ExecutionResource * GrantExternalThreadAllocation(bool doOversubscribeCore); + + /// + /// Returns a pointer to the copy of allocated nodes that were assigned to the proxy at + /// creation time. + /// + SchedulerNode * GetAllocatedNodes() const + { + return m_pAllocatedNodes; + } + + /// + /// Sets the allocated nodes for the scheduler proxy to the nodes provided. + /// + void SetAllocatedNodes(SchedulerNode * pNodes) + { + ASSERT(m_pAllocatedNodes == NULL && pNodes != NULL); + m_pAllocatedNodes = pNodes; + } + /// + /// Returns a pointer to the array that holds the sorted order for nodes. This is used by the + /// RM to sort nodes by whatever criteria it chooses. + /// + unsigned int * GetSortedNodeOrder() const + { + return m_pSortedNodeOrder; + } + + /// + /// Returns a pointer to the scheduler associated with the scheduler proxy. + /// + IScheduler * Scheduler() const + { + return m_pScheduler; + } + + /// + /// Returns a pointer to the resource manager associated with the scheduler proxy. + /// + ResourceManager * GetResourceManager() const + { + return m_pResourceManager; + } + + /// + /// Returns a pointer to a data buffer that is used to store static allocation data. The data + /// is populated and manipulated by the RM, but stored in the scheduler proxy for convenience. + /// + StaticAllocationData * GetStaticAllocationData() + { + return &m_staticData; + } + + /// + /// Returns a pointer to a data buffer that is used to store dynamic allocation data. The data + /// is populated and manipulated by the RM, but stored in the scheduler proxy for convenience. + /// + DynamicAllocationData * GetDynamicAllocationData() + { + return &m_dynamicData; + } + + /// + /// Creates a virtual processor root and adds it to the scheduler proxys list of roots. + /// + virtual VirtualProcessorRoot * CreateVirtualProcessorRoot(SchedulerNode * pNode, unsigned int coreIndex); + + /// + /// Notifies the scheduler associated with this proxy to add the virtual processor roots provided. + /// Called by the RM during initial allocation and dynamic core migration. + /// + void AddVirtualProcessorRoots(IVirtualProcessorRoot ** vprocRoots, unsigned int count); + + /// + /// Adds an appropriate number of virtual processor roots to the scheduler associated with this proxy. + /// Called by the RM during core migration when the RM decides to give this scheduler an additional + /// core. + /// + void AddCore(SchedulerNode * pNode, unsigned int coreIndex, bool fBorrowed); + + /// + /// Notifies the scheduler associated with this proxy to remove the virtual processor roots associated + /// with the core provided. Called by the RM during core migration. + /// + void RemoveCore(SchedulerNode * pNode, unsigned int coreIndex); + + /// + /// Called by the RM to instruct this scheduler proxy to notify its scheduler that this core is now + /// externally busy or externally idle. + /// + void SendCoreNotification(SchedulerCore * pCore, bool isBusyNotification); + + /// + /// Removes a root from the scheduler proxy and destroys it. This API is called in response to a scheduler + /// informing the RM that it is done with a virtual processor root. + /// + void DestroyVirtualProcessorRoot(VirtualProcessorRoot * pRoot); + + /// + /// Removes an execution resource from the scheduler proxy and destroys it. This API is called in response to a scheduler + /// informing the RM that it is done with an execution resource. + /// + void DestroyExecutionResource(ExecutionResource * pExecutionResource); + + /// + /// Returns a hardware affinity for the given node. Note that a scheduler proxy may only be assigned a subset + /// of cores within a node -> the mask in the affinity reflects this subset. + /// + /// + /// An abstraction of the hardware affinity which can be applied to Win32 objects. + /// + HardwareAffinity GetNodeAffinity(unsigned int nodeId) + { + ASSERT(nodeId < m_nodeCount); + ASSERT(m_pAllocatedNodes[nodeId].m_id == nodeId); + + return HardwareAffinity(static_cast(m_pAllocatedNodes[nodeId].m_processorGroup), m_pAllocatedNodes[nodeId].m_nodeAffinity); + } + + /// + /// Adds an execution resource to the list of resources that run on a particular core. + /// + void AddExecutionResource(ExecutionResource * pExecutionResource); + + /// + /// Adds the execution resource to the list of subscribed threads + /// + void AddThreadSubscription(ExecutionResource * pExecutionResource); + + /// + /// Removes the execution resource from the list of subscribed threads + /// + void RemoveThreadSubscription(ExecutionResource * pExecutionResource); + + /// + /// Creates or reuses an execution resource for the thread subscription + /// + ExecutionResource * GetResourceForNewSubscription(ExecutionResource * pParentExecutionResource); + + /// + /// This function retrieves the execution resource associated with this thread, if one exists, + /// and updates the reference count on it for better bookkeeping. + /// + /// + /// The ExecutionResource instance representing current thread in the runtime. + /// + ExecutionResource * ReferenceCurrentThreadExecutionResource(); + + /// + /// This function retrieves the execution resource associated with this thread, if one exists. + /// + /// + /// The ExecutionResource instance representing current thread in the runtime. + /// + ExecutionResource * GetCurrentThreadExecutionResource(); + + /// + /// Registers that a call to SubscribeCurrentThread has occurred for this core, making this core immovable. + /// + void IncrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread); + + /// + /// Registers that a call to IExecutionResource::Release has occurred, potentially freeing this core. + /// + void DecrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread); + + /// + /// Returns the number of external threads on this scheduler proxy. + /// + unsigned int GetNumExternalThreads() + { + return m_numExternalThreads; + } + + /// + /// Decides whether this scheduler proxy should receive notifications when other + /// schedulers borrow its cores or return them back. + /// + bool ShouldReceiveNotifications() + { + return (m_minimumHardwareThreads == m_desiredHardwareThreads); + } + + /// + /// A function that passes statistical information to the hill climbing instance. Based on these + /// statistics, hill climbing will make a recommendation on the number of resources the scheduler + /// should be allocated. + /// + /// + /// The number of resources used in this period of time. + /// + /// + /// The number of completed units or work in that period of time. + /// + /// + /// The number of incoming units or work in that period of time. + /// + /// + /// The total length of the work queue. + /// + /// + /// The recommended allocation for the scheduler. + /// + unsigned int DoHillClimbing(unsigned int currentCoreCount, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength) + { + return m_pHillClimbing->Update(currentCoreCount, completionRate, arrivalRate, queueLength); + } + + /// + /// This function returns whether the scheduler has opted in to statistical rebalancing. + /// + /// + /// Whether hill climbing is enabled. + /// + bool IsHillClimbingEnabled() + { + return m_fDoHillClimbing; + } + + /// + /// Gets the current length of the scheduler queue. + /// + /// + /// The queue length. + /// + unsigned int GetQueueLength() + { + return m_queueLength; + } + + /// + /// Sets the current length of the scheduler queue. + /// + /// + /// The length to be set. + /// + void SetQueueLength(unsigned int queueLength) + { + m_queueLength = queueLength; + } + + /// + /// Gets a new thread proxy from the factory. + /// + virtual IThreadProxy * GetNewThreadProxy(IExecutionContext * pContext); + + /// + /// Called to shutdown a scheduler proxy. Derived classes can override shutdown behavior based on this. + /// + virtual void FinalShutdown(); + + /// + /// Called to assist dynamic resource management in determining whether cores assigned to schedulers + /// are idle. An idle core is one whose subscription level is 0. + /// + void IncrementCoreSubscription(ExecutionResource * pExecutionResource); + + /// + /// Called to assist dynamic resource management in determining whether cores assigned to schedulers + /// are idle. An idle core is one whose subscription level is 0. + /// + void DecrementCoreSubscription(ExecutionResource * pExecutionResource); + +#if defined(CONCRT_TRACING) + /// + /// Captures the initial state of the scheduler map at the beginning of core migration, each cycle. + /// + void TraceInitialDRMState(); +#endif + +protected: + + /// + /// Deletes the scheduler proxy. + /// + virtual void DeleteThis() + { + delete this; + } + + /// + /// Cleans up resources associated with the scheduler. + /// + void Cleanup(); + + /// + /// Destructor. + /// + ~SchedulerProxy(); + + // A cached pointer to a thread proxy factory of the appropriate type for this scheduler proxy. + IThreadProxyFactory * m_pThreadProxyFactory; + + private: + template friend class List; + +#if defined(CONCRT_TRACING) + + struct SchedulerCoreData + { + unsigned char m_nodeIndex; + unsigned char m_coreIndex; + bool m_fAllocated : 1; + bool m_fFixed : 1; + bool m_fBorrowed : 1; + bool m_fIdle : 1; + }; + + // Captures the initial global allocation during the DRM phase. + SchedulerCoreData * m_drmInitialState; + unsigned int m_numTotalCores; + +#endif + IScheduler * m_pScheduler; + + // Pointer to the resource manager instance. + ResourceManager * m_pResourceManager; + + // Local copy of allocation map for this scheduler proxy. + SchedulerNode * m_pAllocatedNodes; + + // Helper array used to sort nodes, used by the RM during core migration. + unsigned int * m_pSortedNodeOrder; + + // Links for a list. + SchedulerProxy * m_pNext{}, * m_pPrev{}; + + // A lock that protects resource allocation and deallocation of roots within this proxy. + _ReentrantBlockingLock m_lock; + + // Hill climbing instance. + HillClimbing * m_pHillClimbing; + + // Static and dynamic allocation data is populated and manipulated by the RM, but + // stored in the scheduler proxy for convenience. + union + { + // Data used during static allocation. + StaticAllocationData m_staticData; + + // Data used during dynamic allocation. + DynamicAllocationData m_dynamicData; + }; + + // Scheduler queue length. + unsigned int m_queueLength; + + // Unique identifier. + unsigned int m_id; + + // Variables that store policy elements. + unsigned int m_desiredHardwareThreads; + unsigned int m_minimumHardwareThreads; + unsigned int m_minConcurrency; + unsigned int m_maxConcurrency; + unsigned int m_targetOversubscriptionFactor; + int m_contextStackSize; + int m_contextPriority; + + // Current concurrency level (number of vproc roots). This includes vproc roots + // that are marked for removal but has not yet been destroyed by the scheduler. + // Protected by the scheduler proxy lock + unsigned int m_currentConcurrency; + + // The number of cores allocated to this scheduler proxy. + unsigned int m_numAllocatedCores; + + // At any time this has the number of additional cores that can be allocated with m_tof threads. + // When this falls to 0, all remaining allocated cores will get m_tof - 1 threads, to ensure that + // we don't go over max concurrency threads. + unsigned int m_numFullySubscribedCores; + + // The number of allocated cores that are borrowed. An borrowed core is a core that is assigned to + // one or more different schedulers, but was found to be idle. The RM temporarily assigns idle resources to + // schedulers that need them. + unsigned int m_numBorrowedCores; + + // The number of cores that have a subscribed thread on them. These cores are 'fixed' in that they cannot + // be removed by static/dynamic allocations, as long as the subscribed thread is present on them. + unsigned int m_numFixedCores; + + // The number of virtual processors (threads) that were added to the related scheduler via initial + // allocation or core migration. Does not include oversubscribed virtual processors. + unsigned int m_numAssignedThreads; + + // The number of external threads that were added to the related scheduler via external subscription calls. + unsigned int m_numExternalThreads; + + // The number of cores that external threads occupy exclusively. + unsigned int m_numExternalThreadCores; + + // The number of hardware threads available on this machine. + unsigned int m_coreCount; + + // Number of nodes in the allocated nodes array. + unsigned int m_nodeCount; + + // List of execution resources representing subscribed threads + List m_threadSubscriptions; + + // Used to determine whether statistical rebalancing is used for this scheduler proxy. + bool m_fDoHillClimbing; + }; + + #pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5c2e640cc8545bbacc2746a63c396b97a429583 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.cpp @@ -0,0 +1,294 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulingNode.cpp +// +// Source file containing the SchedulingNode implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + SchedulingNode::SchedulingNode(const QuickBitSet& resourceSet, DWORD numaNodeNumber, SchedulingRing *pRing) + : m_pRing(pRing) + , m_resourceSet(resourceSet) + , m_virtualProcessorAvailableCount(0) + , m_virtualProcessorsPendingThreadCreate(0) + , m_virtualProcessorCount(0) // needed for scheduling rings + , m_ramblingCount(0) + , m_numaNodeNumber(numaNodeNumber) + , m_virtualProcessors(pRing->m_pScheduler, 256, ListArray::DeletionThresholdInfinite) + { + m_pScheduler = m_pRing->m_pScheduler; + m_id = m_pRing->Id(); + } + + SchedulingNode::~SchedulingNode() + { + Cleanup(); + } + + void SchedulingNode::Cleanup() + { + // + // Do not clean up m_pRing here, it is done at SchedulerBase::m_rings + // + + // Cleanup of the virtual processors does not need to explicitly happen. When + // the destructor of the list array is called, it will internally delete + // all of its elements + } + + /// + /// Creates and adds a new virtual processor in the node to associated with the root provided. + /// NOTE: For non-oversubscribed vprocs this API is currently will only work for initial allocation. + /// + /// + /// The virtual processor root to create the virtual processor with. + /// + /// + /// True if this is an oversubscribed virtual processor. + /// + /// + /// The newly created virtual processor. + /// + VirtualProcessor* SchedulingNode::AddVirtualProcessor(IVirtualProcessorRoot *pOwningRoot, bool fOversubscribed) + { + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + + // Try and grab a virtual processor from the free pool before creating a new one + VirtualProcessor *pVirtualProcessor = m_virtualProcessors.PullFromFreePool(); + if (pVirtualProcessor == NULL) + { + pVirtualProcessor = m_pScheduler->CreateVirtualProcessor(this, pOwningRoot); + } + else + { + pVirtualProcessor->Initialize(this, pOwningRoot); + } + + if (fOversubscribed) + { + ASSERT(pCurrentContext != NULL && !pCurrentContext->IsExternal()); + InternalContextBase * pOversubscribingContext = static_cast(pCurrentContext); + + pVirtualProcessor->m_fOversubscribed = true; + pVirtualProcessor->m_pOversubscribingContext = pOversubscribingContext; + + // The oversubscribed vproc is fenced by adding it to the list array below. + pOversubscribingContext ->SetOversubscribedVProc(pVirtualProcessor); + } + + // We increment the total count of virtual processors on the node since the rambling logic uses this count. + InterlockedIncrement(&m_virtualProcessorCount); + m_pScheduler->IncrementActiveResourcesByMask(pVirtualProcessor->GetMaskId()); + + // If no virtual processors are 'available' in the scheduler, try to start this one up right away, if not, make it available, + // and increment the counts to indicate this. The only exception is the first virtual processor added as part of the initial + // set of virtual processors. + // + // @TODO: Q: Is the lack of relative atomicity between the two counts (avail / pending thread) a problem here for any real + // scenario? + if ((m_pScheduler->m_virtualProcessorAvailableCount == m_pScheduler->m_virtualProcessorsPendingThreadCreate) && (m_pScheduler->m_virtualProcessorCount > 0)) + { + // + // The check above is not accurate, since the count may increase right after the check -> in the worst case, the virtual + // processor is activated when it should've been left available. + // + // We should only be activating virtual processors as they are added, if they are either oversubscribed or as a result + // of core migration. The initial set of virtual processors should never be activated here. + // + ASSERT(pCurrentContext == NULL || fOversubscribed); + + // + // The vproc should be added to the list array only after it is fully initialized. If this is an oversubscribed vproc, + // we need to synchronize with a concurrent RemoveCore, which assumes it can party on the vproc if it is found in the list + // array. + // + m_virtualProcessors.Add(pVirtualProcessor); + + // + // Activation of a virtual processor synchronizes with finalization. If the scheduler is in the middle of finalization + // or has already shutdown, the API will return false. + // + bool activated = m_pScheduler->VirtualProcessorActive(true); + + if (activated) + { + ScheduleGroupSegmentBase * pSegment = (pCurrentContext != NULL) ? + pCurrentContext->GetScheduleGroupSegment() : + m_pRing->GetAnonymousScheduleGroupSegment(); + pVirtualProcessor->StartupWorkerContext(pSegment); + } + else + { + // + // We do nothing here since the scheduler is shutting down/has shutdown. The virtual processor remains unavailable, + // and since we didn't increment available counts, we don't have to decrement them. + // + } + } + else + { + // + // The vproc should be added to the list array only after it is fully initialized. If this is an oversubscribed vproc, + // we need to synchronize with a concurrent RemoveVirtualProcessor, which assumes it can party on the vproc if it is + // found in the list array. + // + m_virtualProcessors.Add(pVirtualProcessor); + pVirtualProcessor->MakeAvailable(VirtualProcessor::AvailabilityInactive, false); + + OMTRACE(MTRACE_EVT_MADEAVAILABLE, m_pScheduler, SchedulerBase::FastCurrentContext(), pVirtualProcessor, NULL); + OMTRACE(MTRACE_EVT_AVAILABLEVPROCS, m_pScheduler, SchedulerBase::FastCurrentContext(), this, m_pScheduler->m_virtualProcessorAvailableCount); + } + + return pVirtualProcessor; + } + + /// + /// Find the virtual processor in this node that matches the root provided. + /// + /// + /// The virtual processor root to match. + /// + /// + /// IMPORTANT: This API is only called while removing virtual processors via IScheduler::RemoveVirtualProcessors. + /// If this functionality is needed at other call sites in the future, the implementation may need to be + /// reevaluated (see comments below). + /// + VirtualProcessor* SchedulingNode::FindMatchingVirtualProcessor(IVirtualProcessorRoot* pRoot) + { + int arraySize = m_virtualProcessors.MaxIndex(); + + for (int i = 0; i < arraySize; i++) + { + VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i]; + + // It is ok to test the owning root here without a lock. If the owning root matches what we're looking for, + // we are guaranteed it will not change (by way of the virtual processor being retired and reused). This is because + // the call to IVirtualProcessorRoot::Remove in the virtual processor retirement code path is serialized in the RM + // before or after the call to IScheduler::RemoveVirtualProcessors. i.e. if we find an owning root that matches, the retirement + // path is unable to set it to NULL until after we're done. + if ((pVirtualProcessor != NULL) && (pVirtualProcessor->m_pOwningRoot == pRoot)) + { + return pVirtualProcessor; + } + } + + return NULL; + } + + InternalContextBase *SchedulingNode::StealLocalRunnableContext(VirtualProcessor* pSkipVirtualProcessor) + { + InternalContextBase *pContext = NULL; + int skipIndex, startIndex; + int arraySize = m_virtualProcessors.MaxIndex(); + + if (pSkipVirtualProcessor != NULL) + { + skipIndex = pSkipVirtualProcessor->m_listArrayIndex; + startIndex = 1; + } + else + { + skipIndex = 0; + startIndex = 0; + } + + for (int i = startIndex; i < arraySize; i++) + { + int index = (i + skipIndex) % arraySize; + VirtualProcessor *pVirtualProcessor = m_virtualProcessors[index]; + if (pVirtualProcessor == NULL) + { + continue; + } + + pContext = pVirtualProcessor->m_localRunnableContexts.Steal(); + if (pContext != NULL) + { +#if defined(_DEBUG) + pContext->SetDebugBits(CTX_DEBUGBIT_STOLENFROMLOCALRUNNABLECONTEXTS); +#endif // _DEBUG + + break; + } + } + return pContext; + } + + /// + /// Find an available virtual processor in the scheduling node. We claim ownership of the virtual + /// processor and return it. + /// + bool SchedulingNode::FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket, + location bias, + ULONG type) + { + if (bias._GetType() == location::_ExecutionResource) + { + VirtualProcessor *pBiasProc = FindVirtualProcessorByLocation(&bias); + ASSERT(!pBiasProc || pBiasProc->GetOwningNode() == this); + if (pBiasProc && pBiasProc->ClaimExclusiveOwnership(ticket, type)) + return true; + } + + // The callers of this API MUST check that that the available virtual processor count in the scheduling node + // is non-zero before calling the API. We avoid putting that check here since it would evaluate to false + // most of the time, and it saves the function call overhead on fast paths (chore push) + + for (int i = 0; i < m_virtualProcessors.MaxIndex(); i++) + { + VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i]; + + if (pVirtualProcessor != NULL && pVirtualProcessor->ClaimExclusiveOwnership(ticket, type)) + return true; + } + + return false; + } + + /// + /// Gets a location object which represents the scheduling node. + /// + location SchedulingNode::GetLocation() + { + return location(location::_SchedulingNode, m_id, m_pScheduler->Id(), this); + } + + /// + /// Returns a virtual processor from the given location. The virtual processor must be within this node. + /// + VirtualProcessor* SchedulingNode::FindVirtualProcessorByLocation(const location* pLoc) + { + if (pLoc->_GetType() != location::_ExecutionResource) + return NULL; + + if (m_pScheduler->IsLocationBound(pLoc)) + return pLoc->_As(); + + // + // The specified location has not been specifically bound yet. Find any virtual processor which we deem appropriate for the binding + // to the specified execution resource id. + // + for (int i = 0; i < m_virtualProcessors.MaxIndex(); i++) + { + VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i]; + + if (pVirtualProcessor != NULL && pVirtualProcessor->GetExecutionResourceId() == pLoc->_GetId()) + return pVirtualProcessor; + } + + return NULL; + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.h new file mode 100644 index 0000000000000000000000000000000000000000..bd407d2a6a41edeedcae8a4611cd08f56710a11f --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.h @@ -0,0 +1,251 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulingNode.h +// +// Source file containing the SchedulingNode declaration. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + /// + /// A scheduling node corresponds to a NUMA node or a processor package; containing one or more virtual processor groups. + /// + class SchedulingNode + { + public: + + /// + /// Constructs a scheduling node. + /// + SchedulingNode(const QuickBitSet& resourceSet, DWORD numaNodeNumber, SchedulingRing *pRing); + + /// + /// Destroys a scheduling node. + /// + ~SchedulingNode(); + + /// + /// Creates and adds a new virtual processor in the node to associated with the root provided. + /// NOTE: For non-oversubscribed vprocs this API is currently will only work for initial allocation. + /// + /// + /// The virtual processor root to create the virtual processor with. + /// + /// + /// True if this is an oversubscribed virtual processor. + /// + /// + /// The newly created virtual processor. + /// + VirtualProcessor* AddVirtualProcessor(IVirtualProcessorRoot *pOwningRoot, bool fOversubscribed = false); + + /// + /// Returns the scheduler associated with the node. + /// + SchedulerBase * GetScheduler() { return m_pScheduler; } + + /// + /// Returns the scheduling ring associated with the node. + /// + SchedulingRing * GetSchedulingRing() { return m_pRing; } + + /// + /// Find the virtual processor in this node that matches the root provided. + /// + /// + /// The virtual processor root to match. + /// + VirtualProcessor* FindMatchingVirtualProcessor(IVirtualProcessorRoot* pRoot); + + /// + /// Returns the ID of the scheduling node. + /// + int Id() const + { + return m_id; + } + + /// + /// Returns the first virtual processor in the non-cyclic range [min, max). If such is found + /// the virtual processor is returned and pIdx contains its index within the list array. + /// If not found, NULL is returned and the value in pIdx is unspecified. + /// + VirtualProcessor *FindVirtualProcessor(int min, int max, int *pIdx) + { + VirtualProcessor *pVProc = NULL; + int i = min; + for (; i < max && pVProc == NULL; ++i) + { + pVProc = m_virtualProcessors[i]; + } + + // + // The loop incremented "i" prior to the check. If found, the index is i - 1. If not, we care + // not what pIdx contains. + // + *pIdx = i - 1; + return pVProc; + } + + /// + /// Returns the first virtual processor. + /// + /// + /// The iterator position of the returned virtual processor will be placed here. This can only be + /// utilized as the pIdx parameter or the idxStart parameter of a GetNextVirtualProcessor. + /// + VirtualProcessor *GetFirstVirtualProcessor(int *pIdx) + { + return FindVirtualProcessor(0, m_virtualProcessors.MaxIndex(), pIdx); + } + + /// + /// Returns the next virtual processor in an iteration. + /// + VirtualProcessor *GetNextVirtualProcessor(int *pIdx, int idxStart = 0) + { + VirtualProcessor *pVProc = NULL; + + int min = *pIdx + 1; + if (min > idxStart) + { + pVProc = FindVirtualProcessor(min, m_virtualProcessors.MaxIndex(), pIdx); + min = 0; + } + + if (pVProc == NULL) + pVProc = FindVirtualProcessor(min, idxStart, pIdx); + + return pVProc; + } + + /// + /// Returns whether a virtual processor is available. + /// + bool HasVirtualProcessorAvailable() const + { + return m_virtualProcessorAvailableCount > 0; + } + + /// + /// Returns whether a virtual processor is waiting for throttling. + /// + bool HasVirtualProcessorPendingThread() const + { + return m_virtualProcessorsPendingThreadCreate > 0; + } + + /// + /// Returns whether a virtual processor is available to execute new work. + /// + bool HasVirtualProcessorAvailableForNewWork() const + { + // + // The observational race (lack of atomicity between the two reads) should not matter. If it does in some obscure + // case, a new atomic counter can be added. + // + return (m_virtualProcessorAvailableCount - m_virtualProcessorsPendingThreadCreate) > 0; + } + + /// + /// Gets a location object which represents the scheduling node. + /// + location GetLocation(); + + /// + /// Returns a virtual processor from the given location. The virtual processor must be within this node. + /// + VirtualProcessor* FindVirtualProcessorByLocation(const location* pLoc); + + /// + /// Determines whether the scheduling node contains an execution resource with ID as specified. Note that this does NOT return + /// whether the said resource is available in the scheduler -- only whether the given resource ID is logically contained in the + /// node. The scheduler may have no virtual processor with that execution resource ID at the moment. + /// + bool ContainsResourceId(unsigned int resourceId) /*const*/ + { + return m_resourceBitMap.Exists(resourceId); + } + + /// + /// Notifies the node of a resource that is contained within it and its assigned position in all bitmasks used by all ConcRT + /// schedulers. + /// + void NotifyResource(unsigned int resourceId, unsigned int maskId) + { + m_resourceBitMap.Insert(resourceId, maskId); + } + + /// + /// Returns the bitset for all resources in the node. + /// + const QuickBitSet& GetResourceSet() + { + return m_resourceSet; + } + + /// + /// Gets the NUMA node to which this scheduling node belongs. + /// + DWORD GetNumaNodeNumber() const + { + return m_numaNodeNumber; + } + + private: + friend class SchedulerBase; + friend class VirtualProcessor; + friend class InternalContextBase; + friend class FairScheduleGroup; + template friend class ListArray; + + // Owning scheduler + SchedulerBase *m_pScheduler; + + // Owning ring + SchedulingRing * const m_pRing; + + // The bit-set identifying execution resources within this node for quick affinity masking. + QuickBitSet m_resourceSet; + + // Maps resource IDs contained within the node to a mask identifier + Hash m_resourceBitMap; + + volatile LONG m_virtualProcessorAvailableCount; + volatile LONG m_virtualProcessorsPendingThreadCreate; + + volatile LONG m_virtualProcessorCount; + volatile LONG m_ramblingCount; // rambling -- searching foreign nodes for work + + DWORD m_numaNodeNumber; + + int m_id; + + // Virtual processors owned by this node. + ListArray m_virtualProcessors; + + InternalContextBase *StealLocalRunnableContext(VirtualProcessor* pSkipVirtualProcessor = NULL); + + /// + /// Find an available virtual processor in the scheduling node. + /// + bool FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket, + location bias = location(), + ULONG type = VirtualProcessor::AvailabilityAny); + + void Cleanup(); + + // Prevent warning about generated assignment operator & copy constructors. + SchedulingNode(const SchedulingNode&); + void operator=(const SchedulingNode&); + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d321d6ca6eccf35c4ecab8307b42137d768daab2 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.cpp @@ -0,0 +1,73 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulingRing.cpp +// +// Source file containing the SchedulingRing implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Construct a new scheduling ring. + /// + SchedulingRing::SchedulingRing(SchedulerBase *pScheduler, int id) + : m_pScheduler(pScheduler) + , m_pNode(NULL) // Will be set later explicitly by the creating scheduler + , m_pAnonymousSegment(NULL) + , m_affineSegments(pScheduler, 256, 64) + , m_nonAffineSegments(pScheduler, 256, 64) + , m_nextAffineSegment(0) + , m_nextNonAffineSegment(0) + , m_id(id) + , m_active(0) + { + // + // Create the anonymous schedule group early. UMS schedulers need somewhere to begin a search for a given node that is guaranteed + // to be safe. This is the only such place. + // + // Create schedule group takes a reference to the schedule group. The scheduling + // node maintains this reference and will release it when it disassociates from the + // schedule group (either in the destructor, or if the schedule group is moved to + // a different node due to resource management reclaiming the node). + // + location unbiased; + m_pAnonymousSegment = pScheduler->GetAnonymousScheduleGroup()->CreateSegment(&unbiased, this); + } + + SchedulingRing::~SchedulingRing() + { + ASSERT(m_pAnonymousSegment != NULL); + m_pAnonymousSegment = NULL; + } + + // + // Called when a schedule group's ref count is 0. remove this schedule group from the action. + // + void SchedulingRing::RemoveScheduleGroupSegment(ScheduleGroupSegmentBase *pSegment) + { + if (pSegment->GetAffinity()._Is_system()) + m_nonAffineSegments.Remove(pSegment); + else + m_affineSegments.Remove(pSegment); + } + + /// + /// Activates the ring. + /// + void SchedulingRing::Activate() + { + InterlockedExchange(&m_active, 1); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.h new file mode 100644 index 0000000000000000000000000000000000000000..badb529727a697a7f049f925b6b28f29a9026d09 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.h @@ -0,0 +1,255 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SchedulingRing.h +// +// Source file containing the SchedulingRing declaration. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + /// + /// A scheduling node corresponds to a NUMA node or a processor package; containing one or more virtual processor groups. + /// + class SchedulingRing + { + public: + SchedulingRing(SchedulerBase *pScheduler, int id); + + ~SchedulingRing(); + + int Id() const + { + return m_id; + } + + // Create a new Schedule Group + ScheduleGroupBase *AllocateScheduleGroup(); + + // Delete a Schedule Group + void FreeScheduleGroup(ScheduleGroupBase *pGroup); + + // Create a schedule group, add it to the list of groups + ScheduleGroupBase *CreateScheduleGroup(); + + ScheduleGroupSegmentBase *GetAnonymousScheduleGroupSegment() const + { + return m_pAnonymousSegment; + } + + /// + /// Returns a shared index to pseudo-round robin through affine schedule group segments within the ring. + /// + ScheduleGroupSegmentBase *GetPseudoRRAffineScheduleGroupSegment(int *pIdx) + { + int min = m_nextAffineSegment; + + ScheduleGroupSegmentBase *pSegment = FindScheduleGroupSegment(min, m_affineSegments.MaxIndex(), pIdx, &m_affineSegments); + if (pSegment == NULL && min != 0) + pSegment = FindScheduleGroupSegment(0, min, pIdx, &m_affineSegments); + + return pSegment; + } + + /// + /// Returns a shared index to pseudo-round robin through non-affine schedule group segments within the ring. + /// + ScheduleGroupSegmentBase *GetPseudoRRNonAffineScheduleGroupSegment(int *pIdx) + { + int min = m_nextNonAffineSegment; + + ScheduleGroupSegmentBase *pSegment = FindScheduleGroupSegment(min, m_nonAffineSegments.MaxIndex(), pIdx, &m_nonAffineSegments); + if (pSegment == NULL && min != 0) + pSegment = FindScheduleGroupSegment(0, min, pIdx, &m_nonAffineSegments); + + return pSegment; + } + + /// + /// Sets a shared index to pseudo-round robin through affine schedule group segments within the ring. This sets the index + /// to the schedule group segment *AFTER* idx in the iterator position. + /// + void SetPseudoRRAffineScheduleGroupSegmentNext(int idx) + { + m_nextAffineSegment = (idx + 1) % (m_affineSegments.MaxIndex()); + ASSERT(m_nextAffineSegment >= 0); + } + + /// + /// Sets a shared index to pseudo-round robin through non-affine schedule group segments within the ring. This sets the index + /// to the schedule group segment *AFTER* idx in the iterator position. + /// + void SetPseudoRRNonAffineScheduleGroupSegmentNext(int idx) + { + m_nextNonAffineSegment = (idx + 1) % (m_nonAffineSegments.MaxIndex()); + ASSERT(m_nextNonAffineSegment >= 0); + } + + /// + /// Returns the first affine schedule group segment within the ring. + /// + /// + /// The iterator position of the returned schedule group segment will be placed here. This can only be + /// utilized as the pIdx parameter or the idxStart parameter of a GetNextAffineScheduleGroup. + /// + ScheduleGroupSegmentBase *GetFirstAffineScheduleGroupSegment(int *pIdx) + { + return GetFirstScheduleGroupSegment(pIdx, &m_affineSegments); + } + + /// + /// Returns the next affine schedule group segment in an iteration. + /// + ScheduleGroupSegmentBase *GetNextAffineScheduleGroupSegment(int *pIdx, int idxStart = 0) + { + return GetNextScheduleGroupSegment(pIdx, idxStart, &m_affineSegments); + } + + /// + /// Returns the first non-affine schedule group segment within the ring. + /// + /// + /// The iterator position of the returned schedule group segment will be placed here. This can only be + /// utilized as the pIdx parameter or the idxStart parameter of a GetNextNonAffineScheduleGroup. + /// + ScheduleGroupSegmentBase *GetFirstNonAffineScheduleGroupSegment(int *pIdx) + { + return GetFirstScheduleGroupSegment(pIdx, &m_nonAffineSegments); + } + + /// + /// Returns the next non-affine schedule group segment in an iteration. + /// + ScheduleGroupSegmentBase *GetNextNonAffineScheduleGroupSegment(int *pIdx, int idxStart = 0) + { + return GetNextScheduleGroupSegment(pIdx, idxStart, &m_nonAffineSegments); + } + + /// + /// Returns the node which owns this ring. + /// + SchedulingNode *GetOwningNode() const + { + return m_pNode; + } + + /// + /// Returns whether this is an active ring or not. + /// + bool IsActive() const + { + return (m_active != 0); + } + + /// + /// Activates the ring. + /// + void Activate(); + + private: + friend class SchedulerBase; + friend class ScheduleGroupBase; + friend class ScheduleGroupSegmentBase; + friend class FairScheduleGroup; + friend class CacheLocalScheduleGroup; + friend class SchedulingNode; + friend class VirtualProcessor; + friend class InternalContextBase; + friend class ThreadInternalContext; + + // Owning scheduler + SchedulerBase *m_pScheduler; + + // Owning Node + SchedulingNode *m_pNode; + + // The anonymous schedule group - for external contexts and tasks without an explicitly specified schedule group. + // There is one anonymous group segment per scheduling node. + ScheduleGroupSegmentBase * m_pAnonymousSegment; + + // Scheduler group segments owned by this ring which have explicitly specified affinity. + ListArray m_affineSegments; + + // Scheduler groups segments owned by this ring which do not have explicitly specified affinity. + ListArray m_nonAffineSegments; + + // Pseudo Round robin indicies. + int m_nextAffineSegment; + int m_nextNonAffineSegment; + + int m_id; + + // An indication as to whether the ring is active. + volatile LONG m_active; + + // Removes the schedule group segment from the appropriate list. + void RemoveScheduleGroupSegment(ScheduleGroupSegmentBase* pGroup); + + void SetOwningNode(SchedulingNode *pNode) + { + m_pNode = pNode; + } + + /// + /// Returns the first schedule group segment in the non-cyclic range [min, max). If such is found + /// the schedule group segment is returned and pIdx contains its index within the list array. + /// If not found, NULL is returned and the value in pIdx is unspecified. + /// + ScheduleGroupSegmentBase *FindScheduleGroupSegment(int min, int max, int *pIdx, ListArray *pSegmentList) + { + ScheduleGroupSegmentBase *pSegment = NULL; + int i = min; + for (; i < max && pSegment == NULL; ++i) + { + pSegment = (*pSegmentList)[i]; + } + + // + // The loop incremented "i" prior to the check. If found, the index is i - 1. If not, we care + // not what pIdx contains. + // + *pIdx = i - 1; + return pSegment; + } + + /// + /// Returns the first schedule group. + /// + /// + /// The iterator position of the returned schedule group will be placed here. This can only be + /// utilized as the pIdx parameter or the idxStart parameter of a GetNextScheduleGroup. + /// + ScheduleGroupSegmentBase *GetFirstScheduleGroupSegment(int *pIdx, ListArray* pSegmentList) + { + return FindScheduleGroupSegment(0, pSegmentList->MaxIndex(), pIdx, pSegmentList); + } + + /// + /// Returns the next schedule group in an iteration. + /// + ScheduleGroupSegmentBase *GetNextScheduleGroupSegment(int *pIdx, int idxStart, ListArray* pSegmentList) + { + ScheduleGroupSegmentBase *pSegment = NULL; + + int min = *pIdx + 1; + if (min > idxStart) + { + pSegment = FindScheduleGroupSegment(min, pSegmentList->MaxIndex(), pIdx, pSegmentList); + min = 0; + } + + if (pSegment == NULL) + pSegment = FindScheduleGroupSegment(min, idxStart, pIdx, pSegmentList); + + return pSegment; + } + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3d99e531e31d891b687dbfef4d4bf951320e558 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.cpp @@ -0,0 +1,1659 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SearchAlgorithms.cpp +// +// Implementation file containing all scheduling algorithms. +// +// **PLEASE NOTE**: +// +// Any search algorithm in here must be fully reentrant. On UMS schedulers, the UMS primary will invoke these routines +// to perform a search for work. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + //*************************************************************************** + // + // General: + // + + /// + /// Constructs a work item from an internal context. + /// + WorkItem::WorkItem(InternalContextBase *pContext) : + m_type(WorkItemTypeContext), + m_pSegment(pContext->GetScheduleGroupSegment()), + m_pContext(pContext) + { + } + + /// + /// Resolves a token to an underlying work item. + /// + bool WorkItem::ResolveToken() + { + CONCRT_COREASSERT(IsToken()); + switch(m_type) + { + case WorkItemTypeRealizedChoreToken: + { + RealizedChore *pChore = m_pSegment->GetRealizedChore(); + if (pChore != NULL) + { + m_pRealizedChore = pChore; + m_type = WorkItemTypeRealizedChore; + } + break; + } + case WorkItemTypeUnrealizedChoreToken: + { + if (m_pWorkQueue == MAILBOX_LOCATION) + { + _UnrealizedChore *pChore; + if (!m_pSegment->m_mailedTasks.Dequeue(&pChore)) + pChore = NULL; + + if (pChore != NULL) + { + // The chore may not be from a detached workqueue, but since it is dequeued from a mailbox, we set it as detached + // which will add the stealing context to a list in the task collection instead of the owning contexts stealer collection. + pChore->_SetDetached(true); + m_pUnrealizedChore = pChore; + m_type = WorkItemTypeUnrealizedChore; + } + } + else + { + _UnrealizedChore *pChore = m_pWorkQueue->Steal(false); + if (pChore != NULL) + { + m_pUnrealizedChore = pChore; + m_type = WorkItemTypeUnrealizedChore; + } + break; + } + } + } + + return !IsToken(); + } + + /// + /// Binds the work item to a context and returns the context. This may or may not allocate a new context. Note that + /// act of binding which performs a context allocation will transfer a single count of work to the counter of the new + /// context. + /// + InternalContextBase *WorkItem::Bind() + { + if (IsToken() && !ResolveToken()) + return NULL; + + switch(m_type) + { + case WorkItemTypeUnrealizedChore: + m_pContext = m_pSegment->GetInternalContext(m_pUnrealizedChore, true); + if (m_pContext != NULL) + { + m_pContext->SaveDequeuedTask(); + m_type = WorkItemTypeContext; + } + break; + case WorkItemTypeRealizedChore: + m_pContext = m_pSegment->GetInternalContext(m_pRealizedChore); + if (m_pContext != NULL) + { + m_pContext->SaveDequeuedTask(); + m_type = WorkItemTypeContext; + } + break; + case WorkItemTypeContext: + break; + } + + return m_pContext; + } + + /// + /// Binds the work item to the specified context (which is allocated). This will never allocate a new context. + /// + void WorkItem::BindTo(InternalContextBase *pContext) + { + switch(m_type) + { + case WorkItemTypeUnrealizedChore: + pContext->PrepareForUse(m_pSegment, m_pUnrealizedChore, true); + break; + case WorkItemTypeRealizedChore: + pContext->PrepareForUse(m_pSegment, m_pRealizedChore, false); + break; + } + + m_pContext = pContext; + m_type = WorkItemTypeContext; + } + + /// + /// Invokes the work item. + /// + void WorkItem::Invoke() + { + CONCRT_COREASSERT(m_type == WorkItemTypeRealizedChore || m_type == WorkItemTypeUnrealizedChore); + switch(m_type) + { + case WorkItemTypeUnrealizedChore: + m_pUnrealizedChore->_Invoke(); + break; + case WorkItemTypeRealizedChore: + m_pRealizedChore->Invoke(); + m_pSegment->GetGroup()->GetScheduler()->ReleaseRealizedChore(m_pRealizedChore); + break; + } + } + + /// + /// Transfers reference counts as necessary to inline the given work item on the given context. This may + /// only be called on a work item that can be inlined (e.g.: an unbound one). + /// + /// + /// The context that is attempting to inline the work item. + /// + void WorkItem::TransferReferences(InternalContextBase *pContext) + { + ASSERT(m_type == WorkItemTypeRealizedChore || m_type == WorkItemTypeUnrealizedChore); + + ScheduleGroupSegmentBase *pSegment = pContext->GetScheduleGroupSegment(); + if (m_type == WorkItemTypeRealizedChore) + { + if (pSegment->GetGroup() != m_pSegment->GetGroup()) + { + pContext->SwapScheduleGroupSegment(m_pSegment, false); + } + else + { + // + // If newGroup is the same as the existing group, we need to release a reference since both, the context, + // and the realized chore, have a reference on the schedule group, and we only need to hold one reference. + // + OMTRACE(MTRACE_EVT_WORKITEMDEREFERENCE, pSegment->GetGroup(), NULL, NULL, 0); + pSegment->GetGroup()->InternalRelease(); + } + + } + else if (pSegment->GetGroup() != m_pSegment->GetGroup()) + { + pContext->SwapScheduleGroupSegment(m_pSegment, true); + } + } + + /// + /// Resets the work search context to utilize the specified algorithm at the starting iterator position. + /// + /// + /// The virtual processor binding the searching. + /// + /// + /// The algorithm to reset the iterator with. + /// + void WorkSearchContext::Reset(VirtualProcessor *pVirtualProcessor, Algorithm algorithm) + { + m_LRCBias = 0;; + m_pVirtualProcessor = pVirtualProcessor; + m_maskId = m_pVirtualProcessor->GetMaskId(); + m_pScheduler = pVirtualProcessor->GetOwningNode()->GetScheduler(); + m_serviceTick = m_lastPriorityPull = platform::__GetTickCount64(); + + switch(algorithm) + { + case AlgorithmCacheLocal: + m_pSearchFn = &WorkSearchContext::SearchCacheLocal; + m_pSearchYieldFn = &WorkSearchContext::SearchCacheLocalYield; + break; + case AlgorithmFair: + m_pSearchFn = &WorkSearchContext::SearchFair; + m_pSearchYieldFn = &WorkSearchContext::SearchFairYield; + break; + default: + ASSERT(false); + } + } + + /// + /// Steals a local runnable from a virtual processor within the specified node. Note that this allows a given virtual processor + /// to be skipped. + /// + bool WorkSearchContext::StealLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pNode, VirtualProcessor *pSkipVirtualProcessor) + { + int idx; + VirtualProcessor *pVProc = pNode->GetFirstVirtualProcessor(&idx); + while (pVProc != NULL) + { + if (pVProc != pSkipVirtualProcessor) + { + pVProc->ServiceMark(m_serviceTick); + InternalContextBase *pContext = pVProc->StealLocalRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + return true; + } + } + + pVProc = pNode->GetNextVirtualProcessor(&idx); + } + + return false; + } + + /// + /// Steals a local runnable from a virtual processor of any scheduling node other than the specified local node. + /// + bool WorkSearchContext::StealForeignLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pLocalNode) + { + int idx; + SchedulingNode *pNode = m_pScheduler->GetFirstSchedulingNode(&idx); + while (pNode != NULL) + { + if (pNode != pLocalNode) + { + if (StealLocalRunnable(pWorkItem, pNode, NULL)) + return true; + } + + pNode = m_pScheduler->GetNextSchedulingNode(&idx); + } + + return false; + + } + + /// + /// Performs a pre-search for any "special" contexts (e.g.: the UMS SUT) + /// + bool WorkSearchContext::PreSearch(WorkItem *pWorkItem) + { + InternalContextBase *pContext = m_pVirtualProcessor->PreRunnableSearch(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + return true; + } + + return false; + } + + /// + /// Gets a local runnable context from the specified virtual processor. + /// + bool WorkSearchContext::GetLocalRunnable(WorkItem *pWorkItem, VirtualProcessor *pVirtualProcessor, bool fYieldingSearch) + { + if (fYieldingSearch) + { + InternalContextBase *pContext = pVirtualProcessor->GetLocalRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + return true; + } + } + else + { + BiasStageType biasStage = BiasStage(); + if (biasStage < BiasStageSkipLRC) + { + InternalContextBase *pContext = (biasStage == BiasStageFlipLRC) ? pVirtualProcessor->StealLocalRunnableContext() : pVirtualProcessor->GetLocalRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + LRCBias(); + return true; + } + } + + ResetLRCBias(); + } + return false; + } + + /// + /// Gets a runnable from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for a runnable context. + /// + /// + /// An indication of whether or not a runnable context was found in the segment. + /// + bool WorkSearchContext::GetRunnableContext(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment) + { + InternalContextBase *pContext = pSegment->GetRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + return true; + } + + return false; + } + + /// + /// Gets a realized chore from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for a realized chore. + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// An indication of whether or not a realized chore was found in the segment. + /// + bool WorkSearchContext::GetRealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork) + { + if (fRealWork) + { + RealizedChore *pRealizedChore = pSegment->GetRealizedChore(); + if (pRealizedChore != NULL) + { + *pWorkItem = WorkItem(pRealizedChore, pSegment); + return true; + } + } + else + { + if (pSegment->HasRealizedChores()) + { + *pWorkItem = WorkItem(pSegment); + return true; + } + } + + return false; + } + + /// + /// Gets an unrealized chore from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for an unrealized chore. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// An indication of whether or not an unrealized chore was found in the segment. + /// + bool WorkSearchContext::GetUnrealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fForceStealLocalized, bool fRealWork) + { + if (fRealWork) + { + _UnrealizedChore *pUnrealizedChore = pSegment->StealUnrealizedChore(fForceStealLocalized); + if (pUnrealizedChore != NULL) + { + *pWorkItem = WorkItem(pUnrealizedChore, pSegment); + return true; + } + } + else + { + // We should never be in the last pass of search for work (which is when fForceStealLocalized is set to true) if we're looking for a token. + ASSERT(!fForceStealLocalized); + WorkQueue *pWorkQueue = pSegment->LocateUnrealizedChores(); + if (pWorkQueue != NULL) + { + *pWorkItem = WorkItem(pWorkQueue, pSegment); + return true; + } + } + + return false; + } + + /// + /// Performs a quick search of a particular segment. + /// + bool WorkSearchContext::QuickSearch(ScheduleGroupSegmentBase *pQCSegment, + WorkItem *pWorkItem, + bool fLastPass, + ULONG allowableTypes) + { + if (((allowableTypes & WorkItem::WorkItemTypeContext) && GetRunnableContext(pWorkItem, pQCSegment)) || + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) && + GetRealizedChore(pWorkItem, pQCSegment, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore))) || + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) && + GetUnrealizedChore(pWorkItem, pQCSegment, fLastPass, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore)))) + { + return true; + } + + return false; + } + + /// + /// Performs a quick yielding search of a particular segment. + /// + bool WorkSearchContext::QuickSearchYield(ScheduleGroupSegmentBase *pQCSegment, + WorkItem *pWorkItem, + bool fLastPass, + ULONG allowableTypes) + { + if (((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) && + GetUnrealizedChore(pWorkItem, pQCSegment, fLastPass, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore))) || + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) && + GetRealizedChore(pWorkItem, pQCSegment, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore))) || + ((allowableTypes & WorkItem::WorkItemTypeContext) && GetRunnableContext(pWorkItem, pQCSegment))) + { + return true; + } + + return false; + } + + /// + /// Determines if a segment should be skipped given the search parameters and the segment's affinity. + /// + /// + /// The segment to query about skipping. + /// + /// + /// A segment which should be arbitrarily skipped regardless of affinity type. This parameter can be NULL. + /// + /// + /// The search affinity type to query for. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication as to whether pSegment should be skipped according to the pSkipSegment and affinity parameters. + /// + bool WorkSearchContext::SkipSegmentSearch(ScheduleGroupSegmentBase *pSegment, ScheduleGroupSegmentBase *pSkipSegment, SearchAffinity affinity, bool fLastPass) + { + if (pSegment == pSkipSegment) + { + return true; + } + + bool fSkip = false; + const location& segmentAffinity = pSegment->GetAffinity(); + + switch(affinity) + { + case SearchNonAffine: + // + // Skip if it has any affinity and we're looking for non-affine work. + // + fSkip = !segmentAffinity._Is_system(); + break; + + case SearchAffineLocal: + // + // Skip if it has specific affinity to something that doesn't intersect with us. + // + fSkip = segmentAffinity._Is_system() || !m_pVirtualProcessor->GetLocation()._FastVPIntersects(segmentAffinity); + break; + + case SearchAffineNotMe: + // + // Skip if it has specific affinity to us **OR** the virtual processors to which it has affinity are in the middle + // of search-for-work. This is an optimization to prevent us from ripping affine work out from underneath someone who + // will soon find it. + // + // In the last pass of SFW, we ignore this heuristic in order to avoid deadlock in required dependence cases. + // + fSkip = segmentAffinity._Is_system() || + (m_pVirtualProcessor->GetLocation()._FastVPIntersects(segmentAffinity) || + (m_pScheduler->HasSearchers(pSegment->GetAffinitySet()) && !fLastPass)); + break; + + default: + break; + + } + + return fSkip; + } + + /// + /// Searches the schedule group to which pSegment belongs to find a runnable. The group is searched for segments according to the specified + /// affinity type. + /// + /// + /// If an appropriate runnable is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool WorkSearchContext::GetRunnableContextWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, SearchAffinity affinity, bool fLastPass) + { + ScheduleGroupBase *pGroup = pSegment->GetGroup(); + + // + // @TODO_LOC: + // + // We need to slice this differently so that we pick up "local" affine work before "non-local" affine work, etc... + // + if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetRunnableContext(pWorkItem, pSegment)) + { + return true; + } + + ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine); + while(pCurSegment != NULL) + { + if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetRunnableContext(pWorkItem, pCurSegment)) + { + return true; + } + + pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment); + } + + return false; + } + + /// + /// Searches the schedule group to which pSegment belongs to find a realized chore. The group is searched for segments according to the specified + /// affinity type. + /// + /// + /// If an appropriate realized chore is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool WorkSearchContext::GetRealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass) + { + ScheduleGroupBase *pGroup = pSegment->GetGroup(); + + // + // @TODO_LOC: + // + // We need to slice this differently so that we pick up "local" affine work before "non-local" affine work, etc... + // + if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetRealizedChore(pWorkItem, pSegment, fRealWork)) + { + return true; + } + + ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine); + while(pCurSegment != NULL) + { + if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetRealizedChore(pWorkItem, pCurSegment, fRealWork)) + { + return true; + } + + pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment); + } + + return false; + } + + /// + /// Searches the schedule group to which pSegment belongs to find an unrealized chore. The group is searched for segments according to the + /// specified affinity type. + /// + /// + /// If an appropriate unrealized chore is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool WorkSearchContext::GetUnrealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass) + { + ScheduleGroupBase *pGroup = pSegment->GetGroup(); + + // + // @TODO_LOC: + // + // We need to slice this differently so that we pick up "local" affine work before "non-local" affine work, etc... We also might need to + // slice out pSegment first. The second aspect requires more thought. + // + if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pSegment, fLastPass, fRealWork)) + { + return true; + } + + ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine); + while(pCurSegment != NULL) + { + if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pCurSegment, fLastPass, fRealWork)) + { + return true; + } + + pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment); + } + + return false; + } + + + //*************************************************************************** + // + // Fair Searches + // + // NOTE: At present, we completely ignore affine lists because fair schedulers ignore location hints. This means you cannot "switch" scheduling + // to fair on a cache local scheduler should that ever come up. + // + + /// + /// Performs a fair search for runnables in the specified ring. + /// + bool WorkSearchContext::SearchFair_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing) + { + int idx; + ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL) + { + InternalContextBase *pContext = pSegment->GetRunnableContext(); + if (pContext != NULL) + { + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + *pWorkItem = WorkItem(pContext); + return true; + } + + pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + + } + + /// + /// Performs a fair search for realized chores in the specified ring. + /// + bool WorkSearchContext::SearchFair_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem) + { + int idx; + ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL) + { + if (fRealItem) + { + RealizedChore *pRealizedChore = pSegment->GetRealizedChore(); + if (pRealizedChore != NULL) + { + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + *pWorkItem = WorkItem(pRealizedChore, pSegment); + return true; + } + } + else + { + if (pSegment->HasRealizedChores()) + { + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + *pWorkItem = WorkItem(pSegment); + return true; + } + } + + pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + + } + + /// + /// Performs a fair search for unrealized chores in the specified ring. + /// + bool WorkSearchContext::SearchFair_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem) + { + int idx; + ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL) + { + if (fRealItem) + { + _UnrealizedChore *pUnrealizedChore = pSegment->StealUnrealizedChore(); + if (pUnrealizedChore != NULL) + { + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + *pWorkItem = WorkItem(pUnrealizedChore, pSegment); + return true; + } + } + else + { + WorkQueue *pWorkQueue = pSegment->LocateUnrealizedChores(); + if (pWorkQueue != NULL) + { + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + *pWorkItem = WorkItem(pWorkQueue, pSegment); + return true; + } + } + + pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + + } + + /// + /// Performs a fair search for work. + /// + bool WorkSearchContext::SearchFair(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool, ULONG allowableTypes) + { + bool fFound = false; + + CONCRT_COREASSERT(pOriginSegment != NULL); + // + // Do any up-front searching required for special circumstances (e.g.: UMS schedulers) + // + if (PreSearch(pWorkItem)) + return true; + + // + // The fair search essentially round robins among scheduling rings and groups within a ring. + // If you consider the search space as follows: + // + // SR SR SR SR + // Contexts ----------------------> + // Realized ----------------------> + // Unrealized ----------------------> + // + // fair scheduling will make horizontal slices through the search space to find work. + // + // Each entry in the above matrix can be viewed as: + // + // SG -> SG -> SG -> SG + // + // However, after finding work in a particular ring, fair will move onto the next ring in round-robin fashion. + // + + // + // At the top of each search, reset to the next ring in the round robin index. This is simply the starting point for this search. + // + SchedulingRing *pStartingRing = m_pScheduler->GetNextSchedulingRing(); + + if (allowableTypes & WorkItem::WorkItemTypeContext) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Runnables(pWorkItem, pRing); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + + if (!fFound) + fFound = StealForeignLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode()); + } + + if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore)) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Realized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore)); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + } + + if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore)) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Unrealized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore)); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + } + + return fFound; + } + + /// + /// Performs a fair search for work in the yielding case. + /// + bool WorkSearchContext::SearchFairYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *, bool, ULONG allowableTypes) + { + // + // The yielding case slices identically to the regular case excepting that the search is done in a pseudo-reverse order + // + bool fFound = false; + + // + // Do any up-front searching required for special circumstances (e.g.: UMS schedulers) + // + if (PreSearch(pWorkItem)) + return true; + + // + // At the top of each search, reset to the next ring in the round robin index. This is simply the starting point for this search. + // + SchedulingRing *pStartingRing = m_pScheduler->GetNextSchedulingRing(); + + if (allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Unrealized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore)); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + } + + + if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore)) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Realized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore)); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + } + + if (!fFound && (allowableTypes & WorkItem::WorkItemTypeContext)) + { + SchedulingRing *pRing = pStartingRing; + while (pRing != NULL) + { + fFound = SearchFair_Runnables(pWorkItem, pRing); + if (fFound) + { + m_pScheduler->SetNextSchedulingRing(pRing); + break; + } + + pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing); + } + + if (!fFound) + fFound = StealForeignLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode()); + } + + return fFound; + + } + + //*************************************************************************** + // + // Cache Local Searches + // + + /// + /// Searches for a runnable within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// Determines whether or not to check other local LRCs in this search. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a runnable was found in the bias segment, group, or the specified ring. + /// + bool WorkSearchContext::SearchCacheLocal_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fOtherLocalLRCCheck, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass) + { + if (pBiasSegment != NULL && GetRunnableContextWithinGroup(pWorkItem, pBiasSegment, affinity, fLastPass)) + { + return true; + } + + // + // As much as I abhor the one off placement of this here, it's the "cleanest" place to put this for its given location within SFW. + // Attempt to steal a local runnable context from the current node. + // + if (fOtherLocalLRCCheck && StealLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode(), m_pVirtualProcessor)) + { + return true; + } + + int idx; + ScheduleGroupSegmentBase *pSegment = + (affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL) + { + ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId); + if (pQCSegment) + { + if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes)) + return true; + } + + // + // Is this a segment we should skip: + // + // - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment). + // - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter. + // + if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetRunnableContext(pWorkItem, pSegment)) + { + if (affinity == SearchNonAffine) + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + else + pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx); + + return true; + } + + pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) : + pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + + } + + /// + /// Searches for a realized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a realized chore was found in the bias segment, group, or the specified ring. + /// + bool WorkSearchContext::SearchCacheLocal_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass) + { + bool fFound = false; + + if (pBiasSegment != NULL && GetRealizedChoreWithinGroup(pWorkItem, pBiasSegment, fRealWork, affinity, fLastPass)) + { + return true; + } + + int idx; + ScheduleGroupSegmentBase *pSegment = + (affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL && !fFound) + { + ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId); + if (pQCSegment) + { + if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes)) + return true; + } + + // + // Is this a segment we should skip: + // + // - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment). + // - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter. + // + if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetRealizedChore(pWorkItem, pSegment, fRealWork)) + { + if (affinity == SearchNonAffine) + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + else + pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx); + + return true; + } + + pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) : + pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + } + + /// + /// Searches for an unrealized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether an unrealized chore was found in the bias segment, group, or the specified ring. + /// + bool WorkSearchContext::SearchCacheLocal_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass) + { + bool fFound = false; + + if (pBiasSegment != NULL && GetUnrealizedChoreWithinGroup(pWorkItem, pBiasSegment, fRealWork, affinity, fLastPass)) + { + return true; + } + + int idx; + ScheduleGroupSegmentBase *pSegment = + (affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx); + + int idxStart = idx; + + while (pSegment != NULL && !fFound) + { + ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId); + if (pQCSegment) + { + if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes)) + return true; + } + + // + // Is this a segment we should skip: + // + // - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment). + // - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter. + // + if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pSegment, fLastPass, fRealWork)) + { + if (affinity == SearchNonAffine) + pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx); + else + pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx); + + return true; + } + + pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) : + pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart); + } + + return false; + } + + /// + /// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The segment to bias the search to. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool WorkSearchContext::SearchCacheLocal(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes) + { + bool fFound = false; + + if (PreSearch(pWorkItem)) + return true; + + ASSERT(pOriginSegment); + + m_serviceTick = platform::__GetTickCount64(); + m_pScheduler->PeriodicScan(m_serviceTick); + + // + // @TODO: This is a temporary patch until we have priority and boosts in the scheduler. Right now, search for any segment in the locked + // FIFO of "priority" segments to see if we need to service someone to avoid livelock. We also periodically scan to determine whether + // groups need to go into this list. + // + + if (CheckPriorityList(m_serviceTick)) + { + if (m_pScheduler->HasPriorityObjects()) + { + BoostedObject *pObject = m_pScheduler->GetNextPriorityObject(); + while (pObject != NULL) + { + if (pObject->IsScheduleGroupSegment()) + { + ScheduleGroupSegmentBase *pSegment = ScheduleGroupSegmentBase::FromBoostEntry(pObject); + OMTRACE(MTRACE_EVT_PRIORITYPULL, pSegment, NULL, m_pVirtualProcessor, 0); + if (QuickSearch(pSegment, pWorkItem, fLastPass, allowableTypes)) + { + fFound = true; + break; + } + } + else if (allowableTypes & WorkItem::WorkItemTypeContext) + { + VirtualProcessor *pVProc = VirtualProcessor::FromBoostEntry(pObject); + InternalContextBase *pContext = pVProc->StealLocalRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + fFound = true; + break; + } + } + + pObject = m_pScheduler->GetNextPriorityObject(); + } + } + + // + // If we found something in a priority segment, we need to mark the V-Proc so that it once again looks for affinitized work + // the next time through SFW. + // + m_pVirtualProcessor->MarkGrabbedPriority(); + } + + SchedulingRing *pOwningRing = m_pVirtualProcessor->GetOwningRing(); + + if (!fFound) + { + // + // Before describing the cache local search algorithm, some definitions to aid in this are in order: + // + // Work: + // local work -- Work within a node/ring that a given virtual processor belongs to is considered local work + // foreign work -- Work within a node/ring that a given virtual processor does *NOT* belong to is considered foreign work + // affine work -- Work which is placed at a location more specific than the system location is affine work + // non-affine work -- Work which is placed at the system location (or no location) is considered non-affine work + // + // Virtual Processors: + // rambling -- a given virtual processor is *rambling* when it is executing foreign work (regardless whether such work is affine to it or not) + // non-affine -- a given virtual processor is *non-affine* when it is executing non-affine work (regardless whether it is rambling or not) + // + // Virtual processors which are rambling or are executing non-affine work are tracked by the scheduler. When such virtual processors + // exist, notifications will be published whenever affine work or local work becomes available. + // + + // + // Look for work in the scheduler. **IN GENERAL**, we want to find work in the following order of precedence: + // + // Phase 1: Affine work + // Affine work in our current group (preferring local affine work) + // Local affine (to us) work (in our starting (home) ring) + // Foreign affine (to us) work (in foreign ring segments that match our affinity mask -- such have a segment in our ring by definition) + // + // - This phase may be skipped if we are executing non-affine work and have not received an affinity notification from the scheduler. + // Doing so prevents SFW from making a full pass per work item if no affinity has been used. + // + // Phase 2: Non-affine work + // Non-Affine work in our current group (preferring local work) + // Local non-affine work (in our starting (home ring)) + // Foreign non-affine work (in foreign rings). + // + // - This phase may *NEVER* be skipped. + // + // Phase 3: Affine work (non-local) + // Non-local affine (*NOT* to us) work (in foreign ring segments that do not match our affinity mask + // + // - This phase may be skipped in theory if we know that there is no affine work in the scheduler. For a case with no affinity used within + // any scheduling API, this phase is only hit if the scheduler is completely idle. At idle, performing a pass is likely little additional + // cost to any performance sensitive scenario. At present, this stage is not skipped for this reason. + // + // At a very high level, you can consider a cache local search to be making vertical slices through the search space as follows: + // + // SR SR SR SR + // Contexts | | | | + // Realized | | | | + // Unrealized v v v v + // + // where each entry in this matrix is a piece of a schedule group. + // + // Note that in the last pass of SFW, we cannot skip phases or segments. Doing so can lead us to deadlock in cases with required dependence + // (assumptions on concurrency level). + // + static const SearchAffinity phaseAffinities[] = { SearchAffineLocal, SearchNonAffine, SearchAffineNotMe }; + // { 1 , 0 , 2 }; + int startPhaseIndex = (!m_pVirtualProcessor->ExecutingAffine() && !m_pVirtualProcessor->CheckAffinityNotification() && !fLastPass) ? 1 : 0; + int maxPhaseIndex = SIZEOF_ARRAY(phaseAffinities) - 1; + + // Make sure we only check the vproc's LRC and local node LRCs once. This is done in this manner to ensure the odd placement of this within the + // search algorithm. This variable is set to false at the end of the first pass through the inner loop. + bool fLocalCheck = true; + for(int phaseIndex = startPhaseIndex; !fFound && phaseIndex <= maxPhaseIndex; ++phaseIndex) // This loop goes through the phases in the phaseAffinity array. + { + SearchAffinity srchType = phaseAffinities[phaseIndex]; + + // At the outset of every pass, we bias to the originating segment/group and the current virtual processors owning ring. + // Note that if we are searching for non-local affinework, we skip the owning ring (by definition, it's local). + ScheduleGroupSegmentBase *pBiasSegment = pOriginSegment; + SchedulingRing *pRing = pOwningRing; + + while (pRing != NULL) + { + ScheduleGroupSegmentBase* pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId); + if (pQCSegment) + { + if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes)) + { + fFound = true; + break; + } + } + + if ((fLocalCheck && (allowableTypes & WorkItem::WorkItemTypeContext) && + GetLocalRunnable(pWorkItem, m_pVirtualProcessor, false)) || + + ((allowableTypes & WorkItem::WorkItemTypeContext) && + SearchCacheLocal_Runnables(pWorkItem, + pRing, + pBiasSegment, + fLocalCheck, + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) && + SearchCacheLocal_Realized(pWorkItem, + pRing, + pBiasSegment, + !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore), + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) && + SearchCacheLocal_Unrealized(pWorkItem, + pRing, + pBiasSegment, + !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore), + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeContext) && phaseIndex == maxPhaseIndex && + StealLocalRunnable(pWorkItem, pRing->GetOwningNode(), m_pVirtualProcessor))) + { + fFound = true; + break; + } + + // Make sure we only steal from vproc LRCs in the local node once. This is done in this manner to ensure the odd placement of this within the + // search algorithm. + fLocalCheck = false; + + // The first time through the loop, not only did we bias to pBiasSegment, but to pStartingRing as well. Remove the bias and move to the next ring. + pBiasSegment = NULL; + pRing = m_pScheduler->GetNextSchedulingRing(pOwningRing, pRing); + + } // end of while (pRing != NULL) - this loop goes over all rings in the scheduler + } // end of for (!fFound && phase <= maxPhase) - this loop goes through all search affinity types + } // end of if (!fFound) + + if (fFound) + { + ScheduleGroupSegmentBase *pSegment = pWorkItem->GetScheduleGroupSegment(); + SchedulingRing *pRing = pSegment->GetSchedulingRing(); + + pSegment->ServiceMark(m_serviceTick); + + bool fAffine = false; + if (!pSegment->GetAffinity()._Is_system()) + { + location vpLoc = m_pVirtualProcessor->GetLocation(); + if (vpLoc._FastVPIntersects(pSegment->GetAffinity())) + fAffine = true; + } + bool fLocal = pRing == pOwningRing; + + m_pVirtualProcessor->UpdateWorkState(fAffine, fLocal); + } + + return fFound; + } + + /// + /// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm for yielding. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The segment to bias the search to. The need to prefer localized and prioritized work will often trump this bias. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool WorkSearchContext::SearchCacheLocalYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes) + { + bool fFound = false; + + if (PreSearch(pWorkItem)) + return true; + + ASSERT(pOriginSegment); + + m_serviceTick = platform::__GetTickCount64(); + m_pScheduler->PeriodicScan(m_serviceTick); + + // + // @TODO: This is a temporary patch until we have priority and boosts in the scheduler. Right now, search for any segment in the locked + // FIFO of "priority" segments to see if we need to service someone to avoid livelock. We also periodically scan to determine whether + // groups need to go into this list. + // + + if (CheckPriorityList(m_serviceTick)) + { + if (m_pScheduler->HasPriorityObjects()) + { + BoostedObject *pObject = m_pScheduler->GetNextPriorityObject(); + while (pObject != NULL) + { + if (pObject->IsScheduleGroupSegment()) + { + ScheduleGroupSegmentBase *pSegment = ScheduleGroupSegmentBase::FromBoostEntry(pObject); + OMTRACE(MTRACE_EVT_PRIORITYPULL, pSegment, NULL, m_pVirtualProcessor, 1); + if (QuickSearchYield(pSegment, pWorkItem, fLastPass, allowableTypes)) + { + fFound = true; + break; + } + } + else if (allowableTypes & WorkItem::WorkItemTypeContext) + { + VirtualProcessor *pVProc = VirtualProcessor::FromBoostEntry(pObject); + InternalContextBase *pContext = pVProc->StealLocalRunnableContext(); + if (pContext != NULL) + { + *pWorkItem = WorkItem(pContext); + fFound = true; + break; + } + } + + pObject = m_pScheduler->GetNextPriorityObject(); + } + } + + // + // If we found something in a priority segment, we need to mark the V-Proc so that it once again looks for affinitized work + // the next time through SFW. + // + m_pVirtualProcessor->MarkGrabbedPriority(); + } + + SchedulingRing *pOwningRing = m_pVirtualProcessor->GetOwningRing(); + + if (!fFound) + { + // + // Before describing the cache local search algorithm, some definitions to aid in this are in order: + // + // Work: + // local work -- Work within a node/ring that a given virtual processor belongs to is considered local work + // foreign work -- Work within a node/ring that a given virtual processor does *NOT* belong to is considered foreign work + // affine work -- Work which is placed at a location more specific than the system location is affine work + // non-affine work -- Work which is placed at the system location (or no location) is considered non-affine work + // + // Virtual Processors: + // rambling -- a given virtual processor is *rambling* when it is executing foreign work (regardless whether such work is affine to it or not) + // non-affine -- a given virtual processor is *non-affine* when it is executing non-affine work (regardless whether it is rambling or not) + // + // Virtual processors which are rambling or are executing non-affine work are tracked by the scheduler. When such virtual processors + // exist, notifications will be published whenever affine work or local work + // + + // + // **IN GENERAL**, we want to find work in the following order of precedence: + // + // Phase 1: Affine work + // Affine work in our current group (preferring local affine work) + // Local affine (to us) work (in our starting (home) ring) + // Foreign affine (to us) work (in foreign ring segments that match our affinity mask -- such have a segment in our ring by definition) + // + // - This phase may be skipped if we are executing non-affine work and have not received an affinity notification from the scheduler. + // Doing so prevents SFW from making a full pass per work item if no affinity has been used. + // + // Phase 2: Non-affine work + // Non-Affine work in our current group (preferring local work) + // Local non-affine work (in our starting (home ring)) + // Foreign non-affine work (in foreign rings). + // + // - This phase may *NEVER* be skipped. + // + // Phase 3: Affine work (non-local) + // Non-local affine (*NOT* to us) work (in foreign ring segments that do not match our affinity mask + // + // - This phase may be skipped in theory if we know that there is no affine work in the scheduler. For a case with no affinity used within + // any scheduling API, this phase is only hit if the scheduler is completely idle. At idle, performing a pass is likely little additional + // cost to any performance sensitive scenario. At present, this stage is not skipped for this reason. + // + // At a very high level, you can consider a cache local search to be making vertical slices through the search space as follows: + // + // SR SR SR SR + // Contexts | | | | + // Realized | | | | + // Unrealized v v v v + // + // where each entry in this matrix is a piece of a schedule group. + // + // Note that in the last pass of SFW, we cannot skip phases or segments. Doing so can lead us to deadlock in cases with required dependence + // (assumptions on concurrency level). + // + static const SearchAffinity phaseAffinities[] = { SearchAffineLocal, SearchNonAffine, SearchAffineNotMe }; + // { 1 , 0 , 2 }; + int startPhaseIndex = (!m_pVirtualProcessor->ExecutingAffine() && !m_pVirtualProcessor->CheckAffinityNotification() && !fLastPass) ? 1 : 0; + int maxPhaseIndex = SIZEOF_ARRAY(phaseAffinities) - 1; + + // @TODO_LOC: We need livelock prevention by doing a priority boost on segments that haven't been serviced in "too long". + + bool fLocalCheck = true; + for (int phaseIndex = startPhaseIndex; !fFound && phaseIndex <= maxPhaseIndex; ++phaseIndex) // This loop goes through the phases in the phaseAffinity array. + { + SearchAffinity srchType = phaseAffinities[phaseIndex]; + + // At the outset of every pass, we bias to the originating segment/group and the current virtual processor's owning ring. + // Note that if we are searching for non-local affine work, we skip the owning ring (by definition, it's local). + ScheduleGroupSegmentBase *pBiasSegment = pOriginSegment; + SchedulingRing *pRing = pOwningRing; + + while (pRing != NULL) + { + if (((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) && + SearchCacheLocal_Unrealized(pWorkItem, + pRing, + pBiasSegment, + !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore), + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) && + SearchCacheLocal_Realized(pWorkItem, + pRing, + pBiasSegment, + !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore), + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeContext) && + SearchCacheLocal_Runnables(pWorkItem, + pRing, + pBiasSegment, + fLocalCheck, + srchType, + allowableTypes, + fLastPass)) || + + ((allowableTypes & WorkItem::WorkItemTypeContext) && phaseIndex == maxPhaseIndex && + StealLocalRunnable(pWorkItem, pRing->GetOwningNode(), m_pVirtualProcessor)) || + + (fLocalCheck && (allowableTypes & WorkItem::WorkItemTypeContext) && + GetLocalRunnable(pWorkItem, m_pVirtualProcessor, true))) + + { + fFound = true; + break; + } + + // Make sure we only steal from vproc LRCs in the local node once. This is done in this manner to ensure the odd placement of this within the + // search algorithm. + fLocalCheck = false; + + // The first time through the loop, not only did we bias to pBiasSegment, but to pStartingRing as well. Remove the bias and move to the next ring. + pBiasSegment = NULL; + pRing = m_pScheduler->GetNextSchedulingRing(pOwningRing, pRing); + + } // end of while (pRing != NULL) - this loop goes over all rings in the scheduler + } // end of for (!fFound && phase <= maxPhase) - this loop goes through all search affinity types + } // end of if (!fFound) + + if (fFound) + { + ScheduleGroupSegmentBase *pSegment = pWorkItem->GetScheduleGroupSegment(); + SchedulingRing *pRing = pSegment->GetSchedulingRing(); + + pSegment->ServiceMark(m_serviceTick); + + bool fAffine = pWorkItem->GetScheduleGroupSegment()->GetAffinity()._Is_system(); + bool fLocal = pRing == pOwningRing; + + m_pVirtualProcessor->UpdateWorkState(fAffine, fLocal); + } + + return fFound; + } +} +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.h new file mode 100644 index 0000000000000000000000000000000000000000..b62c42764f8f0e7be78436df9ec03cfe1c7fad3d --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.h @@ -0,0 +1,767 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SearchAlgorithms.h +// +// Header file containing definitions for all scheduling algorithms. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + + /// + /// Variant type representing a work item returned from a search. + /// + class WorkItem + { + public: + + /// + /// The type of work item. + /// + enum WorkItemType + { + // + // Specific types: + // + + // Empty work item + WorkItemTypeNone = 0x0, + + // Work item is a context + WorkItemTypeContext = 0x1, + + // Work item is a realized chore. Bind() will associate to a context if a context can be allocated + WorkItemTypeRealizedChore = 0x2, + + // Work item is an unrealized chore. Bind() will associate to a context if a context can be allocated + WorkItemTypeUnrealizedChore = 0x4, + + // Work item is a token to an realized chore. ResolveToken() will grab the item if it is still available. + WorkItemTypeRealizedChoreToken = 0x8, + + // Work item is a token to an unrealized chore. ResolveToken() will grab the item if it is still available. + WorkItemTypeUnrealizedChoreToken = 0x10, + + // + // General Masks: + // + + WorkItemTypeMaskAnyRealizedChore = 0xA, + WorkItemTypeMaskAnyUnrealizedChore = 0x14 + + }; + + /// + /// Default constructor for a work item. + /// + WorkItem() : + m_type(WorkItemTypeNone), + m_pItem(NULL) + { + } + + /// + /// Constructs a work item from an internal context. + /// + WorkItem(InternalContextBase *pContext); + + /// + /// Constructs a work item from a realized chore. + /// + WorkItem(RealizedChore *pRealizedChore, ScheduleGroupSegmentBase *pSegment) : + m_type(WorkItemTypeRealizedChore), + m_pSegment(pSegment), + m_pRealizedChore(pRealizedChore) + { + } + + /// + /// Constructs a work item from an unrealized chore. + /// + WorkItem(_UnrealizedChore *pUnrealizedChore, ScheduleGroupSegmentBase *pSegment) : + m_type(WorkItemTypeUnrealizedChore), + m_pSegment(pSegment), + m_pUnrealizedChore(pUnrealizedChore) + { + } + + /// + /// Constructs a work item from an unrealized chore token. + /// + WorkItem(WorkQueue *pWorkQueue, ScheduleGroupSegmentBase *pSegment) : + m_type(WorkItemTypeUnrealizedChoreToken), + m_pSegment(pSegment), + m_pWorkQueue(pWorkQueue) + { + } + + /// + /// Constructs a work item from a realized chore token. + /// + WorkItem(ScheduleGroupSegmentBase *pSegment) : + m_type(WorkItemTypeRealizedChoreToken), + m_pSegment(pSegment), + m_pRealizedChore(nullptr) + { + } + + /// + /// Transfers reference counts as necessary to inline the given work item on the given context. This may + /// only be called on a work item that can be inlined (e.g.: an unbound one). + /// + /// + /// The context that is attempting to inline the work item. + /// + void TransferReferences(InternalContextBase *pContext); + + /// + /// Resolves a token to an underlying work item. + /// + bool ResolveToken(); + + /// + /// Binds the work item to a context and returns the context. This may or may not allocate a new context. Note that + /// act of binding which performs a context allocation will transfer a single count of work to the counter of the new + /// context. + /// + InternalContextBase *Bind(); + + /// + /// Binds the work item to the specified context (which is allocated). This will never allocate a new context. + /// + void BindTo(InternalContextBase *pContext); + + /// + /// Invokes the work item. + /// + void Invoke(); + + /// + /// Accessor for type. + /// + WorkItemType GetType() const + { + return m_type; + } + + /// + /// Returns the work item. + /// + void *GetItem() const + { + return m_pItem; + } + + /// + /// Returns whether the work item is a context or not. + /// + bool IsContext() const + { + return (m_type == WorkItemTypeContext); + } + + /// + /// Returns whether the work item is a token or not. + /// + bool IsToken() const + { + return ((m_type & (WorkItemTypeRealizedChoreToken | WorkItemTypeUnrealizedChoreToken)) != 0); + } + + /// + /// Accessor for a context. + /// + InternalContextBase *GetContext() const + { + CONCRT_COREASSERT(m_type == WorkItemTypeContext); + return m_pContext; + } + + /// + /// Accessor for a realized chore. + /// + RealizedChore *GetRealizedChore() const + { + CONCRT_COREASSERT(m_type == WorkItemTypeRealizedChore); + return m_pRealizedChore; + } + + /// + /// Accessor for an unrealized chore. + /// + _UnrealizedChore *GetUnrealizedChore() const + { + CONCRT_COREASSERT(m_type == WorkItemTypeUnrealizedChore); + return m_pUnrealizedChore; + } + + /// + /// Accessor for the schedule group segment. + /// + ScheduleGroupSegmentBase *GetScheduleGroupSegment() const + { + return m_pSegment; + } + + /// + /// Accessor for the schedule group. + /// + ScheduleGroupBase *GetScheduleGroup() const; + + private: + + // The type of work item + WorkItemType m_type; + + // The schedule group that the work item was found in. + ScheduleGroupSegmentBase *m_pSegment{}; + + // The work item itself + union + { + void *m_pItem; + WorkQueue *m_pWorkQueue; + InternalContextBase *m_pContext; + RealizedChore *m_pRealizedChore; + _UnrealizedChore *m_pUnrealizedChore; + }; + + }; + + /// + /// A class which tracks iterator state for a search-for-work. This is generic in terms of search algorithm. + /// + class WorkSearchContext + { + public: + + /// + /// Describes the search algorithm being utilized. + /// + enum Algorithm + { + AlgorithmNotSet = 0, + AlgorithmCacheLocal, + AlgorithmFair + }; + + /// + /// Describes the type of affinity we are allowed to search for. + /// + enum SearchAffinity + { + // Search for non-affine work within the domain of the search. + SearchNonAffine, + + // Search for work which is affine to the search context within the domain of the search. + SearchAffineLocal, + + // Search for work which is affine to something OTHER than the search context within the domain of the search. + SearchAffineNotMe + }; + + /// + /// Constructs a work search context that will be reset later. + /// + WorkSearchContext() : m_pVirtualProcessor(NULL), m_pScheduler(NULL), m_pSearchFn(NULL), m_pSearchYieldFn(NULL) + { + } + + /// + /// Constructs a work search context (an iterator position for a search algorithm). + /// + WorkSearchContext(VirtualProcessor *pVirtualProcessor, Algorithm algorithm) + { + Reset(pVirtualProcessor, algorithm); + } + + /// + /// Resets the work search context to utilize the specified algorithm at the starting iterator position. + /// + /// + /// The virtual processor binding the searching. + /// + /// + /// What algorithm to reset the iterator with. + /// + void Reset(VirtualProcessor *pVirtualProcessor, Algorithm algorithm); + + /// + /// Searches from the last iterator position according to the set algorithm. This can return any type of work + /// item (context, realized chore, or unrealized chore) + /// + /// + /// Upon successful return, the resulting work item is placed here along with information about what group it was found in, etc... + /// + /// + /// The schedule group segment of the context which is performing the search. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// What type of work items are allowed to be returned. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool Search(WorkItem *pWorkItem, + ScheduleGroupSegmentBase *pOriginSegment, + bool fLastPass = false, + ULONG allowableTypes = WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore | WorkItem::WorkItemTypeUnrealizedChore) + { + return (this->*m_pSearchFn)(pWorkItem, pOriginSegment, fLastPass, allowableTypes); + } + + + /// + /// Searches from the last iterator position according to the set algorithm for a yield. This can return any type of + /// work item (context, realized chore, or unrealized chore) + /// + bool YieldingSearch(WorkItem *pWorkItem, + ScheduleGroupSegmentBase *pOriginSegment, + bool fLastPass = false, + ULONG allowableTypes = WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore) + { + return (this->*m_pSearchYieldFn)(pWorkItem, pOriginSegment, fLastPass, allowableTypes); + } + + private: + + // ************************************************** + // Common: + // + + /// + /// Describes where the bias towards certain lists is at within SFW. + /// + enum BiasStageType + { + BiasStageNone, + BiasStageFlipLRC, + BiasStageSkipLRC + }; + + // The virtual processor binding the search. + VirtualProcessor *m_pVirtualProcessor; + + // The scheduler + SchedulerBase *m_pScheduler; + + // The mask ID of the virtual processor binding the search. + unsigned int m_maskId{}; + + // How many times work has been found in the LRC since the last reset. + ULONG m_LRCBias{}; + + // The service time stamp + ULONGLONG m_serviceTick{}; + + // TRANSITION: This goes with real priority... + ULONGLONG m_lastPriorityPull{}; + + // The search function to utilize. + bool (WorkSearchContext::*m_pSearchFn)(WorkItem *pWorkItem, + ScheduleGroupSegmentBase *pOriginSegment, + bool fLastPass, + ULONG allowableTypes); + + // The search function to utilize for yielding. + bool (WorkSearchContext::*m_pSearchYieldFn)(WorkItem *pWorkItem, + ScheduleGroupSegmentBase *pOriginSegment, + bool fLastPass, + ULONG allowableTypes); + + // + // TRANSITION: This goes with real priority... + // + bool CheckPriorityList(ULONGLONG serviceTime) + { + bool fCheck = ((serviceTime - m_lastPriorityPull) > (ULONGLONG)1000); + if (fCheck) + m_lastPriorityPull = serviceTime; + + return fCheck; + + } + + /// + /// Performs a quick search of a particular segment. + /// + bool QuickSearch(ScheduleGroupSegmentBase *pQCSegment, + WorkItem *pWorkItem, + bool fLastPass, + ULONG allowableTypes); + + /// + /// Performs a quick yielding search of a particular segment. + /// + bool QuickSearchYield(ScheduleGroupSegmentBase *pQCSegment, + WorkItem *pWorkItem, + bool fLastPass, + ULONG allowableTypes); + + /// + /// Performs a pre-search for any "special" contexts (e.g.: the UMS SUT) + /// + bool PreSearch(WorkItem *pWorkItem); + + /// + /// Steals a local runnable from a virtual processor within the specified node. Note that this allows a given virtual processor + /// to be skipped. + /// + bool StealLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pNode, VirtualProcessor *pSkipVirtualProcessor); + + /// + /// Steals a local runnable from a virtual processor of any scheduling node other than the specified local node. + /// + bool StealForeignLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pLocalNode); + + /// + /// Gets a local runnable context from the specified virtual processor. + /// + bool GetLocalRunnable(WorkItem *pWorkItem, VirtualProcessor *pVirtualProcessor, bool fYieldingSearch); + + /// + /// Gets a runnable from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for a runnable context. + /// + /// + /// An indication of whether or not a runnable context was found in the segment. + /// + bool GetRunnableContext(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment); + + /// + /// Gets a realized chore from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for a realized chore. + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// An indication of whether or not a realized chore was found in the segment. + /// + bool GetRealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork); + + /// + /// Gets an unrealized chore from the specified schedule group segment. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The schedule group segment in which to look for an unrealized chore. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// An indication of whether or not an unrealized chore was found in the segment. + /// + bool GetUnrealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fForceStealLocalized, bool fRealWork); + + /// + /// Determines if a segment should be skipped given the search parameters and the segment's affinity. + /// + /// + /// The segment to query about skipping. + /// + /// + /// A segment which should be arbitrarily skipped regardless of affinity type. This parameter can be NULL. + /// + /// + /// The search affinity type to query for. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication as to whether pSegment should be skipped according to the pSkipSegment and affinity parameters. + /// + bool SkipSegmentSearch(ScheduleGroupSegmentBase *pSegment, ScheduleGroupSegmentBase *pSkipSegment, SearchAffinity affinity, bool fLastPass); + + /// + /// Searches the schedule group to which pSegment belongs to find a runnable. The group is searched for segments according to the specified + /// affinity type. + /// + /// + /// If an appropriate runnable is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool GetRunnableContextWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, SearchAffinity affinity, bool fLastPass); + + /// + /// Searches the schedule group to which pSegment belongs to find a realized chore. The group is searched for segments according to the specified + /// affinity type. + /// + /// + /// If an appropriate realized chore is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool GetRealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass); + + /// + /// Searches the schedule group to which pSegment belongs to find an unrealized chore. The group is searched for segments according to the + /// specified affinity type. + /// + /// + /// If an appropriate unrealized chore is found, the resulting work item will be placed here. + /// + /// + /// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool GetUnrealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass); + + /// + /// Called on any biased work. + /// + void LRCBias() + { + m_LRCBias++; + } + + /// + /// Resets the local bias counter but not the ring bias counter. + /// + void ResetLRCBias() + { + m_LRCBias = 0; + } + + /// + /// Returns the current stage of local bias. + /// + BiasStageType BiasStage() + { + if (m_LRCBias < 101) + return BiasStageNone; // (fwd) Normal --> LRC LIFO + else if (m_LRCBias < 127) + return BiasStageFlipLRC; // (fwd) Flip LRC --> LRC FIFO + else + return BiasStageSkipLRC; // (fwd) Skip LRC --> runnables + } + + // ************************************************** + // Cache Local Algorithm: + // + + /// + /// Searches for a runnable within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// Determines whether or not to check other local LRCs in this search. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a runnable was found in the bias segment, group, or the specified ring. + /// + bool SearchCacheLocal_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fOtherLocalLRCCheck, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass); + + /// + /// Searches for a realized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether a realized chore was found in the bias segment, group, or the specified ring. + /// + bool SearchCacheLocal_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass); + + /// + /// Searches for an unrealized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by + /// pBiasSegment according to the rules of the search and the requested affinity type. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The scheduling ring to search. + /// + /// + /// The segment to bias the search to. This segment and its corresponding group are searched first! + /// + /// + /// If true, the actual work item is returned. If false, a token to the work is returned. The work is not dequeued until the token + /// is resolved. + /// + /// + /// The search affinity type to query for. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// An indication of whether an unrealized chore was found in the bias segment, group, or the specified ring. + /// + bool SearchCacheLocal_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment, + bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass); + + /// + /// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The segment to bias the search to. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool SearchCacheLocal(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes); + + /// + /// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm for yielding. + /// + /// + /// If a work item is found, the work item will be returned here. + /// + /// + /// The segment to bias the search to. + /// + /// + /// An indication as to whether this is a last pass SFW. + /// + /// + /// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores + /// can be returned as well as whether the actual work item or only a token should be returned. + /// + /// + /// An indication of whether a work item was found or not. + /// + bool SearchCacheLocalYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes); + + // ************************************************** + // Fair Algorithm: + // + + /// + /// Performs a fair search for runnables in the specified ring. + /// + bool SearchFair_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing); + + /// + /// Performs a fair search for realized chores in the specified ring. + /// + bool SearchFair_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem); + + /// + /// Performs a fair search for unrealized chores in the specified ring. + /// + bool SearchFair_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem); + + /// + /// Performs a fair search for work. + /// + bool SearchFair(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes); + + /// + /// Performs a fair search for work in the yielding case. + /// + bool SearchFairYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes); + + }; + +} +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/StructuredWorkStealingQueue.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/StructuredWorkStealingQueue.h new file mode 100644 index 0000000000000000000000000000000000000000..e342bb588a4d27092905e5d471862fb06d3d6bf9 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/StructuredWorkStealingQueue.h @@ -0,0 +1,414 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// StructuredWorkStealingQueue.h +// +// Header file containing the core implementation of the work stealing data structures and algorithms. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + /// + /// A StructuredWorkStealingQueue is a wait-free, lock-free structure associated with a single + /// thread that can Push and Pop elements. Other threads can do Steal operations + /// on the other end of the StructuredWorkStealingQueue with little contention. + /// + template + class StructuredWorkStealingQueue + { + // A 'StructuredWorkStealingQueue' always runs its code in a single OS thread. We call this the + // 'bound' thread. Only the code in the Steal operation can be executed by + // other 'foreign' threads that try to steal work. + // + // The queue is implemented as a lock-free dequeue of arrays. The m_head and m_tail index this + // array. To avoid copying elements, the m_head and m_tail index the array modulo + // the size of the array. By making this a power of two, we can use a cheap + // bit-and operation to take the modulus. The "m_mask" is always equal to the + // size of the task array minus one (where the size is a power of two). + // + // The m_head and m_tail are volatile as they can be updated from different OS threads. + // The "m_head" is only updated by foreign threads as they Steal a task from + // this queue. By putting a lock in Steal, there is at most one foreign thread + // changing m_head at a time. The m_tail is only updated by the bound thread. + // + // invariants: + // tasks.length is a power of 2 + // m_mask == tasks.length-1 + // m_head is only written to by foreign threads + // m_tail is only written to by the bound thread + // At most one foreign thread can do a Steal + // All methods except Steal are executed from a single bound thread + // m_tail points to the first unused location + // + // This work stealing implementation also supports the notion of out-of-order waiting + // and out-of-order removal from the bound thread given that it is initialized to do so. + // There is additional cost to performing this. + // + + public: + + /// + /// Constructs a new work stealing queue + /// + StructuredWorkStealingQueue(LOCK *pLock) + : m_head(0), + m_tail(0), + m_pLock(pLock) + { + ASSERT(s_initialSize > 1); + m_mask = s_initialSize - 1; + m_ppTasks = _concrt_new T*[s_initialSize]; + m_pSlots = _concrt_new typename Mailbox::Slot[s_initialSize]; + memset(m_ppTasks, 0, s_initialSize * sizeof(T*)); + ASSERT(m_pLock != NULL); + } + + /// + /// Reinitializes a workqueue to the state essentially equivalent to just after construction. + /// This is used when recycling a workqueue from its ListArray + /// + /// + /// Indicates whether or not the work stealing queue will allow out of order waiting on the bound thread. + /// Allowing this has additional cost. + /// + /// + /// Indicates the initially allocated size for the physical work item storage + /// + void Reinitialize() + { + m_head = 0; + m_tail = 0; + } + + // + // unlocked count + // + int Count() const + { + return (m_tail - m_head); + } + + // + // unlocked check + // + bool Empty() const + { + return (m_tail <= m_head); + } + + // + // Push/Pop and Steal can be executed interleaved. In particular: + // 1) A steal and pop should be careful when there is just one element + // in the queue. This is done by first incrementing the m_head/decrementing the m_tail + // and than checking if it interleaved (m_head > m_tail). + // 2) A push and steal can interleave in the sense that a push can overwrite the + // value that is just stolen. To account for this, we check conservatively in + // the push to assume that the size is one less than it actually is. + + /// + /// Attempts to steal the oldest element in the queue. This handles potential interleaving with both + /// a Pop and other Steal operations. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + T* Steal(bool fForceStealLocalized = false) + { + typename LOCK::_Scoped_lock lock(*m_pLock); + return UnlockedSteal(fForceStealLocalized); + } + + /// + /// Must be called under m_pLock->_Acquire/m_pLock->_TryAcquire + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + T* UnlockedSteal(bool fForceStealLocalized) + { + while (m_head < m_tail) + { + int h = m_head; + + // + // Do not allow a steal from this work stealing queue if the bottom task was mailed to a location which has active searchers. + // This will not block finalization in any way as the last pass SFW will pull the task out of the mailbox regardless of affinity. + // We should be careful not to do this if the current context's virtual processor is in the affinity set of the segment. + // If not, there could be cases where all virtual processors deactivate, but the scheduler does not shutdown since there are chores + // in the queue, even if they have been dequeued via the mailbox. + // + if(IS_AFFINITIZED_TASK(m_ppTasks[h & m_mask])) + { + // + // Skip this workqueue if there are affine searchers and we are not one of them. + // + if (!fForceStealLocalized && m_pSlots[h & m_mask].DeferToAffineSearchers()) + return NULL; + } + + T *pResult = (T*) _InterlockedExchangePointer((volatile PVOID*) &m_ppTasks[h & m_mask], (PVOID) NULL); + + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, move on and try to steal again. + // + if (!m_pSlots[h & m_mask].Claim()) + { + m_head = h + 1; + continue; + } + } + + if (pResult != NULL) + m_head = h+1; + + return pResult; + } + + return NULL; + } + + /// + /// Attempts to pop the newest element on the work stealing queue. It may return NULL if there is no such + /// item (either unbalanced push/pop, a chore stolen). A special constant AFFINITY_EXECUTED is returned + // if the item was executed via a mailbox slot. + /// + T* Pop() + { + int t = m_tail - 1; + m_tail = t; + T* pResult = (T*) _InterlockedExchangePointer((volatile PVOID*) &m_ppTasks[t & m_mask], (PVOID) NULL); + if (pResult == NULL) + m_tail = t + 1; + + // + // If the task had an associated affinity, we must deal with the possibility that it was already executed by a virtual + // processor to which it was affine through a mailbox. + // + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, return an indication to the caller. + // + if (!m_pSlots[t & m_mask].Claim()) + { + return (T*)AFFINITY_EXECUTED; + } + } + return pResult; + } + + /// + /// Pushes an element onto the work stealing queue. + /// + void Push(T* element, typename Mailbox::Slot affinitySlot) + { + int t = m_tail; + + AvoidOverflow(t); + + // + // Careful here since we might interleave with Steal. + // This is no problem since we just conservatively check if there is + // enough space left (t < m_head + size). However, Steal might just have + // incremented m_head and we could potentially overwrite the old m_head + // entry, so we always leave at least one extra 'buffer' element and + // check (m_tail < m_head + size - 1). This also plays nicely with our + // initial m_mask of 0, where size is 2^0 == 1, but the tasks array is + // still null. + // + if (t < m_head + m_mask) // == t < m_head + size - 1 + { + if (!affinitySlot.IsEmpty()) + { + // + // Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent + // multiple execution. + // + m_pSlots[t & m_mask] = affinitySlot; + element = ADD_AFFINITY_INDICATOR(T, element); + } + + m_ppTasks[t & m_mask] = element; + // Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models + m_tail = t + 1; + } + else + GrowAndPush(element, affinitySlot); + } + + /// + /// Pushes an element onto the work stealing queue. + /// + void Push(T* element) + { + int t = m_tail; + + AvoidOverflow(t); + + // + // Careful here since we might interleave with Steal. + // This is no problem since we just conservatively check if there is + // enough space left (t < m_head + size). However, Steal might just have + // incremented m_head and we could potentially overwrite the old m_head + // entry, so we always leave at least one extra 'buffer' element and + // check (m_tail < m_head + size - 1). This also plays nicely with our + // initial m_mask of 0, where size is 2^0 == 1, but the tasks array is + // still null. + // + if (t < m_head + m_mask) // == t < m_head + size - 1 + { + m_ppTasks[t & m_mask] = element; + // Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models + m_tail = t + 1; + } + else + GrowAndPush(element, typename Mailbox::Slot()); + } + + /// + /// Destroys a work stealing queue. + /// + ~StructuredWorkStealingQueue() + { + delete [] m_ppTasks; + delete [] m_pSlots; + } + + private: + + // The m_head and m_tail are volatile as they can be updated from different OS threads. + // The "m_head" is only updated by foreign threads as they Steal a task from + // this queue. By putting a lock in Steal, there is at most one foreign thread + // changing m_head at a time. The m_tail is only updated by the bound thread. + // + // invariants: + // tasks.length is a power of 2 + // m_mask == tasks.length-1 + // m_head is only written to by foreign threads + // m_tail is only written to by the bound thread + // At most one foreign thread can do a Steal + // All methods except Steal are executed from a single bound thread + // m_tail points to the first unused location + // + + static const int s_initialSize = 64; // must be a power of 2 + + volatile int m_head; // only updated by Steal + volatile int m_tail; // only updated by Push and Pop + + int m_mask; // the m_mask for taking modulus + + T** m_ppTasks; // the array of tasks + typename Mailbox::Slot *m_pSlots; // the array of side-band affinity structures + + LOCK *m_pLock; + + // private helpers + + T* LockedPop(int t) + { + typename LOCK::_Scoped_lock lock(*m_pLock); + T* pResult = NULL; + + if (m_head <= t) + pResult = m_ppTasks[t & m_mask]; + else + m_tail = t + 1; + if (m_tail <= m_head) + m_head = m_tail = 0; + + return pResult; + } + + void GrowAndPush(T* element, typename Mailbox::Slot affinitySlot) + { + // We're full; expand the queue by doubling its size. + int newLength = (m_mask + 1) << 1; + T** ppNewTasks = _concrt_new T*[newLength]; + T** ppOldTasks = m_ppTasks; + + typename Mailbox::Slot *pNewSlots = _concrt_new typename Mailbox::Slot[newLength]; + typename Mailbox::Slot *pOldSlots = m_pSlots; + + {//for lock scope to exclude the delete[] + typename LOCK::_Scoped_lock lock(*m_pLock); + + int t = m_tail; + int h = m_head; + int count = Count(); + + _Analysis_assume_(newLength > count); // Guaranteed because we're doubling the size. + + for (int i = 0; i < count; i++) + { + ppNewTasks[i] = m_ppTasks[(i + h) & m_mask]; + pNewSlots[i] = m_pSlots[(i + h) & m_mask]; + } + + memset(ppNewTasks + count, 0, (newLength - count) * sizeof(T*)); + + // Reset the field values. + m_ppTasks = ppNewTasks; + m_pSlots = pNewSlots; + m_head = 0; + t = count; + m_mask = newLength - 1; + + if (!affinitySlot.IsEmpty()) + { + // + // Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent + // multiple execution. + // + m_pSlots[t & m_mask] = affinitySlot; + element = ADD_AFFINITY_INDICATOR(T, element); + } + + m_ppTasks[t & m_mask] = element; + m_tail = t + 1; + }//end: lock scope + + delete[] ppOldTasks; + delete[] pOldSlots; + } + + void AvoidOverflow(int& t) { + // Balanced calls to Steal() and Push() will increment m_head and m_tail forever. + // To avoid integer overflow, we need to reduce m_head and m_tail simultaneously, + // preserving their modulo-indexing behavior and relative distance. + + if (t + m_mask == INT_MAX) { // begin: lock scope + typename LOCK::_Scoped_lock lock(*m_pLock); + + int h = m_head; + const int original_distance = t - h; + + h &= m_mask; + t = h + original_distance; + + m_head = h; + m_tail = t; + } // end: lock scope + } + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0e6736053f16687552475a86ad788887d6fe70e --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.cpp @@ -0,0 +1,379 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SubAllocator.cpp +// +// Implementation of ConcRT sub allocator +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +/// +/// Allocates a block of memory of the size specified. +/// +/// +/// Number of bytes to allocate. +/// +/// +/// A pointer to newly allocated memory. +/// +_CONCRTIMP void* Alloc(size_t numBytes) +{ + if (numBytes > MAXINT_PTR) + { + throw std::bad_alloc(); + } + + return SchedulerBase::CurrentContext()->Alloc(numBytes); +} + +/// +/// Frees a block of memory previously allocated by the Alloc API. +/// +/// +/// A pointer to an allocation previously allocated by Alloc. If pAllocation is NULL, the API will ignore it, and return +/// immediately. +/// +_Use_decl_annotations_ +_CONCRTIMP void Free(void * pAllocation) +{ + if (pAllocation == NULL) + { + return; + } + SchedulerBase::CurrentContext()->Free(pAllocation); +} + +namespace details +{ + // + // Define static variables. + // + +#if defined(_DEBUG) + + // Debug patterns to fill allocated blocks (borrowed from dbgheap.c) + + static const unsigned char _bNoMansLandFill = 0xFD; /* fill no-man's land with this */ + static const unsigned char _bAlignLandFill = 0xED; /* fill no-man's land for aligned routines */ + static const unsigned char _bDeadLandFill = 0xDD; /* fill free objects with this */ + static const unsigned char _bCleanLandFill = 0xCD; /* fill new objects with this */ +#endif + +#ifdef _WIN64 + // This supports the same number of buckets and bucket sizes as the LFH heap upto 8192 bytes, i.e., 96 buckets. + const int SubAllocator::s_bucketSizes[SubAllocator::s_numBuckets] = { + /* granularity - 16 */ 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, // sizeClass 0, blockUnits 1 - 16 + /* granularity - 16 */ 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, 480, 496, 512, // sizeClass 0, blockUnits 17 - 32 + /* granularity - 32 */ 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,// sizeClass 1, blockUnits 33 - 64 + /* granularity - 64 */ 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048,// sizeClass 2, blockUnits 65 - 128 + /* granularity - 128 */ 2176, 2304, 2432, 2560, 2688, 2816, 2944, 3072, 3200, 3328, 3456, 3584, 3712, 3840, 3968, 4096,// sizeClass 3, blockUnits 129 - 256 + /* granularity - 256 */ 4352, 4608, 4864, 5120, 5376, 5632, 5888, 6144, 6400, 6656, 6912, 7168, 7424, 7680, 7936, 8192,// sizeClass 4, blockUnits 257 - 512 + }; + + // A number such that 2 ^ GranularityShift = Granularity. + const int SubAllocator::GranularityShift = 4; + + // The allocation size supported by the largest bucket. + const int SubAllocator::MaxAllocationSize = 8192; + +#else + + // This supports the same number of buckets and bucket sizes as the LFH heap upto 4096 bytes, i.e., 96 buckets. + const int SubAllocator::s_bucketSizes[SubAllocator::s_numBuckets] = { + /* granularity - 8 */ 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, // sizeClass 0, blockUnits 1 - 16 + /* granularity - 8 */ 136, 144, 152, 160, 168, 176, 184, 192, 200, 208, 216, 224, 232, 240, 248, 256, // sizeClass 0, blockUnits 17 - 32 + /* granularity - 16 */ 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, 480, 496, 512, // sizeClass 1, blockUnits 33 - 64 + /* granularity - 32 */ 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,// sizeClass 2, blockUnits 65 - 128 + /* granularity - 64 */ 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048,// sizeClass 3, blockUnits 129 - 256 + /* granularity - 128 */ 2176, 2304, 2432, 2560, 2688, 2816, 2944, 3072, 3200, 3328, 3456, 3584, 3712, 3840, 3968, 4096 // sizeClass 4, blockUnits 257 - 512 + }; + + // A number such that 2 ^ GranularityShift = Granularity. + const int SubAllocator::GranularityShift = 3; + + // The allocation size supported by the largest bucket. + const int SubAllocator::MaxAllocationSize = 4096; +#endif + + /// + /// Returns an index into the array of allocator buckets for this sub allocator. The allocation size of the + /// bucket is guaranteed to satisfy numBytes. + /// + /// + /// The size of the allocation. This is what the user requested plus space for the ConcRT allocator header. + /// + /// + /// An index into the array of allocator buckets such that.s_bucketSizes[returnedBucketIndex] >= numBytes + /// + int SubAllocator::GetBucketIndex(size_t numBytes) + { + static const int GranularityMask = (1 << GranularityShift) - 1; + + int bucketIndex = -1; + size_t allocationSize = (size_t) (((ULONG_PTR)numBytes + GranularityMask) & ~((ULONG_PTR)GranularityMask)); + + if (allocationSize > MaxAllocationSize) + { + // We are unable to satisfy this allocation by an allocator bucket. It should be forwarded to the LFH heap. + return bucketIndex; + } + + int blockUnits = (int)(allocationSize >> GranularityShift); + + // blockUnits is the number of Granularity size chunks that make up the allocationSize. A blockUnit of 1 is satisfied + // by allocator bucket 0. We need to find the index of the bucket that holds the minimum sized allocation that will + // satisfy allocationSize. + ASSERT(blockUnits > 0); + + // Detect if the allocation will fall within buckets 0 - 31 + if (blockUnits <= 32) + { + bucketIndex = blockUnits - 1; + } + else + { + int sizeClass = 5; // Add 1 << 5 = 32 + + while ((blockUnits >> sizeClass) > 0) + { + sizeClass += 1; + } + + sizeClass -= 5; + + ASSERT(sizeClass > 0); + + // Round blockUnits up to the block unit granularity of the size class. + int sizeClassMask = (1 << sizeClass) - 1; + blockUnits = (int) (((ULONG_PTR)blockUnits + sizeClassMask) & ~((ULONG_PTR)sizeClassMask)); + + bucketIndex = (sizeClass << 4) + (blockUnits >> sizeClass) - 1; + } + + ASSERT(allocationSize <= (size_t)s_bucketSizes[bucketIndex]); + ASSERT(bucketIndex == 0 || allocationSize > (size_t)s_bucketSizes[bucketIndex - 1]); + + return bucketIndex; + } + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + void* SubAllocator::Alloc(size_t numBytes) + { + AllocationEntry* pAllocationEntry = NULL; + size_t allocationSize = numBytes + sizeof(AllocationEntry); + + int bucketIndex = GetBucketIndex(allocationSize); + + if (bucketIndex != -1) + { + ASSERT(bucketIndex < sizeof(s_bucketSizes)); + pAllocationEntry = m_buckets[bucketIndex].Alloc(); + +#if defined(_DEBUG) + if (pAllocationEntry != NULL) + { + InitAndCheckBlockOnAlloc(pAllocationEntry, s_bucketSizes[bucketIndex]); + } +#endif + + } + + if (pAllocationEntry == NULL) + { + // We need to allocate memory from the CRT heap since either the bucket was empty, + // or the size is not one the allocator caches. + pAllocationEntry = (AllocationEntry*) _concrt_new char[bucketIndex == -1 ? allocationSize : s_bucketSizes[bucketIndex]]; + } + + ASSERT(pAllocationEntry != NULL); + pAllocationEntry->m_bucketIndex = (ULONG_PTR)Security::EncodePointer((PVOID)(intptr_t)bucketIndex); + + return (void*)(pAllocationEntry + 1); + } + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + void SubAllocator::Free(void* pAllocation) + { + AllocationEntry* pAllocationEntry = (AllocationEntry*)pAllocation - 1; + // Disable data truncation warning as only lower 32-bits are needed. + #pragma warning(push) + #pragma warning(disable: 4302) + int bucketIndex = (int)(intptr_t)Security::DecodePointer((PVOID)pAllocationEntry->m_bucketIndex); + #pragma warning(pop) + + ASSERT((bucketIndex == -1) || bucketIndex < sizeof(s_bucketSizes)); + + if ((bucketIndex == -1) || !m_buckets[bucketIndex].Free(pAllocationEntry)) + { + delete [] (char*)pAllocationEntry; + } +#if defined(_DEBUG) + else + { + InitAndCheckBlockOnFree(pAllocationEntry, s_bucketSizes[bucketIndex]); + } +#endif + + } + + /// + /// A static allocation API that allocates directly from the CRT heap, and encodes the bucket id in the allocation, + /// based on the size of the block. This is used by callers that are unable to get access to a suballocator at + /// the time they are allocating memory. + /// + void* SubAllocator::StaticAlloc(size_t numBytes) + { + AllocationEntry* pAllocationEntry = NULL; + size_t allocationSize = numBytes + sizeof(AllocationEntry); + + int bucketIndex = GetBucketIndex(allocationSize); + pAllocationEntry = (AllocationEntry*) _concrt_new char[bucketIndex == -1 ? allocationSize : s_bucketSizes[bucketIndex]]; + + ASSERT(pAllocationEntry != NULL); + pAllocationEntry->m_bucketIndex = (ULONG_PTR)Security::EncodePointer((PVOID)(intptr_t)bucketIndex); + + return (void*)(pAllocationEntry + 1); + } + +#if defined(_DEBUG) + /// + /// Initialize a block allocated from the freelist. Perform debug validation on the block to + /// detect user errors. + /// + bool SubAllocator::InitAndCheckBlockOnAlloc(AllocationEntry *pAllocationEntry, size_t numBytes) + { + // Validate the pointer + ASSERT(_CrtIsValidHeapPointer((const void *)pAllocationEntry)); + + unsigned char * userData = (unsigned char *)(pAllocationEntry + 1); + + ASSERT(numBytes > sizeof(AllocationEntry)); + size_t userNumBytes = numBytes - sizeof(AllocationEntry); + + // Ensure that the free block has not been overwritten. + ASSERT(CheckBytes(userData, _bDeadLandFill, userNumBytes)); + + // Initialize the new block + memset((void *)userData, _bCleanLandFill, userNumBytes); + + return true; + } + + /// + /// Initialize a block that is added to the freelist. Perform debug validation on the block to + /// detect user errors. + /// + bool SubAllocator::InitAndCheckBlockOnFree(AllocationEntry *pAllocationEntry, size_t numBytes) + { + // Validate the pointer. + ASSERT(_CrtIsValidHeapPointer((const void *)pAllocationEntry)); + + ASSERT(numBytes > sizeof(AllocationEntry)); + // Initialize the free block + memset((void *)(pAllocationEntry + 1), _bDeadLandFill, (numBytes - sizeof(AllocationEntry))); + + return true; + } + + /// + /// Helper routine that checks where the given block is filled with + /// the given pattern. + /// + bool SubAllocator::CheckBytes(unsigned char * pBlock, unsigned char bCheck, size_t numBytes) + { + while (numBytes--) + { + if (*pBlock++ != bCheck) + { + return false; + } + } + + return true; + } +#endif + + /// + /// Constructs an allocator bucket. + /// + AllocatorBucket::AllocatorBucket() : m_depth(0) + { + m_pHead = (AllocationEntry*)Security::EncodePointer(NULL); + } + + /// + /// Returns an allocation from the bucket if it is non-empty, and NULL if it is empty. + /// + AllocationEntry* AllocatorBucket::Alloc() + { + AllocationEntry* pAllocationEntry = (AllocationEntry*)Security::DecodePointer(m_pHead); + + if (pAllocationEntry != NULL) + { + ASSERT(m_depth > 0); + m_pHead = pAllocationEntry->m_pNext; + --m_depth; + } + + return pAllocationEntry; + } + + /// + /// Adds the block to the bucket and returns true if the maximum depth is not reached. + /// If the bucket is 'full', it returns false, and the caller is responsible for freeing + /// the block to the CRT heap. + /// + bool AllocatorBucket::Free(AllocationEntry* pAllocation) + { + if (m_depth < s_maxBucketDepth) + { + pAllocation->m_pNext = m_pHead; + m_pHead = (AllocationEntry*)Security::EncodePointer(pAllocation); + ++m_depth; + + ASSERT(m_depth <= s_maxBucketDepth); + return true; + } + + return false; + } + + /// + /// Destroys an allocator bucket. + /// + AllocatorBucket::~AllocatorBucket() + { + while (m_depth != 0) + { + AllocationEntry * pAllocationEntry = (AllocationEntry*)Security::DecodePointer(m_pHead); + ASSERT(pAllocationEntry != NULL); + + m_pHead = pAllocationEntry->m_pNext; + delete [] (char*)pAllocationEntry; + + --m_depth; + } + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..092edac84fe7dc212472f4c79f10fd0b30ac7a93 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.h @@ -0,0 +1,200 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// SubAllocator.h +// +// Class definition for the ConcRT sub allocator. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + /// + /// Each allocation via the sub allocator has an AllocationEntry header. All we need the allocation entry + /// for, is to tell us the id of the bucket, which indicates the size of the allocation. However, the size + /// of the header is pointer size - since we want to align the user's allocation. + /// + union AllocationEntry + { + // The index to the bucket in the suballocator, that this entry belongs to. + ULONG_PTR m_bucketIndex; + + // Pointer to the next allocation in the bucket. This is used to chain allocations in the bucket, and we + // do not require a lock since only one thread is guaranteed to be touching the suballocator at a time. + AllocationEntry* m_pNext; + }; + + // A bucket that stores a particular size memory block. A SubAllocator has several allocator buckets. + class AllocatorBucket + { + public: + + /// + /// Constructs an allocator bucket. + /// + AllocatorBucket(); + + /// + /// Destroys an allocator bucket. + /// + ~AllocatorBucket(); + + /// + /// Returns an allocation from the bucket if it is non-empty, and NULL if it is empty. + /// + AllocationEntry* Alloc(); + + /// + /// Adds the block to the bucket and returns true if the maximum depth is not reached. + /// If the bucket is 'full', it returns false, and the caller is responsible for freeing + /// the block to the CRT heap. + /// + bool Free(AllocationEntry* pAllocation); + + private: + + // The current depth of the bucket. + int m_depth; + + // The head of the free block list. + AllocationEntry* m_pHead; + + // The maximum number of allocations the sub allocator will cache per bucket. + static const int s_maxBucketDepth = 32; + }; + +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class SubAllocator + { + public: + + /// + /// Constructs a suballocator. + /// + SubAllocator() : + m_fExternalAllocator(false) + { + } + + /// + /// Allocates a block of memory of the size specified. + /// + /// + /// Number of bytes to allocate. + /// + /// + /// A pointer to newly allocated memory. + /// + void* Alloc(size_t numBytes); + + /// + /// Frees a block of memory previously allocated by the Alloc API. + /// + /// + /// A pointer to an allocation previously allocated by Alloc. + /// + void Free(void* pAllocation); + + /// + /// A static allocation API that allocates directly from the CRT heap, and encodes the bucket id in the allocation, + /// based on the size of the block. This is used by callers that are unable to get access to a suballocator at + /// the time they are allocating memory. + /// + static void* StaticAlloc(size_t numBytes); + + /// + /// A static free API that frees directly to the CRT heap. This is used by callers that are unable to get access + /// to a suballocator at the time they are freeing memory. + /// + static void StaticFree(void* pAllocation) + { + delete [] (char*) ((AllocationEntry*)pAllocation - 1); + } + + /// + /// Returns an index into the array of allocator buckets for this sub allocator. The allocation size of the + /// bucket is guaranteed to satisfy numBytes. + /// + /// + /// The size of the allocation. This is what the user requested plus space for the ConcRT allocator header. + /// + /// + /// An index into the array of allocator buckets such that.s_bucketSizes[returnedBucketIndex] >= numBytes + /// + static int GetBucketIndex(size_t numBytes); + + /// + /// Every time an allocator is reused, this flag is set to denote whether it is one out of the 'fixed pool' - the set + /// of allocators that are used for external contexts. + /// + void SetExternalAllocatorFlag(bool flag) { m_fExternalAllocator = flag; } + + /// + /// Returns true, if this allocator is assigned to, or was last assigned to an external context. + /// + bool IsExternalAllocator() { return m_fExternalAllocator; } + + private: + + // private methods + +#if defined(_DEBUG) + + /// + /// Initialize a block allocated from the freelist. Perform debug validation on the block to + /// detect user errors. + /// + bool InitAndCheckBlockOnAlloc(AllocationEntry *pAllocationEntry, size_t numBytes); + + /// + /// Initialize a block that is added to the freelist. Perform debug validation on the block to + /// detect user errors. + /// + bool InitAndCheckBlockOnFree(AllocationEntry *pAllocationEntry, size_t numBytes); + + /// + /// Helper routine that checks where the given block is filled with + /// the given pattern. + /// + bool CheckBytes(unsigned char * pBlock, unsigned char bCheck, size_t numBytes); +#endif + + // private member variables + + friend class SchedulerBase; + template friend class LockFreeStack; + + // Entry for freelist of allocators + SLIST_ENTRY m_slNext{}; + + // The total number of buckets. + static const int s_numBuckets = 96; + + // The array of buckets that holds memory for allocation. + AllocatorBucket m_buckets[s_numBuckets]; + + // This flag is set to true, when it this suballocator is handed to a caller that invoked GetSubAllocator with an argument + // of 'true'. + bool m_fExternalAllocator; + + // An array that holds the bucket sizes. + static const int s_bucketSizes[s_numBuckets]; + + // A number such that 2 ^ GranularityShift = the minimum granularity of the allocation buckets. + static const int GranularityShift; + + // The allocation size supported by the largest bucket. + static const int MaxAllocationSize; + }; +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ae0d67303857b5d3223ad168e5382aa6977dd6b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.cpp @@ -0,0 +1,2470 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// TaskCollection.cpp +// +// Internal implementation of task collections and related data structures +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +#pragma warning(disable:4297) //Function expected not to throw but does + +namespace Concurrency +{ +namespace details +{ + /// + /// Destroys a task stack. + /// + TaskStack::~TaskStack() + { + if (m_pStack) + delete [] m_pStack; + } + + /// + /// Pushes an element onto the task stack. Returns a bool as to whether this could happen or not. The only + /// possible error here is out of memory. + /// + /// + /// The task cookie to push onto the stack + /// + /// + /// An indication of whether the stack cap was reached. + /// + bool TaskStack::Push(int taskCookie) + { + if (m_stackPtr >= m_stackSize) + { + // + // Prevent the task stack from growing beyond a predetermined size cap. If we exceed this cap, we will ignore the push. + // Note that the CHORE itself is still pushed to the work stealing queue and can still be stolen. It just won't be on the inlining + // list within the task collection. What this means is that a call to Wait will *NOT* be able to inline the chore. It also means that + // any call to Wait after this return will suffer a *HUGE* penalty as every pop will be out-of-order and incur additional fencing + // in the work stealing queue. + // + // The reason we cap this is specifically because we allow passing task collections between threads. It's entirely possible to have a pattern where + // one thread (thread A) continues to add items to a task collection while another thread (thread B) waits on it. They never reverse roles. In this case, + // the direct alias for thread A will continue to pile up items on this stack (the inlining list). Since wait is never called from that thread, the + // stack will be popped. Without a cap, this list would grow infinitely. Note that in this scenario, there is no penalty in continuing to add + // chores. The only time a penalty will happen is if Wait were called (and once the collection resets, the penalty goes away until the cap is reached + // again). + // + if (m_stackPtr >= TASK_STACK_SIZE_CAP) + { + m_fOverflow = true; + return false; + } + + int size = m_stackSize + TASK_STACK_GROWTH_SIZE; + int *pNewStack = _concrt_new int[size]; + + memcpy(pNewStack, m_pStack, sizeof(int) * m_stackSize); + m_stackSize = size; + + delete[] m_pStack; + m_pStack = pNewStack; + } + + ASSERT(m_stackPtr < m_stackSize); + m_pStack[m_stackPtr++] = taskCookie; + + return true; + } + + /// + /// Pops an element from the task stack. + /// + /// + /// The element + /// + int TaskStack::Pop() + { + ASSERT(m_stackPtr > 0); + return m_pStack[--m_stackPtr]; + } + + /// + /// Returns an indication of whether or not the stack is empty. + /// + bool TaskStack::IsEmpty() const + { + return m_stackPtr == 0; + } + + /// + /// Clears out everything on the stack. + /// + void TaskStack::Clear() + { + m_stackPtr = 0; + } + + // ********************************************************************** + // Structured Task Collection: + // ********************************************************************** + + /// + /// Construct a new structured task collection whose cancellation is governed by the supplied cancellation token. + /// + /// + /// When this cancellation token is canceled, the structured task group will be canceled. + /// + /**/ + _StructuredTaskCollection::_StructuredTaskCollection(_CancellationTokenState *_PTokenState) : + _TaskCollectionBase(_PTokenState) + { + _Construct(); + if (_PTokenState != NULL) + { + ContextBase *pCurrentContext = SchedulerBase::CurrentContext(); + _M_pOwningContext = pCurrentContext; + + if (_PTokenState != _CancellationTokenState::_None()) + { + _PTokenState->_Reference(); + } + + // + // If this is a new cancellation token, we need to register a callback. Remember, this is expensive as it involves a memory allocation. + // We want to avoid this whenever possible. + // + if (pCurrentContext->GetGoverningTokenState() != _PTokenState) + { + if (_PTokenState != _CancellationTokenState::_None()) + { + _CancellationTokenRegistration *pRegistration = _PTokenState->_RegisterCallback( + reinterpret_cast(&_StructuredTaskCollection::_CancelViaToken), this + ); + _M_pTokenState = reinterpret_cast<_CancellationTokenState *>( + (reinterpret_cast(pRegistration) | TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION) + ); + } + else + { + // This should already have been set in the base class constructor. + ASSERT(_M_pTokenState == _CancellationTokenState::_None()); + } + } + } + } + + /// + /// Destruct a task collection and wait on all associated work to finish. Clients must call '_StructuredTaskCollection::_Wait' + /// or '_StructuredTaskCollection::_RunAndWait' prior to destructing the object. If there are chores remaining in the queues, an + /// exception (missing_wait) is thrown. If the destructor is running because of exception unwinding, it will abort any scheduled work. + /// If another exception occurs because work is aborted, the process will terminate (C++ semantics). + /// + /**/ + _StructuredTaskCollection::~_StructuredTaskCollection() + { + if (!_TaskCleanup()) + { + if (_M_pTokenState != NULL && _M_pTokenState != _CancellationTokenState::_None()) + { + _CleanupToken(); + } + + throw missing_wait(); + } + + if (_M_pTokenState != NULL && _M_pTokenState != _CancellationTokenState::_None()) + { + _CleanupToken(); + } + } + + + /// + /// The callback which is made when a cancellation occurs via a token associated with a structured_task_group on the boundary + /// of two cancellation tokens. + /// + void _StructuredTaskCollection::_CancelViaToken(_StructuredTaskCollection *pCollection) + { + // + // NOTE: This is what we would normally consider a violation of the structured task group contract. This cancellation can happen from an + // arbitrary thread. The only reason that this is safe is because _RunAndWait understands tokens and the synchronization is handled via + // the deregister call contained within. + // + pCollection->_Cancel(); + } + + /// + /// Schedules a new unrealized chore on the task collection. + /// + /// + /// The new unrealized chore to schedule + /// + /// + /// The location where the unrealized chore should execute. Specifying the value NULL here indicates that the unrealized chore does not + /// have specific placement. + /// + void _StructuredTaskCollection::_Schedule(_UnrealizedChore * _PChore, location *_PLocation) + { + if (_PChore->_M_pTaskCollection != NULL) + throw invalid_multiple_scheduling(); + + _PChore->_M_pTaskCollection = this; + _PChore->_M_pChoreFunction = &_UnrealizedChore::_StructuredChoreWrapper; + ++_M_unpoppedChores; + if (_M_pOwningContext == NULL) + _M_pOwningContext = SchedulerBase::CurrentContext(); + reinterpret_cast (_M_pOwningContext)->PushStructured(_PChore, _PLocation); + } + + /// + /// Schedules a new unrealized chore on the task collection. + /// + /// + /// The new unrealized chore to schedule + /// + void _StructuredTaskCollection::_Schedule(_UnrealizedChore * _PChore) + { + if (_PChore->_M_pTaskCollection != NULL) + throw invalid_multiple_scheduling(); + + _PChore->_M_pTaskCollection = this; + _PChore->_M_pChoreFunction = &_UnrealizedChore::_StructuredChoreWrapper; + ++_M_unpoppedChores; + if (_M_pOwningContext == NULL) + _M_pOwningContext = SchedulerBase::CurrentContext(); + reinterpret_cast (_M_pOwningContext)->PushStructured(_PChore); + } + + /// + /// Runs a specified chore (pChore) and subsequently waits on all chores associated with the task collection + /// to execute. + /// + /// + /// The chore to run locally. + /// + /// + /// An indication of the status of the wait. + /// + __declspec(noinline) + _TaskCollectionStatus __stdcall _StructuredTaskCollection::_RunAndWait(_UnrealizedChore *pChore) + { + ASSERT(_M_pOwningContext != NULL || _M_unpoppedChores == 0); + if (_M_pOwningContext == NULL) + _M_pOwningContext = SchedulerBase::CurrentContext(); + ContextBase *pCurrentContext = reinterpret_cast (_M_pOwningContext); + + _M_pParent = pCurrentContext->GetExecutingCollection(); + _M_inliningDepth = _M_pParent != NULL ? _M_pParent->_InliningDepth() + 1 : 0; + pCurrentContext->SetExecutingCollection(this); + + _CancellationTokenRegistration *pRegistration = NULL; + _CancellationTokenState *pTokenState = NULL; + + if (_M_pTokenState != NULL) + { + pTokenState = _GetTokenState(&pRegistration); + pCurrentContext->PushGoverningTokenState(pTokenState, _M_inliningDepth); + } + + try + { + if (pChore != NULL) + { + // + // Ordinarily, we need a full fence here to ensure that the write of _M_inliningDepth and the read of the context cancellation + // flag are not reordered with respect to each other as perceived by a cancellation thread. If they are, the cancellation thread + // can miss flagging an entire branch of the work tree rooted at pChore. + // + // The scenario is as follows: + // + // - + // |A| + // - + // | \ + // | (ch x -- already stolen) [](){A.cancel();} + // | + // | + // (ch y -- local chore -- pChore) + // + // - ch y checks whether it is locally marked for cancellation + // - ch x cancels. It doesn't observe _M_inliningDepth yet because there is no barrier on this thread here + // therefore, it does not cancel the context + // - We execute pChore. pChore's descendents do not see the cancellation because the context flag was not set + // + // While a full fence here addresses this issue, it is a cost we do not want to bear during the fast inlining path. Because of + // the special properties of structured task collections, we are going to exploit this nature to elide the fence. When a + // structured collection is canceled, the owning context will be marked as "pending cancellation" if it was not perceived as + // inlined by the canceling thread. Even if we don't see the task collection marked canceled here at this interruption point, + // an interruption point in the inline chore will see the pending flag set and throw the _Interruption_exception. + // + if (_IsMarkedForCancellation() || (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(this))) + { + throw _Interruption_exception(); + } + + pChore->m_pFunction(pChore); + pChore->_M_pTaskCollection = NULL; + } + + long queuedChores = _M_unpoppedChores; + + while (queuedChores > 0) + { + pChore = pCurrentContext->PopStructured(); + + // + // **READ THIS** (This is rather subtle): + // + // In order to avoid a restriction on structured task collections that there cannot be an interruption point between the declaration + // of the collection and its corresponding wait, we must guarantee that we only flag the owning context as canceled if the collection + // is inlined (as evidenced by _M_inliningDepth above). The problem is that there is **NO FENCE** on this set. That means that if the + // cancellation thread perceives the write of _M_inliningDepth out of order with respect to OUR read of the cancellation flags below, + // this branch can fail to cancel for a single chore (and its nested subtrees). + // + // In order to avoid this (in at least the vast majority of cases), the interruption point is being strategically placed between the + // PopStructured call above and the execution of the chore because Pop is -- the vast majority of the time -- a full barrier. We are, + // in essence, borrowing the full fence in pop to order to eliminate this race. + // + // Note -- one of the optimizations of the WSQ (privatization) which may occur in the future can elide the fence on pop some of the time. + // If this happens, it is entirely possible that in rare circumstances, we will STILL miss and the write/read will be perceived in the opposite + // order by the canceling processor. In that case, the worst thing that happens is that we execute a single chore and its subtrees without + // getting the cancel there. Given that an additional barrier specific to cancellation would result in ~25% performance hit on key benchmarks, + // this is something we're living with. + // + // Note also that there must be a fence of _M_inliningDepth and a subsequent interruption point between the set of _M_inliningDepth and the + // WaitOnStolenChores if everything was stolen prior to getting into this function. Otherwise, we can fail to cancel entire branches if the + // Wait() happens **AFTER** all branches are stolen. Between the PopStructured (acting as fence) and the break below is the only place to + // strategically do this without introducing extra overhead. This means that there will be code replication in the catch blocks below. + // + if (_IsMarkedForCancellation() || (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(this))) + { + // + // We need to know whether the local chore has performed accounting or not. Flag this within the collection to avoid additional space + // on the local stack (which affects benchmark performance). This pushes **ALL** of the overhead into the cancellation path. This flag + // will be checked below when the exception is caught. + // + _M_inlineFlags |= _S_localCancel; + throw _Interruption_exception(); + } + + if (pChore == NULL) + break; + + --queuedChores; + + if (pChore == reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + continue; + + --_M_unpoppedChores; + + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + + pChore->m_pFunction(pChore); + pChore->_M_pTaskCollection = NULL; + } + + if (_M_unpoppedChores > 0) + { + // + // Note that the chore difference between _M_unpoppedChores and queuedChores indicates how many were executed via + // explicit affinitization. The wait mechanism is, however, identical. + // + _WaitOnStolenChores(_M_unpoppedChores); + _M_unpoppedChores = 0; + } + } + catch(const _Interruption_exception &) + { + if (pChore != NULL && pChore != reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + { + if (_M_inlineFlags & _S_localCancel) + { + // + // This did not happen above because the interruption point prevented it. The interruption point is located where it is for strategic fence + // reduction. Hence, this code should match **EXACTLY** what is done above between the break and the execution of m_pFunction. + // + --_M_unpoppedChores; + + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + } + pChore->_M_pTaskCollection = NULL; + } + _RaisedCancel(); + } + catch(...) + { + // + // Track the exception that was thrown here and rethrow outside catch handler. + // + if (pChore != NULL && pChore != reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + { + pChore->_M_pTaskCollection = NULL; + } + _RaisedException(); + } + + // + // If necessary remove any registration from the cancellation token -- the destructor will handle the reference + // removal. + // + if (_M_pTokenState != NULL) + { + ASSERT(pTokenState != NULL); + pCurrentContext->PopGoverningTokenState(pTokenState); + // + // This call will synchronize with a corresponding cancellation. + // + if (pRegistration != NULL) + { + pTokenState->_DeregisterCallback(pRegistration); + } + } + + pCurrentContext->SetExecutingCollection(_M_pParent); + + if (_M_pException != NULL) // this could be due to either a user exception or the internal _Interruption_exception. + { + // + // This will rethrow if an exception was caught (both in the catch blocks above and in _UnrealizedChore::_StructuredChoreWrapper) + // However, it will not rethrow an _Interruption_exception. That exception should only be thrown if there is a higher level + // cancel that is visible to this task collection *AFTER* _Abort has returned. Abort will undo the effect of a CancelCollection + // (with CancelCollectionComplete), if this collection was canceled while it was inlined. + // + _Abort(); + // + // As _Abort undoes the effect of cancellations at this level, HasAnyCancellations() and IsCancellationVisible() from this + // refer to cancellation at a higher level. However if this task group had an uncanceled token, _RunAndWait should not throw + // the interruption exception up + // + if (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(this, _M_pTokenState != NULL)) + { + throw _Interruption_exception(); + } + return _Canceled; + } + + // + // It's possible that our last chore caused a cancellation higher up in the tree and we should interrupt for that case, if appropriate. + // + if (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(this, _M_pTokenState != NULL)) + { + throw _Interruption_exception(); + } + + return _Completed; + } + + /// + /// Internal routine to clean up after a cancellation token. + /// + void _StructuredTaskCollection::_CleanupToken() + { + ASSERT(_CancellationTokenState::_IsValid(_M_pTokenState)); + + _CancellationTokenRegistration *pRegistration = NULL; + _CancellationTokenState *pTokenState = _GetTokenState(&pRegistration); + + if (pRegistration != NULL) + { + pRegistration->_Release(); + } + + if (_CancellationTokenState::_IsValid(pTokenState)) + { + pTokenState->_Release(); + } + } + + /// + /// Aborts chores related to the task collection and waits for those which cannot be forcibly aborted. + /// + void _StructuredTaskCollection::_Abort() + { + // + // _Abort cannot be called unless Schedule was called which guaranteed _M_pOwningContext != NULL + // + ASSERT(_M_pOwningContext != NULL); + ContextBase *pCurrentContext = reinterpret_cast (_M_pOwningContext); + + long queuedChores = _M_unpoppedChores; + + while (queuedChores > 0) + { + _UnrealizedChore *pChore = pCurrentContext->PopStructured(); + if (pChore == NULL) + break; + + --queuedChores; + + if (pChore == reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + continue; + + pChore->_M_pTaskCollection = NULL; + + // + // Update the statistical information with the fact that a task has been dequeued + // + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + + --_M_unpoppedChores; + } + + if (_M_unpoppedChores > 0) + { + // + // If there are stolen chores outstanding, redo the cancellation to trigger marking of them in special circumstances. It's entirely possible + // that the cancellation only happened as a result of chaining and all our chores were stolen at the time. + // + _Cancel(); + + // + // Note that the chore difference between _M_unpoppedChores and queuedChores indicates how many were executed via + // explicit affinitization. The wait mechanism is, however, identical. + // + _WaitOnStolenChores(_M_unpoppedChores); + _M_unpoppedChores = 0; + } + + // + // Any caught exception on the collection should be rethrown on this thread. The exception might be one of several things: + // + // _Interruption_exception (or another internal runtime exception): + // + // - We want to let this exception continue propagating unless there's a *more important* one (like an arbitrary exception) that occurred + // elsewhere. + // + // an arbitrary exception: + // + // - We are allowed to choose an arbitrary exception to flow back. + // + _SpinWaitBackoffNone spinWait; + while (((size_t) _Exception() == _S_nonNull) || (_CancelState() == _S_cancelStarted)) // make sure the exception is ready or that cancellation is finished + { + spinWait._SpinOnce(); + } + + if (_PerformedInlineCancel()) + { + pCurrentContext->CancelCollectionComplete(_M_inliningDepth); + } + else if (_PerformedPendingCancel()) + { + pCurrentContext->PendingCancelComplete(); + } + + _RethrowException(); + } + + /// + /// Cancels work on the task collection. + /// + void _StructuredTaskCollection::_Cancel() + { + if (_M_pOwningContext == NULL) + _M_pOwningContext = SchedulerBase::CurrentContext(); + + // + // Multiple stolen chores might cancel at the same time. We can only allow one person into the path + // which fires down threads so the counters get set correctly. + // + if (_MarkCancellation()) + { + // + // Determine which inline context needs to be aborted (we could be canceling from a stolen chore which is perfectly + // legal under the structured semantic). + // + // Note that the original context may not have inlined yet. If we arbitrarily cancel the owning context, we place a + // heavy restriction on structured task collection that it cannot have an interruption point between its declaration + // and its wait. It would be bad for such an interruption point to throw an exception because there may be no one on + // the stack to catch that exception. At the moment, this is deemed to be too heavy a restriction. Therfore, we only + // cancel the collection if it is inlining. There is a subtle implication to this too. Because a full fence is too + // expensive on the inlining side, the setting of inline can be reordered with respect to the read of the cancellation + // bit. If that reordering is perceived by a canceling thread, chores may execute despite cancellation on the inline + // context. This would be unfortunate, but perfectly legal according to the cancellation semantic. + // + // In order to avoid this type of race for the inline chore of a _RunAndWait, we are going to exploit special properties + // of a structured task collection: since we have a guarantee that this collection will be inlined on this thread. We + // are going to mark the thread as pending cancellation if we do not perceive it as currently inlined. This will allow + // us to elide a fence during a local chore in _RunAndWait. + // + ContextBase *pContext = reinterpret_cast (_M_pOwningContext); + if (_M_inliningDepth >= 0) + { + // + // _M_inliningDepth is guaranteed to be stable if we perceive this. Only the inline context or a stolen chore can + // cancel a structured collection. If the collection is currently inlined, we're in a wait which won't be satisfied + // until this thread completes. + // + pContext->CancelCollection(_M_inliningDepth); + _FinishCancelState(_S_cancelShotdownOwner); + } + else + { + pContext->PendingCancel(); + _FinishCancelState(_S_cancelDeferredShootdownOwner); + } + + _CancelStolenContexts(); + } + } + + /// + /// Called to cancel any contexts which stole chores from the given collection. + /// + void _StructuredTaskCollection::_CancelStolenContexts() + { + ContextBase *pContext = reinterpret_cast (_M_pOwningContext); + pContext->CancelStealers(this); + } + + /// + /// Informs the caller whether or not the task collection is currently in the midst of cancellation. Note that this + /// does not necessarily indicate that Cancel was called on the collection (although such certainly qualifies this function + /// to return true). It may be the case that the task collection is executing inline and a task collection further up in the work + /// tree was canceled. In cases such as these where we can determine ahead of time that cancellation will flow through + /// this collection, true will be returned as well. + /// + /// + /// An indication of whether the task collection is in the midst of a cancellation (or is guaranteed to be shortly). + /// + bool _StructuredTaskCollection::_IsCanceling() + { + if (_M_pOwningContext == NULL) + _M_pOwningContext = SchedulerBase::CurrentContext(); + + // + // If This collection has an exception or cancellation we can return true right away. Cancellation flags are stored in + // the last two bits of the exception field + // + if (_M_pException != NULL) + return true; + // + // If our token is canceled, flag us immediately. + // + _CancellationTokenState* pTokenState = _GetTokenState(); + if (_CancellationTokenState::_IsValid(pTokenState) && pTokenState->_IsCanceled()) + { + _Cancel(); + return true; + } + + ContextBase *pOwningContext = reinterpret_cast (_M_pOwningContext); + // + // Either we were canceled or someone higher than us on our context was canceled. This is all safe without lock because of the rules for using + // a structured task collection. NOTHING changes those rules. You may only call this from the owning context or a thread within the work tree. This has + // the same "special" properties as ::_Cancel in that regard. + // + return ((_IsCurrentlyInlined() && pOwningContext->IsCanceledAtDepth(this)) || + (pOwningContext->HasPendingCancellation() && _WillInterruptForPendingCancel())); + } + + /// + /// Waits on a specified number of stolen chores. + /// + /// + /// The number of stolen chores to wait upon + /// + void _StructuredTaskCollection::_WaitOnStolenChores(long stolenChoreCount) + { + if (_M_completedStolenChores <= _CollectionInitializationInProgress) + _Initialize(); + + long count = InterlockedExchangeAdd(&_M_completedStolenChores, -stolenChoreCount) - stolenChoreCount; + + if (count < 0) + reinterpret_cast (_M_event)->Wait(); + } + + /// + /// Indicates that a stolen chore has completed. + /// + void _StructuredTaskCollection::_CountUp() + { + if (_M_completedStolenChores <= _CollectionInitializationInProgress) + _Initialize(); + + LONG count = InterlockedIncrement(&_M_completedStolenChores); + + if (count == 0) + reinterpret_cast (_M_event)->Set(); + } + + /// + /// Initializes the structured task collection to count stolen chores. + /// + void _StructuredTaskCollection::_Initialize() + { + if (InterlockedCompareExchange(&_M_completedStolenChores, + _CollectionInitializationInProgress, + _CollectionNotInitialized) == _CollectionNotInitialized) + { + new (reinterpret_cast (_M_event)) StructuredEvent(); +#if _DEBUG + long previousCompleted = InterlockedExchange(&_M_completedStolenChores, _CollectionInitialized); + ASSERT(previousCompleted == _CollectionInitializationInProgress); +#else + InterlockedExchange(&_M_completedStolenChores, _CollectionInitialized); +#endif + } + else + { + _SpinWaitBackoffNone spinWait; + while (_M_completedStolenChores <= _CollectionInitializationInProgress) + spinWait._SpinOnce(); + } + } + + // ********************************************************************** + // Unstructured Task Collections: + // ********************************************************************** + + /// + /// Constructs a new unstructured task collection + /// + _TaskCollection::_TaskCollection() + : _M_executionStatus(TASKCOLLECTION_EXECUTION_STATUS_CLEAR) + , _M_pNextAlias(NULL) + , _M_pTaskExtension(NULL) + , _M_flags(0) + , _M_stackPos(0) + , _M_completionHandler(NULL) + { + // + // CurrentContext may create a context + // + _M_pOwningContext = SchedulerBase::CurrentContext(); + ContextBase *pCurrentContext = reinterpret_cast (_M_pOwningContext); + _M_pParent = pCurrentContext->GetExecutingCollection(); + + _Initialize(); + _M_event.set(); + _M_pOriginalCollection = this; + _M_boundQueueId = SchedulerBase::FastCurrentContext()->GetWorkQueueIdentity(); + _M_inlineFlags = 0; + } + + /// + /// Constructs a new task collection whose cancellation is governed by the specified cancellation token state. + /// + /// + /// When this cancellation token is canceled, the task collection is canceled. + /// + _TaskCollection::_TaskCollection(_CancellationTokenState *_PTokenState) + : _TaskCollectionBase(_PTokenState) + , _M_executionStatus(TASKCOLLECTION_EXECUTION_STATUS_CLEAR) + , _M_pNextAlias(NULL) + , _M_pTaskExtension(NULL) + , _M_flags(0) + , _M_stackPos(0) + , _M_completionHandler(NULL) + { + if (_CancellationTokenState::_IsValid(_PTokenState)) + { + _PTokenState->_Reference(); + } + + // + // CurrentContext may create a context + // + _M_pOwningContext = SchedulerBase::CurrentContext(); + ContextBase *pCurrentContext = reinterpret_cast (_M_pOwningContext); + _M_pParent = pCurrentContext->GetExecutingCollection(); + + _Initialize(); + _M_event.set(); + _M_pOriginalCollection = this; + _M_boundQueueId = SchedulerBase::FastCurrentContext()->GetWorkQueueIdentity(); + _M_inlineFlags = 0; + } + + /// + /// Performs task cleanup normally done at destruction time. + /// + /// + /// An indication if the cleanup is exceptional and the collection should be left in a canceled state. + /// + bool _TaskCollection::_TaskCleanup(bool fExceptional) + { + bool fThrow = false; + + // + // Direct alias destruction should not attempt to go through any wait/abort cycle. It's simply the deletion/abandonment + // of the alias. The original collection might not even be around to touch. + // + if (!_IsDirectAlias()) + { + if (!__uncaught_exception()) + { + // + // Users are required to call Wait() before letting the destructor run. Otherwise, throw. Note that before throwing, + // we must actually wait on the tasks since they contain pointers into stack frames and unwinding without the wait is + // instant stack corruption. + // + fThrow = (_M_unpoppedChores > 0); + + // + // We must check all direct aliases as well. + // + if (_M_pOriginalCollection == this && _M_pNextAlias != NULL) + { + _TaskCollection *pAlias = _M_pNextAlias; + while (pAlias != NULL) + { + if (pAlias->_M_unpoppedChores > 0) + fThrow = true; + + pAlias = pAlias->_M_pNextAlias; + } + } + + if (fThrow) + _Abort(fExceptional); + } + else + _Abort(fExceptional); + + } + + return !fThrow; + } + + /// + /// Destructs a new unstructured task collection + /// + _TaskCollection::~_TaskCollection() + { + bool fThrow = false; + + // + // Direct alias destruction should not attempt to go through any wait/abort cycle. It's simply the deletion/abandonment + // of the alias. The original collection might not even be around to touch. + // + if (!_IsDirectAlias()) + { + fThrow = !_TaskCleanup(false); + + // + // Go through and cleanup direct aliases. Note that there's an inherent problem and conflict here: + // + // - An internal context may go away and need to destroy its alias table -- it cannot touch the original task collection since it does + // not know when that collection may be deleted (it may have already) + // + // - The original task collection may be deleted but it cannot remove entries from alias tables. + // + // In order to resolve this and appropriately free the aliases, there's a simple cleanup state machine with a set of rules to act + // as a last man out frees the object. + // + // - If the destructor runs, it flags each alias so that the context can delete them + // - When a context exits, it flags each alias so that the destructor deletes them + // - First one to reach an alias with the flag set frees it. + // + // Note this is essentially a fixed reference count of two, but done with a bit flag to allow for other shared state in the flags. + // + if (_M_pOriginalCollection == this) + { + _TaskCollection *pAlias = _M_pNextAlias; + _TaskCollection *pNext = NULL; + + for (; pAlias; pAlias = pNext) + { + pNext = pAlias->_M_pNextAlias; + pAlias->_ReleaseAlias(); + } + } + } + + TaskStack *pStack = reinterpret_cast (_M_pTaskExtension); + if (pStack) delete pStack; + + // If this task collection was used for a PPL task, the exception could still be stored here. + std::exception_ptr *pException = _Exception(); + if (pException != NULL && (size_t)pException != _S_cancelException) + { + delete pException; + } + + if (_CancellationTokenState::_IsValid(_M_pTokenState)) + { + _M_pTokenState->_Release(); + } + + if (fThrow) + throw missing_wait(); + } + + /// + /// Constructs a new unstructured task collection as an alias of an already existing one. An alias in this particular + /// case is a context-local representation of the original task collection. + /// + /// + /// The source of the aliasing. The newly constructed collection will be a direct or indirect + /// alias of this collection + /// + /// + /// Indicates whether the collection is a direct alias (the collection is used on an arbitrary thread + /// not related to stolen work) or an indirect alias (a collection implicitly created for stolen chores). + /// + _TaskCollection::_TaskCollection(_TaskCollection *pOriginCollection, bool fDirectAlias) + : _M_executionStatus(TASKCOLLECTION_EXECUTION_STATUS_CLEAR) + , _M_pOriginalCollection(pOriginCollection->_M_pOriginalCollection) + , _M_pTaskExtension(NULL) + , _M_flags(0) + , _M_stackPos(0) + , _M_completionHandler(NULL) + { + // + // CurrentContext may create a context + // + _M_pOwningContext = SchedulerBase::CurrentContext(); + ContextBase *pCurrentContext = reinterpret_cast (_M_pOwningContext); + _M_pParent = pCurrentContext->GetExecutingCollection(); + _M_pTokenState = pOriginCollection->_M_pTokenState; + if (_CancellationTokenState::_IsValid(_M_pTokenState)) + { + _M_pTokenState->_Reference(); + } + _Initialize(); + _M_event.set(); + if (fDirectAlias) + { + _TaskCollection *pAlias = _M_pOriginalCollection->_M_pNextAlias; + for (;;) + { + _M_pNextAlias = pAlias; + _TaskCollection *pxchgAlias = reinterpret_cast <_TaskCollection *> (InterlockedCompareExchangePointer((volatile PVOID*)&_M_pOriginalCollection->_M_pNextAlias, this, pAlias)); + if (pxchgAlias == pAlias) + break; + + pAlias = pxchgAlias; + } + } + else + { + _M_flags = _M_flags | TASKCOLLECTIONFLAG_ALIAS_IS_INDIRECT; + _M_pNextAlias = NULL; + } + + _M_boundQueueId = SchedulerBase::FastCurrentContext()->GetWorkQueueIdentity(); + _M_inlineFlags = 0; + } + + /// + /// Determines whether the alias is stale (waiting to be deleted) + /// + bool _TaskCollection::_IsStaleAlias() const + { + ASSERT (_IsAlias()); + return (_M_flags & TASKCOLLECTIONFLAG_ALIAS_FREE_ON_VIEW) != 0; + } + + /// + /// Releases an alias (frees it if appropriate) + /// + void _TaskCollection::_ReleaseAlias() + { + ASSERT (_IsAlias()); + long flags = _M_flags; + // + // Future proof against usage of the flags field. + // + for (;;) + { + // + // If we observed the flag but weren't the one to set it, we're responsible for freeing the alias. + // + if (flags & TASKCOLLECTIONFLAG_ALIAS_FREE_ON_VIEW) + break; + + long xchgFlags = InterlockedCompareExchange(&_M_flags, flags | TASKCOLLECTIONFLAG_ALIAS_FREE_ON_VIEW, flags); + if (xchgFlags == flags) + { + // + // If we get here, *this* is poison. + // + return; + } + flags = xchgFlags; + } + delete this; + } + + /// + /// Returns the original task collection (the collection that this object is an alias for). + /// + _TaskCollection *_TaskCollection::_OriginalCollection() const + { + ASSERT(_IsAlias()); + return _M_pOriginalCollection; + } + + /// + /// Returns the alias for the specified task collection on the current context. A NULL return would indicate + /// an error condition (e.g.: inability to allocate a new direct alias, etc...). + /// + /// + /// The alias for the specified task collection on the current context or NULL on error + /// + _TaskCollection *_TaskCollection::_Alias() + { + ASSERT(!_IsDirectAlias()); + + // + // Someone may have used this task collection on an arbitrary new thread -- hence, we need to make sure there's + // a current context (not FastCurrentContext). Note that such usage will imply a direct alias (the code + // will fall through to that point) + // + // Note that a task collection is bound to both the thread and the work queue. Normally, these won't differ, but may + // in certain cases where a task collection is used on an internal context which exits before deletion and we get into + // detached work queue cases. Those queues get deleted when empty and it's entirely possible that another queue + // could get reallocated in the exact same memory location. Hence -- we bind to an identity assigned to each + // work queue. Thus, aliasing checks both the owning context and the queue identity. + // + ContextBase *pCurrentContext = SchedulerBase::CurrentContext(); + DWORD queueId = pCurrentContext->GetWorkQueueIdentity(); + if (pCurrentContext != reinterpret_cast (_M_pOwningContext) || queueId != _M_boundQueueId) + { + // + // The task collection has been used on an alternate thread. We need an alias for the task collection. The alias can + // take one of two forms: a direct alias (the collection is used on an arbitrary thread) or an indirect alias + // (the collection is used during a stolen chore). + // + // Indirect aliases are simple: they have the lifetime (and wait span) of the stolen chore. Direct aliases + // have far more complication. + // + _TaskCollection *pIndirectAlias = pCurrentContext->GetIndirectAlias(); + if (pIndirectAlias != NULL) + { + if (pIndirectAlias->_M_pOriginalCollection == this) + return pIndirectAlias; + + // + // It's still possible that this follows the pattern used by indirect aliases. It could be transitive: + // + // _TaskCollection rtp; + // rtp.Schedule( + // { + // _TaskCollection tp; + // tp.Schedule( + // { + // rtp.Schedule(...); // <-- this is transitive. + // rtp.Cancel(...); // <-- this is transitive. + // } + // }); + // + // The unfortunate reality of this situation is that indirect aliasing cannot work here (see below). We need + // a direct alias. + // + // Second generation or older transitivity: While the indirect alias could be used for this to satisfy the wait, + // it would lead to deadlock and unexpected behavior if there are out-of-band dependencies between the code after the wait and the + // whatever we add to the transitive object. For example, + // + // A -> B -> C + // + // If C does A.Schedule(x); + // x == { receive_message(); } + // and someone in the middle does B.Wait(); send_message(); + // + // using the indirect alias would deadlock because C would wait on x, B waits on C, and after B waits on C, x is satisfied. + // + // Hence -- we must use a direct alias in this case. + // + } + + ASSERT(!_IsAlias()); + + _TaskCollection *pAlias = pCurrentContext->GetArbitraryAlias(this); + if (pAlias != NULL) + { + // + // Make certain the alias we are returning to the client is an alias for the task collection and thread we think it is and that it is **NOT** + // stale. Stale would imply that either the this pointer was deleted (bad) or that the context underlying the alias was deleted (bad). In any + // of these cases, there's an issue with the alias we are returning and the caller will corrupt another thread's data structure. + // + ASSERT(pAlias->_M_pOriginalCollection == this && reinterpret_cast(pAlias->_M_pOwningContext) == pCurrentContext && !pAlias->_IsStaleAlias()); + return pAlias; + } + + // + // At this stage, we are forced to create a direct alias. + // + _TaskCollection *pDirectAlias = _concrt_new _TaskCollection(this, true); + pCurrentContext->AddArbitraryAlias(this, pDirectAlias); + + return pDirectAlias; + } + return this; + } + + /// + /// Returns whether the task collection is an alias. + /// + bool _TaskCollection::_IsAlias() const + { + return (_M_pOriginalCollection != this); + } + + /// + /// Returns whether the task collection is an indirect alias. + /// + bool _TaskCollection::_IsIndirectAlias() const + { + return (_M_pOriginalCollection != this && (_M_flags & TASKCOLLECTIONFLAG_ALIAS_IS_INDIRECT) != 0); + } + + /// + /// Returns whether the task collection has a direct alias + /// + bool _TaskCollection::_HasDirectAlias() const + { + return (_M_pOriginalCollection->_M_pNextAlias != NULL); + } + + /// + /// Returns whether the task collection is a direct alias. + /// + bool _TaskCollection::_IsDirectAlias() const + { + return (_M_pOriginalCollection != this && (_M_flags & TASKCOLLECTIONFLAG_ALIAS_IS_INDIRECT) == 0); + } + + /// + /// Returns whether this task collection is marked for abnormal exit. + /// + bool _TaskCollection::_IsMarkedForAbnormalExit() const + { + return (_M_pOriginalCollection->_M_exitCode != 0); + } + + /// + /// Called when a new chore is placed upon the task collection. Guarantees forward synchronization with the completion of them. + /// + void _TaskCollection::_NotifyNewChore() + { + long val = InterlockedIncrement(&_M_unpoppedChores); + ASSERT(val > 0); + // + // Because the task collection can be passed between threads and waited upon, either this thread or a stealer might need to wake + // another thread on final completion (we might never wait). Thus, we need to fence these operations. We also need + // to make sure 0->1 and 1->0 transitions correctly perform the appropriate signaling. + // + if (val == 1) + { + // + // It's entirely possible that we're racing with a _NotifyCompletedChoreAndFree which just did a 1->0 and we just did a 0->1. We need to make + // sure that the event is signaled before we clear it. Otherwise, it's possible that the event winds up out of sync with + // the counter. + // + // In the vast majority of cases, the pEvent->Wait() call has no fences and merely checks the state seeing it signaled and returns. + // The only time there's even a fence is during the race. + // + _M_event.wait(); + + // + // This is the barrier at which point other threads think there's something to wait upon. Note that it's not upon the WSQ yet + // (meaning no one can steal and transition us from 1->0 as of yet). + // + _M_event.reset(); + } + } + + /// + /// Called when a chore is completed. + /// + void _TaskCollection::_NotifyCompletedChoreAndFree(_UnrealizedChore * pChore) + { + // Check if the chore needs to be freed. + if (pChore->_GetRuntimeOwnsLifetime()) + { + _UnrealizedChore::_InternalFree(pChore); + } + + // Save the member variables as locals since task collection could be deleted + // as soon as the event is set. + TaskProc completionCallback = _M_completionHandler; + void * completionContext = _M_pCompletionContext; + + long val = InterlockedDecrement(&_M_unpoppedChores); + ASSERT(val >= 0); + // + // Because the task collection can be passed between threads and waited upon, any transition from 1->0 needs to wake an arbitrary set + // of threads, hence -- this needs a fence. + // + if (val == 0) + { + // + // No games need be played here. Anyone who pushes a chore will see the event clear and wait before pushing it upon the WSQ. This + // means there can be no race with messing up the event state. Setting the event suffices. + // + _M_event.set(); + } + + if (completionCallback != NULL) + { + completionCallback(completionContext); + } + } + + /// + /// Perform a wait on every alias. Note that we make no attempt to inline any of the executions of things pushed on other threads. We merely + /// wait for them. They'll be stolen and executed eventually. + /// + /// + /// The snapshot point which indicates which aliases are involved in the wait + /// + void _TaskCollection::_FullAliasWait(_TaskCollection *pSnapPoint) + { + _TaskCollection *pAlias = pSnapPoint; + int count = 0; + while (pAlias != NULL) + { + count++; + pAlias = pAlias->_M_pNextAlias; + } + + if (count > 0) + { + _MallocaArrayHolder mholder; + event **pEvents = mholder._InitOnRawMalloca(_malloca(sizeof (event *) * (count + 1))); + + pEvents[0] = &(_M_pOriginalCollection->_M_event); + + int i = 1; + pAlias = pSnapPoint; + while (i < count + 1) + { + pEvents[i] = &(pAlias->_M_event); + i++; + pAlias = pAlias->_M_pNextAlias; + } + + event::wait_for_multiple(pEvents, (count + 1), true); + } + else + { + _M_event.wait(); + } + } + + /// + /// Schedules a new unstructured chore upon an unstructured task collection + /// + /// + /// The new unrealized chore to schedule + /// + /// + /// The location where the unrealized chore should execute. Specifying the value NULL here indicates that the unrealized chore does not + /// have specific placement. + /// + void _TaskCollection::_Schedule(_UnrealizedChore *pChore, location *_PLocation) + { + if (pChore->_M_pTaskCollection != NULL) + throw invalid_multiple_scheduling(); + + try + { + _TaskCollection *pAlias = _Alias(); + + pChore->_M_pTaskCollection = pAlias; + pChore->_M_pChoreFunction = &_UnrealizedChore::_UnstructuredChoreWrapper; + + ASSERT(pAlias->_M_stackPos >= 0); // Satisfy static analyzers that might assume _M_unpoppedChores could be negative (it's signed). + int locationBase = pAlias->_M_stackPos++; + if (locationBase >= SIZEOF_ARRAY(pAlias->_M_taskCookies)) + { + // + // We've spilled outside the allowable internal allocation of tasks (this is largely an optimization to avoid + // heap allocations on typically sized task collections). + // + TaskStack *pStack = reinterpret_cast (pAlias->_M_pTaskExtension); + if (pStack == NULL) + { + pStack = _concrt_new TaskStack(); + pAlias->_M_pTaskExtension = pStack; + } + + pAlias->_NotifyNewChore(); + // + // ctor has already guaranteed context exists + // + if (!pStack->Push(SchedulerBase::FastCurrentContext()->PushUnstructured(pChore, _PLocation))) + { + // + // It's not on the inlining list -- it must be stolen! This is due to the cap being reached (see comments in + // TaskStack). + // + pAlias->_M_stackPos--; + } + } + else + { + pAlias->_NotifyNewChore(); + // + // ctor has already guaranteed context exists + // + ASSERT(locationBase < SIZEOF_ARRAY(pAlias->_M_taskCookies)); + pAlias->_M_taskCookies[locationBase] = SchedulerBase::FastCurrentContext()->PushUnstructured(pChore, _PLocation); + } + } + catch (...) + { + // + // We are responsible for the freeing of the chore. If any exception was thrown out, we didn't schedule it and hence + // won't free it later. It must be done now. + // + if (pChore->_GetRuntimeOwnsLifetime()) + { + _UnrealizedChore::_InternalFree(pChore); + } + throw; + } + } + + /// + /// Schedules a new unstructured chore upon an unstructured task collection + /// + /// + /// The new unrealized chore to schedule + /// + void _TaskCollection::_Schedule(_UnrealizedChore *pChore) + { + if (pChore->_M_pTaskCollection != NULL) + throw invalid_multiple_scheduling(); + + try + { + _TaskCollection *pAlias = _Alias(); + + pChore->_M_pTaskCollection = pAlias; + pChore->_M_pChoreFunction = &_UnrealizedChore::_UnstructuredChoreWrapper; + + ASSERT(pAlias->_M_stackPos >= 0); // Satisfy static analyzers that might assume _M_unpoppedChores could be negative (it's signed). + int locationBase = pAlias->_M_stackPos++; + if (locationBase >= SIZEOF_ARRAY(pAlias->_M_taskCookies)) + { + // + // We've spilled outside the allowable internal allocation of tasks (this is largely an optimization to avoid + // heap allocations on typically sized task collections). + // + TaskStack *pStack = reinterpret_cast (pAlias->_M_pTaskExtension); + if (pStack == NULL) + { + pStack = _concrt_new TaskStack(); + pAlias->_M_pTaskExtension = pStack; + } + + pAlias->_NotifyNewChore(); + // + // ctor has already guaranteed context exists + // + if (!pStack->Push(SchedulerBase::FastCurrentContext()->PushUnstructured(pChore))) + { + // + // It's not on the inlining list -- it must be stolen! This is due to the cap being reached (see comments in + // TaskStack). + // + pAlias->_M_stackPos--; + } + } + else + { + pAlias->_NotifyNewChore(); + // + // ctor has already guaranteed context exists + // + ASSERT(locationBase < SIZEOF_ARRAY(pAlias->_M_taskCookies)); + pAlias->_M_taskCookies[locationBase] = SchedulerBase::FastCurrentContext()->PushUnstructured(pChore); + } + } + catch (...) + { + // + // We are responsible for the freeing of the chore. If any exception was thrown out, we didn't schedule it and hence + // won't free it later. It must be done now. + // + if (pChore->_GetRuntimeOwnsLifetime()) + { + _UnrealizedChore::_InternalFree(pChore); + } + throw; + } + } + + /// + /// Resets the task collection for future usage. + /// + /// + /// The snapshot from which to reset + /// + void _TaskCollection::_Reset(_TaskCollection *pSnapPoint) + { + // + // Clear the cancellation flag. Note that if a cancellation was done for the context, we must clear the collection cancel flag. This is only + // safe to do for the owning context. If the execution status indicates any kind of inlining, the owning context is in the midst of a + // _Abort, _Reset, or Wait and will take care of itself. Only on non-inline status do we need to do something cross thread. The only state + // to which that applies is TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED. + // + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + ContextBase *pOwningContext = reinterpret_cast (_M_pOwningContext); + + LONG capturedStatus = _M_executionStatus; + + for(;;) + { + if (capturedStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS) + { + // + // If someone is in the middle of canceling, we must let them proceed until they've reached the point where the cancellation + // of the context happens. Spin wait. Note that if we do not do this, it's entirely possible that we check cancellation + // of the context below BEFORE they cancel it, they cancel it, and some arbitrary task collection gets canceled instead of the one + // intended on the inline side. + // + _SpinWaitBackoffNone spinWait; + while (_M_executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS) + { + spinWait._SpinOnce(); + } + + capturedStatus = _M_executionStatus; + continue; + } + + long xchgVal; + + if (pCurrentContext == pOwningContext) + { + xchgVal = InterlockedCompareExchange(&_M_executionStatus, + TASKCOLLECTION_EXECUTION_STATUS_CLEAR, + capturedStatus); + + if (xchgVal == capturedStatus) + { + if (xchgVal == TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE) + { + pCurrentContext->CancelCollectionComplete(_M_inliningDepth); + } + + _M_inliningDepth = -1; + break; + } + } + else + { + xchgVal = InterlockedCompareExchange(&_M_executionStatus, + TASKCOLLECTION_EXECUTION_STATUS_CLEAR, + TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED); + + if (xchgVal != TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS) + { + break; + } + } + + capturedStatus = xchgVal; + } + + // + // If there are direct aliases, we must clear those up too. + // + if (!_IsAlias()) + { + if (pSnapPoint) + { + _TaskCollection *pAlias = pSnapPoint; + while (pAlias) + { + if (!pAlias->_IsStaleAlias()) + { + pAlias->_Reset(NULL); + } + pAlias = pAlias->_M_pNextAlias; + } + } + // + // Any caught exception on the collection should be rethrown on this thread. The exception can be one of several things: + // + // _Interruption_exception (or another internal runtime exception): + // + // - We want to let this exception continue propagating unless there's a *more important* one (like an arbitrary exception) that occurred + // elsewhere. There is an unfortunate situation here: + // + // o We might be within a destructor. Here, by the C++ standard, we cannot throw a different exception or the + // process will terminate. This is unfortunate because it might be better to throw one of the exceptions + // which did happen. You might run into code like this where you have + // + // try + // { + // *_TaskCollection tp; + // tp.Schedule(t1); // throws e1 + // tp.Schedule(t2); // throws e2 + // + // // arbitrary code with an interruption point that causes _Interruption_exception to be thrown. + // + // tp.Wait(); + // } + // catch (...) { } + // + // an arbitrary exception: + // + // - We are allowed to choose an arbitrary exception to flow back. + // + long exitCode = InterlockedExchange(&_M_exitCode, 0); + if ((exitCode & EXIT_STATUS_FLAG_EXCEPTION_RAISED) != 0) + { + _SpinWaitBackoffNone spinWait; + while ((size_t) _M_pException == _S_nonNull) // make sure the exception is ready + spinWait._SpinOnce(); + _RethrowException(); + } + } + else + { + // + // A reset of the alias must reset the overall collection. + // + if (_IsDirectAlias() && pSnapPoint != NULL) + _M_pOriginalCollection->_Reset(pSnapPoint); + } + } + + /// + /// Called when the task collection is canceled via a cancellation token. + /// + void _TaskCollection::_CancelViaToken(_TaskCollection *pCollection) + { + pCollection->_Cancel(); + } + + /// + /// Runs a specified chore (pChore) and subsequently waits on all chores associated with the task collection + /// to execute. + /// + /// + /// The chore to run locally. + /// + /// + /// An indication of the status of the wait. + /// + _TaskCollectionStatus __stdcall _TaskCollection::_RunAndWait(_UnrealizedChore *pChore) + { + ASSERT(!_IsDirectAlias()); + + _TaskCollection *pAlias = _Alias(); + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + + // + // Snapshot the list of aliases so we have internal consistency between what we wait upon, what we reset, etc... + // + _TaskCollection *pSnapPoint = _M_pNextAlias; + bool fOverflow = false; + + // + // The parent context needs to be snapped here. It's possible that the executing collection on the + // context at the time that _RunAndWait is invoked, is different from the executing collection on the current + // context when the task collection was created. + // + pAlias->_M_pParent = pCurrentContext->GetExecutingCollection(); + pAlias->_M_inliningDepth = pAlias->_M_pParent ? pAlias->_M_pParent->_InliningDepth() + 1 : 0; + + // + // Set up the EH frame. We need to stop cancellation propagation when we hit someone who + // has become canceled. + // + pCurrentContext->SetExecutingCollection(pAlias); + + // + // The token on this collection is used interchangeably with the alias token (if the alias is not 'this'), so they must match. + // + ASSERT(pAlias->_M_pTokenState == _M_pTokenState); + // + // Handle any token which might be present. We only need to register for callbacks on token boundaries. + // + _CancellationTokenRegistration *pRegistration = NULL; + if (_M_pTokenState != NULL) + { + if (_M_pTokenState != _CancellationTokenState::_None() && _M_pTokenState != pCurrentContext->GetGoverningTokenState()) + { + pRegistration = _M_pTokenState->_RegisterCallback( + reinterpret_cast(_TaskCollection::_CancelViaToken), this + ); + } + pCurrentContext->PushGoverningTokenState(_M_pTokenState, pAlias->_M_inliningDepth); + } + + try + { + // + // This *MUST* be fenced due to allowing cancellation from arbitrary threads. The cancellation routine may have switched + // to deferred cancellation based on us not being inline. We cannot arbitrarily overwrite that result. + // + LONG xchgStatus = InterlockedCompareExchange(&pAlias->_M_executionStatus, TASKCOLLECTION_EXECUTION_STATUS_INLINE, TASKCOLLECTION_EXECUTION_STATUS_CLEAR); + if (xchgStatus == TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED) + { + // + // The catch block will expect this. + // + if (pChore != NULL) + pAlias->_NotifyNewChore(); + throw _Interruption_exception(); + } + + if (pChore != NULL) + { + pAlias->_NotifyNewChore(); + + if (_IsMarkedForAbnormalExit() || (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(pAlias))) + { + throw _Interruption_exception(); + } + + pChore->m_pFunction(pChore); + pChore->_M_pTaskCollection = NULL; + pAlias->_NotifyCompletedChoreAndFree(pChore); + pChore = NULL; + } + + for(;;) + { + TaskStack *pStack; + + while (pAlias->_M_stackPos > 0) + { + // + // The _IsMarkedForAbnormalExit() is a necessary semantic (pass a canceled task collection to a new thread -- this is the only check that + // will prevent stuff from going onto it prior to a reset). It's also necessary to check the exit code on the original collection because + // we could have a scenario where a chore is stolen from a direct alias which then pushes chores back to the original collection. This will + // result in an indirect alias being used and the stealing won't see the alias inlined. Hence -- waiting on the indirect alias cannot be canceled. + // + if (_IsMarkedForAbnormalExit() || (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(pAlias))) + { + throw _Interruption_exception(); + } + + int taskCookie; + + if (pAlias->_M_stackPos > SIZEOF_ARRAY(pAlias->_M_taskCookies)) + { + pStack = reinterpret_cast(pAlias->_M_pTaskExtension); + ASSERT(!pStack->IsEmpty()); + taskCookie = pStack->Pop(); + } + else + { + taskCookie = pAlias->_M_taskCookies[pAlias->_M_stackPos - 1]; + } + + pAlias->_M_stackPos--; + + pChore = pCurrentContext->TryPopUnstructured(taskCookie); + if (pChore == NULL) + { + // + // If we failed because something was stolen, everything underneath us was stolen as well and the wait on stolen chores + // will guarantee that we wait on everything necessary. We can clear out the stack to prevent reuse of the task collection + // from just building up excess entries. + // + TaskStack *pStack = reinterpret_cast (pAlias->_M_pTaskExtension); + if (pStack != NULL) pStack->Clear(); + pAlias->_M_stackPos = 0; + + break; + } + + if (pChore == reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + continue; + + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + + pChore->m_pFunction(pChore); + pChore->_M_pTaskCollection = NULL; + pAlias->_NotifyCompletedChoreAndFree(pChore); + pChore = NULL; + } + + // + // If the task stack overflowed, there are potentially still items on the work stealing queue we could not inline. If we simply + // block without care and one of those items cancels, we can deadlock (since we cannot steal from canceled contexts). If the + // stack overflowed, we need to perform special handling. + // + pStack = reinterpret_cast(pAlias->_M_pTaskExtension); + if (pStack != NULL && pStack->Overflow()) + { + fOverflow = true; + + // + // We need to tell the canceling thread to perform the WSQ sweep or do ourselves as determined by a CAS. + // + LONG xchgStatus = InterlockedCompareExchange(&pAlias->_M_executionStatus, + TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK, + TASKCOLLECTION_EXECUTION_STATUS_INLINE); + + switch(xchgStatus) + { + case TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS: + case TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE: + throw _Interruption_exception(); + default: + break; + } + } + + _FullAliasWait(pSnapPoint); + + if (fOverflow) + { + // + // We cannot *EVER* touch the work stealing queue if another context has canceled and is sweeping it for cancellation. + // CAS back to INLINE. If the CAS turns up INLINE_CANCEL_IN_PROGRESS, another thread is playing with our WSQ and we must spin + // until that's done. + // + // Note that this path should be rather rare and requires the use both of direct aliasing (passing between threads) **AND** pushing + // more than the task collection cap onto a single alias (1026 tasks) before the wait operation. + // + if (InterlockedCompareExchange(&pAlias->_M_executionStatus, + TASKCOLLECTION_EXECUTION_STATUS_INLINE, + TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK) == + TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS) + { + _SpinWaitBackoffNone spinWait; + while(_M_executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS) + { + spinWait._SpinOnce(); + } + } + } + + // + // It is entirely possible that we took a snapshot and during the execution of a chore on this task collection, the task collection + // was passed to another thread that has not yet touched the task collection (be it an arbitrary one or an N-level descendent + // (N > 1). In this case, a new alias was created and we did not see it in the snapshot. We cannot know until after + // the _FullAliasWait call. If the snap point has changed, we must loop around or we will miss waiting on chores that + // were created on other threads during execution of a chore which was known about. This would be contrary to user expectation. + // + if (pSnapPoint == _M_pNextAlias) + break; + + pSnapPoint = _M_pNextAlias; + + } + } + catch (const _Interruption_exception &) + { + if (pChore != NULL && pChore != reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + { + pChore->_M_pTaskCollection = NULL; + pAlias->_NotifyCompletedChoreAndFree(pChore); + } + // + // This exception will be rethrown to a higher level if cancellation is still triggered on this context. In order to conserve + // stack space on x64 and consolidate this path with the exception path, the rethrow happens below outside this particular + // catch. + // + pAlias->_RaisedCancel(); + } + catch(...) + { + if (pChore != NULL && pChore != reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + { + pChore->_M_pTaskCollection = NULL; + pAlias->_NotifyCompletedChoreAndFree(pChore); + } + + pAlias->_RaisedException(); + } + + if (_M_pTokenState != NULL) + { + pCurrentContext->PopGoverningTokenState(_M_pTokenState); + if (pRegistration != NULL) + { + _M_pTokenState->_DeregisterCallback(pRegistration); + pRegistration->_Release(); + } + } + + pCurrentContext->SetExecutingCollection(pAlias->_M_pParent); + + if (_IsMarkedForAbnormalExit()) + { + // + // _Abort invokes _Reset, which will rethrow a user exception that was caught either in the catch blocks above and in + // _UnrealizedChore::_UnstructuredChoreWrapper for a stolen chore. _Interruption_exception is not thrown here. That exception is only + // thrown if a cancellation is visible after _Abort has returned. + // + pAlias->_Abort(); + // + // _Abort will undo the effect of cancellations at this level, therefore HasAnyCancellations() and IsCancellationVisible() from this + // refer to cancellation at a higher level. + // + if (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(pAlias, _M_pTokenState != NULL)) + { + throw _Interruption_exception(); + } + return _Canceled; + } + + pAlias->_Reset(pSnapPoint); + // + // Similar to the structured task collection, if there is a cancellation at a higher level the interruption exception should be thrown + // here since this is an interruption point. + // + if (pCurrentContext->HasAnyCancellation() && pCurrentContext->IsCancellationVisible(pAlias, _M_pTokenState != NULL)) + { + throw _Interruption_exception(); + } + + return _Completed; + } + + /// + /// Performs an abortive sweep of the WSQ for inline stack overflow. + /// + /// + /// The context to sweep + /// + void _TaskCollection::_AbortiveSweep(void *_PCtx) + { + ContextBase *pContext = reinterpret_cast(_PCtx); + + SweeperContext ctx(this); + pContext->SweepUnstructured(reinterpret_cast::SweepPredicate> (_TaskCollection::_CollectionMatchPredicate), + &ctx, + &_TaskCollection::_SweepAbortedChore); + + // + // Update the statistical information with the fact that a task has been dequeued + // + if (ctx.m_sweptChores > 0) + { + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(ctx.m_sweptChores); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(ctx.m_sweptChores); + } + } + + /// + /// A predicate function checking whether a given chore belongs to a given collection. + /// + /// + /// The chore to check + /// + /// + /// The data to check against + /// + /// + /// Whether or not the chore belongs to the collection + /// + bool _TaskCollection::_CollectionMatchPredicate(_UnrealizedChore *_PChore, void *_PData) + { + SweeperContext *pCtx = reinterpret_cast(_PData); + return (_PChore->_M_pTaskCollection == pCtx->m_pTaskCollection); + } + + /// + /// Called to sweep an aborted chore in the case of inline stack overflow. + /// + /// + /// The chore to sweep + /// + /// + /// The data which was passed into the sweeper predicate + /// + /// + /// An indication of whether the chore is now gone + /// + bool _TaskCollection::_SweepAbortedChore(_UnrealizedChore *_PChore, void *_PData) + { + SweeperContext *pCtx = reinterpret_cast(_PData); + _TaskCollection *pCollection = static_cast<_TaskCollection *>(_PChore->_M_pTaskCollection); + + // + // Aggregate the number of chores that were aborted so that the dequeued task counter + // can be updated appropriately. + // + pCtx->m_sweptChores++; + pCollection->_NotifyCompletedChoreAndFree(_PChore); + + return true; + } + + /// + /// Aborts chores related to the task collection and waits for those which cannot be forcibly aborted. + /// + /// + /// An indication as to whether or not to leave the task collection canceled after the abort. + /// + void _TaskCollection::_Abort(bool fLeaveCanceled /* = false */) + { + // + // ctor has already guaranteed context exists + // + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + TaskStack *pStack = reinterpret_cast (_M_pTaskExtension); + + _TaskCollection *pSnapPoint = _IsIndirectAlias() ? NULL : _M_pOriginalCollection->_M_pNextAlias; + + // + // If the stack hasn't overflowed, do this the "efficient way". + // + if (pStack == NULL || !pStack->Overflow()) + { + while (_M_stackPos > 0) + { + int taskCookie; + + if (_M_stackPos > SIZEOF_ARRAY(_M_taskCookies)) + { + ASSERT(!pStack->IsEmpty()); + taskCookie = pStack->Pop(); + } + else + taskCookie = _M_taskCookies[_M_stackPos - 1]; + + _M_stackPos--; + + _UnrealizedChore *pChore = static_cast<_UnrealizedChore *> (pCurrentContext->TryPopUnstructured(taskCookie)); + if (pChore == NULL) + break; + + if (pChore == reinterpret_cast<_UnrealizedChore *>(AFFINITY_EXECUTED)) + continue; + + // + // Update the statistical information with the fact that a task has been dequeued + // + if (pCurrentContext->IsExternal()) + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + else + static_cast(pCurrentContext)->IncrementDequeuedTaskCounter(); + + pChore->_M_pTaskCollection = NULL; + _NotifyCompletedChoreAndFree(pChore); + } + } + else + { + // + // Because we've overflowed the inlining stack, some chores that were pushed onto this collection are unknown. This means we can't abort by popping + // known ones and waiting for stolen ones. Stealing is not allowed until the _Reset call to avoid infighting. The unknown chores -- if still on the WSQ -- + // would deadlock a normal Abort. Instead, we sweep the ENTIRE work stealing queue looking for chores associated with this collection and remove them. + // This is very inefficient compared to the above. It does, however, only happen if you cancel a task collection onto which greater than the inline cap + // chores have been pushed. + // + _AbortiveSweep(pCurrentContext); + pStack->ResetOverflow(); + } + + // + // Only take the penalty of lock and traversal if there are stolen chores or direct aliases. This is what allows the transitive + // takedown of stolen chores as well as the takedown of aliases. + // + for(;;) + { + if (fLeaveCanceled || _M_unpoppedChores > 0 || _IsDirectAlias() || pSnapPoint != NULL) + { + _M_pOriginalCollection->_Cancel(false, pSnapPoint); + } + _FullAliasWait(pSnapPoint); + + // + // If the snap point changed, it's always possible that one of the aliases waited upon passed to a new thread. It's further possible + // that the underlying client code guarantees that the wait on the collection transitively encapsulates the scheduling of the work. + // In that case, we should probably go back and cancel much as we do for wait. + // + _TaskCollection *pNewSnapPoint = _IsIndirectAlias() ? NULL : _M_pOriginalCollection->_M_pNextAlias; + + if (pSnapPoint == pNewSnapPoint) + break; + + pSnapPoint = pNewSnapPoint; + } + + _M_stackPos = 0; + if (pStack != NULL) + pStack->Clear(); + + if (!fLeaveCanceled) + _Reset(pSnapPoint); + } + + /// + /// Cancels work on the task collection. + /// + void _TaskCollection::_Cancel() + { + _M_pOriginalCollection->_Cancel(false, _M_pNextAlias); + } + + /// + /// Performs an arbitrary thread cancellation for a single taskcollection/alias. + /// + void _TaskCollection::_CancelFromArbitraryThread(bool insideException) + { + LONG executionStatus = _M_executionStatus; + LONG xchgStatus = TASKCOLLECTION_EXECUTION_STATUS_CLEAR; + + for (;;) + { + switch (executionStatus) + { + case TASKCOLLECTION_EXECUTION_STATUS_CLEAR: + // + // If it's not inlined, we must defer cancellation of the inline context. This will be cleared eventually by a Wait(). + // + xchgStatus = TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED; + break; + case TASKCOLLECTION_EXECUTION_STATUS_INLINE: + case TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK: + // + // If it's inlined, we can cancel the underlying context (as long as it *IS* inlined). + // + xchgStatus = TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS; + break; + default: + // + // Any other state, we do not fiddle with. + // + break; + } + + if (xchgStatus == TASKCOLLECTION_EXECUTION_STATUS_CLEAR) + break; + + xchgStatus = InterlockedCompareExchange(&_M_executionStatus, xchgStatus, executionStatus); + if (xchgStatus == executionStatus) + { + bool fInlineInProgress = false; + + // + // We succeeded in marking. If it wasn't a deferral (we swapped from inline), complete the cancellation of the underlying context. + // Anything waiting on the alias will pause while we're in the middle of an in-progress cancel (which is what allows canceling the + // context to be safe). + // + if (executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE || + executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK) + { + fInlineInProgress = true; + ContextBase *pContext = reinterpret_cast (_M_pOwningContext); + pContext->CancelCollection(_M_inliningDepth); + + if (executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK) + { + // + // Because the stack overflowed and the original thread is blocking and will do nothing that will throw the exception, we must sweep + // the WSQ and get rid of any chores. This is safe for several reasons: + // + // - The initial status was INLINE_WAIT_WITH_OVERFLOW_STACK. At the point where that particular status was set, we have + // a guarantee that the context is waiting. + // + // - We successfully CAS'd that status to INLINE_CANCEL_IN_PROGRESS. This will prevent the original thread from progressing beyond + // the _FullAliasWait and doing anything with the WSQ. + // + _AbortiveSweep(pContext); + } + + } + + _CancelStolenContexts(insideException, fInlineInProgress); + + if (fInlineInProgress) + InterlockedExchange(&_M_executionStatus, TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE); + + break; + } + executionStatus = xchgStatus; + } + } + + /// + /// Goes through the direct alias list and performs a cancellation of all contexts which are running chores from any alias. + /// + void _TaskCollection::_CancelDirectAliases(bool insideException, _TaskCollection *pSnapPoint) + { + ASSERT(!_IsAlias()); + + _TaskCollection *pAlias = pSnapPoint; + while (pAlias != NULL) + { + // + // We *CANNOT* free the stale alias right now. Doing so will interfere with the lock free nature of this list and result in ABA. + // Only the task collection destructor in this area is allowed to do this. Just skip stale aliases. + // + pAlias->_CancelFromArbitraryThread(insideException); + + pAlias = pAlias->_M_pNextAlias; + } + } + + /// + /// Cancels work on the task collection. + /// + /// + /// Indicates whether the cancellation is taking place due to exception unwinding within the runtime + /// + /// + /// Identifies a snapshot within the direct alias list where the cancellation will take place. Only aliases within the snapshot are canceled. + /// + void _TaskCollection::_Cancel(bool insideException, _TaskCollection *pSnapPoint) + { + // + // There's several scenarios where we might have come into here: + // + // - On the thread that owns a task collection. + // - On a context transitively stolen from the context that owns a task collection. + // - On an arbitrary thread. + // + // Further, the thread that owns the collection might be doing: + // + // - Something related to the collection + // - Something related to a DIFFERENT collection. + // + // We cannot arbitrarily take down the owning context as we can with structured task collections. There's no guarantee + // we'd be canceling the right context. If we're within a transitive steal and the thread that owns context + // is running a Wait on the original collection, we're safe to take down the context (it'll still be within wait while + // we're in here). If however, it's not within that collection or we're on an arbitrary thread, things get a whole + // lot more interesting. + // + const _TaskCollection *pAlias = _Alias(); + ASSERT(_M_pOriginalCollection == this); + // + // Multiple stolen chores might cancel at the same time. We can only allow one person into the path + // which fires down threads so the counters get set correctly. + // + if (_SetCancelState(EXIT_STATUS_START_CANCEL)) + { + // + // We cannot touch the owning context unless we are on it or we are an indirect alias. + // + if (pAlias->_IsIndirectAlias() || pAlias == this) + { + // + // This is cancellation from a directly transitive child or on the owning thread. We do not need to play + // games with execution state -- we can simply and safely cancel. The reasoning here is that we're guaranteed + // that the inline status will *NOT* change during the call. Inlined means we're waiting on the collection and since + // we're either on the owning context or a transitive steal, the wait on the collection waits on us. Since state only + // changes after the wait, we're safe. + // + for (;;) + { + LONG executionStatus = _M_executionStatus; + if (executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE || + executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK) + { + // + // Only here are we allowed to touch the context. Now we need to determine + // which inline context needs to be aborted. + // + ContextBase *pContext = reinterpret_cast (_M_pOwningContext); + pContext->CancelCollection(_M_inliningDepth); + + if (executionStatus == TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK) + { + // + // The caller will no longer do anything with the task collection besides wait. We must sweep the WSQ (and are safe to do so because + // we are a stolen chore preventing the unblock from happening). + // + _AbortiveSweep(pContext); + } + InterlockedExchange(&_M_executionStatus, TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE); + } + else + { + // + // Note that being here doesn't mean we're not inlined. It only means we weren't inlined as far as WE COULD SEE + // a split second ago. It's entirely possible that it was inlined and has already done its check of _M_exitCode. + // In order to push all the weight to the cancellation side, there's a multi-phase approach to cancellation. + // Cancellation fences the exitCode to START_CANCEL and then checks the inlined flag. After checking, + // it fences the exit flag AGAIN to one of two states: SHOTDOWN_OWNER or DEFERRED_SHOOTDOWN_OWNER. The owning side will cancel + // and throw on any of these states; *HOWEVER* -- it will not propagate the exception until the state changes away from + // START_CANCEL and which way it changed will determine HOW it propagates the exception (how the counter manipulation needs + // to happen). + // + LONG xchgStatus = InterlockedCompareExchange(&_M_executionStatus, TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED, TASKCOLLECTION_EXECUTION_STATUS_CLEAR); + if (xchgStatus == executionStatus) + break; + + executionStatus = xchgStatus; + } + } + _CancelStolenContexts(insideException, true); + } + else + { + _CancelFromArbitraryThread(insideException); + } + _CancelDirectAliases(insideException, pSnapPoint); + } + } + + /// + /// Called when an exception is raised on a chore on an unstructured task collection, this makes a determination of what to do with the exception + /// and stores it for potential transport back to the thread performing a join on a task collection. + /// + void _TaskCollection::_RaisedException() + { + _M_pOriginalCollection->_TaskCollectionBase::_RaisedException(); + + // + // _M_exitCode may be set by more than one thread + // + InterlockedOr(&(static_cast<_TaskCollection*> (_M_pOriginalCollection)->_M_exitCode), EXIT_STATUS_FLAG_EXCEPTION_RAISED); + } + + /// + /// Called when an exception is raised on a chore on an unstructured task collection, this makes a determination of what to do with the exception + /// and stores it for potential transport back to the thread performing a join on a task collection. + /// + void _TaskCollection::_RaisedCancel() + { + _M_pOriginalCollection->_TaskCollectionBase::_RaisedCancel(); + + // + // _M_exitCode may be set by more than one thread + // + InterlockedOr(&(static_cast<_TaskCollection*> (_M_pOriginalCollection)->_M_exitCode), EXIT_STATUS_FLAG_CANCELLATION_RAISED); + } + + /// + /// Informs the caller whether or not the task collection is currently in the midst of a cancellation. Note that this + /// does not necessarily indicate that Cancel was called on the collection (although such certainly qualifies this function + /// to return true). It may be the case that the task collection is executing inline and a task collection further up in the work + /// tree was canceled. In cases such as these where we can determine ahead of time that cancellation will flow through + /// this collection, true will be returned as well. + /// + /// + /// An indication of whether the task collection is in the midst of a cancellation (or is guaranteed to be shortly). + /// + bool _TaskCollection::_IsCanceling() + { + // + // Right off the bat is the "easy" one -- if the task collection itself has been canceled we know we can answer the question immediately. + // Note that the execution status of the alias is irrelevant to this question for now _M_exitCode of the original collection propagates to execution + // status of the aliases. + // + if (_M_exitCode != 0) return true; + + // + // If our token is canceled, flag us immediately. + // + if (_CancellationTokenState::_IsValid(_M_pTokenState) && _M_pTokenState->_IsCanceled()) + { + _Cancel(); + return true; + } + + // + // It is slightly more difficult to answer the question the is someone higher than us in the work tree canceled to return a definitive answer + // here. That's because we can pass task collections between arbitrary threads and it might be inlined on an arbitrary number of threads which would need + // checked. Worse yet -- those contexts aren't guaranteed to be around unless we take locks and make validity checks. Since this is designed + // to be a mechanism which can be polled, taking an arbitrary number of locks to return a more deterministic answer isn't what we want. We will return + // an *OPTIMISTIC* answer -- one that we can answer QUICKLY. + // + _TaskCollection *pAlias = _Alias(); + + // + // We can always check the *CURRENT* thread since it's not going away while we're a frame on its stack. We can also check the original collection if we're + // an indirect alias (though not for a direct one). + // + ContextBase *pOwningContext = reinterpret_cast (pAlias->_M_pOwningContext); + if ((pAlias->_IsCurrentlyInlined() && pOwningContext->IsCanceledAtDepth(pAlias)) || + (pOwningContext->HasPendingCancellation() && pAlias->_WillInterruptForPendingCancel())) + return true; + + if (pAlias->_IsIndirectAlias()) + { + ASSERT(pAlias->_M_pOriginalCollection == this); + pOwningContext = reinterpret_cast (_M_pOwningContext); + + if ((_IsCurrentlyInlined() && pOwningContext->IsCanceledAtDepth(this)) || + (pOwningContext->HasPendingCancellation() && _WillInterruptForPendingCancel())) + return true; + } + + // + // There are additional cases where we could return true, but they are far too expensive. You could check inlining status on every thread that has ever touched + // the task collection and perform a depth comparison. Unfortunately, as mentioned, this takes a large number of locks, so we take the optimistic approach. If someone + // polls, an exception will eventually propagate there and we'll return true in one of the above cases. + // + return false; + } + + /// + /// Returns the steal tracking list. + /// + void *_TaskCollection::_GetStealTrackingList() const + { + return (void *)_M_stealTracker; + } + + /// + /// Initializes the task collection to count stolen chores. + /// + void _TaskCollection::_Initialize() + { + _M_activeStealersForCancellation = 0; + _M_exitCode = 0; + _M_chaining = 0; + static_assert(sizeof(SafeRWList) <= sizeof(_M_stealTracker), "size of _M_stealTracker too small for list entry"); + new(_M_stealTracker) SafeRWList(); + } + + /// + /// Called in order to set the cancellation status of the collection. + /// + /// + /// The cancellation status to set + /// + /// + /// An indication of whether the set succeeded. The set will fail if the task collection already has a cancellation status. + /// + bool _TaskCollection::_SetCancelState(long _Status) + { + long oldStatus = _M_exitCode; + while((oldStatus & EXIT_CANCELLATION_MASK) == 0) + { + long xchgStatus = InterlockedCompareExchange(&_M_exitCode, _Status | (oldStatus & ~EXIT_CANCELLATION_MASK), oldStatus); + if (xchgStatus == oldStatus) + { + return true; + } + oldStatus = xchgStatus; + } + return false; + } + + /// + /// Called to cancel any contexts which stole chores from the given collection. This is *PART* of a cancellation + /// scheme. The remainder must be handled by the derived class in particular. This should be called last. + /// + void _TaskCollection::_CancelStolenContexts(bool, bool fInlineGated) + { + // + // Terminate any contexts running stolen chores. + // + SafeRWList *pList = reinterpret_cast *> (_M_stealTracker); + { + SafeRWList::_Scoped_lock_read readLock(*pList); + // + // Most of the time, the task collection based list will be empty (it will only not upon detachment). We need to + // go to the context list. Allowing all the passing between threads and detachment, however, means that we cannot guarantee + // that pContext is valid to touch. We must first validate that before we walk there. Here is how we accomplish that: + // + // - First, if a chore is stolen from a work queue that's detached, it's flagged as detached and the steal chain goes onto the task collection list + // + // - Second, a chore stolen from a non-detached work queue puts a temporary reference count on the context which is removed AFTER it is added + // to the context list. The owning context cannot go away while the reference count is non-zero. + // + // - Third, under pList's write lock, the stealing context will increment _M_activeStealersForCancellation and will decrement it upon completion + // (again under the same write lock). With respect to this lock, the decrement and the removal from the CONTEXT LIST **OR** TASK LIST + // are atomic. + // + // - Fourth, when a context dies, it transfers everything from its lists to the task collection lists under BOTH its lock and pList's lock. + // + // This means that if _M_activeStealersForCancellation > 0, there is still an active stolen chore. As long as this is true and it hasn't yet + // moved to pList from the context's list, the context is guaranteed to be safe. Since everything atomically moves from the context list to + // pList under pList's write lock, we can simply check pList's count to validate the second. + // + if (fInlineGated || (_M_activeStealersForCancellation > 0 && pList->Empty())) + { + ContextBase *pContext = reinterpret_cast(_M_pOwningContext); + pContext->CancelStealers(this); + } + + ListEntry *pLE = pList->First(); + while (pLE != NULL) + { + InternalContextBase *pContext = CONTAINING_RECORD(pLE, InternalContextBase, m_stealChain); + pContext->CancelEntireContext(); + pContext->CancelStealers(NULL); + pLE = pList->Next(pLE); + } + } + } + + /// + /// Registers a notification handler for completion of chores + /// + /// + /// The callback function + /// + /// + /// The completion context for the callback function + /// + void _TaskCollection::_RegisterCompletionHandler(TaskProc _CompletionHandler, void * _PCompletionContext) + { + _M_completionHandler = _CompletionHandler; + _M_pCompletionContext = _PCompletionContext; + } + + /// + /// Constructs a new task collection whose cancellation is governed by the specified cancellation token state. + /// + /// + /// When this cancellation token is canceled, the task collection is canceled. + /// + /// + /// Pointer to a new instance of _AsyncTaskCollection. + /// + _AsyncTaskCollection * __cdecl _AsyncTaskCollection::_NewCollection(_CancellationTokenState *_PTokenState) + { + return new _AsyncTaskCollection(_PTokenState); + } + + /// + /// Constructs a new task collection whose cancellation is governed by the specified cancellation token state. + /// + /// + /// When this cancellation token is canceled, the task collection is canceled. + /// + _AsyncTaskCollection::_AsyncTaskCollection(_CancellationTokenState *_PTokenState) : + _M_taskCollection(_PTokenState) + { + _M_taskCollection._RegisterCompletionHandler(reinterpret_cast(&_AsyncTaskCollection::_CompletionHandler), this); + } + + /// + /// Delete this instance of the task collection + /// + void _AsyncTaskCollection::_Destroy() + { + delete this; + } + + /// + /// Called when a chore is completed. + /// + void _AsyncTaskCollection::_NotificationHandler() + { + _Release(); + } + + /// + /// Chore execution completion callback + /// + __declspec(noinline) + void __cdecl _AsyncTaskCollection::_CompletionHandler(void * _PCompletionContext) + { + _AsyncTaskCollection * asyncCollection = static_cast<_AsyncTaskCollection *>(_PCompletionContext); + asyncCollection->_NotificationHandler(); + } + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.h new file mode 100644 index 0000000000000000000000000000000000000000..404dd55536a48e30acab929b4e54318771a01359 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.h @@ -0,0 +1,241 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// TaskCollection.h +// +// Miscellaneous internal support structure definitions for a task collection +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +// +// The amount that we resize the task stack by per alloc. +// +#define TASK_STACK_GROWTH_SIZE 8 + +// +// The number of chores that we cap the task stack at. If after this many tasks are pushed, another is -- it cannot +// be inlined and will cause performance penalty for out-of-order WSQ utilization. +// +#define TASK_STACK_SIZE_CAP 1024 + +// ************************************************************************** +// The phases of task collection cancellation (particularly for unstructured task collections). +// ************************************************************************** + +// +// The exit status mask (indicating which portion actively indicates status) +// +#define EXIT_CANCELLATION_MASK 0x3FFFFFFF + +// +// Indicates that an exception has happened and while cancellation may proceed in due course, the end result should +// be a thrown exception. +// +#define EXIT_STATUS_FLAG_EXCEPTION_RAISED 0x80000000 + +// +// Indicates that the cancellation exception was thrown because cancellation was detected. The phases of cancellation are defined below. +// +#define EXIT_STATUS_FLAG_CANCELLATION_RAISED 0x40000000 + +// +// Indicates that cancel has started on the task collection. +// +#define EXIT_STATUS_START_CANCEL 0x00000001 + +// ************************************************************************** +// Execution status meanings: Execution status is used for cancellation of the original task collection and its direct aliases +// ************************************************************************** + +// +// The task collection is in clear state -- it's not inlined, it's not canceled, etc... +// +#define TASKCOLLECTION_EXECUTION_STATUS_CLEAR 0 + +// +// The task collection is inlined. +// +#define TASKCOLLECTION_EXECUTION_STATUS_INLINE 1 + +// +// The task collection's cancellation for this alias was deferred because it was not inline. +// +#define TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED 3 + +// +// The cancellation is complete on the arbitrary thread. +// +#define TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE 4 + +// +// The task collection is inlined and about to wait for stolen chores yet the task stack has overflowed. This requires +// extra care during cancellation. +// +#define TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK 5 // 4 | TASKCOLLECTION_EXECUTION_STATUS_INLINE + +// +// The task collection is inlined and a cancellation is in progress some arbitrary thread. +// +#define TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS 9 // 8 | TASKCOLLECTION_EXECUTION_STATUS_INLINE + +// ************************************************************************** +// Task collection flags: +// ************************************************************************** + +// +// This is an indirect alias. +// +#define TASKCOLLECTIONFLAG_ALIAS_IS_INDIRECT 1 + +// +// The entity involved in aliasing which views this flag is responsible for cleaning up the alias. +// +#define TASKCOLLECTIONFLAG_ALIAS_FREE_ON_VIEW 2 + +// ************************************************************************** +// Related flags: +// ************************************************************************** + +// +// The bit indicating that this pointer is a registration rather than a token +// +#define TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION 1 + +// ************************************************************************** +// Class definitions: +// ************************************************************************** + +namespace Concurrency +{ +namespace details +{ + /// + /// This class is an *INTERNAL* structure which will retain specific optimizations to keeping track + /// of tasks associated with an unstructured task collection. + /// + class TaskStack + { + public: + + /// + /// Constructs a new task stack + /// + TaskStack() : m_stackSize(0), m_stackPtr(0), m_pStack(NULL), m_fOverflow(false) + { + } + + /// + /// Destroys a task stack + /// + ~TaskStack(); + + /// + /// Pushes an element onto the task stack. Returns a bool as to whether this could happen or not. The only + /// possible error here is out of memory. + /// + /// + /// The task cookie to push onto the stack + /// + /// + /// An indication of whether the stack cap was reached. + /// + bool Push(int taskCookie); + + /// + /// Pops an element from the task stack. + /// + /// + /// The element + /// + int Pop(); + + /// + /// Returns an indication of whether or not the stack is empty. + /// + bool IsEmpty() const; + + /// + /// Clears out everything on the stack. Does *NOT* reset the overflow flag. + /// + void Clear(); + + /// + /// Resets the overflow flag. + /// + void ResetOverflow() + { + m_fOverflow = false; + } + + /// + /// An indication if the stack overflowed (was pushed beyond the cap). + /// + bool Overflow() const + { + return m_fOverflow; + } + + private: + + int m_stackSize; + int m_stackPtr; + int *m_pStack; + bool m_fOverflow; + }; + +#define EVENT_UNSIGNALED ((void*) 0) +#define EVENT_SIGNALED ((void*) 1) + + /// + /// A single fire (non-resettable) event supporting a single waiter. + /// + class StructuredEvent + { + + public: + + /// + /// Constructs a new structured event. + /// + StructuredEvent() + : m_ptr(EVENT_UNSIGNALED) + { + } + + /// + /// Waits until the event is signaled (via some other context calling Set()) + /// + void Wait(); + + /// + /// Set the event as signaled, and unblock any other contexts waiting on the event. + /// + void Set(); + + private: + void * volatile m_ptr; + }; + + /// + /// Context record for WSQ sweeps. + /// + struct SweeperContext + { + /// + /// Constructs a new sweeper context. + /// + SweeperContext(_TaskCollection *pTaskCollection) : + m_pTaskCollection(pTaskCollection), + m_sweptChores(0) + { + } + + _TaskCollection *m_pTaskCollection; + unsigned int m_sweptChores; + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollectionBase.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollectionBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9a9430e8422bc628274311f098dce424a8ebcce --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollectionBase.cpp @@ -0,0 +1,236 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// TaskCollectionBase.cpp +// +// General abstract collection of work counting / eventing implementation +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Called when an exception is raised on a chore on a given task collection, this makes a determination of what to do with the exception + /// and stores it for potential transport back to the thread performing a join on a task collection. + /// + void _TaskCollectionBase::_RaisedException() + { + // + // Current strategy is that the first exception in is kept and rethrown. We may update this in the future. + // + void * _OldStatus = _M_pException; + for (;;) + { + // + // We always overwrite the cancel exception being here. Everything else is "more important". + // + std::exception_ptr *_pException = (std::exception_ptr *)((size_t)_OldStatus & ~_S_cancelBitsMask); + if (_pException != NULL && (size_t)_pException != _S_cancelException) + return; + + // + // Maintain the lower bit as a cancel status flag to determine where to stop a cancellation. + // + size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask); + + void * _XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, (void *) (_S_nonNull | _cancelStatus), _OldStatus); + if (_XchgStatus == _OldStatus) + break; + + _OldStatus = _XchgStatus; + } + + // + // Note that this is safe as this will only be called on a chore executing on the collection; therefore it will not be touched by the forking + // thread until after we "_CountUp" which comes after this. + // + void *_pExc = _concrt_new std::exception_ptr(std::current_exception()); + _OldStatus = _M_pException; + for(;;) + { + size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask); + void *_pExcWC = (void *)((size_t)_pExc | _cancelStatus); + + void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, _pExcWC, _OldStatus); + if (_XchgStatus == _OldStatus) + break; + + _OldStatus = _XchgStatus; + } + } + + /// + /// Potentially rethrows the exception which was set with _RaisedException. The caller has responsibility to ensure that _RaisedException + /// was called prior to calling this and that _M_pException has progressed beyond the _S_nonNull state. + /// + void _TaskCollectionBase::_RethrowException() + { + // + // The cancellation exception is treated very specially within the runtime. Do not arbitrarily rethrow from here. + // + std::exception_ptr *_pException = _Exception(); + if (_pException != NULL && (size_t)_pException != _S_cancelException) + { + std::exception_ptr _curException = *_Exception(); + + delete _pException; + _M_pException = NULL; + + if ( !__uncaught_exception()) + std::rethrow_exception(_curException); + } + } + + /// + /// Marks the collection for cancellation and returns whether the collection was thus marked. + /// + bool _TaskCollectionBase::_MarkCancellation() + { + void *_OldStatus = _M_pException; + for(;;) + { + if ((size_t)_OldStatus & _S_cancelBitsMask) // already canceled + return false; + + void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, + (void *)((size_t)_OldStatus | _S_cancelStarted), + _OldStatus); + if (_XchgStatus == _OldStatus) + return true; + + _OldStatus = _XchgStatus; + } + } + + /// + /// Finishes the cancellation state (changing from _S_cancelStarted to one of the other states). Note that only the + /// thread which successfully marked cancellation may call this. + /// + void _TaskCollectionBase::_FinishCancelState(size_t _NewCancelState) + { + ASSERT(_CancelState() == _S_cancelStarted); + ASSERT(_NewCancelState != _S_cancelNone && _NewCancelState != _S_cancelStarted); + + void *_OldStatus = _M_pException; + for(;;) + { + void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, + (void *)(((size_t)_OldStatus & ~_S_cancelBitsMask) | _NewCancelState), + _OldStatus); + + if (_XchgStatus == _OldStatus) + break; + + _OldStatus = _XchgStatus; + } + } + + /// + /// Called when a cancellation is raised on a chore on a given task collection. This makes a determination of what to do with the exception + /// and stores it for potential transport back to the thread performing a join on a chore collection. Note that every other exception + /// has precedence over a cancellation. + /// + void _TaskCollectionBase::_RaisedCancel() + { + void *_OldStatus = _M_pException; + for (;;) + { + std::exception_ptr *_pException = (std::exception_ptr *)((size_t)_OldStatus & ~_S_cancelBitsMask); + if (_pException != NULL) + return; + + size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask); + void *pExcWC = (void *)(_S_cancelException | _cancelStatus); + + void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, pExcWC, _OldStatus); + if (_XchgStatus == _OldStatus) + break; + + _OldStatus = _XchgStatus; + } + } + + /// + /// Called in order to determine whether this task collection will interrupt for a pending cancellation at or above it. + /// + bool _TaskCollectionBase::_WillInterruptForPendingCancel() + { + // + // We can only perform the interruption point if someone in the parentage chain is actually inlined. The number of times where we get here + // without such should be minimal. + // + // Note that structured collections do not initialize _M_pParent until they are inlined. In order to avoid excess initialization in the + // structured case, we key off that to determine the validity of the field. Note that this check is perfectly okay for task collections + // as well. + // + _TaskCollectionBase *pParent = _SafeGetParent(); + _CancellationTokenState *pTokenState = _GetTokenState(); + + while (pParent != NULL) + { + // + // If this token is non null- it could hide cancellation from a parent task collection. + // + if (pTokenState == NULL) + { + if ((pParent->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pParent))->_IsMarkedForCancellation()) || + (!pParent->_IsStructured() && (static_cast<_TaskCollection *>(pParent))->_IsMarkedForAbnormalExit())) + return true; + } + else + { + if (pTokenState == _CancellationTokenState::_None()) + return false; + else + return pTokenState->_IsCanceled(); + } + // + // Grab the parent token before switching to its parent. + // + pTokenState = pParent->_GetTokenState(); + pParent = pParent->_SafeGetParent(); + } + + return false; + } + + /// + /// Returns the cancellation token state associated with this task collection. + /// + _CancellationTokenState *_TaskCollectionBase::_GetTokenState(_CancellationTokenRegistration **_PRegistration) + { + _CancellationTokenState *pTokenState = _M_pTokenState; + _CancellationTokenRegistration *pRegistration = NULL; + + if (reinterpret_cast(pTokenState) & TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION) + { + pRegistration = reinterpret_cast<_CancellationTokenRegistration *>( + reinterpret_cast(pTokenState) & ~TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION + ); + + if (pRegistration != NULL) + { + pTokenState = pRegistration->_GetToken(); + } + else + { + pTokenState = _CancellationTokenState::_None(); + } + } + if (_PRegistration != NULL) + { + *_PRegistration = pRegistration; + } + return pTokenState; + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d3e3b0c6385f99b6f20c81d387ab8e9c52b966c --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.cpp @@ -0,0 +1,23 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadInternalContext.cpp +// +// Source file containing that implementation for a thread based internal execution context/stack. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.h new file mode 100644 index 0000000000000000000000000000000000000000..c48f9a4d9d69ff4b9a7ecdb2c53fd699af8ac857 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.h @@ -0,0 +1,51 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadInternalContext.h +// +// Header file containing the metaphor for an thread based internal execution context/stack. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + + class ThreadInternalContext : public InternalContextBase + { + public: + // + // Public Methods + // + + /// + /// Construct an internal thread based context. + /// + ThreadInternalContext(SchedulerBase *pScheduler) : + InternalContextBase(pScheduler) + { + } + + /// + /// Destroys an internal thread based context. + /// + virtual ~ThreadInternalContext() + { + } + + /// + /// Returns the type of context + /// + virtual ContextKind GetContextKind() const { return ThreadContext; } + + private: + friend class ThreadScheduler; + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..997fd2a2c2cb6f7f2459033705048d93967fc5c6 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.cpp @@ -0,0 +1,180 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadProxy.cpp +// +// Proxy for an OS context. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs a thread proxy. + /// + ThreadProxy::ThreadProxy(IThreadProxyFactory * pFactory, unsigned int stackSize) + : m_pFactory(pFactory) + , m_stackSize(stackSize) + , m_threadPriority(THREAD_PRIORITY_NORMAL) + , m_fSuspended(false) + , m_fBlocked(TRUE) + , m_fCanceled(FALSE) + { + // Thread proxy factories for Win32 threads need to be reference counted by the individual thread proxies, unlike + // UMS based thread proxy factories. This is because thread proxies that were loaned out to threads based schedulers + // could still be executing their dispatch loop and about to put themselves onto the idle pool on the factory at + // the time that the schedulers and corresponding scheduler proxies are actually destroyed (and have removed their + // references on the RM). If no references exist on the RM, the RM goes aheads and destroys the factories. However, + // it is dangerous to do this while thread proxies are possibly in the process of returning to the factory. Therefore, + // the outstanding thread proxies (alive but not in the idle pool), need to keep the factory alive until they have all + // returned. + // + // UMS thread proxies on the other hand, need the existence of a UMS virtual processor root in order to execute, and the + // UMS virtual processor roots are responsible for adding them to the idle pool. It is safe to say that all UMS thread + // proxies loaned out to a UMS scheduler are back in the idle pool of the factory at the time the UMS scheduler/scheduler + // proxy (virtual processors roots and all) are destroyed, and the factory can safely be shutdown without worrying about + // stragglers. + m_pFactory->Reference(); + + m_id = ResourceManager::GetThreadProxyId(); + + // Auto-reset event that is not signalled initially + m_hBlock = platform::__CreateAutoResetEvent(); // VSO#459907 + + m_hPhysicalContext = LoadLibraryAndCreateThread(NULL, + m_stackSize*KB, + ThreadProxyMain, + this, + STACK_SIZE_PARAM_IS_A_RESERVATION, + &m_threadId); + + if (m_hPhysicalContext == NULL) + { + // Cleanup everything we've allocated because this exception may be caught by a higher + // layer to provide resiliency against thread creation failures during thread proxy construction. + CloseHandle(m_hBlock); + m_pFactory->Release(); + throw scheduler_worker_creation_error(HRESULT_FROM_WIN32(GetLastError())); + } + } + + /// + /// Destroys a thread proxy. + /// + ThreadProxy::~ThreadProxy() + { + CloseHandle(m_hBlock); + platform::__CloseThreadHandle(m_hPhysicalContext); + m_pFactory->Release(); + } + + /// + /// Returns a process unique identifier for the thread proxy. + /// + unsigned int ThreadProxy::GetId() const + { + return m_id; + } + +#pragma warning (push) +#pragma warning (disable : 4702) // unreachable code + /// + /// Sets the priority of the underlying thread. + /// + /// + /// The new priority value for the thread. + /// + void ThreadProxy::SetPriority(int priority) + { + m_threadPriority = priority; + + platform::__SetThreadPriority(m_hPhysicalContext, m_threadPriority); + } +#pragma warning (pop) + + /// + /// Blocks the thread proxy until is is resumed via ResumeExecution or a different thread proxy switching to it. + /// + void ThreadProxy::SuspendExecution() + { + ASSERT(m_fBlocked == FALSE); + InterlockedExchange(&m_fBlocked, TRUE); + + WaitForSingleObjectEx(m_hBlock, INFINITE, FALSE); + + ASSERT(m_fBlocked == TRUE); + InterlockedExchange(&m_fBlocked, FALSE); + } + + /// + /// Resumes execution of a thread proxy. + /// + void ThreadProxy::ResumeExecution() + { + SetEvent(m_hBlock); + } + + /// + /// Cancels the thread proxy causing the underlying thread to exit. + /// + void ThreadProxy::Cancel() + { + ASSERT(m_fCanceled == false); + m_fCanceled = true; + ResumeExecution(); + } + + /// + /// Spins until the 'this' thread proxy is in a firmly blocked state. + /// + /// + /// This implements a sort of barrier. At certain points during execution, it is essential to wait until a thread proxy + /// has set the flag indicating it is blocked, in order to preserve correct behavior. One example is if there is a race + /// between block and unblock for the same proxy, i.e. if a thread proxy is trying to block at the same time a different + /// context is trying to unblock it. + /// + void ThreadProxy::SpinUntilBlocked() + { + if (m_fBlocked == FALSE) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + + } while (m_fBlocked == FALSE); + } + ASSERT(m_fBlocked == TRUE); + } + + /// + /// Thread start routine for proxies. + /// + DWORD CALLBACK ThreadProxy::ThreadProxyMain(LPVOID lpParameter) + { + ThreadProxy* pThreadProxy = reinterpret_cast (lpParameter); + + // To start the dispatch loop cleanly, the context must block until it is switched to, or resumed.. + WaitForSingleObjectEx(pThreadProxy->m_hBlock, INFINITE, FALSE); + InterlockedExchange(&pThreadProxy->m_fBlocked, FALSE); + + pThreadProxy->Dispatch(); + + ASSERT(pThreadProxy->m_fCanceled); + // Thread proxy needs to be deleted after it is canceled and it returns from the dispatch loop. + delete pThreadProxy; + FreeLibraryAndDestroyThread(0); + return 0; + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.h new file mode 100644 index 0000000000000000000000000000000000000000..f5d4dbfac893cf9a766d6358fc614ae2ee09f2fc --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxy.h @@ -0,0 +1,144 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadProxy.h +// +// Proxy for an OS context. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + class ThreadProxy : public ::Concurrency::IThreadProxy + { + public: + /// + /// Constructs a thread proxy. + /// + ThreadProxy(IThreadProxyFactory * pFactory, unsigned int stackSize); + + /// + /// Destroys a thread proxy. + /// + virtual ~ThreadProxy(); + + /// + /// Retrieves a process unique id for the thread proxy. + /// + unsigned int GetId() const; + + /// + /// Blocks the thread proxy until is is resumed via ResumeExecution or a different thread proxy switching to it. + /// + void SuspendExecution(); + + /// + /// Resumes execution of a thread proxy. + /// + void ResumeExecution(); + + /// + /// Spins until the 'this' thread proxy is in a firmly blocked state. + /// + /// + /// This implements a sort of barrier. At certain points during execution, it is essential to wait until a thread proxy + /// has set the flag indicating it is blocked, in order to preserve correct behavior. One example is if there is a race + /// between block and unblock for the same proxy, i.e. if a thread proxy is trying to block at the same time a different + /// context is trying to unblock it. + /// + void SpinUntilBlocked(); + + /// + /// Gets the priority of the thread proxy. + /// + int GetPriority() { return m_threadPriority; } + + /// + /// Sets the priority of the underlying thread. + /// + /// + /// The new priority value for the thread. + /// + void SetPriority(int priority); + + /// + /// Gets the stack size of the thread proxy. Multiply by 1 KB to get actual stack size in bytes. + /// + unsigned int GetStackSize() { return m_stackSize; } + + /// + /// Cancels the thread proxy causing the underlying thread to exit. + /// + void Cancel(); + + /// + /// Returns the virtual processor root the thread proxy is running on. + /// + VirtualProcessorRoot * GetVirtualProcessorRoot() { return m_pRoot; } + + /// + /// Sets the virtual processor root - used during affinitization. + /// + void SetVirtualProcessorRoot(VirtualProcessorRoot * pRoot) { m_pRoot = pRoot; } + + /// + /// Returns a Win32 handle to the thread that is backing this proxy. + /// + HANDLE GetThreadHandle() { return m_hPhysicalContext; } + +#if _DEBUG + // _DEBUG helper + DWORD GetThreadId() const { return m_threadId; } +#endif + + protected: + + // The thread proxy factory that created this thread proxy, and maintains the idle pool of thread proxies. + IThreadProxyFactory * m_pFactory; + + // The OS handle for the underlying UT. + HANDLE m_hPhysicalContext; + + // The blocking handle. + HANDLE m_hBlock; + + // The virtual processor root on which this thread proxy is executing. + VirtualProcessorRoot *m_pRoot{}; + + // Stores the stack size of the thread proxy. Multiply by 1 KB to get actual stack size in bytes. + unsigned int m_stackSize; + + // Stores the last priority value that was set on the thread. Initial value is normal priority. + int m_threadPriority; + + bool m_fSuspended; + volatile LONG m_fBlocked; + volatile LONG m_fCanceled; + + private: + + // Process wide unique identifier. + unsigned int m_id; + + // Thread id. + DWORD m_threadId{}; + + /// + /// Dispatch routine for thread proxies. + /// + virtual void Dispatch() = 0; + + /// + /// Thread start routine for proxies. + /// + static DWORD CALLBACK ThreadProxyMain(LPVOID lpParameter); + }; + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactory.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..c06111286c614d676690a35678b548244b2cc2b9 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactory.h @@ -0,0 +1,409 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadProxyFactory.h +// +// Factory for creating thread proxies. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + struct IThreadProxyFactory + { + virtual ::Concurrency::IThreadProxy* RequestProxy(unsigned int stackSize, int contextPriority) =0; + virtual void ReclaimProxy(::Concurrency::IThreadProxy* pThreadProxy) =0; + virtual LONG Reference() =0; + virtual LONG Release() =0; + virtual DWORD GetExecutionResourceTls() =0; + virtual ~IThreadProxyFactory() {} + }; + + class ThreadProxyFactoryManager; + +#pragma warning (push) +#pragma warning (disable : 4702) // unreachable code + template + class ThreadProxyFactory : public IThreadProxyFactory + { + public: + /// + /// Returns a thread proxy from a pool of proxies, creating a new one, if needed. + /// + /// + /// The required minimum stack size for the thread proxy. + /// + /// + /// The required thread priority for the thread proxy. + /// + virtual ::Concurrency::IThreadProxy* RequestProxy(unsigned int stackSize, int contextPriority) + { + // Based on the requested stack size of the proxy, find the index into the pool array. + threadProxy * pProxy = NULL; + + for (int i = 0; i < s_numBuckets; ++i) + { + if (stackSize <= s_proxyStackSize[i]) + { + pProxy = m_proxyPool[i].Pop(); + if (pProxy != NULL) + break; + } + } + + if (pProxy == NULL) + { + // Either we couldn't find a proxy in one of the pools, or we received a stack size + // larger than the largest size we pool. + pProxy = Create(stackSize); + } + + if (pProxy != NULL) + { + Prepare(pProxy, contextPriority); + } + + return pProxy; + } + + /// + /// Returns a proxy back to the idle pool for reuse. + /// + /// + /// The thread proxy being returned. + /// + virtual void ReclaimProxy(::Concurrency::IThreadProxy* pThreadProxy) + { + threadProxy * pProxy = static_cast(pThreadProxy); + for (int i = 0; i < s_numBuckets; ++i) + { + if (pProxy->GetStackSize() == s_proxyStackSize[i]) + { + // If the pool is close to full, cancel the proxy and allow the thread to exit. + if (m_proxyPool[i].Count() < s_bucketSize) + { + m_proxyPool[i].Push(pProxy); + pProxy = NULL; + } + break; + } + } + + if (pProxy != NULL) + { + Retire(pProxy); + } + } + + /// + /// Destroys a thread proxy factory. + /// + virtual ~ThreadProxyFactory() + { + } + + /// + /// Retires the proxies that are present in the free pools of a thread proxy factory, causing them to run to + /// completion, and exit. + /// + void RetireThreadProxies() + { + for (int i = 0; i < s_numBuckets; ++i) + { + threadProxy *pProxy = m_proxyPool[i].Flush(); + while (pProxy != NULL) + { + threadProxy *pNextProxy = LockFreeStack::Next(pProxy); + + // Retiring the proxy will cause it to perform any necessary cleanup, and exit its dispatch loop. + Retire(pProxy); + pProxy = pNextProxy; + } + } + } + + /// + /// Initiates shutdown of the factory, and deletes it if shutdown can be completed inline. + /// + virtual void ShutdownFactory() =0; + + /// + /// Returns a TLS index used by thread proxies and subscribed threads to store per-thread data. + /// + virtual DWORD GetExecutionResourceTls() + { + return m_executionResourceTlsIndex; + } + + protected: + + /// + /// Protected constructor. All construction must go through the CreateFactory API. + /// + ThreadProxyFactory(ThreadProxyFactoryManager * pManager); + + /// + /// Initialize static data + /// + static void StaticInitialize() + { + if (s_bucketSize == 0) + { + s_bucketSize = 4*::Concurrency::GetProcessorCount(); + } + ASSERT(s_bucketSize >= 4); + } + + protected: + + /// + /// Creates a new thread proxy. + /// + /// + /// The stack size for the thread proxy. + /// + virtual threadProxy* Create(unsigned int stackSize) =0; + + /// + /// Retires a thread proxy. + /// + virtual void Retire(threadProxy *pProxy) =0; + + /// + /// Prepares a thread proxy for use. + /// + /// + /// The proxy to prepare. + /// + /// + /// The required thread priority for the thread proxy. + /// + virtual void Prepare(threadProxy *pProxy, int contextPriority) + { + // + // Adjust the thread priority if necessary. + // + if (pProxy->GetPriority() != contextPriority) + { + pProxy->SetPriority(contextPriority); + } + } + + // Each factory supports a small number of pools of specific stack sizes. + // Currently supported stack sizes are the default process stack size, 64KB, 256KB and 1024KB (1MB) + static const int s_numBuckets = 4; + static int s_bucketSize; + static const unsigned int s_proxyStackSize[s_numBuckets]; + + // Cached copy of the execution resource TLS index that was created by the factory manager. + DWORD m_executionResourceTlsIndex; + + // A list that will hold thread proxies. + LockFreeStack m_proxyPool[s_numBuckets]; + }; +#pragma warning (pop) + + template int ThreadProxyFactory::s_bucketSize = 0; + template const unsigned int ThreadProxyFactory::s_proxyStackSize[s_numBuckets] = { 0, 64, 256, 1024 }; + + /// + /// A factory that creates thread proxies for thread schedulers. + /// +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class FreeThreadProxyFactory : public ThreadProxyFactory + { + public: + + /// + /// Creates a singleton thread proxy factory. + /// + static FreeThreadProxyFactory * CreateFactory(ThreadProxyFactoryManager * pManager) + { + StaticInitialize(); + return _concrt_new FreeThreadProxyFactory(pManager); + } + + /// + /// Destroys a free thread proxy factory. + /// + virtual ~FreeThreadProxyFactory() + { + } + + /// + /// Adds a reference to the thread proxy factory. + /// + LONG Reference() + { + return InterlockedIncrement(&m_referenceCount); + } + + /// + /// Releases a reference on the thread proxy factory. + /// + LONG Release() + { + LONG refCount = InterlockedDecrement(&m_referenceCount); + if (refCount == 0) + delete this; + return refCount; + } + + /// + /// Returns a proxy back to the idle pool, for reuse. + /// + /// + /// The thread proxy being returned. + /// + virtual void ReclaimProxy(::Concurrency::IThreadProxy* pThreadProxy) + { + FreeThreadProxy * pProxy = static_cast(pThreadProxy); + + // If the factory has been shut down, we should retire the proxy right away. + if (!m_fShutdown) + { + for (int i = 0; i < s_numBuckets; ++i) + { + if (pProxy->GetStackSize() == s_proxyStackSize[i]) + { + // If the pool is close to full, cancel the proxy and allow the thread to exit. + if (m_proxyPool[i].Count() < s_bucketSize) + { + m_proxyPool[i].Push(pProxy); + + // After adding the thread proxy to the pool, check if the factory has been shut down. + // At shutdown, the flag is set to true before the shutdown routine goes through + // and retires all the thread proxies. However, if we've added this proxy after + // that point, there is a good chance that the shutdown routine missed us. We + // need to make sure the bucket is empty and all proxies are retired, in this case. + if (m_fShutdown) + { + pProxy = m_proxyPool[i].Flush(); + while (pProxy != NULL) + { + FreeThreadProxy *pNextProxy = LockFreeStack::Next(pProxy); + // Retiring the proxy will cause it to perform any necessary cleanup, and exit its dispatch loop. + Retire(pProxy); + pProxy = pNextProxy; + } + } + + pProxy = NULL; + } + break; + } + } + } + + if (pProxy != NULL) + { + Retire(pProxy); + } + } + + /// + /// Initiates shutdown of the factory, and deletes it if shutdown can be completed inline. + /// + virtual void ShutdownFactory() + { + m_fShutdown = true; + RetireThreadProxies(); + Release(); + } + + protected: + + /// + /// Creates a new Win32 free thread proxy factory. + /// Protected constructor. All construction must go through the CreateFactory API. + /// + FreeThreadProxyFactory(ThreadProxyFactoryManager * pManager) : + ThreadProxyFactory(pManager), + m_referenceCount(1), + m_fShutdown(false) + { + } + + + private: + + /// + /// Creates a new thread proxy. + /// + virtual FreeThreadProxy* Create(unsigned int stackSize) + { + return _concrt_new FreeThreadProxy(this, stackSize); + } + + /// + /// Retires a thread proxy. + /// + virtual void Retire(FreeThreadProxy *pProxy) + { + // Canceling the proxy will cause it to perform any necessary cleanup, and exit its dispatch loop. + pProxy->Cancel(); + } + + // Reference count for the thread proxy factory. For details, see comments in the constructor of ThreadProxy. + volatile LONG m_referenceCount; + + // Flag that is set to true if shutdown has been initiated on the thread proxy factory. + volatile bool m_fShutdown; + }; +#pragma warning(pop) + + // + // A class that holds a collection of thread proxy factories, one for each type of thread proxy. + // + class ThreadProxyFactoryManager + { + public: + + /// + /// Creates a thread proxy factory manager. + /// + ThreadProxyFactoryManager(); + + /// + /// Destroys a thread proxy factory manager. + /// + ~ThreadProxyFactoryManager(); + + /// + /// Returns a Win32 thread proxy factory. + /// + FreeThreadProxyFactory * GetFreeThreadProxyFactory(); + + /// + /// Returns the TLS index used to store execution resource information by subscribed threads and thread proxies. + /// + DWORD GetExecutionResourceTls() const + { + return m_dwExecutionResourceTlsIndex; + } + + private: + // A thread proxy factory for Win32 thread proxies. + FreeThreadProxyFactory * m_pFreeThreadProxyFactory; + + // An index to a TLS slot where execution resource pointers are stored. + DWORD m_dwExecutionResourceTlsIndex; + + // A lock that guards creation of the thread proxy factories. + _NonReentrantBlockingLock m_proxyFactoryCreationLock; + }; + +template +ThreadProxyFactory::ThreadProxyFactory(ThreadProxyFactoryManager * pManager) : + m_executionResourceTlsIndex(pManager->GetExecutionResourceTls()) +{ } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactoryManager.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactoryManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d711001a822bf2bcbbda867f00f2c4bcea75e120 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadProxyFactoryManager.cpp @@ -0,0 +1,59 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadProxyFactoryManager.cpp +// +// Manager for thread proxy factories. The RM relies on a factory manager to pool thread proxies of different types. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Creates a thread proxy factory manager. + /// + ThreadProxyFactoryManager::ThreadProxyFactoryManager() : + m_pFreeThreadProxyFactory(NULL) + { + // Allocate a TLS slot to track execution resources in the RM. + m_dwExecutionResourceTlsIndex = platform::__TlsAlloc(); + } + + /// + /// Destroys a thread proxy factory manager. + /// + ThreadProxyFactoryManager::~ThreadProxyFactoryManager() + { + if (m_pFreeThreadProxyFactory != NULL) + { + m_pFreeThreadProxyFactory->ShutdownFactory(); + } + + platform::__TlsFree(m_dwExecutionResourceTlsIndex); + } + + /// + /// Returns a Win32 thread proxy factory. + /// + FreeThreadProxyFactory * ThreadProxyFactoryManager::GetFreeThreadProxyFactory() + { + if (m_pFreeThreadProxyFactory == NULL) + { + _NonReentrantBlockingLock::_Scoped_lock lock(m_proxyFactoryCreationLock); + if (m_pFreeThreadProxyFactory == NULL) + { + m_pFreeThreadProxyFactory = FreeThreadProxyFactory::CreateFactory(this); + } + } + return m_pFreeThreadProxyFactory; + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c43aa47b80f91ad7dbfc5eb67b0f4f6ab9b74414 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.cpp @@ -0,0 +1,61 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadScheduler.cpp +// +// Source file containing the implementation for a thread based concrt scheduler +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Creates a thread based scheduler + /// + ThreadScheduler::ThreadScheduler(_In_ const ::Concurrency::SchedulerPolicy& policy) : + SchedulerBase(policy) + { + } + + /// + /// Creates a thread based scheduler + /// + ThreadScheduler* ThreadScheduler::Create(_In_ const ::Concurrency::SchedulerPolicy& policy) + { + return _concrt_new ThreadScheduler(policy); + } + + /// + /// Creates a thread based virtual processor. + /// + VirtualProcessor* ThreadScheduler::CreateVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot* pOwningRoot) + { + return _concrt_new ThreadVirtualProcessor(pOwningNode, pOwningRoot); + } + + /// + /// Returns a newly created thread internal context to the base scheduler. + /// + InternalContextBase *ThreadScheduler::CreateInternalContext() + { + return _concrt_new ThreadInternalContext(this); + } + + /// + /// Destroys a thread based scheduler + /// + ThreadScheduler::~ThreadScheduler() + { + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..59d25cd2a84fbfa57ff17e0673655eef5e5b8dbc --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadScheduler.h @@ -0,0 +1,172 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// threadscheduler.h +// +// Header file containing the metaphor for a thread based concrt scheduler +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +#pragma warning (push) +#pragma warning (disable: 4100) // unreferenced formal parameter, for comments + +namespace Concurrency +{ +namespace details +{ + class ThreadScheduler : public IScheduler, public SchedulerBase + { + public: + + /// + /// Creates a thread based scheduler + /// + ThreadScheduler(_In_ const ::Concurrency::SchedulerPolicy& pPolicy); + + /// + /// Creates a thread based scheduler + /// + static ThreadScheduler* Create(_In_ const ::Concurrency::SchedulerPolicy& pPolicy); + + /// + /// Create the correct flavor of virtual processor + /// + virtual VirtualProcessor *CreateVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot); + + /// + /// Destroys a thread based scheduler + /// + virtual ~ThreadScheduler(); + + /// + /// Returns a scheduler unique identifier for the context. + /// + /// + /// The Id for the IScheduler. + /// + virtual unsigned int GetId() const { return Id(); } + + /// + /// Get the scheduler policy. + /// + /// + /// The policy of the scheduler. + /// + virtual SchedulerPolicy GetPolicy() const + { + return SchedulerBase::GetPolicy(); + } + + /// + /// Called by the resource manager in order to gather statistics for a given scheduler. The statistics gathered here + /// will be used to drive dynamic feedback with the scheduler to determine when it is appropriate to assign more resources + /// or take resources away. Note that these counts can be optimistic and do not necessarily have to reflect the current + /// count with 100% synchronized accuracy. + /// + /// + /// The number of tasks which have been completed by the scheduler since the last call to the Statistics method. + /// + /// + /// The number of tasks that have arrived in the scheduler since the last call to the Statistics method. + /// + /// + /// The total number of tasks in all scheduler queues. + /// + virtual void Statistics(unsigned int *pTaskCompletionRate, unsigned int *pTaskArrivalRate, unsigned int *pNumberOfTasksEnqueued) + { + SchedulerBase::Statistics(pTaskCompletionRate, pTaskArrivalRate, pNumberOfTasksEnqueued); + } + + /// + /// Called when the resource manager is giving virtual processors to a particular scheduler. The virtual processors are + /// identified by an array of IVirtualProcessorRoot interfaces. This call is made to grant virtual processor roots + /// at initial allocation during the course of ISchedulerProxy::RequestInitialVirtualProcessors, and during dynamic + /// core migration. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors being added to the scheduler. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + virtual void AddVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count) + { + SchedulerBase::AddVirtualProcessors(ppVirtualProcessorRoots, count); + } + + /// + /// Called when the resource manager is taking away virtual processors from a particular scheduler. The scheduler should + /// mark the supplied virtual processors such that they are removed asynchronously and return immediately. Note that + /// the scheduler should make every attempt to remove the virtual processors as quickly as possible as the resource manager + /// will reaffinitize threads executing upon them to other resources. Delaying stopping the virtual processors may result + /// in unintentional oversubscription within the scheduler. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors which are to be removed. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + virtual void RemoveVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count) + { + SchedulerBase::RemoveVirtualProcessors(ppVirtualProcessorRoots, count); + } + + /// + /// Called when the resource manager is made aware that the hardware threads underneath the virtual processors assigned to + /// this particular scheduler are 'externally idle' once again i.e. any other schedulers that may have been using them have + /// stopped using them. This API is called only when a scheduler proxy was created with MinConcurrency = MaxConcurrency. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors on which other schedulers have become idle. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + virtual void NotifyResourcesExternallyIdle(IVirtualProcessorRoot ** ppVirtualProcessorRoots, unsigned int count) {} + + /// + /// Called when the resource manager is made aware that the execution resources underneath the virtual processors assigned to + /// this particular scheduler are busy (active) on other schedulers. The reason these execution resources were lent to + /// other schedulers is usually a lack of activation on the part of this scheduler, or a system-wide oversubscription. + /// This API is called only when a scheduler proxy was created with MinConcurrency = MaxConcurrency. + /// + /// + /// An array of IVirtualProcessorRoot interfaces representing the virtual processors on which other schedulers have become busy. + /// + /// + /// Number of IVirtualProcessorRoot interfaces in the array. + /// + virtual void NotifyResourcesExternallyBusy(IVirtualProcessorRoot ** ppVirtualProcessorRoots, unsigned int count) {} + + /// + /// Returns an IScheduler interface. + /// + /// + /// An IScheduler interface. + /// + virtual IScheduler * GetIScheduler() { return this; } + + protected: + + /// + /// Creates a new thread internal context and returns it to the base scheduler. + /// + virtual InternalContextBase *CreateInternalContext(); + + private: + + // Hide the assignment operator and copy constructor. + ThreadScheduler const &operator =(ThreadScheduler const &); // no assign op + ThreadScheduler(ThreadScheduler const &); // no copy ctor + + }; +} // namespace details +} // namespace Concurrency + +#pragma warning (pop) diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a33a8329204133f2a829f5a0238d0aac2a19f72 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.cpp @@ -0,0 +1,34 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadVirtualProcessor.cpp +// +// Source file containing the ThreadVirtualProcessor implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructor + /// + ThreadVirtualProcessor::ThreadVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot) + { + VirtualProcessor::Initialize(pOwningNode, pOwningRoot); + } + + /// + /// Destructor + /// + ThreadVirtualProcessor::~ThreadVirtualProcessor() + { + } +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.h new file mode 100644 index 0000000000000000000000000000000000000000..f7e82a26f6cceece89db397f8bb77835783b420d --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadVirtualProcessor.h @@ -0,0 +1,34 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ThreadVirtualProcessor.h +// +// Header file containing the metaphor for a thread based virtual processor +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + class ThreadVirtualProcessor : public VirtualProcessor + { + public: + + /// + /// Constructor + /// + ThreadVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot); + + /// + /// Destructor + /// + virtual ~ThreadVirtualProcessor(); + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c72dd98993f0e216f12e25e1dde5cfe691b2b8d --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.cpp @@ -0,0 +1,131 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Timer.cpp +// +// Shared timer implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +#pragma warning (disable : 4702) + +namespace Concurrency +{ +namespace details +{ + /// + /// A stub class that is friends with _Timer in order to avoid pulling in too many windows.h definitions into agents.h. + /// + class _TimerStub + { + public: + + /// + /// Timer callback for Vista and above (except MSDK) + /// + static void CALLBACK FireTimer(PTP_CALLBACK_INSTANCE, void* context, PTP_TIMER) + { + FireTimerXP(context, true); + } + + /// + /// Timer callback for XP and MSDK + /// + static void CALLBACK FireTimerXP(PVOID pContext, BOOLEAN) + { + _Timer* pTimer = reinterpret_cast<_Timer *>(pContext); + pTimer->_Fire(); + // Do not delete the timer - it will be deleted in the destructor + } + }; + + /// + /// Constructs a new timer. + /// + /// + /// The duration and period of the timer in milliseconds. + /// + /// + /// An indication of whether the timer is repeating (periodic) or not. + /// + _Timer::_Timer(unsigned int _Ms, bool _FRepeating) + : _M_hTimer(NULL) + , _M_ms(_Ms) + , _M_fRepeating(_FRepeating) + { + } + + /// + /// Starts the timer. + /// + void _Timer::_Start() + { + if (_M_hTimer == NULL) + { + if ((_M_hTimer = RegisterAsyncTimerAndLoadLibrary(_M_ms, &_TimerStub::FireTimer, this, _M_fRepeating)) == nullptr) + { + throw std::bad_alloc(); + } + } + } + + /// + /// Destroys the timer. + /// + _Timer::~_Timer() + { + if (_M_hTimer != NULL) + _Stop(); + } + + /// + /// Stops the timer. + /// + void _Timer::_Stop() + { + DeleteAsyncTimerAndUnloadLibrary(static_cast(_M_hTimer)); + _M_hTimer = NULL; + } +} // namespace details + +/// +/// Wait for a specified number of milliseconds +/// +_CONCRTIMP void __cdecl wait(unsigned int milliseconds) +{ + if (milliseconds < 1) + { + Context::Yield(); + } + else + { + class TimerObj : public _Timer + { + public: + + TimerObj(unsigned int mS) : _Timer(mS, false) + { + m_pContext = Context::CurrentContext(); + _Start(); + Context::Block(); + } + + private: + + virtual void _Fire() + { + m_pContext->Unblock(); + } + + Context *m_pContext; + + } _t(milliseconds); + } +} +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.h new file mode 100644 index 0000000000000000000000000000000000000000..d195cbb94e9aec600328f2b305c5a600e9d9d5ab --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Timer.h @@ -0,0 +1,25 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Timer.h +// +// Shared timers. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Returns the demand initialized single timer queue used for event timeouts, timer agents, etc... + /// + _CONCRTIMP HANDLE GetSharedTimerQueue(); +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..177e1a1effa93ae1d0fe7aa80e3f246d6dde536e --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.cpp @@ -0,0 +1,488 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Trace.cpp +// +// Implementation of ConcRT tracing API. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +#pragma warning (push) +#pragma warning (disable : 4702) // unreachable code + +namespace Concurrency +{ + +/// +/// The ETW provider GUID for the Concurrency Runtime. +/// +/**/ +_CONCRTIMP const GUID ConcRT_ProviderGuid = { 0xF7B697A3, 0x4DB5, 0x4d3b, { 0xBE, 0x71, 0xC4, 0xD2, 0x84, 0xE6, 0x59, 0x2F } }; + +// +// GUIDS for events +// + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are not more specifically described by another category. +/// +/// +/// This category of events is not currently fired by the Concurrency Runtime. +/// +/**/ +_CONCRTIMP const GUID ConcRTEventGuid = { 0x72B14A7D, 0x704C, 0x423e, { 0x92, 0xF8, 0x7E, 0x6D, 0x64, 0xBC, 0xB9, 0x2A } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to scheduler activity. +/// +/// +/// +/**/ +_CONCRTIMP const GUID SchedulerEventGuid = { 0xE2091F8A, 0x1E0A, 0x4731, { 0x84, 0xA2, 0x0D, 0xD5, 0x7C, 0x8A, 0x52, 0x61 } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to schedule groups. +/// +/// +/// This category of events is not currently fired by the Concurrency Runtime. +/// +/// +/**/ +_CONCRTIMP const GUID ScheduleGroupEventGuid = { 0xE8A3BF1F, 0xA86B, 0x4390, { 0x9C, 0x60, 0x53, 0x90, 0xB9, 0x69, 0xD2, 0x2C } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to contexts. +/// +/// +/**/ +_CONCRTIMP const GUID ContextEventGuid = { 0x5727A00F, 0x50BE, 0x4519, { 0x82, 0x56, 0xF7, 0x69, 0x98, 0x71, 0xFE, 0xCB } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to chores or tasks. +/// +/// +/// This category of events is not currently fired by the Concurrency Runtime. +/// +/// +/// +/**/ +_CONCRTIMP const GUID ChoreEventGuid = { 0x7E854EC7, 0xCDC4, 0x405a, { 0xB5, 0xB2, 0xAA, 0xF7, 0xC9, 0xE7, 0xD4, 0x0C } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to virtual processors. +/// +/**/ +_CONCRTIMP const GUID VirtualProcessorEventGuid = { 0x2f27805f, 0x1676, 0x4ecc, { 0x96, 0xfa, 0x7e, 0xb0, 0x9d, 0x44, 0x30, 0x2f } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to locks. +/// +/// +/// This category of events is not currently fired by the Concurrency Runtime. +/// +/// +/// +/**/ +_CONCRTIMP const GUID LockEventGuid = { 0x79A60DC6, 0x5FC8, 0x4952, { 0xA4, 0x1C, 0x11, 0x63, 0xAE, 0xEC, 0x5E, 0xB8 } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to the resource manager. +/// +/// +/// This category of events is not currently fired by the Concurrency Runtime. +/// +/// +/**/ +_CONCRTIMP const GUID ResourceManagerEventGuid = { 0x2718D25B, 0x5BF5, 0x4479, { 0x8E, 0x88, 0xBA, 0xBC, 0x64, 0xBD, 0xBF, 0xCA } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to usage of the parallel_invoke +/// function. +/// +/// +/**/ +_CONCRTIMP const GUID PPLParallelInvokeEventGuid = { 0xd1b5b133, 0xec3d, 0x49f4, { 0x98, 0xa3, 0x46, 0x4d, 0x1a, 0x9e, 0x46, 0x82 } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to usage of the parallel_for +/// function. +/// +/// +/**/ +_CONCRTIMP const GUID PPLParallelForEventGuid = { 0x31c8da6b, 0x6165, 0x4042, { 0x8b, 0x92, 0x94, 0x9e, 0x31, 0x5f, 0x4d, 0x84 } }; + +/// +/// A category GUID describing ETW events fired by the Concurrency Runtime that are directly related to usage of the parallel_for_each +/// function. +/// +/// +/**/ +_CONCRTIMP const GUID PPLParallelForeachEventGuid = { 0x5cb7d785, 0x9d66, 0x465d, { 0xba, 0xe1, 0x46, 0x11, 0x6, 0x1b, 0x54, 0x34 } }; + +/// +/// A category GUID ({B9B5B78C-0713-4898-A21A-C67949DCED07}) describing ETW events fired by the Agents library in the Concurrency Runtime. +/// +/**/ +_CONCRTIMP const GUID AgentEventGuid = {0xb9b5b78c, 0x713, 0x4898, { 0xa2, 0x1a, 0xc6, 0x79, 0x49, 0xdc, 0xed, 0x7 } }; + +namespace details +{ + TRACEHANDLE g_ConcRTPRoviderHandle; + TRACEHANDLE g_ConcRTSessionHandle; + + _CONCRT_TRACE_INFO g_TraceInfo = {0}; + + Etw* g_pEtw = NULL; + + Etw::Etw() noexcept + { +#ifdef _ONECORE +#define TRACE_DLL L"api-ms-win-eventing-classicprovider-l1-1-0.dll" +#else +#define TRACE_DLL L"advapi32.dll" +#endif + HMODULE hTraceapi = LoadLibraryExW(TRACE_DLL, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); +#ifndef _ONECORE + if (!hTraceapi && GetLastError() == ERROR_INVALID_PARAMETER) + { + // LOAD_LIBRARY_SEARCH_SYSTEM32 is not supported on this platform, but TRACE_DLL is a KnownDLL so it is safe to load + // it without supplying the full path. On Windows 8 and higher, LOAD_LIBRARY_SEARCH_SYSTEM32 should be used as a best practice. + hTraceapi = LoadLibraryW(TRACE_DLL); + } +#endif + if (hTraceapi != NULL) + { + m_pfnRegisterTraceGuidsW = (FnRegisterTraceGuidsW*) Security::EncodePointer(GetProcAddress(hTraceapi, "RegisterTraceGuidsW")); + m_pfnUnregisterTraceGuids = (FnUnregisterTraceGuids*) Security::EncodePointer(GetProcAddress(hTraceapi, "UnregisterTraceGuids")); + m_pfnTraceEvent = (FnTraceEvent*) Security::EncodePointer(GetProcAddress(hTraceapi, "TraceEvent")); + m_pfnGetTraceLoggerHandle = (FnGetTraceLoggerHandle*) Security::EncodePointer(GetProcAddress(hTraceapi, "GetTraceLoggerHandle")); + m_pfnGetTraceEnableLevel = (FnGetTraceEnableLevel*) Security::EncodePointer(GetProcAddress(hTraceapi, "GetTraceEnableLevel")); + m_pfnGetTraceEnableFlags = (FnGetTraceEnableFlags*) Security::EncodePointer(GetProcAddress(hTraceapi, "GetTraceEnableFlags")); + } + } + + ULONG Etw::RegisterGuids(WMIDPREQUEST controlCallBack, LPCGUID providerGuid, ULONG guidCount, PTRACE_GUID_REGISTRATION eventGuidRegistration, PTRACEHANDLE providerHandle) + { + if (m_pfnRegisterTraceGuidsW != Security::EncodePointer(NULL)) + { + FnRegisterTraceGuidsW* pfnRegisterTraceGuidsW = (FnRegisterTraceGuidsW*) Security::DecodePointer(m_pfnRegisterTraceGuidsW); + return pfnRegisterTraceGuidsW(controlCallBack, NULL, providerGuid, guidCount, eventGuidRegistration, NULL, NULL, providerHandle); + } + + return ERROR_PROC_NOT_FOUND; + } + + ULONG Etw::UnregisterGuids(TRACEHANDLE handle) + { + if (m_pfnUnregisterTraceGuids != Security::EncodePointer(NULL)) + { + FnUnregisterTraceGuids* pfnUnregisterTraceGuids = (FnUnregisterTraceGuids*) Security::DecodePointer(m_pfnUnregisterTraceGuids); + return pfnUnregisterTraceGuids(handle); + } + + return ERROR_PROC_NOT_FOUND; + } + + ULONG Etw::Trace(TRACEHANDLE handle, PEVENT_TRACE_HEADER eventHeader) + { + if (m_pfnTraceEvent != Security::EncodePointer(NULL)) + { + FnTraceEvent* pfnTraceEvent = (FnTraceEvent*) Security::DecodePointer(m_pfnTraceEvent); + return pfnTraceEvent(handle, eventHeader); + } + + return ERROR_PROC_NOT_FOUND; + } + + TRACEHANDLE Etw::GetLoggerHandle(PVOID buffer) + { + if (m_pfnGetTraceLoggerHandle != Security::EncodePointer(NULL)) + { + FnGetTraceLoggerHandle* pfnGetTraceLoggerHandle = (FnGetTraceLoggerHandle*) Security::DecodePointer(m_pfnGetTraceLoggerHandle); + return pfnGetTraceLoggerHandle(buffer); + } + + SetLastError(ERROR_PROC_NOT_FOUND); + return (TRACEHANDLE)INVALID_HANDLE_VALUE; + } + + UCHAR Etw::GetEnableLevel(TRACEHANDLE handle) + { + if (m_pfnGetTraceEnableLevel != Security::EncodePointer(NULL)) + { + FnGetTraceEnableLevel* pfnGetTraceEnableLevel = (FnGetTraceEnableLevel*) Security::DecodePointer(m_pfnGetTraceEnableLevel); + return pfnGetTraceEnableLevel(handle); + } + + SetLastError(ERROR_PROC_NOT_FOUND); + return 0; + } + + ULONG Etw::GetEnableFlags(TRACEHANDLE handle) + { + if (m_pfnGetTraceEnableFlags != Security::EncodePointer(NULL)) + { + FnGetTraceEnableFlags* pfnGetTraceEnableFlags = (FnGetTraceEnableFlags*) Security::DecodePointer(m_pfnGetTraceEnableFlags); + return pfnGetTraceEnableFlags(handle); + } + + SetLastError(ERROR_PROC_NOT_FOUND); + return 0; + } + + + /// WMI control call back + ULONG WINAPI ControlCallback(WMIDPREQUESTCODE requestCode, void*, ULONG*, void* buffer) + { + DWORD rc; + + switch (requestCode) + { + case WMI_ENABLE_EVENTS: + // Enable the provider + { + g_ConcRTSessionHandle = g_pEtw->GetLoggerHandle(buffer); + if ((HANDLE)g_ConcRTSessionHandle == INVALID_HANDLE_VALUE) + return GetLastError(); + + SetLastError(ERROR_SUCCESS); + ULONG level = g_pEtw->GetEnableLevel(g_ConcRTSessionHandle); + if (level == 0) + { + rc = GetLastError(); + if (rc == ERROR_SUCCESS) + { + // Enable level of 0 means TRACE_LEVEL_INFORMATION + level = TRACE_LEVEL_INFORMATION; + } + else + { + return rc; + } + } + + ULONG flags = g_pEtw->GetEnableFlags(g_ConcRTSessionHandle); + if (flags == 0) + { + rc = GetLastError(); + if (rc == ERROR_SUCCESS) + { + flags = static_cast(AllEventsFlag); + } + else + { + return rc; + } + } + + // Tracing is now enabled. + g_TraceInfo._EnableTrace((unsigned char)level, (unsigned long)flags); + } + + break; + + case WMI_DISABLE_EVENTS: // Disable the provider + g_TraceInfo._DisableTrace(); + g_ConcRTSessionHandle = 0; + break; + + case WMI_EXECUTE_METHOD: + case WMI_REGINFO: + case WMI_DISABLE_COLLECTION: + case WMI_ENABLE_COLLECTION: + case WMI_SET_SINGLE_ITEM: + case WMI_SET_SINGLE_INSTANCE: + case WMI_GET_SINGLE_INSTANCE: + case WMI_GET_ALL_DATA: + default: + return ERROR_INVALID_PARAMETER; + } + + return ERROR_SUCCESS; + } + + void PPL_Trace_Event(const GUID& guid, ConcRT_EventType eventType, UCHAR level) + { + if (g_pEtw != NULL) + { + CONCRT_TRACE_EVENT_HEADER_COMMON concrtHeader = {0}; + + concrtHeader.header.Size = sizeof concrtHeader; + concrtHeader.header.Flags = WNODE_FLAG_TRACED_GUID; + concrtHeader.header.Guid = guid; + concrtHeader.header.Class.Type = (UCHAR) eventType; + concrtHeader.header.Class.Level = level; + + g_pEtw->Trace(g_ConcRTSessionHandle, &concrtHeader.header); + } + } + + void _RegisterConcRTEventTracing() + { +#if defined(_ONECORE) + g_pEtw = NULL; +#else + // Initialize ETW dynamically, and only once, to avoid a static dependency on Advapi32.dll. + _StaticLock::_Scoped_lock lockHolder(Etw::s_lock); + + if (g_pEtw == NULL) + { + g_pEtw = _concrt_new Etw(); + + static TRACE_GUID_REGISTRATION eventGuidRegistration[] = { + { &Concurrency::ConcRTEventGuid, NULL }, + { &Concurrency::SchedulerEventGuid, NULL }, + { &Concurrency::ScheduleGroupEventGuid, NULL }, + { &Concurrency::ContextEventGuid, NULL }, + { &Concurrency::ChoreEventGuid, NULL }, + { &Concurrency::LockEventGuid, NULL }, + { &Concurrency::ResourceManagerEventGuid, NULL } + }; + + ULONG eventGuidCount = sizeof eventGuidRegistration / sizeof eventGuidRegistration[0]; + + g_pEtw->RegisterGuids(Concurrency::details::ControlCallback, &ConcRT_ProviderGuid, eventGuidCount, eventGuidRegistration, &g_ConcRTPRoviderHandle); + } +#endif // defined(_ONECORE) + } + + void _UnregisterConcRTEventTracing() + { + if (g_pEtw != NULL) + { + ENSURE_NOT_APP(); + g_TraceInfo._DisableTrace(); + g_pEtw->UnregisterGuids(g_ConcRTPRoviderHandle); + delete g_pEtw; + g_pEtw = NULL; + } + } +} // namespace details + +/// +/// Enable tracing +/// +/// +/// If tracing was correctly initiated, S_OK is returned, otherwise E_NOT_STARTED is returned +/// +_CONCRTIMP HRESULT EnableTracing() +{ + // Deprecated + return S_OK; +} + + +/// +/// Disables tracing +/// +/// +/// If tracing was correctly disabled, S_OK is returned. If tracing was not previously initiated, +/// E_NOT_STARTED is returned +/// +_CONCRTIMP HRESULT DisableTracing() +{ + // Deprecated + return S_OK; +} + +_CONCRTIMP const _CONCRT_TRACE_INFO* _GetConcRTTraceInfo() +{ + if (g_pEtw == NULL) + { + ::Concurrency::details::_RegisterConcRTEventTracing(); + } + + return &g_TraceInfo; +} + +// Trace an event signaling the begin of a PPL function +_CONCRTIMP void _Trace_ppl_function(const GUID& guid, UCHAR level, ConcRT_EventType type) +{ + const _CONCRT_TRACE_INFO * traceInfo = _GetConcRTTraceInfo(); + + if (traceInfo->_IsEnabled(level, PPLEventFlag)) + Concurrency::details::PPL_Trace_Event(guid, type, level); +} + +// Trace an event from the Agents library +_CONCRTIMP void _Trace_agents(::Concurrency::Agents_EventType eventType, __int64 agentId, ...) +{ + va_list args; + va_start(args, agentId); + + UCHAR level = TRACE_LEVEL_INFORMATION; + const _CONCRT_TRACE_INFO * traceInfo = _GetConcRTTraceInfo(); + + if (traceInfo->_IsEnabled(level, AgentEventFlag)) + { + AGENTS_TRACE_EVENT_DATA agentsData = {0}; + + // Header + agentsData.header.Size = sizeof(agentsData); + agentsData.header.Flags = WNODE_FLAG_TRACED_GUID; + agentsData.header.Guid = AgentEventGuid; + agentsData.header.Class.Type = (UCHAR) eventType; + agentsData.header.Class.Level = level; + + // Payload + agentsData.payload.AgentId1 = agentId; + + switch (eventType) + { + case AGENTS_EVENT_CREATE: + // LWT id + agentsData.payload.AgentId2 = va_arg(args, __int64); + break; + + case AGENTS_EVENT_DESTROY: + // No other payload + break; + + case AGENTS_EVENT_LINK: + case AGENTS_EVENT_UNLINK: + // Target's id + agentsData.payload.AgentId2 = va_arg(args, __int64); + break; + + case AGENTS_EVENT_START: + // No other payload + break; + + case AGENTS_EVENT_END: + // Number of messages processed + agentsData.payload.Count = va_arg(args, long); + break; + + case AGENTS_EVENT_SCHEDULE: + // No other payload + break; + + case AGENTS_EVENT_NAME: + { + wchar_t * name = va_arg(args, wchar_t*); + + if (name != NULL) + { + wcsncpy_s(agentsData.payload.Name, _countof(agentsData.payload.Name), name, _TRUNCATE); + } + } + break; + + default: + break; + }; + + va_end(args); + g_pEtw->Trace(g_ConcRTSessionHandle, &agentsData.header); + } +} + +} // namespace Concurrency + +#pragma warning (pop) diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.h new file mode 100644 index 0000000000000000000000000000000000000000..c352b34735e518f914d8e57b58f9ca530bfb2bc3 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Trace.h @@ -0,0 +1,103 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// Trace.h +// +// Header file containing internal declarations for event tracing infrastructure. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#pragma once + +namespace Concurrency +{ +namespace details +{ + // Singleton ETW wrapper to avoid having a static dependency on advapi32.dll. + class Etw + { + private: + Etw() noexcept; + + public: + ULONG RegisterGuids(WMIDPREQUEST controlCallBack, LPCGUID providerGuid, ULONG guidCount, PTRACE_GUID_REGISTRATION eventGuidRegistration, PTRACEHANDLE providerHandle); + ULONG UnregisterGuids(TRACEHANDLE handle); + ULONG Trace(TRACEHANDLE handle, PEVENT_TRACE_HEADER eventHeader); + TRACEHANDLE GetLoggerHandle(PVOID); + UCHAR GetEnableLevel(TRACEHANDLE handle); + ULONG GetEnableFlags(TRACEHANDLE handle); + + private: + friend void ::Concurrency::details::_RegisterConcRTEventTracing(); + + typedef ULONG WINAPI FnRegisterTraceGuidsW(WMIDPREQUEST, PVOID, LPCGUID, ULONG, PTRACE_GUID_REGISTRATION, LPCWSTR, LPCWSTR, PTRACEHANDLE); + FnRegisterTraceGuidsW* m_pfnRegisterTraceGuidsW{}; + + typedef ULONG WINAPI FnUnregisterTraceGuids(TRACEHANDLE); + FnUnregisterTraceGuids* m_pfnUnregisterTraceGuids{}; + + typedef ULONG WINAPI FnTraceEvent(TRACEHANDLE, PEVENT_TRACE_HEADER); + FnTraceEvent* m_pfnTraceEvent{}; + + typedef TRACEHANDLE WINAPI FnGetTraceLoggerHandle(PVOID); + FnGetTraceLoggerHandle* m_pfnGetTraceLoggerHandle{}; + + typedef UCHAR WINAPI FnGetTraceEnableLevel(TRACEHANDLE); + FnGetTraceEnableLevel* m_pfnGetTraceEnableLevel{}; + + typedef ULONG WINAPI FnGetTraceEnableFlags(TRACEHANDLE); + FnGetTraceEnableFlags* m_pfnGetTraceEnableFlags{}; + + static _StaticLock s_lock; + }; + + extern _CONCRT_TRACE_INFO g_TraceInfo; + extern TRACEHANDLE g_ConcRTSessionHandle; + extern Etw* g_pEtw; +} // namespace details + +/// +/// Common trace header structure for all ConcRT diagnostic events +/// +struct CONCRT_TRACE_EVENT_HEADER_COMMON +{ + EVENT_TRACE_HEADER header; + DWORD VirtualProcessorID; + DWORD SchedulerID; + DWORD ContextID; + DWORD ScheduleGroupID; +}; + +/// +/// Common trace payload for agents +/// +struct AGENTS_TRACE_PAYLOAD +{ + // Identifier of the agent or message block that is emitting the event + __int64 AgentId1; + union + { + // The identifier of a target block for link/unlink event + __int64 AgentId2; + + // Count of messages processed for the end event + long Count; + + // Name of this agent for the purposes of the ETW trace + wchar_t Name[32]; + }; +}; + +/// +/// Common trace header structure for all Agents diagnostic events +/// +struct AGENTS_TRACE_EVENT_DATA +{ + EVENT_TRACE_HEADER header; + AGENTS_TRACE_PAYLOAD payload; +}; + +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f26a44ecba63c89269f4a7033801d4c59d23440a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.cpp @@ -0,0 +1,706 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// VirtualProcessor.cpp +// +// Source file containing the VirtualProcessor implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs a virtual processor. + /// + VirtualProcessor::VirtualProcessor() + : m_localRunnableContexts(&m_lock) + { + // Derived classes should use Initialize(...) to init the virtual processor + } + + /// + /// Initializes the virtual processor. This API is called by the constructor, and when a virtual processor is to + /// be re-initialized, when it is pulled of the free pool in the list array. + /// + /// + /// The owning schedule node for this virtual processor + /// + /// + /// The owning IVirtualProcessorRoot + /// + void VirtualProcessor::Initialize(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot) + { + OMTRACE(MTRACE_EVT_INITIALIZED, this, NULL, NULL, NULL); + + m_lastServiceTime = 0; + m_priorityServiceLink.m_boostState = BoostedObject::BoostStateUnboosted; + m_priorityServiceLink.m_type = BoostedObject::BoostTypeVirtualProcessor; + m_pPushContext = NULL; + m_pOwningNode = pOwningNode; + m_pOwningRing = pOwningNode->GetSchedulingRing(); + m_pOwningRoot = pOwningRoot; + m_fMarkedForRetirement = false; + m_fOversubscribed = false; + m_availabilityType = AvailabilityClaimed; + m_enqueuedTaskCounter = 0; + m_dequeuedTaskCounter = 0; + m_enqueuedTaskCheckpoint = 0; + m_dequeuedTaskCheckpoint = 0; + m_pExecutingContext = NULL; + m_pOversubscribingContext = NULL; + m_safePointMarker.Reset(); + m_pSubAllocator = NULL; + m_fLocal = false; + m_fAffine = false; + + // + // When a VPROC first comes online, it **MUST** do one affine SFW before moving on with life. This avoids a wake/arrive race with affine + // work. + // + m_fShortAffine = true; + + SchedulerBase *pScheduler = m_pOwningNode->GetScheduler(); + + // A virtual processor has the same id as its associated virtual processor root. The roots have process unique ids. + m_id = pOwningRoot->GetId(); + + // Keep track of the abstract identifier for the underlying execution resource. + m_resourceId = pOwningRoot->GetExecutionResourceId(); + + // Determine our hash id and create our map. + m_maskId = pScheduler->GetResourceMaskId(m_resourceId); + m_resourceMask.Grow(pScheduler->GetMaskIdCount()); + m_resourceMask.Wipe(); + m_resourceMask.Set(m_maskId); + + if (pScheduler->GetSchedulingProtocol() == ::Concurrency::EnhanceScheduleGroupLocality) + m_searchCtx.Reset(this, WorkSearchContext::AlgorithmCacheLocal); + else + m_searchCtx.Reset(this, WorkSearchContext::AlgorithmFair); + + m_location = location(location::_ExecutionResource, m_resourceId, m_pOwningNode->m_pScheduler->Id(), this); + + // Notify the scheduler that we are listening for events pertaining to affinity and locality. + pScheduler->ListenAffinity(m_maskId); + + TraceVirtualProcessorEvent(CONCRT_EVENT_START, TRACE_LEVEL_INFORMATION, m_pOwningNode->m_pScheduler->Id(), m_id); + } + + /// + /// Destroys a virtual processor + /// + VirtualProcessor::~VirtualProcessor() + { + ASSERT(m_localRunnableContexts.Count() == 0); + + if (m_pSubAllocator != NULL) + { + SchedulerBase::ReturnSubAllocator(m_pSubAllocator); + m_pSubAllocator = NULL; + } + } + + /// + /// Activates a virtual processor with the context provided. + /// + void VirtualProcessor::Activate(IExecutionContext * pContext) + { + VMTRACE(MTRACE_EVT_ACTIVATE, ToInternalContext(pContext), this, SchedulerBase::FastCurrentContext()); + m_pOwningRoot->Activate(pContext); + } + + /// + /// Temporarily deactivates a virtual processor. + /// + /// + /// An indication of which side the awakening occurred from (true -- we activated it, false -- the RM awoke it). + /// + bool VirtualProcessor::Deactivate(IExecutionContext * pContext) + { + VMTRACE(MTRACE_EVT_DEACTIVATE, ToInternalContext(pContext), this, false); + + return m_pOwningRoot->Deactivate(pContext); + } + + /// + /// Invokes the underlying virtual processor root to ensure all tasks are visible + /// + void VirtualProcessor::EnsureAllTasksVisible(IExecutionContext * pContext) + { + VMTRACE(MTRACE_EVT_DEACTIVATE, ToInternalContext(pContext), this, true); + + m_pOwningRoot->EnsureAllTasksVisible(pContext); + } + + /// + /// Exercises a claim of ownership over a virtual processor and starts it up. + /// + bool VirtualProcessor::ExerciseClaim(VirtualProcessor::AvailabilityType type, ScheduleGroupSegmentBase *pSegment, InternalContextBase *pContext) + { + VMTRACE(MTRACE_EVT_TICKETEXERCISE, SchedulerBase::FastCurrentContext(), this, type); + + SchedulerBase *pScheduler = GetOwningNode()->GetScheduler(); + + CONCRT_COREASSERT(type != AvailabilityClaimed); + + // + // @TODO: Should we allow a generic exercise with AvailabilityInactivePendingThread or should this require an explicit exercise. + // + switch(type) + { + case AvailabilityInactive: + case AvailabilityInactivePendingThread: + if (!pScheduler->VirtualProcessorActive(true)) + { + // + // This happened during a shutdown/DRM race. We do not need to notify the background thread of anything. It will all work out + // as finalization proceeds. + // + if (pContext != NULL) + { + CONCRT_COREASSERT(!pContext->IsPrepared()); + + // + // Only a pre-bound context is passed into here. If we cannot start up the vproc right now, the context needs + // to get retired. + // + pScheduler->ReleaseInternalContext(pContext, true); + } + + MakeAvailable(type, false); + return false; + } + + if (pSegment == NULL) + pSegment = pScheduler->GetAnonymousScheduleGroupSegment(); + + return StartupWorkerContext(pSegment, pContext); + + case AvailabilityIdlePendingThread: + // + // This path is not generalized and is specific to UMS. + // + // Consideration might be given to allowing push to this virtual processor we just decided to wake up instead of allowing the + // SFW. The problem here is that the context might be doing its own SFW and the two contexts might collide. If they do, there's + // a question about what's reasonable to do. For now, this is unsupported -- we only push to inactive vprocs. + // + CONCRT_COREASSERT(pContext == NULL); + + break; + + default: + // + // See above comments under IdlePendingThread. + // + CONCRT_COREASSERT(pContext == NULL); + + CONCRT_COREASSERT(m_pAvailableContext != NULL); + + // + // Note: We cannot validate that m_pExecutingContext is running atop this. On UMS, it's legal (although extremely discouraged) to UMS + // block between MakeAvailable and Deactivate in the SFW path. In that case, we pick up other runnables. The context which is going + // to be activated and subsequently swallow the activate with a corresponding deactivate is m_pAvailableContext. m_pExecutingContext + // may be the random thing we switched to. If this happens, m_pAvailableContext may also have a NULL vproc. + // + // Note that this typically occasionally happens due to the FlushProcessWriteBuffers call before final deactivation. + // +#if defined(_DEBUG) + { + VirtualProcessor *pVProc = ToInternalContext(m_pAvailableContext) ? ToInternalContext(m_pAvailableContext)->m_pVirtualProcessor : NULL; + CONCRT_COREASSERT(pVProc == this || pVProc == NULL); + } +#endif // defined(_DEBUG) + } + + m_pOwningRoot->Activate(m_pAvailableContext); + return true; + } + + /// + /// Start a worker context executing on this.virtual processor. + /// + bool VirtualProcessor::StartupWorkerContext(ScheduleGroupSegmentBase *pSegment, InternalContextBase *pContext) + { + // + // We need to spin until m_pExecutingContext is NULL so we can appropriately affinitize a new thread and not conflict. + // + if (m_pExecutingContext != NULL) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + while(m_pExecutingContext != NULL) + spinWait._SpinOnce(); + } + + if (pContext != NULL) + { + if (!pContext->IsPrepared()) + pContext->PrepareForUse(pSegment, NULL, false); + } + else + { + pContext = pSegment->GetInternalContext(); + } + + // + // It's entirely possible we could *NOT* get a thread to wake up this virtual processor. In this case, we need to make it idle + // again and tell the background thread to wake us up when there is a thread available. + // + if (pContext == NULL) + { + MakeAvailable(AvailabilityInactivePendingThread); + GetOwningNode()->GetScheduler()->DeferredGetInternalContext(); + return false; + } + + Affinitize(pContext); + m_pOwningRoot->Activate(m_pExecutingContext); + return true; + } + + /// + /// Affinitizes an internal context to the virtual processor. + /// + /// + /// The internal context to affinitize. + /// + _Post_satisfies_(this->m_pExecutingContext == pContext) + void VirtualProcessor::Affinitize(InternalContextBase *pContext) + { + // + // Wait until the context is firmly blocked, if it has started. This is essential to prevent vproc orphanage + // if the context we're switching to is IN THE PROCESS of switching out to a different one. An example of how this + // could happen: + // + // 1] ctxA is running on vp1. It is in the process of blocking, and wants to switch to ctxB. This means ctxA needs to + // affinitize ctxB to its own vproc, vp1. + // + // 2] At the exact same time, ctxA is unblocked by ctxY and put onto a runnables collection in its scheduler. Meanwhile, ctxZ + // executing on vp2, has also decided to block. It picks ctxA off the runnables collection, and proceeds to switch to it. + // This means that ctxZ needs to affinitize ctxA to ITS vproc vp2. + // + // 3] Now, if ctxZ affinitizes ctxA to vp2 BEFORE ctxA has had a chance to affinitize ctxB to vp1, ctxB gets mistakenly + // affinitized to vp2, and vp1 is orphaned. + // + // In order to prevent this, ctxZ MUST wait until AFTER ctxA has finished its affinitization. This is indicated via the + // blocked flag. ctxA will set its blocked flag to 1, after it has finished affintizing ctxB to vp1, at which point it is + // safe for ctxZ to modify ctxA's vproc and change it from vp1 to vp2. + // + // Note that it is possible that pContext is NULL in the case where we are going to SwitchOut a virtual processor due to a lack of + // available threads. + // + if (pContext != NULL) + { + pContext->SpinUntilBlocked(); + pContext->PrepareToRun(this); + + VCMTRACE(MTRACE_EVT_AFFINITIZED, pContext, this, NULL); + +#if defined(_DEBUG) + pContext->ClearDebugBits(); + pContext->SetDebugBits(CTX_DEBUGBIT_AFFINITIZED); +#endif // _DEBUG + } + + // Make sure there is a two-way mapping between a virtual processor and the affinitized context attached to it. + // The pContext-> side of this mapping was established in PrepareToRun. + m_pExecutingContext = pContext; + + // + // If we were unable to update the statistical information because internal context was not + // affinitized to a virtual processor, then do it now when the affinitization is done. + // + if (pContext != NULL && pContext->m_fHasDequeuedTask) + { + m_dequeuedTaskCounter++; + pContext->m_fHasDequeuedTask = false; + } + } + + /// + /// Marks the virtual processor such that it removes itself from the scheduler once the context it is executing + /// reaches a safe yield point. Alternatively, if the context has not started executing yet, it can be retired immediately. + /// + void VirtualProcessor::MarkForRetirement() + { + ClaimTicket ticket; + if (ClaimExclusiveOwnership(ticket)) + { + // + // If there is a context attached to this virtual processor but we were able to claim it for + // retirement then we have to unblock this context and send it for retirement. Otherwise, if + // there was no context attached we can simply retire the virtual processor. + // + if (ticket.ExerciseWakesExisting()) + { + m_fMarkedForRetirement = true; + ticket.Exercise(); + } + else + { + Retire(); + } + } + else + { + // + // Instruct the virtual processor to exit at a yield point - when the context it is executing enters the scheduler + // from user code. + // + m_fMarkedForRetirement = true; + } + } + + /// + /// Attempts to claim exclusive ownership of the virtual processor by resetting the available flag. + /// + /// + /// If true is returned, this will contain the claim ticket used to activate the virtual processor. + /// + /// + /// If specified, indicates the type of availability that we can claim. If the caller is only interested in inactive virtual processors, + /// for instance, AvailabilityInactive can be passed. + /// + /// + /// True if it was able to claim the virtual processor, false otherwise. + /// + bool VirtualProcessor::ClaimExclusiveOwnership(VirtualProcessor::ClaimTicket &ticket, ULONG type, bool updateCounters) + { + CONCRT_COREASSERT(type != AvailabilityClaimed); + + AvailabilityType curType = m_availabilityType; + if ((curType & type) != 0) + { + AvailabilityType prevType = AvailabilityType(); + bool fClaimed = false; + + if (type == AvailabilityAny) + { + prevType = (AvailabilityType)(InterlockedExchange(reinterpret_cast(&m_availabilityType), AvailabilityClaimed)); + fClaimed = (prevType != AvailabilityClaimed); + } + else + { + for(;;) + { + if ((curType & type) == 0) + break; + + prevType = (AvailabilityType)(InterlockedCompareExchange(reinterpret_cast(&m_availabilityType), AvailabilityClaimed, curType)); + if (prevType == curType) + { + fClaimed = true; + break; + } + + curType = prevType; + } + } + + if (fClaimed) + { + CONCRT_COREASSERT(m_availabilityType == AvailabilityClaimed); + + if (updateCounters) + { + InterlockedDecrement(&m_pOwningNode->m_pScheduler->m_virtualProcessorAvailableCount); + InterlockedDecrement(&m_pOwningNode->m_virtualProcessorAvailableCount); + + // + // Keep track of the number of virtual processors pending thread creation. + // + if (prevType == AvailabilityInactivePendingThread || prevType == AvailabilityIdlePendingThread) + { + InterlockedDecrement(&m_pOwningNode->m_pScheduler->m_virtualProcessorsPendingThreadCreate); + InterlockedDecrement(&m_pOwningNode->m_virtualProcessorsPendingThreadCreate); + } + + OMTRACE(MTRACE_EVT_CLAIMEDOWNERSHIP, m_pOwningNode->m_pScheduler, pCurrentContext, this, pCurrentContext); + } + + OMTRACE(MTRACE_EVT_AVAILABLEVPROCS, m_pOwningNode->m_pScheduler, pCurrentContext, this, m_pOwningNode->m_pScheduler->m_virtualProcessorAvailableCount); + + ticket.InitializeTicket(prevType, this); + m_claimantType = prevType; + + return true; + } + } + return false; + } + + /// + /// Makes a virtual processor available for scheduling work. + /// + /// + /// Indicates whether the routine should update active state for the vproc based upon type or not. + /// + void VirtualProcessor::MakeAvailable(AvailabilityType type, bool fCanChangeActiveState) + { + ASSERT(m_availabilityType == AvailabilityClaimed); + + // + // Keep track of the context which made the virtual processor available. It will be the one that deactivates if there's a corresponding activate + // from outside. This is a spec requirement. On UMS, we can temporarily execute another context if the scheduler blocks with a Win32 primitive + // between the MakeAvailable and the Deactivate call. This should be avoided if at all possible -- it is a performance hit! + // + m_pAvailableContext = m_pExecutingContext; + + if (fCanChangeActiveState && (type == AvailabilityInactive || type == AvailabilityInactivePendingThread)) + GetOwningNode()->GetScheduler()->VirtualProcessorActive(false); + + InterlockedIncrement(&m_pOwningNode->m_pScheduler->m_virtualProcessorAvailableCount); + InterlockedIncrement(&m_pOwningNode->m_virtualProcessorAvailableCount); + + // + // Keep track of the number of virtual processors pending thread creation (if any are). + // + if (type == AvailabilityInactivePendingThread || type == AvailabilityIdlePendingThread) + { + InterlockedIncrement(&m_pOwningNode->m_pScheduler->m_virtualProcessorsPendingThreadCreate); + InterlockedIncrement(&m_pOwningNode->m_virtualProcessorsPendingThreadCreate); + } + + OMTRACE(MTRACE_EVT_MADEAVAILABLE, m_pOwningNode->m_pScheduler, pCurrentContext, this, NULL); + OMTRACE(MTRACE_EVT_AVAILABLEVPROCS, m_pOwningNode->m_pScheduler, pCurrentContext, this, m_pOwningNode->m_pScheduler->m_virtualProcessorAvailableCount); + InterlockedExchange(reinterpret_cast(&m_availabilityType), type); + } + + /// + /// Oversubscribes the virtual processor by creating a new virtual processor root affinitized to the same + /// execution resource as that of the current root + /// + /// + /// A virtual processor that oversubscribes this one. + /// + VirtualProcessor * VirtualProcessor::Oversubscribe() + { + IVirtualProcessorRoot *pOversubscriberRoot = GetOwningNode()->GetScheduler()->GetSchedulerProxy()->CreateOversubscriber(m_pOwningRoot); + ASSERT(pOversubscriberRoot != NULL); + + return m_pOwningNode->AddVirtualProcessor(pOversubscriberRoot, true); + } + + /// + /// Causes the virtual processor to remove itself from the scheduler. This is used either when oversubscription + /// ends or when the resource manager asks the vproc to retire. + /// + void VirtualProcessor::Retire() + { + VMTRACE(MTRACE_EVT_RETIRE, SchedulerBase::FastCurrentContext(), this, m_availabilityType); + + m_pOwningNode->m_pScheduler->RemovePrioritizedObject(&m_priorityServiceLink); + + // Virtual processor available counts are already decremented by this point. We need to decrement the total counts + // on both the node and the scheduler. Oversubscribed vprocs do not contribute to the total vproc count on the scheduler. + m_pOwningNode->m_pScheduler->DecrementActiveResourcesByMask(m_maskId); + InterlockedDecrement(&m_pOwningNode->m_virtualProcessorCount); + if (!m_fOversubscribed) + { + InterlockedDecrement(&m_pOwningNode->m_pScheduler->m_virtualProcessorCount); + } + + // Since virtual processor is going away we'd like to preserve its counts + m_pOwningNode->GetScheduler()->SaveRetiredVirtualProcessorStatistics(this); + + // Make sure we're no longer flagged as listening for affinity messages. + if (!m_fAffine) + m_pOwningNode->GetScheduler()->IgnoreAffinity(m_maskId); + + // If this is a virtual processor currently associated with an executing context, it's important to assert there that + // the scheduler is not shutting down. We want to make sure that all virtual processor root removals (for executing virtual + // processors) occur before the scheduler shuts down. This will ensure that all IVirtualProcessorRoot::Remove calls + // that can originate from a scheduler's internal contexts instance are received the RM before the ISchedulerProxy::Shutdown call, + // which asks the RM to release all resources and destroy the remaining virtual processor roots allocated to the scheduler. + // RM should not receive Remove calls for roots that are already destroyed. + ASSERT(ClaimantWasInactive() || ToInternalContext(m_pExecutingContext) == SchedulerBase::FastCurrentContext()); + ASSERT(ClaimantWasInactive() || (!m_pOwningNode->GetScheduler()->InFinalizationSweep() && !m_pOwningNode->GetScheduler()->HasCompletedShutdown())); + + m_pExecutingContext = NULL; + + // Check if there are contexts in the Local Runnables Collection and put them into the collection of runnables in their + // respective schedule groups. + InternalContextBase *pContext = GetLocalRunnableContext(); + while (pContext != NULL) + { + ScheduleGroupSegmentBase *pSegment = pContext->GetScheduleGroupSegment(); + pSegment->AddRunnableContext(pContext, pSegment->GetAffinity()); + pContext = GetLocalRunnableContext(); + } + + // Send an IScheduler pointer into to Remove. Scheduler does derive from IScheduler, and therefore we need + // an extra level of indirection. + m_pOwningRoot->Remove(m_pOwningNode->GetScheduler()->GetIScheduler()); + m_pOwningRoot = NULL; + + TraceVirtualProcessorEvent(CONCRT_EVENT_END, TRACE_LEVEL_INFORMATION, m_pOwningNode->m_pScheduler->Id(), m_id); + + if (m_pSubAllocator != NULL) + { + SchedulerBase::ReturnSubAllocator(m_pSubAllocator); + m_pSubAllocator = NULL; + } + + // Removing this VirtualProcessor from the ListArray will move it to a pool for reuse + // This must be done at the end of this function, otherwise, this virtual processor itself could be + // pulled out of the list array for reuse and stomped over before retirement is complete. + m_pOwningNode->m_virtualProcessors.Remove(this); + // *DO NOT* touch 'this' after removing it from the list array. + } + + /// + /// Returns a pointer to the suballocator for the virtual processor. + /// + SubAllocator * VirtualProcessor::GetCurrentSubAllocator() + { + if (m_pSubAllocator == NULL) + { + m_pSubAllocator = SchedulerBase::GetSubAllocator(false); + } + return m_pSubAllocator; + } + + /// + /// Updates tracking on the virtual processor whether it is executing affine work and/or local work. + /// + /// + /// An indication of whether the virtual processor is executing work which has affinity to it or not. + /// + /// + /// An indication of whether the virtual processor is executing work which is local to it or not. + /// + void VirtualProcessor::UpdateWorkState(bool fAffine, bool fLocal) + { + SchedulerBase *pScheduler = m_pOwningNode->GetScheduler(); + + // + // Notify the scheduler if we need to listen for affinity events or not. + // + if (m_fAffine) + { + if (!fAffine) + { + VCMTRACE(MTRACE_EVT_CHANGEAFFINITYSTATE, m_pExecutingContext, this, 0); + + // + // See CheckAffinityNotification comments. We need to avoid a listen/arrive race to prevent ourselves getting stuck on non-affine + // work. + // + m_fShortAffine = true; + pScheduler->ListenAffinity(m_maskId); + } + } + else + { + if (fAffine) + { + VCMTRACE(MTRACE_EVT_CHANGEAFFINITYSTATE, m_pExecutingContext, this, 1); + pScheduler->IgnoreAffinity(m_maskId); + } + } + + m_fAffine = fAffine; + m_fLocal = fLocal; + } + + /// + /// Performs a quick check as to whether work which is affine to the virtual processor has arrived. This allows short circuiting of + /// expensive searches for affine work in cases where a user does not use any location objects. + /// + /// + /// An indication of whether or not work affine to the virtual processor has arrived since UpdateWorkState was called to indicate that + /// the virtual processor began working on non-affine work. + /// + bool VirtualProcessor::CheckAffinityNotification() + { + // + // Once we switch to executing non-affine work and flag that we are listening to messages, we will get affinity notifications and do not + // need to SFW for affine work. There is an inherent race in this, however. If we are doing an affine search and have passed segment "S" + // (affine to us), and a series of work comes into "S", and then we find non-affine work (because we already checked "S"), we will get no + // message for that work that came into "S". We must ensure that we do an affine SFW **ONCE** immediately after flagging ourselves + // as a listener. m_fShortAffine tracks this requirement. + // + if (m_fShortAffine) + { + VCMTRACE(MTRACE_EVT_ACKNOWLEDGEAFFINITYMESSAGE, m_pExecutingContext, this, 1); + + m_fShortAffine = false; + return true; + } + else + { + bool fAck = GetOwningNode()->GetScheduler()->AcknowledgedAffinityMessage(m_maskId); + + return fAck; + } + } + + /// + /// Send a virtual processor ETW event. + /// + void VirtualProcessor::ThrowVirtualProcessorEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD vprocId) + { + if (g_pEtw != NULL) + { + CONCRT_TRACE_EVENT_HEADER_COMMON concrtHeader = {0}; + + concrtHeader.header.Size = sizeof concrtHeader; + concrtHeader.header.Flags = WNODE_FLAG_TRACED_GUID; + concrtHeader.header.Class.Type = (UCHAR)eventType; + concrtHeader.header.Class.Level = level; + concrtHeader.header.Guid = VirtualProcessorEventGuid; + + concrtHeader.SchedulerID = schedulerId; + concrtHeader.VirtualProcessorID = vprocId; + + g_pEtw->Trace(g_ConcRTSessionHandle, &concrtHeader.header); + } + } + + /// + /// Returns a type-cast of pContext to an InternalContextBase or NULL if it is not. + /// + InternalContextBase *VirtualProcessor::ToInternalContext(IExecutionContext *pContext) + { + return static_cast(pContext); + } + + /// + /// Called when the context running atop this virtual processor has reached a safe point. + /// + /// + /// An indication of whether the caller should perform a commit. + /// + bool VirtualProcessor::SafePoint() + { + return GetOwningNode()->GetScheduler()->MarkSafePoint(&m_safePointMarker); + } + + /// + /// Exercises the ticket with a particular context. This is only valid if ExerciseWakesExisting() returns false. Callers should have + /// sought virtual processors with specific claim rights. + /// + bool VirtualProcessor::ClaimTicket::ExerciseWith(InternalContextBase *pContext) + { + bool fResult = false; + if (m_type != AvailabilityClaimed) + { + // + // @TODO: It should be started on a specific group plumbed through from the point at which the vproc couldn't find a thread. + // Right now, this info is not plumbed through so we pick up the anonymous group. + // + fResult = m_pVirtualProcessor->ExerciseClaim(m_type, m_pVirtualProcessor->GetOwningNode()->GetSchedulingRing()->GetAnonymousScheduleGroupSegment(), pContext); + m_type = AvailabilityClaimed; + } + + return fResult; + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.h new file mode 100644 index 0000000000000000000000000000000000000000..65fdd4ed2978621416f9cc2663b83b8569954b30 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessor.h @@ -0,0 +1,725 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// VirtualProcessor.h +// +// Source file containing the VirtualProcessor declaration. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + // + // TRANSITION: This is temporary until priority based livelock prevention is real. + // + struct BoostedObject + { + enum BoostType + { + BoostTypeScheduleGroupSegment, + BoostTypeVirtualProcessor + + }; + + enum BoostState + { + BoostStateDisallowed, + BoostStateUnboosted, + BoostStateBoosted + }; + + BoostType m_type; + BoostedObject *m_pNext; + BoostedObject *m_pPrev; + LONG m_boostState; + + bool IsScheduleGroupSegment() const + { + return m_type == BoostTypeScheduleGroupSegment; + } + + bool IsVirtualProcessor() const + { + return m_type == BoostTypeVirtualProcessor; + } + }; + + // + // virtualized hardware thread + // + /// + /// A virtual processor is an abstraction of a hardware thread. However, there may very well be more than one + /// virtual processor per hardware thread. The SchedulerPolicy key TargetOversubscriptionFactor determines + /// the number of virtual processor per hardware thread, scheduler wide. + /// + /// + /// Virtual processors may be created and destroyed at any time, since resource management (RM) may give or take + /// away hardware threads. But as such batches of TargetOversubscriptionFactor virtual processors are created or + /// destroyed simultaneously. + /// + class VirtualProcessor + { + public: + + /// + /// Indicates the type of availability of a virtual processor. + /// + enum AvailabilityType + { + // The virtual processor is claimed and running -- it is not available for claiming + AvailabilityClaimed = 0x0, + + // The virtual processor was marked available and is/will go inactive with nothing running atop it + AvailabilityInactive = 0x01, + + // The virtual processor is available with an idle/sleeping (or soon to be) thread running atop it. + AvailabilityIdle = 0x2, + + // The virtual processor was marked available and is/will deactivate; however -- it is pending a thread. It should + // not be awoken unless a thread is ready for it (e.g.: not for LWTs / WSQ items) + AvailabilityInactivePendingThread = 0x4, + + // The virtual processor is available with an idle/sleeping (or soon to be) thread running atop it; however -- it is pending a thread. + // This is a state exclusive to a scheduler with a specific scheduling context (e.g.: UMS) + AvailabilityIdlePendingThread = 0x8, + + // Mask for any type of availability (e.g.: if trying to find/claim a vproc) + AvailabilityAny = 0xf + }; + + /// + /// Represents a claim of exclusive ownership on a virtual processor. + /// + class ClaimTicket + { + public: + + /// + /// Constructs a new empty ticket. + /// + ClaimTicket() : + m_type(AvailabilityClaimed) + { + } + + /// + /// Exercises the ticket. Starts up a new context on the virtual processor or activates the idle one as appropriate. + /// + bool Exercise(ScheduleGroupSegmentBase *pSegment = NULL) + { + ASSERT(m_type != AvailabilityClaimed); + + bool fResult = m_pVirtualProcessor->ExerciseClaim(m_type, pSegment); + + // + // Ensure that a second call to exercise the same ticket asserts. + // + m_type = AvailabilityClaimed; + + return fResult; + } + + /// + /// Exercises the ticket with a particular context. This is only valid if ExerciseWakesExisting() returns false. Callers should have + /// sought virtual processors with specific claim rights. + /// + bool ExerciseWith(InternalContextBase *pContext); + + /// + /// Informs the caller whether the claim simply wakes an existing thread. + /// + bool ExerciseWakesExisting() const + { + return m_type == AvailabilityIdle || m_type == AvailabilityIdlePendingThread; + } + + + private: + + friend class VirtualProcessor; + + ClaimTicket(AvailabilityType type, VirtualProcessor *pVirtualProcessor) + { + InitializeTicket(type, pVirtualProcessor); + } + + void InitializeTicket(AvailabilityType type, VirtualProcessor *pVirtualProcessor) + { + m_type = type; + m_pVirtualProcessor = pVirtualProcessor; + } + + AvailabilityType m_type; + VirtualProcessor *m_pVirtualProcessor{}; + + }; + + /// + /// Constructs a virtual processor. + /// + VirtualProcessor(); + + /// + /// Destroys a virtual processor + /// + virtual ~VirtualProcessor(); + + /// + /// Returns a scheduler unique identifier for the virtual processor. + /// + unsigned int GetId() const { return m_id; } + + /// + /// Returns the execution resource id associated with this virtual processor. + /// + unsigned int GetExecutionResourceId() const { return m_resourceId; } + + /// + /// Returns the mask id for this virtual processor. + /// + unsigned int GetMaskId() const { return m_maskId; } + + /// + /// Updates tracking on the virtual processor whether it is executing affine work and/or local work. + /// + /// + /// An indication of whether the virtual processor is executing work which has affinity to it or not. + /// + /// + /// An indication of whether the virtual processor is executing work which is local to it or not. + /// + void UpdateWorkState(bool fAffine, bool fLocal); + + /// + /// Performs a quick check as to whether work which is affine to the virtual processor has arrived. This allows short circuiting of + /// expensive searches for affine work in cases where a user does not use any location objects. + /// + /// + /// An indication of whether or not work affine to the virtual processor has arrived since UpdateWorkState was called to indicate that + /// the virtual processor began working on non-affine work. + /// + bool CheckAffinityNotification(); + + /// + /// Returns an indication of whether the virtual processor is (or was last) executing affine work. + /// + /// + /// An indication of whether the virtual processor is (or was last) executing affine work. + /// + bool ExecutingAffine() + { + return m_fAffine; + } + + /// + /// Attempts to claim exclusive ownership of the virtual processor by resetting the available flag. + /// + /// + /// If true is returned, this will contain the claim ticket used to activate the virtual processor. + /// + /// + /// If specified, indicates the type of availability that we can claim. If the caller is only interested in inactive virtual processors, + /// for instance, AvailabilityInactive can be passed. + /// + /// + /// True if it was able to claim the virtual processor, false otherwise. + /// + bool ClaimExclusiveOwnership(ClaimTicket &ticket, ULONG type = AvailabilityAny, bool updateCounters = true /* GET RID OF THIS */); + + /// + /// Returns the state of the virtual processor's availability prior to the last claim. + /// + AvailabilityType ClaimantType() const + { + ASSERT(m_availabilityType == AvailabilityClaimed); + return m_claimantType; + } + + /// + /// Returns whether the last claimant claimed us while inactive. + /// + bool ClaimantWasInactive() const + { + return ((ClaimantType() & (AvailabilityInactive | AvailabilityInactivePendingThread)) != 0); + } + + /// + /// Makes a virtual processor available for scheduling work. + /// + void MakeAvailableForIdle() + { + MakeAvailable(AvailabilityIdle); + } + + /// + /// Makes a virtual processor available for scheduling work. + /// + void MakeAvailableForInactive() + { + MakeAvailable(AvailabilityInactive); + } + + /// + /// Makes a virtual processor available pending a thread. + /// + void MakeAvailablePendingThread() + { + MakeAvailable(AvailabilityInactivePendingThread); + } + + /// + /// Returns a pointer to the internal context that is executing on this virtual processor. + /// + IExecutionContext * GetExecutingContext() { return m_pExecutingContext; } + + /// + /// Returns a pointer to the owning node for the virtual processor. + /// + SchedulingNode * GetOwningNode() { return m_pOwningNode; } + + /// + /// Returns a pointer to the owning ring for the virtual processor. + /// + SchedulingRing * GetOwningRing() { return m_pOwningRing; } + + /// + /// Returns a pointer to the owning root for the virtual processor. + /// + IVirtualProcessorRoot * GetOwningRoot() { return m_pOwningRoot; } + + /// + /// Returns a pointer to the suballocator for the virtual processor. + /// + SubAllocator * GetCurrentSubAllocator(); + + /// + /// Returns true if the virtual processor is marked as available, false otherwise. + /// + bool IsAvailable() { return (m_availabilityType != AvailabilityClaimed); } + + /// + /// Returns the type of availability of the virtual processor. + /// + AvailabilityType TypeOfAvailability() { return m_availabilityType; } + + /// + /// Returns true if the virtual processor is marked for retirement, false otherwise. + /// + bool IsMarkedForRetirement() { return m_fMarkedForRetirement; } + + /// + /// Activates a virtual processor with the context provided. + /// + void Activate(IExecutionContext *pContext); + + /// + /// Temporarily deactivates a virtual processor. + /// + /// + /// An indication of which side the awakening occurred from (true -- we activated it, false -- the RM awoke it). + /// + bool Deactivate(IExecutionContext *pContext); + + /// + /// Invokes the underlying virtual processor root to ensure all tasks are visible. + /// + void EnsureAllTasksVisible(IExecutionContext * pContext); + + /// + /// Returns the default destination of a SwitchTo(NULL). There is none on a default virtual processor. + /// + virtual IExecutionContext *GetDefaultDestination() + { + return NULL; + } + + /// + /// Performs a search for work for the given virtual processor. + /// + bool SearchForWork(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass) + { + return m_searchCtx.Search(pWorkItem, pOriginSegment, fLastPass); + } + + /// + /// Performs a search for work for the given virtual processor only allowing certain types of work to be found. + /// + bool SearchForWork(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes) + { + return m_searchCtx.Search(pWorkItem, pOriginSegment, fLastPass, allowableTypes); + } + + /// + /// Performs a yielding search for work for the given virtual processor. + /// + bool SearchForWorkInYield(WorkItem *pWork, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass) + { + return m_searchCtx.YieldingSearch(pWork, pOriginSegment, fLastPass); + } + + /// + /// Performs a yielding search for work for the given virtual processor only allowing certain types of work to be found. + /// + bool SearchForWorkInYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes) + { + return m_searchCtx.YieldingSearch(pWorkItem, pOriginSegment, fLastPass, allowableTypes); + } + + /// + /// Stub called in SFW before we search for runnable contexts. + /// + /// + /// A context which should be run. + /// + virtual InternalContextBase *PreRunnableSearch() + { + return NULL; + } + + /// + /// Called when the context running atop this virtual processor has reached a safe point. + /// + /// + /// An indication of whether the caller should perform a commit. + /// + bool SafePoint(); + + /// + /// Gets a location object which represents the virtual processor. + /// + const location& GetLocation() const + { + return m_location; + } + + // + // TRANSITION: This goes with real priority. + // + void MarkGrabbedPriority() + { + m_fShortAffine = true; + } + + /// + /// Marks the segment as serviced at a particular time mark. + /// + void ServiceMark(ULONGLONG markTime) + { + // + // Avoid cache contention on this by only writing the service time every so often. We only care about this on granularities of something + // like 1/2 seconds anyway -- it's effectively the priority boost time granularity that we care about. + // + if (TimeSinceServicing(markTime) > 100) + m_lastServiceTime = markTime; + } + + /// + /// Returns the time delta between the last service time and the passed service time. + /// + ULONG TimeSinceServicing(ULONGLONG markTime) + { + return (ULONG)(markTime - m_lastServiceTime); + } + + /// + /// Returns a segment from its internal list entry. + /// + static VirtualProcessor* FromBoostEntry(BoostedObject *pEntry) + { + return CONTAINING_RECORD(pEntry, VirtualProcessor, m_priorityServiceLink); + } + + protected: + // + // protected data + // + + // Indicates whether vproc is available to perform work. + volatile AvailabilityType m_availabilityType{}; + + // Indicates how the current claimant acquired the vproc. + AvailabilityType m_claimantType{}; + + // Local caching of realized chores/contexts + StructuredWorkStealingQueue m_localRunnableContexts; + + // The search context which keeps track of where this virtual processor is in a search-for-work regardless of algorithm. + WorkSearchContext m_searchCtx; + + // Owning scheduling node + SchedulingNode *m_pOwningNode{}; + + // Owning ring - ring associated with the owning node + SchedulingRing *m_pOwningRing{}; + + // Owning virtual processor root + IVirtualProcessorRoot *m_pOwningRoot{}; + + // Sub allocator + SubAllocator *m_pSubAllocator{}; + + // Tracks the types of work that the virtual processor is currently operating on. + bool m_fAffine{}; + bool m_fLocal{}; + + // Once m_fAffine is clear, we need to post ONE notification to make sure that an affine search happens AFTER + // m_fAffine is set. This tracks the need for the ONE search. + bool m_fShortAffine{}; + + // The index that this Virtual Processor is at in its list array + int m_listArrayIndex{}; + + // Statistics data counters + unsigned int m_enqueuedTaskCounter{}; + unsigned int m_dequeuedTaskCounter{}; + + // Statistics data checkpoints + unsigned int m_enqueuedTaskCheckpoint{}; + unsigned int m_dequeuedTaskCheckpoint{}; + + // The context pushed to startup this virtual processor. + InternalContextBase *m_pPushContext{}; + + // Internal context that is affinitized to and executing on this virtual processor + // This is always an InternalContextBase except on UMS in very special circumstances. + IExecutionContext * volatile m_pExecutingContext{}; + + // The context which made the virtual processor available. + IExecutionContext * m_pAvailableContext{}; + + _HyperNonReentrantLock m_lock; + + // Unique identifier for vprocs within a scheduler. + unsigned int m_id{}; + + // The execution resource id for this virtual processor. + unsigned int m_resourceId{}; + + // The mask id assigned by the scheduler to this virtual processor. + unsigned int m_maskId{}; + + // Stashed location for this virtual processor. + location m_location; + + // The resource mask for this virtual processor. + QuickBitSet m_resourceMask; + + // Flag specifying whether this is a virtual processor created as a result of a call to Oversubscribe. + bool m_fOversubscribed{}; + + // Flag that is set when the virtual processor should remove itself from the scheduler at a yield point, + // i.e, either when the context executing on it calls Block or Yield, or when it is in the dispatch loop + // looking for work. + bool m_fMarkedForRetirement{}; + + // Whether this virtual processor has reached a safe point in the code + // Used to demark when all virtual processors have reached safe points and a list array deletion + // can occur + bool m_fReachedSafePoint{}; + + /// + /// Causes the virtual processor to remove itself from the scheduler. This is used either when oversubscription + /// ends or when the resource manager asks the vproc to retire. + /// + virtual void Retire(); + + // The internal context that caused this virtual processor to be created, if this is an oversubscribed vproc. + InternalContextBase * m_pOversubscribingContext{}; + + /// + /// Affinitizes an internal context to the virtual processor. + /// + /// + /// The internal context to affinitize. + /// + _Post_satisfies_(this->m_pExecutingContext == pContext) + virtual void Affinitize(InternalContextBase *pContext); + + /// + /// Returns a type-cast of pContext to an InternalContextBase or NULL if it is not. + /// + virtual InternalContextBase *ToInternalContext(IExecutionContext *pContext); + + /// + /// Initializes the virtual processor. This API is called by the constructor, and when a virtual processor is to + /// be re-initialized, when it is pulled of the free pool in the list array. + /// + /// + /// The owning schedule node for this virtual processor + /// + /// + /// The owning IVirtualProcessorRoot + /// + virtual void Initialize(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot); + + /// + /// Makes a virtual processor available for scheduling work. + /// + /// + /// Indicates whether the routine should update active state for the vproc based upon type or not. + /// + void MakeAvailable(AvailabilityType type, bool fCanChangeActiveState = true); + + private: + friend class SchedulerBase; + friend class ContextBase; + friend class InternalContextBase; + friend class ThreadInternalContext; + friend class ScheduleGroup; + friend class FairScheduleGroup; + friend class CacheLocalScheduleGroup; + friend class SchedulingNode; + friend class WorkSearchContext; + friend class ClaimTicket; + template friend class ListArray; + template friend class List; + + // Links for throttling + VirtualProcessor *m_pNext{}; + VirtualProcessor *m_pPrev{}; + + // Intrusive links for list array. + SLIST_ENTRY m_listArrayFreeLink{}; + + // The safe point marker. + SafePointMarker m_safePointMarker; + + // The last time this virtual processor's LRC was serviced. + ULONGLONG m_lastServiceTime{}; + + // + // TRANSITION: This is a temporary patch on livelock until we can tie into priority for livelock prevention. + // + bool m_prioritized{}; // Under m_priorityServiceLink's lock. + BoostedObject m_priorityServiceLink{}; + + /// + /// Exercises a claim over the virtual processor. + /// + bool ExerciseClaim(AvailabilityType type, ScheduleGroupSegmentBase *pSegment, InternalContextBase *pContext = NULL); + + /// + /// Start a worker context executing on this.virtual processor. + /// + virtual bool StartupWorkerContext(ScheduleGroupSegmentBase* pSegment, InternalContextBase *pContext = NULL); + + /// + /// Oversubscribes the virtual processor by creating a new virtual processor root affinitized to the same + /// execution resource as that of the current root + /// + /// + /// A virtual processor that oversubscribes this one. + /// + virtual VirtualProcessor * Oversubscribe(); + + /// + /// Marks the virtual processor such that it removes itself from the scheduler, once the context it is executing + /// reaches a safe yield point. Alternatively, if the context has not started executing yet, it can be retired immediately. + /// + void MarkForRetirement(); + + /// + /// Steals a context from the local runnables queue of this virtual processor. + /// + InternalContextBase *StealLocalRunnableContext() + { + InternalContextBase *pContext = NULL; + if (!m_localRunnableContexts.Empty()) + { + pContext = m_localRunnableContexts.Steal(); + } + + if (pContext != NULL) + { +#if defined(_DEBUG) + ::Concurrency::details::SetContextDebugBits(pContext, CTX_DEBUGBIT_STOLENFROMLOCALRUNNABLECONTEXTS); +#endif // _DEBUG + } + + return pContext; + } + + /// + /// Pops a runnable context from the local runnables queue of the vproc, if it can find one. + /// + InternalContextBase *GetLocalRunnableContext() + { + if (m_localRunnableContexts.Count() > 0) // Is this check worthwhile? Yes, I believe. We'd take a fence to check otherwise. + { + InternalContextBase *pContext = m_localRunnableContexts.Pop(); +#if defined(_DEBUG) + ::Concurrency::details::SetContextDebugBits(pContext, CTX_DEBUGBIT_POPPEDFROMLOCALRUNNABLECONTEXTS); +#endif // _DEBUG + return pContext; + } + return NULL; + } + + /// + /// Resets the count of work coming in. + /// + /// + /// This function is using modulo 2 behavior of unsigned ints to avoid overflow and + /// reset problems. For more detail look at ExternalStatistics class in externalcontextbase.h. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetEnqueuedTaskCount() + { + unsigned int currentValue = m_enqueuedTaskCounter; + unsigned int retVal = currentValue - m_enqueuedTaskCheckpoint; + + // Update the checkpoint value with the current value + m_enqueuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Resets the count of work being done. + /// + /// + /// This function is using modulo 2 behavior of unsigned ints to avoid overflow and + /// reset problems. For more detail look at the ExternalStatistics class in externalcontextbase.h. + /// + /// + /// Previous value of the counter. + /// + unsigned int GetDequeuedTaskCount() + { + unsigned int currentValue = m_dequeuedTaskCounter; + unsigned int retVal = currentValue - m_dequeuedTaskCheckpoint; + + // Update the checkpoint value with the current value + m_dequeuedTaskCheckpoint = currentValue; + + ASSERT(retVal < INT_MAX); + return retVal; + } + + /// + /// Send a virtual processor ETW event + /// + void TraceVirtualProcessorEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD vprocId) + { + if (g_TraceInfo._IsEnabled(level, VirtualProcessorEventFlag)) + ThrowVirtualProcessorEvent(eventType, level, schedulerId, vprocId); + } + + /// + /// Send a virtual processor ETW event + /// + static void ThrowVirtualProcessorEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD vprocId); + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92be47d75c46c65aee3cc7504604cc633aaf58db --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.cpp @@ -0,0 +1,137 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// VirtualProcessorRoot.cpp +// +// Part of the ConcRT Resource Manager -- this file contains the internal implementation for the base virtual +// processor root. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + // The current unique identifier being handed out to created virtual processor roots. + long VirtualProcessorRoot::s_currentId = 0; + + /// + /// Constructs a new virtual processor root. + /// + /// + /// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// + /// The processor node that this root belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + VirtualProcessorRoot::VirtualProcessorRoot(SchedulerProxy * pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex) + : m_pActivatedContext(NULL) + , m_executionResource(pSchedulerProxy, pNode, coreIndex) + , m_fRemovedFromScheduler(false) + , m_fOversubscribed(false) + , m_activationFence(0) + { + m_id = (unsigned int)InterlockedIncrement(&s_currentId); + m_executionResource.MarkAsVirtualProcessorRoot(this); + } + + /// + /// Called to indicate that a scheduler is done with a virtual processor root and wishes to return it to the resource manager. + /// + /// + /// The scheduler making the request to remove this virtual processor root. + /// + void VirtualProcessorRoot::Remove(IScheduler *pScheduler) + { + if (pScheduler == NULL) + throw std::invalid_argument("pScheduler"); + + if (GetSchedulerProxy()->Scheduler() != pScheduler) + throw invalid_operation(); + + ResetSubscriptionLevel(); + + // This particular call does not have to worry about the RM receiving a SchedulerShutdown for the scheduler proxy in question. + GetSchedulerProxy()->DestroyVirtualProcessorRoot(this); + } + + /// + /// Notifies the underlying RM that the core is subscribed by this root *if* necessary. + /// + void VirtualProcessorRoot::Subscribe() + { + // + // Note that there is a possibility in a race between activate/deactivate or activate/idle that we might race between the increment and + // decrement and see a subscription count of: + // + // 1->2->1 instead of 1->0->1 + // + // This *SHOULD* be fine in the RM layer and might even be a more desirable outcome so RM doesn't try to "give away" the idle core + // which is idle for a split second. In any case, it is noted here and can be fixed here if deemed necessary at a later point + // in time. + // + GetSchedulerProxy()->IncrementCoreSubscription(GetExecutionResource()); + } + + /// + /// Notifies the underlying RM that the core is not subscribed by this root *if* necessary. + /// + void VirtualProcessorRoot::Unsubscribe() + { + GetSchedulerProxy()->DecrementCoreSubscription(GetExecutionResource()); + } + + /// + /// This API is called when a virtual processor root is being destroyed. It removes the effect of this virtual processor root + /// on the subscription level for the underlying core. + /// + void VirtualProcessorRoot::ResetSubscriptionLevel() + { + + // + // This should **ONLY** be called in the remove path to quickly address the subscription level change. There's now a race between this + // happening from two different paths -- one a thread removing itself from a virtual processor via IThreadProxy::SwitchOut and another + // via the removal of said virtual processor via IVirtualProcessorRoot::Remove. + // + // Since the fence can only be 1 or 0 at this point (you can't race remove/activate or there's another bug at a higher level), only the + // entity which decrements the fence to 0 plays with the subscription level. + // + +#if defined(_DEBUG) + // + // Assert that there is no activate/remove race. We must snap the value of the fence as our observation might change between two + // reads. + // + LONG snapFence = m_activationFence; + ASSERT(snapFence == 0 || snapFence == 1); +#endif // _DEBUG + LONG newVal = InterlockedDecrement(&m_activationFence); + if (newVal == 0) + { + // + // The virtual processor was in an activated state when it was removed -- we need to reduce the subscription level here. + // + Unsubscribe(); + } + else + { + // + // The value could be -1 if we raced with the virtual processor switching out. + // + ASSERT(newVal == -1); + } + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.h new file mode 100644 index 0000000000000000000000000000000000000000..b041cb8685fb9df1bc7799b4ac7dcb7badd9e321 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/VirtualProcessorRoot.h @@ -0,0 +1,258 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// VirtualProcessorRoot.h +// +// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the base virtual +// processor root. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ + /// + /// An abstraction for a virtual processor -- an entity on top of which a single thread of execution (of whatever + /// type) runs. Note that there are specific derived classes for free and bound virtual processor roots -- necessary + /// so as to easily hand out different types of thread proxies and message thread proxies upon Activate for bound + /// schedulers, etc... + /// + class VirtualProcessorRoot : public IVirtualProcessorRoot + { + public: + + /// + /// Constructs a new virtual processor root. + /// + /// + /// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of + /// a scheduler. + /// + /// + /// The processor node that this root belongs to. The processor node is one among the nodes allocated to the + /// scheduler proxy. + /// + /// + /// The index into the array of cores for the processor node specified. + /// + VirtualProcessorRoot(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex); + + /// + /// Destroys a virtual processor root. + /// + virtual ~VirtualProcessorRoot() + { + } + + /// + /// Returns a unique identifier for the virtual processor root. + /// + virtual unsigned int GetId() const + { + return m_id; + } + + /// + /// Returns a unique identifier for the node that the given virtual processor root belongs to. The identifier returned + /// will fall in the range [0, nodeCount] where nodeCount is the value returned from Concurrency::GetProcessorNodeCount. + /// + virtual unsigned int GetNodeId() const + { + return m_executionResource.GetNodeId(); + } + + /// + /// Returns a unique identifier for the execution resource that this virtual processor root runs atop. + /// + virtual unsigned int GetExecutionResourceId() const + { + return m_executionResource.GetExecutionResourceId(); + } + + /// + /// Causes the scheduler to start running a thread proxy on the specified virtual processor root which will execute + /// the Dispatch method of the context supplied by pContext. + /// + /// + /// The context which will be dispatched on a (potentially) new thread running atop this virtual processor root. + /// + virtual void Activate(::Concurrency::IExecutionContext *pContext) =0; + + /// + /// Causes the thread proxy running atop this virtual processor root to temporarily stop dispatching pContext. + /// + /// + /// The context which should temporarily stop being dispatched by the thread proxy running atop this virtual processor root. + /// + virtual bool Deactivate(::Concurrency::IExecutionContext *pContext) =0; + + /// + /// Forces all data in the memory heirarchy of one processor to be visible to all other processors. + /// + /// + /// The context which is currently being dispatched by this root. + /// + virtual void EnsureAllTasksVisible(::Concurrency::IExecutionContext *pContext) =0; + + /// + /// Called to indicate that a scheduler is done with a virtual processor root and wishes to return it to the resource manager. + /// + /// + /// The scheduler making the request to remove this virtual processor root. + /// + virtual void Remove(IScheduler *pScheduler); + + /// + /// Returns a number of active virtual processors and external threads running on top of the execution resource + /// associated with this virtual processor root. + /// + /// + /// A current subscription level of the underlying execution resource. + /// + virtual unsigned int CurrentSubscriptionLevel() const + { + return m_executionResource.CurrentSubscriptionLevel(); + } + + // ************************************************** + // Internal + // ************************************************** + + /// + /// Returns a pointer to the scheduler proxy this virtual processor root was created by. + /// + SchedulerProxy * GetSchedulerProxy() + { + return m_executionResource.GetSchedulerProxy(); + } + + /// + /// Returns the core index into the array of cores, for the node that this virtual processor root is part of. + /// + int GetCoreIndex() + { + return m_executionResource.GetCoreIndex(); + } + + /// + /// Retrieves an underlying execution resource. + /// + ExecutionResource * GetExecutionResource() + { + return &m_executionResource; + } + + /// + /// Helpers to prevent from removing a virtual processor root twice. We remove the root from the list in the allocated + /// nodes when the corresponding vprocroot::Remove call is made. + /// + bool IsRootRemoved() { return m_fRemovedFromScheduler; } + void MarkRootRemoved() { m_fRemovedFromScheduler = true; } + + /// + /// Deletes the virtual processor. + /// + virtual void DeleteThis() =0; + + /// + /// Notifies the underlying RM that the core is subscribed by this root *if* necessary. + /// + void Subscribe(); + + /// + /// Notifies the underlying RM that the core is not subscribed by this root *if* necessary. + /// + void Unsubscribe(); + + /// + /// This API is called when a virtual processor root is being destroyed. It removes the effect of this virtual processor root + /// on the subscription level for the underlying core. + /// + void ResetSubscriptionLevel(); + + /// + /// Sets the activated context to the specified value. + /// + void SetActivatedContext(::Concurrency::IExecutionContext *pContext) + { + // + // The below need not be atomic but must have at least write release semantics. + // + InterlockedExchangePointer(reinterpret_cast(&m_pActivatedContext), pContext); + } + + /// + /// Gets the activated context and simultaneously sets it to NULL. + /// + ::Concurrency::IExecutionContext *AcquireActivatedContext() + { + // + // Once this is set, we are the only entity that will ever acquire/reset. We simply need to wait for the set which may + // be a few instructions behind. + // + _SpinWaitBackoffNone spinWait(_Sleep0); + while (m_pActivatedContext == NULL) + { + spinWait._SpinOnce(); + } + + // + // The only entity which will subsequently set this won't come until after this has happened and we woke up another thread. This + // need not be atomic or have barrier semantics. + // + ::Concurrency::IExecutionContext *pActivatedContext = m_pActivatedContext; + m_pActivatedContext = NULL; + + return pActivatedContext; + } + + /// + /// This API is called by the RM to indicate that this vproc does not contribute towards concurrency limits + /// set by the user + /// + void MarkAsOversubscribed() + { + m_fOversubscribed = true; + } + + /// + /// Returns true if this is an oversubscribed vproc. + /// + bool IsOversubscribed() + { + return m_fOversubscribed; + } + + protected: + + // Internal context that was last activated. This is used to resolve activate/deactivate,idle races. + IExecutionContext * volatile m_pActivatedContext; + + // Execution resource underneath this virtual processor root + ExecutionResource m_executionResource; + + // Set to true when a RemoveVirtualProcessors call has been made on the corresponding scheduler interface for this + // virtual processor root. + bool m_fRemovedFromScheduler; + + // Flag to distinguish vprocs that were created through CreateOversubscribe() call. + bool m_fOversubscribed; + + // The process unique identifier assigned to this virtual processor root. + unsigned int m_id; + + // Fence used to avoid kernel transitions with activation/deactivation races. + volatile LONG m_activationFence; + + private: + + // The current unique identifier being handed out to created virtual processor roots. + static long s_currentId; + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dd73c79967016d704e9c91b05edfd86b3080da4 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.cpp @@ -0,0 +1,81 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// WinRTWrapper.cpp +// +// Dynamic wrappers around Windows Runtime functions. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + + volatile LONG WinRT::s_fInitialized = FALSE; + HMODULE WinRT::m_hModule = NULL; + + /// + /// Initializes all static function pointers to Windows Runtime functions. We do not call or link against these for distribution + /// against OS's below Windows 8. + /// + void WinRT::Initialize() + { +#if !defined(_ONECORE) + // + // There is no guarantee that combase.dll is loaded in the process unless it's compiled /ZW. Make sure that combase.dll sticks + // around. + // + // TODO: It might be nice to FreeLibrary this at some point in the future and not hold it until end of process. At the very least, + // it needs to live until the end of the RM and synchronize with anyone else touching these APIs. + // + m_hModule = LoadLibraryExW(L"combase.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (m_hModule == NULL) + { + ASSERT(GetLastError() != ERROR_INVALID_PARAMETER); + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + + GETPROC_FROM_MODULE_HANDLE(m_hModule, RoInitialize); + GETPROC_FROM_MODULE_HANDLE(m_hModule, RoUninitialize); +#endif //!defined(_ONECORE) + + InterlockedExchange(&s_fInitialized, TRUE); + } + + /// + /// Returns whether or not the Windows Runtime wrappers have been initialized yet. + /// + bool WinRT::Initialized() + { + return (s_fInitialized != FALSE); + } + +#if !defined(_ONECORE) + DEFINE_STATIC_WRAPPER_FN_1(WinRT, RoInitialize, HRESULT, RO_INIT_TYPE); + DEFINE_STATIC_WRAPPER_FN(WinRT, RoUninitialize, void); + +#else + // The threads created under MSDK come from WINRT thread-pool. They are already + // initialized appropriately. These functions are just noops. + HRESULT WinRT::RoInitialize(RO_INIT_TYPE) + { + return S_OK; + } + + void WinRT::RoUninitialize() + { + + } +#endif //!defined(_ONECORE) + + + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..6b3802e157dedfc212d553cd42629eed3bca9244 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WinRTWrapper.h @@ -0,0 +1,89 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// WinRTWrapper.h +// +// Dynamic wrappers around Windows Runtime functions. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +#define DEFINE_STATIC_WRAPPER_FN(classname, name, rt) \ + classname ::Pfn_ ## name classname ::s_pfn_ ## name;\ + rt classname :: name() \ + {\ + Pfn_ ## name pfn = (Pfn_ ## name) Security::DecodePointer(s_pfn_ ## name); \ + ASSERT(pfn != NULL);\ + return pfn();\ + } + +#define DECLARE_STATIC_WRAPPER_FN(name, rt) \ + public:\ + static rt name();\ + private:\ + typedef rt (WINAPI *Pfn_ ## name)();\ + static Pfn_ ## name s_pfn_ ## name; + +#define DEFINE_STATIC_WRAPPER_FN_1(classname, name, rt, a1t) \ + classname ::Pfn_ ## name classname ::s_pfn_ ## name;\ + rt classname :: name(a1t a1) \ + {\ + Pfn_ ## name pfn = (Pfn_ ## name) Security::DecodePointer(s_pfn_ ## name); \ + ASSERT(pfn != NULL);\ + return pfn(a1);\ + } + +#define DECLARE_STATIC_WRAPPER_FN_1(name, rt, a1t) \ + public:\ + static rt name(a1t);\ + private:\ + typedef rt (WINAPI *Pfn_ ## name)(a1t);\ + static Pfn_ ## name s_pfn_ ## name; + +#define GETPROC_FROM_MODULE_HANDLE(module_handle, name) \ + {\ + Pfn_ ## name pfn = (Pfn_ ## name)(GetProcAddress(module_handle, #name));\ + if (pfn == NULL) throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));\ + s_pfn_ ## name = (Pfn_ ## name) Security::EncodePointer(pfn);\ + } + +namespace Concurrency +{ +namespace details +{ + class WinRT + { + public: + + /// + /// Initializes all static function pointers to Windows Runtime functions. We do not call or link against these for distribution + /// against OS's below Win8. + /// + static void Initialize(); + + /// + /// Returns whether or not the Windows Runtime wrappers have been initialized yet. + /// + static bool Initialized(); + +#if !defined(_ONECORE) + DECLARE_STATIC_WRAPPER_FN_1(RoInitialize, HRESULT, RO_INIT_TYPE); + DECLARE_STATIC_WRAPPER_FN(RoUninitialize, void); +#else + static HRESULT RoInitialize(RO_INIT_TYPE); + static void RoUninitialize(); +#endif // !defined(_ONECORE) + + private: + + static HMODULE m_hModule; + static volatile LONG s_fInitialized; + + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkQueue.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkQueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e799bfab927362efef361c838b4bd927cf33a6a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkQueue.cpp @@ -0,0 +1,251 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// workqueue.cpp +// +// Work stealing queues pair implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// Constructs a new work queue. + /// + WorkQueue::WorkQueue() + : m_structuredQueue(&m_lock) + , m_detachmentState(QUEUE_ATTACHED) + , m_pOwningContext(NULL) + , m_unstructuredQueue(&m_lock) + { + m_detachment.m_listArrayIndex = 0; + m_detachment.m_pObject = this; + m_id = SchedulerBase::GetNewWorkQueueId(); + } + + /// + /// Steal a chore from the work stealing queue for unrealized parallelism. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + _UnrealizedChore *WorkQueue::UnlockedSteal(bool fForceStealLocalized) + { + if (IsEmpty()) + return NULL; + + // + // Make certain we do not steal from a canceled context. The exception handling will properly unwind this. This avoids a degree on infighting + // on cancellation. When a subtree which has stolen chores is canceled, the stealing threads are canceled, unwind, and immediately become available + // for stealing. They can easily pick up a region of the tree where exception handling has not unwound to the cancellation point and the exception + // handlers wind up in a little battle with the stealing threads (the exception handlers shooting down contexts and the contexts stealing different + // pieces of the tree, wash, rinse, repeat). In order to avoid *some* of the contention, we simply will refuse to steal from any context which was + // shot down as part of a subtree cancellation. + // + // Further, as an optimization, we do temporarily suspend stealing from a context which has an inflight cancellation -- even if the stealing happens + // in a different piece of the subtree than being canceled. This allows us to avoid yet more infighting during a cancellation. It should be a rare + // enough event that the suspension of stealing from that context during the in flight cancel shouldn't hurt performance. Note that this is the difference + // between the pCheckContext->HasInlineCancellation() and a pCheckContext->IsEntireContextCanceled() below. The latter would only check fully canceled + // contexts. The former does the suspension on contexts with in flight cancellations. + // + // Allow stealing to occur from a blocked context as it could be relying on stolen chores to make further progress. + // + + _UnrealizedChore *pResult = NULL; + ContextBase *pOwningContext = m_pOwningContext; + if (pOwningContext != NULL && pOwningContext->HasInlineCancellation() && !pOwningContext->IsSynchronouslyBlocked()) + { + // + // There is a scenario that we need to be extraordinarily careful of here. Normally, we could just ignore the steal. Unfortunately, + // it's entirely possible that a detached queue was reused on a context (A) and then A became cancelled while we waited on a task + // collection that had chores in the detached region. This would lead to deadlock. We need to allow stealing from the region of + // the WSQ which was detached. + // + // m_unstructuredQueue may contains tasks from task collections that are not being canceled. However, we cannot quickly detect the difference. Thus + // before arbitrary stealing from m_unstructuredQueue, we need to finish cancellation of the task collections that need to be canceled, which is why + // pOwningContext->HasInlineCancellation() is true. Cancellation is over when pOwningContext->HasInlineCancellation() is false and then uninhibited + // stealing from m_unstructuredQueue may occur again. However, in the meantime, stealing threads may go idle because no work can be found and if + // m_pOwningContext exits w/o waiting, there may be work left to execute, but all vprocs are idle. This 'deadlock' is prevented by calling + // NotifyWorkSkipped() that assures an associated vproc will not go idle without verifying there is no work left by executing this function again. + // + if (m_unstructuredQueue.MarkedForDetachment()) + pResult = (_UnrealizedChore *) m_unstructuredQueue.UnlockedSteal(fForceStealLocalized, true); + if (pResult != NULL) + pResult->_SetDetached(true); + else + static_cast(SchedulerBase::FastCurrentContext())->NotifyWorkSkipped(); + } + else + { + pResult = (_UnrealizedChore *) m_structuredQueue.UnlockedSteal(fForceStealLocalized); + + // + // Structured does not need to deal with detachment and cancellation references, simply return the value. + // + if (pResult != NULL) + return pResult; + + pResult = (_UnrealizedChore *) m_unstructuredQueue.UnlockedSteal(fForceStealLocalized, false); + + // + // If we stole and there is an owning context and it's not a detached steal (which always goes on the task collection list), keep the owning context + // alive until the wrapper can add the task to the appropriate cancellation list. Since we're holding the workqueue lock, we can safely access m_pOwningContext. + // NOTE: pResult is unstructured. + // + if (pResult != NULL) + { + if (m_pOwningContext != NULL + && reinterpret_cast (pResult->_OwningCollection()->_OwningContext()) == m_pOwningContext) + { + m_pOwningContext->ReferenceForCancellation(); + pResult->_SetDetached(false); + } + else + { + pResult->_SetDetached(true); + } + } + } + + return pResult; + } + + /// + /// Attempts to steal an unrealized chore from the unstructured work stealing queue. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + /// + /// The try lock was successfully acquired. + /// + /// + /// An unrealized chore stolen from the work stealing queues or NULL if no such chore can be stolen + /// + _UnrealizedChore *WorkQueue::TryToSteal(bool fForceStealLocalized, bool& fSuccessfullyAcquiredLock) + { + _UnrealizedChore *pResult = NULL; + if (m_lock._TryAcquire()) + { + __try + { + pResult = UnlockedSteal(fForceStealLocalized); + } + __finally + { + m_lock._Release(); + } + fSuccessfullyAcquiredLock = true; + } + else + fSuccessfullyAcquiredLock = false; + + return pResult; + } + + /// + /// Steal a chore from both work stealing queues. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + _UnrealizedChore* WorkQueue::Steal(bool fForceStealLocalized) + { + _CriticalNonReentrantLock::_Scoped_lock lockHolder(m_lock); + return UnlockedSteal(fForceStealLocalized); + } + + /// + /// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them + /// based on the result of a callback. + /// + /// + /// The predicate for things to call pSweepFn on. + /// + /// + /// The data for the predicate callback + /// + /// + /// The sweep function + /// + void WorkQueue::SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate, + void *pData, + WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn + ) + { + m_unstructuredQueue.Sweep(pPredicate, pData, pSweepFn); + } + + /// + /// Causes a detached work queue to release its reference on the passed-in schedule group and remove itself from that schedule group's + /// list of work queues at the next available safe point. + /// + void WorkQueue::RetireAtSafePoint(ScheduleGroupSegmentBase *pSegment) + { + m_pDetachedSegment = pSegment; + m_detachmentSafePoint.InvokeAtNextSafePoint(reinterpret_cast(&WorkQueue::StaticRetire), + this, + pSegment->GetGroup()->GetScheduler()); + } + + /// + /// Causes a detached work queue to redetach due to roll-back of retirement at the next available safe point. + /// + void WorkQueue::RedetachFromScheduleGroupAtSafePoint(ScheduleGroupSegmentBase *pSegment) + { + m_pDetachedSegment = pSegment; + m_detachmentSafePoint.InvokeAtNextSafePoint(reinterpret_cast(&WorkQueue::StaticRedetachFromScheduleGroup), + this, + pSegment->GetGroup()->GetScheduler()); + } + + /// + /// Retires the detached work queue. + /// + void WorkQueue::StaticRetire(WorkQueue *pQueue) + { + pQueue->m_pDetachedSegment->RetireDetachedQueue(pQueue); + } + + /// + /// Places the work queue back in a detached state on roll back. + /// + void WorkQueue::StaticRedetachFromScheduleGroup(WorkQueue *pQueue) + { + pQueue->m_pDetachedSegment->RedetachQueue(pQueue); + } + + /// + /// Reinitialize a work queue pulled from a free pool + /// + void WorkQueue::Reinitialize() + { + // Grab steal locks, this will prevent other readers from grabbing this work + // queue while we are reinitializing (h=t=0 is non-atomic, is it worth it to fix?) + m_lock._Acquire(); + m_id = SchedulerBase::GetNewWorkQueueId(); + // Reinitialize the reused workqueue + m_structuredQueue.Reinitialize(); + m_unstructuredQueue.Reinitialize(); + m_detachmentState = QUEUE_ATTACHED; + m_pOwningContext = NULL; + // Release the work queue locks + m_lock._Release(); + } + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkStealingQueue.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkStealingQueue.h new file mode 100644 index 0000000000000000000000000000000000000000..0baf7c9e091628aab3dd4f9a3bb3984c9e3baad3 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/WorkStealingQueue.h @@ -0,0 +1,697 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// WorkStealingQueue.h +// +// Header file containing the core implementation of the work stealing data structures and algorithms. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +#define AFFINITY_EXECUTED 0x1 +#define IS_AFFINITIZED_TASK(t) ((ULONG_PTR)t & 0x1) +#define STRIP_AFFINITY_INDICATOR(type, t) ((type *)((ULONG_PTR)t & ~((ULONG_PTR)0x1))) +#define ADD_AFFINITY_INDICATOR(type, t) ((type *)((ULONG_PTR)(t) | 0x1)) + +namespace Concurrency +{ +namespace details +{ + /// + /// A WorkStealingQueue is a wait-free, lock-free structure associated with a single + /// thread that can Push and Pop elements. Other threads can do Steal operations + /// on the other end of the WorkStealingQueue with little contention. + /// + template + class WorkStealingQueue + { + // A 'WorkStealingQueue' always runs its code in a single OS thread. We call this the + // 'bound' thread. Only the code in the Steal operation can be executed by + // other 'foreign' threads that try to steal work. + // + // The queue is implemented as an array. The m_head and m_tail index this + // array. To avoid copying elements, the m_head and m_tail index the array modulo + // the size of the array. By making this a power of two, we can use a cheap + // bit-and operation to take the modulus. The "m_mask" is always equal to the + // size of the task array minus one (where the size is a power of two). + // + // The m_head and m_tail are volatile as they can be updated from different OS threads. + // The "m_head" is only updated by foreign threads as they Steal a task from + // this queue. By putting a lock in Steal, there is at most one foreign thread + // changing m_head at a time. The m_tail is only updated by the bound thread. + // + // invariants: + // tasks.length is a power of 2 + // m_mask == tasks.length-1 + // m_head is only written to by foreign threads + // m_tail is only written to by the bound thread + // At most one foreign thread can do a Steal + // All methods except Steal are executed from a single bound thread + // m_tail points to the first unused location + // + // This work stealing implementation also supports the notion of out-of-order waiting + // and out-of-order removal from the bound thread given that it is initialized to do so. + // There is additional cost to performing this. + // + + public: + + /// + /// The callback for a sweep of the workstealing queue. This will be called under the stealing lock on the owning thread + /// for every chore matching a predefined predicate. If true is returned, the item is pulled from the WSQ. If false is returned, + /// the item stays in the WSQ. + /// + typedef bool (*SweepFunction)(T *pObject, void *pData); + + /// + /// A predicate for a WSQ sweep. + /// + typedef bool (*SweepPredicate)(T *pObject, void *pData); + + + /// + /// Constructs a new work stealing queue + /// + WorkStealingQueue(LOCK *pLock) + : m_pLock(pLock) + { + ASSERT(m_pLock != NULL); + ASSERT(s_initialSize > 1); + Reinitialize(); + m_mask = s_initialSize - 1; + m_pTasks = _concrt_new T*[s_initialSize]; + m_pSlots = _concrt_new typename Mailbox::Slot[s_initialSize]; + } + + /// + /// Reinitializes a workqueue to the state just after construction. This is used when recycling a work + /// queue from its ListArray + /// + void Reinitialize() + { + m_head = 0; + m_tail = 0; + m_detachmentTail = 0; + m_fMarkedForDetachment = false; + m_cookieBase = 0; + } + + /// + /// Unlocked count + /// + int Count() const + { + return (m_tail - m_head); + } + + /// + /// Unlocked check if empty + /// + bool Empty() const + { + return (m_tail - m_head <= 0); + } + + /// + /// Check whether to skip the steal + /// + bool MarkedForDetachment() const + { + return m_fMarkedForDetachment; + } + + // + // Push/Pop and Steal can be executed interleaved. In particular: + // 1) A steal and pop should be careful when there is just one element + // in the queue. This is done by first incrementing the m_head/decrementing the m_tail + // and than checking if it interleaved (m_head > m_tail). + // 2) A push and steal can interleave in the sense that a push can overwrite the + // value that is just stolen. To account for this, we check conservatively in + // the push to assume that the size is one less than it actually is. + // + + /// + /// Attempts to steal the oldest element in the queue. This handles potential interleaving with both + /// a Pop and TryPop operation. + /// + T* UnlockedSteal(bool fForceStealLocalized, bool = false) + { + T* pResult = NULL; + + for (;;) + { + // + // increment the m_head. Save in local h for efficiency + // + int h = m_head; + + InterlockedExchange((volatile LONG*)&m_head, h + 1); + + // + // insert a memory fence here -- memory may not be sequentially consistent + // + + if (0 < m_tail - h) + { + // + // Do not allow a steal from this work stealing queue if the bottom task was mailed to a location which has active searchers. + // This will not block finalization in any way as the last pass SFW will pull the task out of the mailbox regardless of affinity. + // We should be careful not to do this if the current context's virtual processor is in the affinity set of the segment. + // If not, there could be cases where all virtual processors deactivate, but the scheduler does not shutdown since there are chores + // in the queue, even if they have been dequeued via the mailbox. + // + if(IS_AFFINITIZED_TASK(m_pTasks[h & m_mask])) + { + if (!fForceStealLocalized && m_pSlots[h & m_mask].DeferToAffineSearchers()) + { + // + // Skip this workqueue if there are affine searchers and we are not one of them. + // + m_head = h; + return NULL; + } + } + + // + // If the queue is detached and we've crossed the point of detachment, end the detachment marker. + // + if (m_fMarkedForDetachment && 0 >= m_detachmentTail - m_head) + m_fMarkedForDetachment = false; + + // + // == (h+1 <= m_tail) == (m_head <= m_tail) + // + // When we allow out-of-order waits, it's entirely possible that a TryPop + // executing on the bound thread will grab this out from underneath us. Not + // only do we need guards against interleave with ordered pop, but we also + // need a guard against an out-of-order trypop. + // + pResult = reinterpret_cast (InterlockedExchangePointer( + reinterpret_cast( &(m_pTasks[h & m_mask])), + (PVOID) NULL + )); + + if (pResult != NULL) + { + // + // If the task had an associated affinity, we must deal with the possibility that it was already executed by a virtual + // processor to which it was affine. + // + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, move on and try to steal again. + // + if (!m_pSlots[h & m_mask].Claim()) + { + pResult = NULL; + continue; + } + } + break; + } + } + else + { + // + // failure: either empty or single element interleaving with pop + // + m_head = h; // restore the m_head + break; + } + } + + return pResult; + } + + // only used in a test + T* Steal(bool fForceStealLocalized = false) + { + typename LOCK::_Scoped_lock lockHolder(*m_pLock); + return UnlockedSteal(fForceStealLocalized); + } + + /// + /// Attempts to pop the newest element on the work stealing queue. It may return NULL if there is no such + /// item (either unbalanced push/pop, a chore stolen) + /// + T* Pop() + { + T* pResult = NULL; + int t; + + for(;;) + { + // + // decrement the m_tail. Use local t for efficiency. + // + t = m_tail - 1; + InterlockedExchange((volatile LONG*)&m_tail, t); + + // + // insert a memory fence here (InterlockedExchange does the job) -- + // memory may not be sequentially consistent + // + + if (0 <= t - m_head) + { + // + // == (m_head <= m_tail) + // + pResult = m_pTasks[t & m_mask]; + + // + // Out of order TryPops on the bound thread will set this without + // the need for a fence. + // + if (pResult == NULL) continue; + break; + } + else + { + // + // failure: either empty or single element interleaving with steal + // + m_tail = t + 1; // restore the m_tail + return SyncPop(); // do a single-threaded pop + } + } + + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, return an indication to the caller. + // + if (!m_pSlots[t & m_mask].Claim()) + { + return (T*)AFFINITY_EXECUTED; + } + } + + return pResult; + } + + /// + /// Tries to pop a previously pushed element from the work stealing queue. Note that this executes + /// a potentially out-of-order wait. + /// + /// + /// The value returned from a Push() call for the work in question + /// + T* TryPop(int cookie) + { + cookie = (cookie - m_cookieBase); + + // + // TryPop() has Pop() semantics if we try the topmost element. We only need to do something + // "special" in the out of order case. + // + if (cookie == m_tail - 1) return Pop(); + + if (cookie - m_tail >= 0 || cookie - m_head < 0) return NULL; + + T* pResult = reinterpret_cast (InterlockedExchangePointer( + reinterpret_cast( &(m_pTasks[cookie & m_mask])), + (PVOID) NULL + )); + + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, return an indication to the caller. + // + if (!m_pSlots[cookie & m_mask].Claim()) + { + return (T*)AFFINITY_EXECUTED; + } + } + + return pResult; + + } + + /// + /// Pushes an element onto the work stealing queue. The returned cookie can be utilized to identify + /// the work item for a future TryPop() call. Note that the returned cookie is only valid until a Pop() + /// or TryPop() call removes the work in question. + /// + int Push(T* elem, typename ::Concurrency::details::Mailbox::Slot affinitySlot) + { + int t = m_tail; + // + // Careful here since we might interleave with Steal. + // This is no problem since we just conservatively check if there is + // enough space left (t < m_head + size). However, Steal might just have + // incremented m_head and we could potentially overwrite the old m_head + // entry, so we always leave at least one extra 'buffer' element and + // check (m_tail < m_head + size - 1). This also plays nicely with our + // initial m_mask of 0, where size is 2^0 == 1, but the tasks array is + // still null. + // + if (0 < m_head + m_mask - t) // == t < m_head + size - 1 + { + if (!affinitySlot.IsEmpty()) + { + // + // Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent + // multiple execution. + // + m_pSlots[t & m_mask] = affinitySlot; + elem = ADD_AFFINITY_INDICATOR(T, elem); + } + m_pTasks[t & m_mask] = elem; + // Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models + m_tail = t + 1; + return t + m_cookieBase; + } + else + { + // + // failure: we need to resize or re-index + // + return SyncPush(elem, affinitySlot); + } + } + + /// + /// Pushes an element onto the work stealing queue. The returned cookie can be utilized to identify + /// the work item for a future TryPop() call. Note that the returned cookie is only valid until a Pop() + /// or TryPop() call removes the work in question. + /// + int Push(T* elem) + { + int t = m_tail; + // + // Careful here since we might interleave with Steal. + // This is no problem since we just conservatively check if there is + // enough space left (t < m_head + size). However, Steal might just have + // incremented m_head and we could potentially overwrite the old m_head + // entry, so we always leave at least one extra 'buffer' element and + // check (m_tail < m_head + size - 1). This also plays nicely with our + // initial m_mask of 0, where size is 2^0 == 1, but the tasks array is + // still null. + // + if (0 < m_head + m_mask - t) // == t < m_head + size - 1 + { + m_pTasks[t & m_mask] = elem; + // Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models + m_tail = t + 1; + return t + m_cookieBase; + } + else + { + // + // failure: we need to resize or re-index + // + return SyncPush(elem, Mailbox::Slot()); + } + } + + /// + /// Only called from the bound thread, this sweeps the work stealing queue under the steal lock for any chores matching the + /// specified predicate. + /// + void Sweep(SweepPredicate pPredicate, void *pData, SweepFunction pSweepFn) + { + typename LOCK::_Scoped_lock lockHolder(*m_pLock); + + int nt = m_tail; + int t = m_tail - 1; + + while (t - m_head >= 0) + { + T* pResult = m_pTasks[t & m_mask]; + if (pResult != NULL) + { + if (pPredicate(pResult, pData)) + { + if (pSweepFn(pResult, pData)) + { + // + // If it's atop the WSQ, just decrement the tail (nt == new tail); otherwise, + // make sure to NULL out the entry to indicate an out-of-order rip. + // + if (t + 1 == nt) + nt--; + else + m_pTasks[t & m_mask] = NULL; + } + } + } + + t--; + } + + InterlockedExchange((volatile LONG *)&m_tail, nt); + } + + /// + /// Marks the work stealing queue as detached. The current head pointer marks the end point of detachment. Note + /// that this should only be called when there is a guarantee of no concurrent pushes or pops from the owning thread. + /// + void MarkDetachment() + { + typename LOCK::_Scoped_lock lockHolder(*m_pLock); + m_fMarkedForDetachment = true; + m_detachmentTail = m_tail; + } + + /// + /// Destroys a work stealing queue. + /// + ~WorkStealingQueue() + { + delete [] m_pTasks; + delete [] m_pSlots; + } + + private: + + // The m_head and m_tail are volatile as they can be updated from different OS threads. + // The "m_head" is only updated by foreign threads as they Steal a task from + // this queue. By putting a lock in Steal, there is at most one foreign thread + // changing m_head at a time. The m_tail is only updated by the bound thread. + // + // invariants: + // tasks.length is a power of 2 + // m_mask == tasks.length-1 + // m_head is only written to by foreign threads + // m_tail is only written to by the bound thread + // At most one foreign thread can do a Steal + // All methods except Steal are executed from a single bound thread + // m_tail points to the first unused location + // + + static const int s_initialSize = 64; // must be a power of 2 + volatile int m_head; // only updated by Steal + volatile int m_tail; // only updated by Push and Pop + + int m_mask; // the m_mask for taking modulus + int m_cookieBase; // the base cookie index + + LOCK *m_pLock; // the lock that guards stealing from push/pops + + bool m_fMarkedForDetachment; // Indicates whether or not the work stealing queue is marked for detachment + int m_detachmentTail; // The tail pointer for detachment. When the head crosses this, the mark ends + + T** m_pTasks; // the array of tasks + typename Mailbox::Slot *m_pSlots; // the array of side-band affinity structures + + /// + /// Pushes an element onto the work stealing queue under the queue lock. This guarantees that no steal + /// interleaves and guarantees the ability to reallocate the physical store. The returned value is a cookie + /// per Push(). + /// + int SyncPush(T* elem, typename ::Concurrency::details::Mailbox::Slot affinitySlot) + { + // + // Because WorkStealingQueue is used for LRC and LRC needs to be searched in a SFW from a UMS primary, the lock here is a hyper + // lock and no memory allocations can happen inside its scope. Preallocate everything up front! + // + // Keep in mind that the only thing that's going to happen without the lock held is a steal. No one else will try to resize, + // pop, push, etc... + // + // + // == (count >= size-1) + // + int oldsize = m_mask + 1; + int newsize = 2 * oldsize; // highly unlikely, but throw out-of-memory if this overflows + + // + // Yes -- it's entirely possible that we allocate and DON'T need to in rare circumstances - steal just opened up a slot. In that particular + // case, we will just do the resizing since it's almost full. + // + T** pNewTasks = _concrt_new T*[newsize]; + // + // Again, for reasons of UMS, we cannot delete the old array until after we release the hyper lock. Stash it away + // and defer the deletion. + // + T** pOldTasks = m_pTasks; + + typename Mailbox::Slot *pNewSlots = _concrt_new typename Mailbox::Slot[newsize]; + typename Mailbox::Slot *pOldSlots = m_pSlots; + + { + // + // ensure that no Steal interleaves here + // + typename LOCK::_Scoped_lock lockHolder(*m_pLock); + + // + // cache m_head, and calculate number of tasks + // + int h = m_head; + const int count = m_tail - h; + + // + // normalize indices + // + h = h & m_mask; // normalize m_head + m_cookieBase += m_tail - (h + count); + m_head = h; + m_tail = h + count; + +#pragma warning(push) +#pragma warning(disable:26010) + + // we get here the first time we've overflowed, + // so as long as m_mask >= 1, which is asserted in the ctor, there's plenty of room + CONCRT_COREASSERT(count < newsize); + CONCRT_COREASSERT(pNewTasks != NULL); + for (int i = 0; i < count; ++i) + { + pNewTasks[i] = m_pTasks[(h + i) & m_mask]; + pNewSlots[i] = m_pSlots[(h + i) & m_mask]; + } + + m_pTasks = pNewTasks; + m_pSlots = pNewSlots; + +#pragma warning(pop) + + // + // Rebase the cookie index. We can't hand out duplicate cookies due to this. + // + m_cookieBase += m_head; + + // + // Rebase the detachment point if necessary. + // + if (m_fMarkedForDetachment) + { + CONCRT_COREASSERT(m_detachmentTail - m_head >= 0); + m_detachmentTail -= m_head; + } + + m_mask = newsize - 1; + m_head = 0; + m_tail = count; + + CONCRT_COREASSERT(count < m_mask); + + // + // push the element + // + int t = m_tail; + + if (!affinitySlot.IsEmpty()) + { + // + // Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent + // multiple execution. + // + m_pSlots[t & m_mask] = affinitySlot; + elem = ADD_AFFINITY_INDICATOR(T, elem); + } + + m_pTasks[t & m_mask] = elem; + m_tail = t + 1; + + } + + delete[] pOldTasks; + delete[] pOldSlots; + return m_tail - 1 + m_cookieBase; + } + + /// + /// Synchronously pops an element from the work stealing queue. Note that this is called in the case where + /// a Pop() call and a Steal() call interleave. + /// + T* SyncPop() + { + // + // ensure that no Steal interleaves with this pop + // + typename LOCK::_Scoped_lock lockHolder(*m_pLock); + + typename Mailbox::Slot affinitySlot; + + T* pResult = NULL; + int t = m_tail - 1; + m_tail = t; + if (0 <= t - m_head) + { + // + // == (m_head <= m_tail) + // + pResult = m_pTasks[t & m_mask]; + + // + // Because this was a single element / interleave with steal, there is nothing + // below this in the WSQ in the event of a NULL return. Hence, we do not need + // to perform an explicit skip as in Pop(). + // + affinitySlot = m_pSlots[t & m_mask]; + } + else + { + m_tail = t + 1; // restore m_tail + } + if (0 >= t - m_head) + { + // + // Rebase the cookie index so we guarantee that currently handed out cookie values are + // still valid until they are trypop()'d. + // + m_cookieBase += m_head; + + // + // queue is empty: reset m_head and m_tail + // + m_head = 0; + m_tail = 0; + m_detachmentTail = 0; + m_fMarkedForDetachment = false; + } + + if (IS_AFFINITIZED_TASK(pResult)) + { + pResult = STRIP_AFFINITY_INDICATOR(T, pResult); + + // + // If the task was already executed via a mailbox dequeue, return an indication to the caller. + // + if (!affinitySlot.Claim()) + { + return (T*)AFFINITY_EXECUTED; + } + } + + return pResult; + } + + }; +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/align.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/align.h new file mode 100644 index 0000000000000000000000000000000000000000..1dcb38ba40e16a5552c31475141ca1cf53ceec56 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/align.h @@ -0,0 +1,29 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// align.h +// +// Alignment / Packing definitions +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#define WORD_ALIGN 1 +#define DWORD_ALIGN 3 +#define QWORD_ALIGN 7 +#define DQWORD_ALIGN 15 + +#ifdef _WIN64 +#define P2_ALIGN 15 +#else // !_WIN64 +#define P2_ALIGN 7 +#endif // _WIN64 + +#define ALIGNED_SIZE(size, alignment) (((size) + (alignment)) & ~(alignment)) + +#ifndef SIZEOF_ARRAY +#define SIZEOF_ARRAY(x) ((sizeof(x))/(sizeof(x[0]))) +#endif // SIZEOF_ARRAY diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/cds_cache_aligned_allocator.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/cds_cache_aligned_allocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a81bf529c5db00a43893d5774620e12c344c047b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/cds_cache_aligned_allocator.cpp @@ -0,0 +1,80 @@ +/*** +* ==++== +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* Microsoft would like to acknowledge that this concurrency data structure implementation +* is based on Intel's implementation in its Threading Building Blocks ("Intel Material"). +* +* ==--== +* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +* +* cds_cache_aligned_allocator.cpp +* +* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +****/ + +/* + Intel Material Copyright 2005-2008 Intel Corporation. All Rights Reserved. +*/ + + +#include "cds_cache_aligned_allocator.h" +#include +#include +#include +#include + +using namespace std; + +namespace Concurrency +{ + +namespace details +{ + + static size_t NFS_LineSize = 64; + + _CONCRTIMP size_t NFS_GetLineSize() + { + return NFS_LineSize; + } + + #pragma warning( push ) + // unary minus operator applied to unsigned type, result still unsigned + #pragma warning( disable: 4146 4706 ) + + _CONCRTIMP void* NFS_Allocate( size_t n, size_t element_size, void*) + { + size_t m = NFS_LineSize; + _CONCRT_ASSERT( m<=NFS_MaxLineSize ); // illegal value for NFS_LineSize + _CONCRT_ASSERT( (m & m-1)==0 ); // must be power of two + size_t bytes = n*element_size; + unsigned char* base; + if( bytes + +namespace Concurrency +{ + +namespace details +{ + + // Compile-time constant that is upper bound on cache line/sector size. + /** It should be used only in situations where having a compile-time upper + bound is more useful than a run-time exact answer. */ + const size_t NFS_MaxLineSize = 128; + + // Cache/sector line size. + _CONCRTIMP size_t NFS_GetLineSize(); + + // Allocate memory on cache/sector line boundary. + _CONCRTIMP void* NFS_Allocate( size_t n_element, size_t element_size, void* hint ); + + // Free memory allocated by NFS_Allocate. + /** Freeing a NULL pointer is allowed, but has no effect. */ + _CONCRTIMP void NFS_Free( void* ); + + // Meets "allocator" requirements of ISO C++ Standard, Section 20.1.5 + /** The members are ordered the same way they are in section 20.4.1 + of the ISO C++ standard. */ + template + class cache_aligned_allocator + { + public: + typedef _Ty* pointer; + typedef const _Ty* const_pointer; + typedef _Ty& reference; + typedef const _Ty& const_reference; + typedef _Ty value_type; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + + template struct rebind + { + typedef cache_aligned_allocator<_U> other; + }; + + cache_aligned_allocator() noexcept + { + } + + cache_aligned_allocator( const cache_aligned_allocator& ) noexcept + { + } + + template cache_aligned_allocator(const cache_aligned_allocator<_U>&) noexcept + { + } + + pointer address(reference x) const + { + return &x; + } + + const_pointer address(const_reference x) const + { + return &x; + } + + // Allocate space for n objects, starting on a cache/sector line. + pointer allocate( size_type n, const void* hint=0 ) + { + // The "hint" argument is always ignored in NFS_Allocate thus const_cast shouldn't hurt + return pointer(details::NFS_Allocate( n, sizeof(_Ty), const_cast(hint) )); + } + + // Free block of memory that starts on a cache line + void deallocate( pointer p, size_type ) + { + details::NFS_Free(p); + } + + // Largest value for which method allocate might succeed. + size_type max_size() const noexcept + { + return (~size_t(0)-details::NFS_MaxLineSize)/sizeof(_Ty); + } + + // Copy-construct value at location pointed to by p. + void construct( pointer p, const _Ty& value ) + { + new(static_cast(p)) _Ty(value); + } + + // Destroy value at location pointed to by p. + void destroy( pointer p ) + { + p->~_Ty(); + } + }; + + // Analogous to std::allocator, as defined in ISO C++ Standard, Section 20.4.1 + template<> + class cache_aligned_allocator { + public: + typedef void* pointer; + typedef const void* const_pointer; + typedef void value_type; + + template struct rebind + { + typedef cache_aligned_allocator<_U> other; + }; + }; + + template + inline bool operator==( const cache_aligned_allocator<_Ty>&, const cache_aligned_allocator<_U>& ) + { + return true; + } + + template + inline bool operator!=( const cache_aligned_allocator<_Ty>&, const cache_aligned_allocator<_U>& ) + { + return false; + } + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/collections.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/collections.h new file mode 100644 index 0000000000000000000000000000000000000000..c25daae0a907feda6227062253610ca7c196e8b0 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/collections.h @@ -0,0 +1,2201 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// collections.h +// +// Header file containing collection classes for ConcRT +// +// These data structures assume in-data links with the names m_pNext and m_pPrev +// Currently defined collections are: Stack, LockFreeStack, SafeStack +// SQueue, SafeSQueue +// List, SafeRWList +// Hash, SafeHash +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#if !defined(ASSERT) && defined(_DEBUG) +#define ASSERT(x) do {_CONCRT_ASSERT(x); __assume(x);} while(false) +#elif !defined(ASSERT) +#define ASSERT(x) __assume(x) +#endif + +#ifndef CONTAINING_RECORD +#define CONTAINING_RECORD(address, type, field) \ + ((type *)((char *)(address) - (ULONG_PTR)(&((type *)0)->field))) +#endif + +#if !defined(UNREACHED) +#define UNREACHED 0 +#endif + +namespace Concurrency +{ +namespace details +{ + // + // Allows multiple intrusive links within a single data structure. + // + struct ListEntry + { + ListEntry *m_pPrev; + ListEntry *m_pNext; + }; + + // + // Heap allocated generic list block. + // + template + struct ListNode + { + ListNode(T* pData) : m_pData(pData) + { + } + + ListNode *m_pPrev; + ListNode *m_pNext; + T* m_pData; + }; + + class CollectionTypes + { + public: + // + // public types + // + + class Count + { + public: + Count() : m_count(0) {} + void Increment() { ++m_count; } + void Decrement() { --m_count; } + int Value() const { return m_count; } + void Clear() { m_count = 0; } + private: + int m_count; + }; + + class NoCount + { + public: + static void Increment() {} + static void Decrement() {} + static int Value() { ASSERT(UNREACHED); return -1; } + static void Clear() {} + }; + }; + + // + // The base class of stacks. This implementation is not thread-safe. + // + template + class Stack : public Counter + { + public: + Stack() : m_pHead(NULL) {} + + T* Pop() + { + if (m_pHead == NULL) + { + return NULL; + } + T* pHead = m_pHead; + m_pHead = m_pHead->m_pNext; + Counter::Decrement(); + return pHead; + } + + void Push(T* pNode) + { + ASSERT(pNode != NULL); + + Counter::Increment(); + pNode->m_pNext = m_pHead; + m_pHead = pNode; + } + + bool Empty() const + { + return m_pHead == NULL; + } + + int Count() const + { + return Counter::Value(); + } + + T* First() + { + return m_pHead; + } + + T* Next(T* pNode) + { + //OACR_USE_PTR(this); + return pNode->m_pNext; + } + + private: + T* m_pHead; + }; + + // + // An implementation of interlocked SLIST that does not support Pop. This + // avoids the ABA problem. The reason for this data structure is to get + // to the top node (Windows SLIST does not provide this functionality + // without FirstSListEntry). + // Type T is required to have an intrusive SLIST_ENTRY m_slNext. + // + template + class LockFreePushStack + { + public: + LockFreePushStack() + { + m_pTop = NULL; + } + + ~LockFreePushStack() + { + // We expect the user to have flushed the stack + // before deleting it. + ASSERT(m_pTop == NULL); + } + + // Returns the current top of the stack + // THIS OPERATION IS NOT SYNCHRONIZED + // Anyone walking the list needs to ensure that there + // are no concurrent push/flush operations. + T * Unsafe_Top() + { + return Delta(m_pTop); + } + + // Push an element into the stack + void Push(T * pNode) + { + PSLIST_ENTRY top; + + do + { + // Make this node point to the head. + // m_pTop needs to be volatile to ensure that it is not enregistered + top = m_pTop; + pNode->m_slNext.Next = top; + + // Make head point to this node + } + while ((InterlockedCompareExchangePointer(reinterpret_cast(&m_pTop), &pNode->m_slNext, top) != top)); + } + + // Flush all the elements in the stack + T * Flush() + { + return Delta(reinterpret_cast(InterlockedExchangePointer(reinterpret_cast(&m_pTop), NULL))); + } + + static T* Next(T* pNode) + { + return Delta(pNode->m_slNext.Next); + } + + private: + + // m_pTop needs to be volatile to ensure that it is not enregistered + volatile PSLIST_ENTRY m_pTop; + + static T* Delta(void* p) { return (p == NULL) ? NULL : (T*) ((BYTE*)p - offsetof(T, m_slNext)); } + }; + + // + // Lock free stack implemented using a windows SLIST. Type T is required to have an intrusive SLIST_ENTRY m_slNext. + // + template + class LockFreeStack + { + public: + LockFreeStack() + { + InitializeSListHead(&m_head); + } + + T* Pop() + { + return Delta(InterlockedPopEntrySList(&m_head)); + } + + T* Flush() + { + return Delta(InterlockedFlushSList(&m_head)); + } + + void Push(T* pNode) + { + InterlockedPushEntrySList(&m_head, &(pNode->m_slNext)); + } + + static T* Next(T* pNode) + { + return Delta(pNode->m_slNext.Next); + } + + // implicit max of 64K entries + int Count() const { return static_cast (QueryDepthSList(const_cast (&m_head))); } + + private: + SLIST_HEADER m_head; // must be 16-bye aligned in x64 + + static T* Delta(void* p) { return (p == NULL) ? NULL : (T*) ((BYTE*)p - offsetof(T, m_slNext)); } + }; + + // + // The derived SafeStack class, which acquires a lock around accesses to the stack. + // + template + class SafeStack : public Stack + { + public: + T* Pop() + { + typename LOCK::_Scoped_lock lockHolder(m_lock); + return Stack::Pop(); + } + + void Push(T* pNode) + { + typename LOCK::_Scoped_lock lockHolder(m_lock); + Stack::Push(pNode); + } + + void Acquire() const { m_lock._Acquire(); } + void Release() const { m_lock._Release(); } + + private: + mutable LOCK m_lock; + }; + + + // + // The base class of singly-linked queues. This implementation is not thread-safe. + // + template + class SQueue + { + public: + SQueue() : m_pHead(NULL), m_ppTail(&m_pHead) { }; + + void Enqueue(T* pNode) + { + ASSERT(pNode != NULL); + + pNode->m_pNext = NULL; + *m_ppTail = pNode; + m_ppTail = &pNode->m_pNext; + } + + T* Dequeue() + { + if (m_pHead == NULL) + { + return NULL; + } + T *pHead = m_pHead; + m_pHead = m_pHead->m_pNext; + if (m_pHead == NULL) + m_ppTail = &m_pHead; + + return pHead; + } + + T* Current() const { return m_pHead; } + bool Empty() const { return m_pHead == NULL; } + + private: + T *m_pHead; + T **m_ppTail; + }; + + // + // The derived safe singly-linked queue class. This implementation acquires + // a lock before accessing the Queue. + // + template + class SafeSQueue : public SQueue + { + public: + void Enqueue(T* pNode) + { + typename LOCK::_Scoped_lock lockHolder(m_lock); + SQueue::Enqueue(pNode); + } + + T* Dequeue() + { + typename LOCK::_Scoped_lock lockHolder(m_lock); + return SQueue::Dequeue(); + } + + void Acquire() const { m_lock._Acquire(); } + void Release() const { m_lock._Release(); } + + private: + mutable LOCK m_lock; + }; + + // + // An unsafe circular linked list. + // + template + class List : public Counter + { + public: + List() : m_pTail(NULL) + { + } + + void Swap(List* pList) + { + T* pTail = pList->m_pTail; + pList->m_pTail = m_pTail; + m_pTail = pTail; + } + + void AddHead(T* pNode) + { + ASSERT(pNode != NULL); + + // if the list is empty, add it accordingly + if (m_pTail == NULL) + { + m_pTail = pNode; + m_pTail->m_pPrev = m_pTail; + m_pTail->m_pNext = m_pTail; + } + else + { + // hook up pNode + pNode->m_pNext = m_pTail->m_pNext; // pNode->next = head + pNode->m_pPrev = m_pTail; + + // hook up old head (viz., tail->next) + m_pTail->m_pNext->m_pPrev = pNode; // head->prev = pNode + m_pTail->m_pNext = pNode; // head = pNode + } + + Counter::Increment(); + } + + void AddTail(T* pNode) + { + ASSERT(pNode != NULL); + + if (m_pTail == NULL) + { + pNode->m_pPrev = pNode->m_pNext = pNode; + } + else + { + // hook up pNode + pNode->m_pNext = m_pTail->m_pNext; // pNode->next = head + pNode->m_pPrev = m_pTail; + + // hook up old head (viz., tail->next) + m_pTail->m_pNext->m_pPrev = pNode; // head->prev = pNode + m_pTail->m_pNext = pNode; // head = pNode + } + + m_pTail = pNode; // same as AddHead except we change the tail + + Counter::Increment(); + } + + T* RemoveHead() + { + if (m_pTail == NULL) + return NULL; + + Counter::Decrement(); + T *pNode = (T*) m_pTail->m_pNext; + + if (m_pTail == pNode) + { + m_pTail = NULL; + } + else + { + // hook up tail to head->next + pNode->m_pNext->m_pPrev = m_pTail; // head->next->prev = tail + m_pTail->m_pNext = pNode->m_pNext; // tail->next = head->next + } + + return pNode; + } + + T* RemoveTail() + { + if (m_pTail == NULL) + return NULL; + + Counter::Decrement(); + T *pNode = m_pTail; + + if (m_pTail == m_pTail->m_pNext) + { + m_pTail = NULL; + } + else + { + // hook up head to tail->prev and set tail = tail->prev, preserves head + pNode->m_pNext->m_pPrev = pNode->m_pPrev; // head->prev = tail->prev + pNode->m_pPrev->m_pNext = pNode->m_pNext; // tail->prev->next = head + m_pTail = (T*) m_pTail->m_pPrev; + } + + return pNode; + } + + void Enqueue(T* pNode) + { + AddHead(pNode); + } + + T* Dequeue() + { + return RemoveTail(); + } + + // + // Remove an element from the list. + // The function asserts that the write lock is held + // + void Remove(T* pNode) + { + ASSERT(pNode != NULL && m_pTail != NULL); + + Counter::Decrement(); + + pNode->m_pNext->m_pPrev = pNode->m_pPrev; + pNode->m_pPrev->m_pNext = pNode->m_pNext; + if (pNode == m_pTail) + { + m_pTail = (m_pTail == m_pTail->m_pNext) ? NULL : (T*) m_pTail->m_pPrev; + } + } + + // + // Iterator functions + // + T* First() const + { + return (m_pTail != NULL) ? (T*) m_pTail->m_pNext : NULL; + } + + T* Last() const + { + return m_pTail; + } + + T* Next(T* pNode) const + { + return (pNode != m_pTail) ? (T*) pNode->m_pNext : NULL; + } + + static T* Next(T* pNode, T* pPosition) + { + return (pNode != pPosition) ? (T*) pNode->m_pNext : NULL; + } + + static T* Prev(T* pNode, T* pPosition) + { + return (pNode != pPosition) ? (T*) pNode->m_pPrev : NULL; + } + + int Count() const { return Counter::Value(); } + + bool Empty() const { return (m_pTail == NULL); } + + void Clear() { m_pTail = NULL; Counter::Clear(); } + + protected: + T *m_pTail; + }; + + // + // A safe circular linked list. This implementation uses + // a _ReaderWriterLock on the list accesses. + // + template + class SafeRWList : public List + { + public: + SafeRWList() + { + } + + void Swap(List* pList) + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + List::Swap(pList); + } + + void AddHead(T* pNode) + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + List::AddHead(pNode); + } + + void AddTail(T* pNode) + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + List::AddTail(pNode); + } + + T* RemoveHead() + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + return List::RemoveHead(); + } + + T* RemoveTail() + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + return List::RemoveTail(); + } + + // + // Wrapper functions around AddHead/RemoveTail for consistency purposes + // + void Enqueue(T* pNode) + { + AddHead(pNode); + } + + T* Dequeue() + { + return RemoveTail(); + } + + // + // Synchronized remove an element from the list. + // + void Remove(T* pNode) + { + typename RWLOCK::_Scoped_lock writeLock(m_lock); + List::Remove(pNode); + } + +#pragma region "unlocked variants" + void UnlockedAddHead(T* pNode) + { + ASSERT(m_lock._HasWriteLock()); + List::AddHead(pNode); + } + + void UnlockedAddTail(T* pNode) + { + ASSERT(m_lock._HasWriteLock()); + List::AddTail(pNode); + } + + T* UnlockedRemoveHead() + { + ASSERT(m_lock._HasWriteLock()); + return List::RemoveHead(); + } + + T* UnlockedRemoveTail() + { + ASSERT(m_lock._HasWriteLock()); + return List::RemoveTail(); + } + + void UnlockedEnqueue(T* pNode) + { + ASSERT(m_lock._HasWriteLock()); + List::AddHead(pNode); + } + + T* UnlockedDequeue() + { + ASSERT(m_lock._HasWriteLock()); + return List::RemoveTail(); + } + + // + // Remove an element from the list. + // The function asserts that the write lock is held + // + void UnlockedRemove(T* pNode) + { + ASSERT(m_lock._HasWriteLock()); + List::Remove(pNode); + } +#pragma endregion + + // + // R/W Lock acquisition functions + // + void AcquireRead() const { m_lock._AcquireRead(); } + bool TryAcquireRead() const { return m_lock._TryAcquireRead(); } + void ReleaseRead() const { m_lock._ReleaseRead(); } + void AcquireWrite() const { m_lock._AcquireWrite(); } + bool TryAcquireWrite() const { return m_lock._TryAcquireWrite(); } + void ReleaseWrite() const { m_lock._ReleaseWrite(); } + void FlushWriteOwners() const { m_lock._FlushWriteOwners(); } + + /// + /// An exception safe RAII wrapper for writes. + /// + class _Scoped_lock + { + public: + explicit _Scoped_lock(SafeRWList& _Lock) : _M_lock(_Lock) + { + _M_lock.AcquireWrite(); + } + + ~_Scoped_lock() + { + _M_lock.ReleaseWrite(); + } + + private: + + SafeRWList& _M_lock; + + _Scoped_lock(const _Scoped_lock&); // no copy constructor + _Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator + }; + + /// + /// An exception safe RAII wrapper for reads. + /// + class _Scoped_lock_read + { + public: + explicit _Scoped_lock_read(SafeRWList& _Lock) : _M_lock(_Lock) + { + _M_lock.AcquireRead(); + } + + ~_Scoped_lock_read() + { + _M_lock.ReleaseRead(); + } + + private: + + SafeRWList& _M_lock; + + _Scoped_lock_read(const _Scoped_lock_read&); // no copy constructor + _Scoped_lock_read const & operator=(const _Scoped_lock_read&); // no assignment operator + }; + + protected: + mutable RWLOCK m_lock; + }; + + // + // Naive hash table implemented as an array of single linked lists. + // + template + class Hash + { + public: + // + // nested classes + // + + struct ListNode + { + ListNode(const KEY& key = 0, const VALUE& value = 0) : + m_pNext(NULL), + m_key(key), + m_value(value) + { + } + + ListNode* m_pNext; + KEY m_key; + VALUE m_value; + }; + + public: + // + // ctor + // + + Hash(int size = s_hashsize) + { + m_size = size; + m_count = 0; + m_ppHashtable = _concrt_new ListNode*[m_size]; + memset(m_ppHashtable, 0, m_size*sizeof(ListNode*)); + } + + // + // public methods + // + + // + // iterator - The First() and Next() functions do not have supporting Safe versions. Currently they are used + // by the memory dump tool which uses these APIs from a single thread. If thread safe access + // is desired the apis must be called after acquiring the read lock in the SafeHash class. + // + ListNode* First(int* x) + { + ASSERT(x != NULL); + *x = 0; + return NextList(x); + } + + ListNode* Next(int* x, ListNode* p) + { + ASSERT(p != NULL && x != NULL && *x < m_size); + if (p->m_pNext != NULL) + { + return p->m_pNext; + } + else + { + ++*x; + return NextList(x); + } + } + + ListNode* Insert(const KEY& key, const VALUE& value) + { + int hashValue = HashValue(key, m_size); + + ListNode* pNode = Lookup(key, hashValue); + if (pNode == NULL) + { + pNode = _concrt_new ListNode(key, value); + + pNode->m_pNext = m_ppHashtable[hashValue]; + m_ppHashtable[hashValue] = pNode; + + m_count++; + + return pNode; + } + return NULL; + } + + ListNode* Lookup(const KEY& key, VALUE* pValue) + { + ListNode* pNode = Lookup(key, HashValue(key, m_size)); + if (pNode != NULL) + { + *pValue = pNode->m_value; + } + return pNode; + } + + bool Exists(const KEY& key) + { + return (Lookup(key, HashValue(key, m_size)) != NULL); + } + + bool FindAndDelete(const KEY& key, VALUE* pValue) + { + ListNode* pNode = Remove(key, HashValue(key, m_size)); + if (pNode != NULL) + { + if (pValue != NULL) + { + *pValue = pNode->m_value; + } + FreeNode(pNode); + + return true; + } + return false; + } + + ListNode *Find(const KEY& key, VALUE* pValue) + { + ListNode* pNode = Lookup(key, HashValue(key, m_size)); + if (pNode != NULL) + { + if (pValue != NULL) + { + *pValue = pNode->m_value; + } + return pNode; + } + return NULL; + } + + bool Delete(const KEY& key) + { + return FindAndDelete(key, NULL); + } + + void Wipe() + { + if (m_count > 0) + { + for (int i = 0; i < m_size; ++i) + { + ListNode* pNode = m_ppHashtable[i]; + while (pNode != NULL) + { + ListNode* pNext = pNode->m_pNext; + FreeNode(pNode); + pNode = pNext; + } + } + m_count = 0; + memset(m_ppHashtable, 0, m_size*sizeof(ListNode*)); + } + } + + int Count() const + { + return m_count; + } + + // + // dtor + // + + ~Hash() + { + Wipe(); + delete[] m_ppHashtable; + } + + protected: + // + // protected data + // + static const int s_hashsize = 4097; + + private: + // + // private data + // + + int m_size; + int m_count; + + ListNode** m_ppHashtable; + + // + // private methods + // + + ListNode* NextList(int* x) + { + ASSERT(x != NULL && *x >= 0 && *x <= m_size); + + for (int i = *x; i < m_size; ++i) + { + if (m_ppHashtable[i] != NULL) + { + *x = i; + return m_ppHashtable[i]; + } + } + return NULL; + } + + ListNode* Lookup(const KEY& key, int hashValue) + { + ASSERT(hashValue >= 0 && hashValue < m_size); + ListNode* pNode = m_ppHashtable[hashValue]; + while (pNode != NULL) + { + if (pNode->m_key == key) + { + return pNode; + } + pNode = pNode->m_pNext; + } + return NULL; + } + + ListNode* Remove(const KEY& key, int hashValue) + { + ListNode* pNode = m_ppHashtable[hashValue], *pPrev = NULL; + + while (pNode != NULL) + { + if (pNode->m_key == key) + { + if (pPrev == NULL) + { + m_ppHashtable[hashValue] = pNode->m_pNext; + } + else + { + pPrev->m_pNext = pNode->m_pNext; + } + + m_count--; + + return pNode; + } + pPrev = pNode; + pNode = pNode->m_pNext; + } + return NULL; + } + + // + // This method could be specialized to provide better distribution for certain values of the template parameter KEY. + // + static unsigned int HashValue(const KEY& key, int the_size) + { + // We use Fowler-Noll-Vo FNV-1a hash algorithm. + + // Setup FNV constants for different size of (size_t) +#ifdef _WIN64 + static_assert(sizeof(size_t) == 8, "This code is for 64-bit size_t."); + const size_t FNVOffsetBasis = 14695981039346656037ULL; + const size_t FNVPrime = 1099511628211ULL; +#else + static_assert(sizeof(size_t) == 4, "This code is for 32-bit size_t."); + const size_t FNVOffsetBasis = 2166136261U; + const size_t FNVPrime = 16777619U; +#endif + + // Mix each byte of key into hash value + size_t hashVal = FNVOffsetBasis; + for (size_t i = 0; i < sizeof(key); i++) + { + hashVal ^= reinterpret_cast(&key)[i]; + hashVal *= FNVPrime; + } + + // mod operation is not exactly fair, but it does not matter + ASSERT(the_size > 0); + return static_cast (hashVal % static_cast(the_size)); + } + + // + // This function could be specialized to provide cleanup for non-trivial keys. + // + static void DeleteKey(KEY&) {} + // + // This function could be specialized to provide cleanup for non-trivial values. + // + static void DeleteValue(VALUE&) {} + + static void FreeNode(ListNode* pNode) + { + DeleteKey(pNode->m_key); + DeleteValue(pNode->m_value); + pNode->ListNode::~ListNode(); + delete pNode; + } + }; + + // + // reader/writer lock hash table + // not polymorphic -- never cast to base + // + template + class SafeHash : public Hash + { + public: + typedef Hash Base; + + // + // ctors + // + SafeHash(int size = Base::s_hashsize) : Hash(size) + { + } + + // + // public methods + // + + typename Base::ListNode* Insert(const KEY& key, const VALUE& value) + { + _ReaderWriterLock::_Scoped_lock writeLock(m_lock); + return Base::Insert(key, value); + } + + bool Exists(const KEY& key) + { + _ReaderWriterLock::_Scoped_lock_read readLock(m_lock); + return Base::Exists(key); + } + + typename Base::ListNode* Lookup(const KEY& key, VALUE* pValue) + { + _ReaderWriterLock::_Scoped_lock writeLock(m_lock); + return Base::Lookup(key, pValue); + } + + bool FindAndDelete(const KEY& key, VALUE* pValue) + { + _ReaderWriterLock::_Scoped_lock writeLock(m_lock); + return Base::FindAndDelete(key, pValue); + } + + bool Delete(const KEY& key) + { + return FindAndDelete(key, NULL); + } + + + void AcquireWrite() { m_lock._AcquireWrite(); } + void ReleaseWrite() { m_lock._ReleaseWrite(); } + void AcquireRead() { m_lock._AcquireRead(); } + void ReleaseRead() { m_lock._ReleaseRead(); } + + // + // dtor -- use default dtor + // + + private: + // + // private data + // + + _ReaderWriterLock m_lock; + }; + +#define _ARRAYNODE_FULL -2 +#define _ARRAYNODE_NOTFULL -1 + + class SchedulerBase; + + // + // The ListArray class is a generalized array that can be accessed by index + // Each node in the list includes an array of elements is default constructed to bucket size 256 + // and contains a pointer to the next list and a searchIndex field. + // + // The searchIndex field is an indicator as to whether this array is full. A value of _ARRAYNODE_FULL + // means the array is full and can be skipped over on insertion. A value of _ARRAYNODE_NOTFULL means + // the array is not full and should be searched. A value >=0 means that that specific element in the + // array has been removed and could be used. + // + // On the side, an Array pointing to the each array node is kept in m_ppArrayNodes. This allows + // for fast O(1) access on removal and the index operator, up to size m_arrayNodeSize*m_arrayLength + // elements (default 512*256). + // + // m_ppArrayNodes: + // +---+---+---+---+ + // | 1 | 2 | |512| + // +---+---+---+---+ + // | | + // | +---------------------------------------------+ + // | | + // V V + // ArrayNode 1: ArrayNode 2: + // +---+---+---+-------+---+------+-------+ +---+---+---+-------+---+------+-------+ + // | 1 | 2 | 3 | ... |256| next | index | +--> | 1 | 2 | 3 | ... |256| next | index | + // +---+---+---+-------+---+------+-------+ | +---+---+---+-------+---+------+-------+ + // | | + // +----------------+ + // + // An Add(object) will currently run through the arrays for a non-full (not _ARRAYNODE_FULL) array, then start + // searching that specific array for a non-NULL slot. A CAS is used to place the element in that + // slot. + // + // Any object that has an integer m_listArrayIndex field can be placed into this ListArray implementation. + // In the ConcRT scheduler, it will be mainly used for R/W objects that are often read, to avoid using a + // lock-based collection like the SafeRWList. + // + // + // ELEMENT DELETION FROM LIST ARRAYS + // + // The general algorithm for deletion is as follows: + // + // ListArray.Remove() CAS's items out of the main list array and inserts them into the free pool. After + // the insertion, the ListArray checks to see if the number of items in the free pool has exceeded a set + // threshold amount (stored in m_deletionThreshold). If so, it calls the scheduler and asks it to invoke + // the deletion at the next safe point: a point where all Contexts have reached a point in their + // dispatch loops where they are outside of their stealing logic and could not possibly be holding a bad pointer. + // At this point, the Remove() function moves half of the elements on the free pool over to a "elements to delete" + // list and sets a flag (m_fHasElementsToDelete) in this ListArray indicating it is the list array awaiting contexts + // to reach safe points. + // + // In the InterContextBase::Dispatch code, a single check is placed in one of its safe points which will mark the + // virtual processor as "ReachedSafePoint" if there is a pending cleanup. + // + // The m_fHasElementsToDelete call prevents two outstanding invocations for deletion at once. + // + // Note: it is currently not safe to walk a list array from an external context if the list array is deleting items. +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + template + class ListArray + { + struct ArrayNode { + ArrayNode(ELEMENT ** ppArray) + : m_ppArray(ppArray), m_pNext(NULL), m_searchIndex(_ARRAYNODE_NOTFULL) + { + } + // The actual array of elements being stored + ELEMENT ** m_ppArray; + // The next array + ArrayNode *m_pNext; + // A integer indicating whether this array is full, or where a free index slot is + // -2: array is full + // -1: array is not full, and should be + // >=0: some array element has been removed + int m_searchIndex; + }; + + // + // Pool of free Elements, can be returned and reused + // The user is responsible for reinitializing the elements to a correct state before using them + // + typedef struct __FreeElement { + SLIST_ENTRY ItemEntry; + ELEMENT * m_pElement; + } FreeElement, *PFreeElement; + + // The Slist of free elements saved for reuse + SLIST_HEADER m_freeElementPool; // must be 16-bye aligned in x64 + + // Elements removed from the free pool because it exceeded its threshold size. + // The elements are held in this list until they are safe to delete + SLIST_HEADER m_elementsToDelete; // must be 16-bye aligned in x64 + + // When a deletion is started, all elements to delete are snapped, and pointed to + // by this SLIST_ENTRY. + PSLIST_ENTRY m_deletionList; + + // The invocation for deletion which will happen on safe points. + SafePointInvocation m_deletionSafePoint{}; + + public: + /// + /// Constructor for ListArray + /// + /// + /// The length of each array in the list + /// + ListArray(::Concurrency::details::SchedulerBase * pScheduler, int arrayLength = 256, int deletionThreshold = 64) + : m_deletionList(NULL) + , m_pScheduler(pScheduler) + , m_shiftBits(0) + , m_pArrayHead(NULL) + , m_arrayNodesSize(512) + , m_nextArrayNodeSlot(1) + , m_maxArrayIndex(0) + , m_deletionThreshold(deletionThreshold) + , m_fHasElementsToDelete(FALSE) + { + // + // Initialize the arrayLength to the next largest power of 2 + // + if ((arrayLength & (arrayLength-1)) != 0) + { + arrayLength = (arrayLength >> 1) | arrayLength; + arrayLength = (arrayLength >> 2) | arrayLength; + arrayLength = (arrayLength >> 4) | arrayLength; + arrayLength = (arrayLength >> 8) | arrayLength; + arrayLength = (arrayLength >> 16) | arrayLength; + arrayLength = arrayLength + 1; + } + m_arrayLength = arrayLength; + + // Create an array of m_arrayLength (default is 256) + ELEMENT ** elementArray = _concrt_new ELEMENT*[m_arrayLength]; + memset(elementArray, 0, m_arrayLength*sizeof(ELEMENT*)); + m_pArrayHead = _concrt_new ArrayNode(elementArray); + + // Creates an array for quick access to the right ArrayNode + m_ppArrayNodes = _concrt_new ArrayNode*[m_arrayNodesSize]; + m_ppArrayNodes[0] = m_pArrayHead; + + // Initialize the Free Element Pool Slist + InitializeSListHead(&m_freeElementPool); + + InitializeSListHead(&m_elementsToDelete); + + // Precalculate number of bits to shift this arraylength + int i = m_arrayLength; + while ((i >>= 1) != 0) + { + m_shiftBits++; + } + } + + void SetScheduler(::Concurrency::details::SchedulerBase *pScheduler) + { + m_pScheduler = pScheduler; + } + + /// + /// ListArray destructor + /// + ~ListArray() + { + // + // Delete items that were added to the free list + // + PSLIST_ENTRY pListEntry = InterlockedFlushSList(&m_freeElementPool); + DeleteElements(pListEntry); + + // + // Delete items that were added to the elements to delete slist + // + pListEntry = InterlockedFlushSList(&m_elementsToDelete); + DeleteElements(pListEntry); + + // + // Delete any elements that were snapped for deletion but the + // deletion did not actually occur yet + // + DeleteElements(m_deletionList); + + // + // Delete each individual array + // + ArrayNode * node = m_pArrayHead; + while (node != NULL) + { + for (int i = 0; i < m_arrayLength; i++) + { + _InternalDeleteHelper(node->m_ppArray[i]); + } + ArrayNode * next = node->m_pNext; + delete [] node->m_ppArray; + delete node; + node = next; + } + + delete [] m_ppArrayNodes; + } + + /// + /// Determines if there are any elements in the list array. + /// This routine shall only be called when the list array is + ///. is not being modified. + /// + /// + /// true if the list array is empty, false otherwise + /// + bool IsEmptyAtSafePoint() + { + ArrayNode * node = m_pArrayHead; + while (node != NULL) + { + for (int i = 0; i < m_arrayLength; i++) + { + if (node->m_ppArray[i] != NULL) + { + return false; + } + } + node = node->m_pNext; + } + + return true; + } + + /// + /// Add an element into the ListArray + /// + /// + /// The element being inserted + /// + /// + /// The absolute index in the array that it was inserted at + /// + int Add(ELEMENT * element) + { + // A flag for whether the object has actually been inserted into the ListArray + bool inserted = false; + // The return value: the absolute index in the array that the item was inserted + int index = 0; + + ASSERT(m_pArrayHead != NULL); + + ArrayNode * node = m_pArrayHead; + while (inserted == false) + { + // + // A m_searchIndex value of -1 indicates that this current array being looked at + // is not known to be full. A walk of the array to find a non-NULL slot is performed + // + if (node->m_searchIndex >= -1) + { + ELEMENT ** elementArray = node->m_ppArray; + + for (int i = 0; i < m_arrayLength; i++) + { + // Continue if the slot is non-NULL + if (elementArray[i] != NULL) + { + continue; + } + + // Set this element's m_listArrayIndex field to point to this field we're trying + // to insert at. This is set before the CAS with the ListArray bucket to avoid + // races that may occur if the object is immediately removed before the index field + // is set. + element->m_listArrayIndex = index+i; + + // Check the current index to see whether or not we need to increment m_maxArrayIndex + // for this insertion + int currentMaxIndex = m_maxArrayIndex; + + // Try to insert at array slot i + PVOID initPtr = InterlockedCompareExchangePointer((volatile PVOID *) &elementArray[i], + (PVOID) element, (PVOID) NULL); + if (initPtr == NULL) + { + // Mark this element as inserted at location i + inserted = true; + index += i; + if (index >= currentMaxIndex) + { + InterlockedIncrement(&m_maxArrayIndex); + } + + // If a previous remove call had marked this location as free, reset the + // array as 0, so that the next call will walk again. The return of this CAS + // is irrelevant, it could have been reset by another remove + InterlockedCompareExchange((volatile LONG *) &node->m_searchIndex, + (LONG) _ARRAYNODE_NOTFULL, (LONG) i); + + break; + } + + } + } + + // + // If nothing was inserted during this pass, try and mark the array as FULL (-2) and + // move on to the next array to search, creating a new one if necessary. If a remove + // of an element in this array happened in the meantime, that's okay, the next Add to + // this ListArray will happen in that location + // + if (inserted == false) + { + // + // Try to set this array in "Full" mode. If an intervening Remove() happened, this + // CAS will fail. This current element will just be stored somewhere in the next array + // + InterlockedCompareExchange((volatile LONG *) &node->m_searchIndex, + (LONG) _ARRAYNODE_FULL, (LONG) _ARRAYNODE_NOTFULL); + index += m_arrayLength; + + // + // Try and increase the size of this ListArray + // + if (node->m_pNext == NULL) + { + if (InterlockedCompareExchangePointer((PVOID volatile *) &node->m_pNext, (PVOID) s_nonNull, NULL) == NULL) + { + // + // Create a new element array, which is where the actual elements are stored + // + ELEMENT **elementArray = _concrt_new ELEMENT*[m_arrayLength]; + memset(elementArray, 0, m_arrayLength*sizeof(ELEMENT*)); + + // + // Create an ArrayNode, which is a wrapper around each element array + // + ArrayNode *pNode = _concrt_new ArrayNode(elementArray); + + // + // The m_ppArrayNodes array is used for fast index into the list array + // It supports up to 512 ArrayNodes, each with m_arrayLength elements + // if we exceed this number, additional array nodes are accessed by as + // a linked list off of the last element. + // + // Note: this is safe since the CAS to s_nonNull is effectively a lock on this until the publication of + // pNode below. **EVERYTHING** must be set up before pNode is published and the relative ordering + // of node, node->m_pNext must concur with m_ppArrayNodes[m_nextArrayNodeSlot - 1], + // m_nextArrayNodeSlot] + // + if (m_nextArrayNodeSlot < m_arrayNodesSize) + m_ppArrayNodes[m_nextArrayNodeSlot++] = pNode; + + _InterlockedExchangePointer((PVOID volatile *) &node->m_pNext, pNode); + + } + } + + // + // Make sure the next array is ready. + // + if ((size_t) node->m_pNext == s_nonNull) + { + _SpinWaitBackoffNone spinWait; + do + { + // Here and in other places in the runtime, we're looping around checking the value of a non-volatile variable, + // but the function call _SpinOnce prevents the value from being cached. A simple _YieldProcessor() here + // would have resulted in an infinite loop. + spinWait._SpinOnce(); + } while ((size_t) node->m_pNext == s_nonNull) ; + } + } + + ASSERT(inserted == true || (inserted == false && node->m_pNext != NULL)); + + // Move to the next array + node = node->m_pNext; + } + + ASSERT(index >= 0); + + return index; + } + + /// + /// Add a free element into the free pool. Ignore depth. + /// + /// + /// The element being inserted + /// + void AddToFreePool(ELEMENT * element) + { + // + // Add this removed element to the free pool + // + InterlockedPushEntrySList(&m_freeElementPool, &(element->m_listArrayFreeLink)); + } + + /// + /// Remove an element from the array + /// + /// + /// A pointer to the element being removed + /// + /// + /// Whether we want this removed element to be added to the free pool for reuse + /// + /// + /// False when the element does not exist. + /// + bool Remove(ELEMENT * element, bool addToFreePool = true) + { + return Remove(element, element->m_listArrayIndex, addToFreePool); + } + + /// + /// Remove an element from the array + /// + /// + /// A pointer to the element being removed + /// + /// + /// ListArrayIndex of element. + /// + /// + /// Whether we want this removed element to be added to the free pool for reuse + /// + /// + /// False when the element does not exist. + /// + bool Remove(ELEMENT * element, int listArrayIndex, bool addToFreePool = true) + { + int arrayIndex = listArrayIndex >> m_shiftBits; + int removeIndex = listArrayIndex & m_arrayLength-1; + + // + // The element clearly does not exist. + // + if (arrayIndex >= m_nextArrayNodeSlot) + { + return false; + } + + ArrayNode * node = NULL; + if (arrayIndex >= m_arrayNodesSize) + { + // If this is actually an element that exceeded the m_ppArrayNodes index, + // run through the linked list to find the right arrayNode to access. + // This will only occur with very large number of items in the ListArray + node = m_ppArrayNodes[m_arrayNodesSize-1]; + for (int i = 0; i <= arrayIndex - m_arrayNodesSize; i++) + { + node = node->m_pNext; + } + } + else + { + node = m_ppArrayNodes[arrayIndex]; + } + + ELEMENT ** elementArray = node->m_ppArray; + + // + // Try and remove the element from the array + // + volatile PVOID oldPtr = (PVOID) element; + volatile PVOID initPtr = InterlockedCompareExchangePointer((volatile PVOID *) &elementArray[removeIndex], + (PVOID) NULL, (PVOID) oldPtr); + + if (initPtr == oldPtr) + { + // + // If the remove was successful, then update the Array node to know that the array is not full + // + InterlockedCompareExchange((volatile LONG *) &node->m_searchIndex, + (LONG) removeIndex, (LONG) _ARRAYNODE_FULL); + } + else + { + return false; + } + + // + // Add this item to the free list. The AddToFreePool flag is necessary because some elements, like the + // WorkQueue, don't actually want to remove an element for and have it reused by someone else. It is + // removing it from one ListArray in order to place it on another. + // + if (addToFreePool) + { + // + // Check if the number of elements in the free pool has exceeded the threshold for deletion + // If so, put this element on the deletion pool rather than the free pool + // + + if (QueryDepthSList(&m_freeElementPool) > m_deletionThreshold) + { + ASSERT(m_deletionThreshold != DeletionThresholdInfinite); + + // + // Add this removed element to the deletion pool + // + InterlockedPushEntrySList(&m_elementsToDelete, &(element->m_listArrayFreeLink)); + + int elementsToDeleteDepth = QueryDepthSList(&m_elementsToDelete); + + // + // Try marking this list array as the one we want to delete from + // if the length of the deletion list has hit the threshold + // + if (elementsToDeleteDepth > m_deletionThreshold && + m_pScheduler->HasCompletedShutdown() == false && + InterlockedCompareExchange(&m_fHasElementsToDelete, TRUE, FALSE) == FALSE) + { + ASSERT(m_deletionList == NULL); + + // Take a snapshot of the deletion pool, these are the elements we will actually delete + m_deletionList = InterlockedFlushSList(&m_elementsToDelete); + + // + // Inform the scheduler to call us at the next safe point for deletion. This will guarantee that no virtual + // processor has a handle to any of the objects we are deleting. + // + m_deletionSafePoint.InvokeAtNextSafePoint(reinterpret_cast(&CheckForDeletionBridge), this, m_pScheduler); + + } + } + else + { + // + // Add this removed element to the free pool + // + InterlockedPushEntrySList(&m_freeElementPool, &(element->m_listArrayFreeLink)); + } + } + return true; + } + + /// + /// Index operator for the ListArray + /// + /// + /// The index being retrieved + /// + /// + /// The element being accessed + /// + ELEMENT * operator[](int index) const + { + int arrayIndex = index >> m_shiftBits; + + if (arrayIndex >= m_nextArrayNodeSlot) + { + return NULL; + } + + ArrayNode * node = NULL; + if (arrayIndex >= m_arrayNodesSize) + { + // If this is actually an element that exceeded the m_ppArrayNodes index, + // run through the linked list to find the right arrayNode to access. + // This will only occur with very large number of items in the ListArray + node = m_ppArrayNodes[m_arrayNodesSize-1]; + for (int i = 0; i <= arrayIndex - m_arrayNodesSize; i++) + { + node = node->m_pNext; + } + } + else + { + node = m_ppArrayNodes[arrayIndex]; + } + + // Index into the array at position (index & m_arrayLength-1), this is the element + return node->m_ppArray[index & m_arrayLength-1]; + } + + /// + /// Called in order to retrieve an item from the free pool for reuse + /// + /// + /// The user of this ListArray is responsible for repurposing this returned object for reuse. + /// Thus, reinitialization of the ELEMENT may need to occur + /// + /// + /// An element from the free pool + /// + ELEMENT * PullFromFreePool() + { + PSLIST_ENTRY pListEntry = InterlockedPopEntrySList(&m_freeElementPool); + if (pListEntry == NULL) + { + return NULL; + } + ELEMENT * returnElement = CONTAINING_RECORD(pListEntry, ELEMENT, m_listArrayFreeLink); + return returnElement; + } + + /// + /// Called in order to retrieve the maximum size the ListArray has grown to + /// + /// + /// This is used to index into the array + /// + /// + /// The maximum size of the array + /// + int MaxIndex() + { + return m_maxArrayIndex; + } + public: + + static const int DeletionThresholdInfinite = INT_MAX; + + private: + + /// + /// A function to check whether a deletion needs to occur + /// + /// + /// This function assumes that all virtual processors have already reached their safe point. + /// + void CheckForDeletion() + { + // Early return from this function if: + // 1. The scheduler is already in its shutdown process -- the entire list array will be deleted anyway + // 2. The scheduler has not been set in cleanup mode + if (m_pScheduler->HasCompletedShutdown()) + { + return; + } + + DeleteElements(m_deletionList); + m_deletionList = NULL; + + // + // Allow other deletions to happen on this list array. + // + InterlockedExchange(&m_fHasElementsToDelete, FALSE); + } + + /// + /// A thunk to CheckForDeletion that safe point invocation will call. + /// + static void CheckForDeletionBridge(ListArray *pThis) + { + pThis->CheckForDeletion(); + } + + /// + /// A function that deletes all the elements of an SList pointed to by a PSLIST_ENTRY + /// + /// + /// The head node of the list being deleted. + /// + void DeleteElements(PSLIST_ENTRY pListEntry) + { + while (pListEntry != NULL) + { + ELEMENT *pElement = CONTAINING_RECORD(pListEntry, ELEMENT, m_listArrayFreeLink); + pListEntry = pListEntry->Next; + _InternalDeleteHelper(pElement); + } + } + + // The scheduler instance the listarray belongs to. + ::Concurrency::details::SchedulerBase * m_pScheduler; + + // The bucketlength of each array + int m_arrayLength; + // The number of bits to shift an index by + int m_shiftBits; + + // The head of the ListArray + ArrayNode * m_pArrayHead; + + // An Array of pointers to each of the ArrayNodes that are created + ArrayNode ** m_ppArrayNodes; + // The current size of the m_ppArrayNodes array + int m_arrayNodesSize; + // The next ArrayNode slot that should be inserted into + int m_nextArrayNodeSlot; + + // The farthest into the array any element has been inserted + // used for iterating on this array + volatile long m_maxArrayIndex; + + // The maximum number of elements this array should hold before it begins deletion some + int m_deletionThreshold; + + // A flag indicating whether or not this ListArray has elements that it wants to delete + // This set to true immediately after elements have successfully been moved from the + // free pool to the deletion list. + // It is checked in "Check for Deletion" to ensure that only one thread is actually doing + // the delete of elements, and reset to false. + volatile long m_fHasElementsToDelete; + + static const size_t s_nonNull = 1; + }; + + + template + struct ListArrayInlineLink + { + int m_listArrayIndex; + SLIST_ENTRY m_listArrayFreeLink; + + T* m_pObject; + }; +#pragma warning(pop) + + /// + /// Provides a set of N bits which have usual bitwise operators on them in order to allow relatively rapid intersections of subsets + /// of virtual processors when checking affinity. + /// + class QuickBitSet + { + public: + + // + // *NOTE*: There is duplication of code since we are below STL and I do not use std::move. + // + + QuickBitSet() noexcept : m_size(0), m_pBits(NULL) + { + } + + QuickBitSet(unsigned int size) : m_size(size) + { + m_pBits = _concrt_new unsigned int[(m_size + 31) >> 5]; + memset(m_pBits, 0, sizeof(unsigned int) * ASIZE()); + } + + QuickBitSet(const QuickBitSet& copySrc) : + m_size(0), + m_pBits(NULL) + { + CopyFrom(copySrc); + } + + QuickBitSet(QuickBitSet&& moveSrc) noexcept + { + m_size = moveSrc.m_size; + m_pBits = moveSrc.m_pBits; + + moveSrc.m_size = 0; + moveSrc.m_pBits = NULL; + } + + ~QuickBitSet() + { + delete[] m_pBits; + } + + QuickBitSet& operator=(const QuickBitSet& assignor) + { + CopyFrom(assignor); + + return *this; + } + + QuickBitSet& operator=(QuickBitSet&& assignor) noexcept + { + delete[] m_pBits; + + m_size = assignor.m_size; + m_pBits = assignor.m_pBits; + + assignor.m_size = 0; + assignor.m_pBits = NULL; + + return *this; + } + + QuickBitSet operator|(const QuickBitSet& rhs) const + { + ASSERT(rhs.m_size == m_size); + + QuickBitSet result(m_size); + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + result.m_pBits[i] = (m_pBits[i] | rhs.m_pBits[i]); + + return result; + } + + QuickBitSet operator|(QuickBitSet&& rhs) const + { + ASSERT(rhs.m_size == m_size); + + QuickBitSet result; + result.m_size = rhs.m_size; + result.m_pBits = rhs.m_pBits; + + rhs.m_size = 0; + rhs.m_pBits = NULL; + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + { + result.m_pBits[i] |= m_pBits[i]; + } + + return result; + } + + QuickBitSet operator&(const QuickBitSet& rhs) const + { + ASSERT(rhs.m_size == m_size); + + QuickBitSet result(m_size); + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + result.m_pBits[i] = (m_pBits[i] & rhs.m_pBits[i]); + + return result; + } + + QuickBitSet operator&(QuickBitSet&& rhs) const + { + ASSERT(rhs.m_size == m_size); + + QuickBitSet result; + result.m_size = rhs.m_size; + result.m_pBits = rhs.m_pBits; + + rhs.m_size = 0; + rhs.m_pBits = NULL; + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + { + result.m_pBits[i] &= m_pBits[i]; + } + + return result; + } + + void Grow(unsigned int size) + { + unsigned int new_aSize = (size + 31) >> 5; + unsigned int aSize = ASIZE(); + + if (new_aSize > aSize) + { + unsigned int *pBits = _concrt_new unsigned int [new_aSize]; + for (unsigned int i = 0; i < aSize; ++i) + pBits[i] = m_pBits[i]; + + memset(pBits + aSize, 0, (new_aSize - aSize) * sizeof(unsigned int)); + + delete[] m_pBits; + m_pBits = pBits; + } + + m_size = size; + } + + bool Intersects(const QuickBitSet& comparator) const + { + ASSERT(comparator.m_size == m_size); + + unsigned int val = 0; + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize && val == 0; ++i) + val |= (m_pBits[i] & comparator.m_pBits[i]); + + return (val != 0); + } + + bool IsSet(unsigned int bitNumber) const + { + return ((m_pBits [bitNumber >> 5] & (1 << (bitNumber & 0x1F))) != 0); + } + + bool IsClear(unsigned int bitNumber) const + { + return !IsSet(bitNumber); + } + + void Set(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + m_pBits[bitNumber >> 5] |= (1 << (bitNumber & 0x1F)); + } + + void Clear(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + m_pBits[bitNumber >> 5] &= ~(1 << (bitNumber & 0x1F)); + } + + void InterlockedSet(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + _InterlockedOr(reinterpret_cast (m_pBits + (bitNumber >> 5)), (1 << (bitNumber & 0x1F))); + } + + void InterlockedSet(const QuickBitSet& bitSet) + { + ASSERT(m_size == bitSet.m_size); + + unsigned int aSize = ASIZE(); + for(unsigned int i = 0; i < aSize; ++i) + _InterlockedOr(reinterpret_cast (m_pBits + i), bitSet.m_pBits[i]); + } + + void InterlockedClear(const QuickBitSet& bitSet) + { + ASSERT(m_size == bitSet.m_size); + + unsigned int aSize = ASIZE(); + for(unsigned int i = 0; i < aSize; ++i) + _InterlockedAnd(reinterpret_cast (m_pBits + i), ~(bitSet.m_pBits[i])); + } + + void InterlockedClear(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + _InterlockedAnd(reinterpret_cast (m_pBits + (bitNumber >> 5)), ~(1 << (bitNumber & 0x1F))); + } + + void SpinUntilClear(unsigned int bitNumber) const + { + volatile long *pBit = reinterpret_cast(m_pBits + (bitNumber >> 5)); + long mask = 1 << (bitNumber & 0x1F); + + if ((*pBit & mask) != 0) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + while ((*pBit & mask) != 0) + { + spinWait._SpinOnce(); + } + } + } + + void SpinUntilSet(unsigned int bitNumber) const + { + volatile long *pBit = reinterpret_cast(m_pBits + (bitNumber >> 5)); + long mask = 1 << (bitNumber & 0x1F); + + if ((*pBit & mask) == 0) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + while ((*pBit & mask) == 0) + { + spinWait._SpinOnce(); + } + } + } + + void Wipe() + { + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + m_pBits[i] = 0; + } + + void Fill() + { + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + m_pBits[i] = 0xFFFFFFFF; + } + + unsigned int Size() const + { + return m_size; + } + + unsigned int DbgAcquireBits(unsigned int psn) const + { + return m_pBits[psn]; + } + + protected: + + void CopyFrom(const QuickBitSet& copySrc) + { + if (m_size != copySrc.m_size) + Reallocate(copySrc.m_size); + + unsigned int aSize = ASIZE(); + for (unsigned int i = 0; i < aSize; ++i) + m_pBits[i] = copySrc.m_pBits[i]; + } + + void Reallocate(unsigned int size) + { + delete[] m_pBits; + m_size = size; + m_pBits = _concrt_new unsigned int [ASIZE()]; + } + + unsigned int ASIZE() const + { + return (m_size + 31) >> 5; + } + + unsigned int m_size; + unsigned int *m_pBits; + + }; + + /// + /// Provides a QuickBitSet whose set and clear operations are reference counted. + /// + class ReferenceCountedQuickBitSet : public QuickBitSet + { + public: + + ReferenceCountedQuickBitSet() : m_pRefCounts(NULL) + { + } + + ReferenceCountedQuickBitSet(unsigned int size) : QuickBitSet(size) + { + m_pRefCounts = _concrt_new LONG[size]; + memset(const_cast(m_pRefCounts), 0, sizeof(LONG) * size); + } + + ~ReferenceCountedQuickBitSet() + { + delete[] m_pRefCounts; + } + + void Set(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + LONG val = m_pRefCounts[bitNumber]; + ++val; + m_pRefCounts[bitNumber] = val; + ASSERT(val > 0); + if (val == 1) + { + QuickBitSet::Set(bitNumber); + } + } + + void Clear(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + LONG val = m_pRefCounts[bitNumber]; + --val; + m_pRefCounts[bitNumber] = val; + ASSERT(val >= 0); + if (val == 0) + { + QuickBitSet::Clear(bitNumber); + } + } + + void Grow(unsigned int size) + { + if (size > m_size) + { + unsigned int oldSize = m_size; + + QuickBitSet::Grow(size); + volatile LONG *pRefCounts = _concrt_new LONG[size]; + + for (unsigned int i = 0; i < oldSize; ++i) + pRefCounts[i] = m_pRefCounts[i]; + + memset(const_cast(pRefCounts + oldSize), 0, sizeof(LONG) * (size - oldSize)); + + delete[] m_pRefCounts; + m_pRefCounts = pRefCounts; + } + else if (size < m_size) + { + QuickBitSet::Grow(size); + } + } + + unsigned int InterlockedSet(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + LONG val = InterlockedIncrement(m_pRefCounts + bitNumber); + ASSERT(val > 0); + if (val == 1) + { + SpinUntilClear(bitNumber); + QuickBitSet::InterlockedSet(bitNumber); + } + + return val; + } + + unsigned int InterlockedClear(unsigned int bitNumber) + { + ASSERT(bitNumber < m_size); + + LONG val = InterlockedDecrement(m_pRefCounts + bitNumber); + ASSERT(val >= 0); + if (val == 0) + { + SpinUntilSet(bitNumber); + QuickBitSet::InterlockedClear(bitNumber); + } + + return val; + } + + void Wipe() + { + QuickBitSet::Wipe(); + + for (unsigned int i = 0; i < m_size; ++i) + m_pRefCounts[i] = 0; + } + + protected: + + volatile LONG *m_pRefCounts; + + }; + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concrtinternal.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concrtinternal.h new file mode 100644 index 0000000000000000000000000000000000000000..f1dad151a19b3bd1a6c5153d9fd382b8cb9fde47 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concrtinternal.h @@ -0,0 +1,323 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// concrtinternal.h : include file for standard system include files, +// or project specific include files that are used frequently, but +// are changed infrequently +// + +#pragma once + +// +// Operating systems < Vista treat a periodic timer with a period of INFINITE as a one shot meaning that you cannot correctly reschedule the timer. +// The throttling timer is a periodic timer which gets rescheduled with changing due times instead of getting recreated frequently. If we fall below +// throttling threshold, it is scheduled for an infinite period/due time until we hit the throttling threshold again. +// +// Since infinite periods don't work on < Vista, we'll make the timer pseudo-infinite. +// +// Pseudo infinite would be defined to 0xFFFFFFFE; however, on WinXP, scheduling a timer with a timeout between 0x80000000 and 0xFFFFFFFE creates an issue +// if another timer is scheduled within 1 millisecond of such a long pole timer (the second timer never fires). Hence, we define pseudo-infinite +// to be 0x7FFFFFFF to avoid both of these problems. Yes this means that every 24 days of continuous computation on a scheduler, +// we'll get a spurious throttler awakening. Oh well. +// +#define PSEUDOINFINITE 0x7FFFFFFF + +// +// If this is defined to 1, we will not use the allocation routines that hide ConcRT's allocations from the CRT memory leak detection tool so +// that ConcRT leaks will be reported. +// +#define _DEBUG_MEMORY_LEAKS 0 + +// _ONECORE is defined if the CRT is targeting MSDK. For both cases, the surface area of the CRT +// is the reduced surface area that excludes methods and types under if defined(_CRT_USE_WINAPI_FAMILY_DESKTOP_APP) + +#if defined(_ONECORE) +#define ENSURE_NOT_APP() throw invalid_operation() + +// Concrt public headers hide certain APIs from MSDK compliant +// However, for internal builds we need those API declarations. +#ifndef _CRT_USE_WINAPI_FAMILY_DESKTOP_APP +#define _CRT_USE_WINAPI_FAMILY_DESKTOP_APP 1 +#endif // _CRT_USE_WINAPI_FAMILY_DESKTOP_APP + +#else +#define ENSURE_NOT_APP() +#endif // defined(_ONECORE) + +#include "targetver.h" + +// All the platform specific headers are included here +#include "Platform.h" + +// C Runtime Header Files: + +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma warning(disable :4127) + +#ifndef _DEBUG +#define _concrt_new new +#else /* _DEBUG */ +#if !_DEBUG_MEMORY_LEAKS +// _ConcRTNewMoniker is used to make the signature of ConcRT operators new and delete globally unique, +// so that they don't clash with the operators defined in MFC (if statically linked) and user code. +class _ConcRTNewMoniker{}; + +inline void * __cdecl operator new(size_t _Size, _ConcRTNewMoniker, const char *_File, int _Line) +{ + return ::operator new(_Size, _CRT_BLOCK, _File, _Line); +} +inline void __cdecl operator delete(void * _P, _ConcRTNewMoniker, const char *, int) noexcept +{ + ::operator delete(_P); +} +inline void * __cdecl operator new[](size_t _Size, _ConcRTNewMoniker, const char *_File, int _Line) +{ + return ::operator new[](_Size, _CRT_BLOCK, _File, _Line); +} +inline void __cdecl operator delete[](void * _P, _ConcRTNewMoniker, const char *, int) noexcept +{ + ::operator delete[](_P); +} +#define _concrt_new new(_ConcRTNewMoniker(), __FILE__, __LINE__) +#else +#define _concrt_new new +#endif +#endif + +// Forward declarations +namespace Concurrency +{ +namespace details +{ + // From runtime + + class ScheduleGroupBase; + class ScheduleGroupSegmentBase; + class CacheLocalScheduleGroup; + class FairScheduleGroup; + class SchedulingRing; + class SchedulingNode; + class VirtualProcessor; + class ThreadVirtualProcessor; + class SchedulerBase; + class ThreadScheduler; + class ContextBase; + class InternalContextBase; + class ExternalContextBase; + class ExternalStatistics; + + class _UnrealizedChore; + + // From resource manager + + class ThreadProxy; + + class SchedulerProxy; + class ResourceManager; + class ExecutionResource; + class VirtualProcessorRoot; + class FreeVirtualProcessorRoot; + class ThreadProxy; + class FreeThreadProxy; + struct IThreadProxyFactory; + class FreeThreadProxyFactory; + class SubAllocator; +} + +// From runtime + + +struct IExecutionContext; + +// From resource manager + +struct IScheduler; +struct IResourceManager; + +} // namespace Concurrency + +const int KB = 1024; +const size_t s_cacheLineSize = 64; + +// Public ConcRT Header Files: +#include +#include + +#include +#include + +// Make sure that we never will use pplconcrt.h while compiling CRT +#define _PPLWIN_H +#include + +#if defined(_DEBUG) +#define CTX_DEBUGBIT_ADDEDTORUNNABLES 0x00000001 +#define CTX_DEBUGBIT_REMOVEDFROMRUNNABLES 0x00000002 +#define CTX_DEBUGBIT_ADDEDTOLOCALRUNNABLECONTEXTS 0x00000004 +#define CTX_DEBUGBIT_POPPEDFROMLOCALRUNNABLECONTEXTS 0x00000008 +#define CTX_DEBUGBIT_STOLENFROMLOCALRUNNABLECONTEXTS 0x00000010 +#define CTX_DEBUGBIT_PULLEDFROMCOMPLETIONLIST 0x00000020 +#define CTX_DEBUGBIT_AFFINITIZED 0x00000040 +#define CTX_DEBUGBIT_COOPERATIVEBLOCKED 0x00000080 +#define CTX_DEBUGBIT_UMSBLOCKED 0x00000100 +#define CTX_DEBUGBIT_CRITICALNOTIFY 0x00000200 +#define CTX_DEBUGBIT_CHAINEDCRITICALBLOCK 0x00000400 +#define CTX_DEBUGBIT_WAKEFROMCHAINEDCRITICALBLOCK 0x00000800 +#define CTX_DEBUGBIT_LIKELYTOSTARTUPIDLEVPROCONOTHERCONTEXT 0x00001000 +#define CTX_DEBUGBIT_STARTUPIDLEVPROCONADD 0x00002000 +#define CTX_DEBUGBIT_ACTIVATEDAFTERRMAWAKEN 0x00004000 +#define CTX_DEBUGBIT_RELEASED 0x00008000 +#define CTX_DEBUGBIT_REINITIALIZED 0x00010000 +#define CTX_DEBUGBIT_SWITCHTOWITHASSOCIATEDCHORE 0x00020000 +#define CTX_DEBUGBIT_PRIMARYAFFINITIZEFROMSEARCH 0x00040000 +#define CTX_DEBUGBIT_PRIMARYRESERVEDCONTEXT 0x00080000 +#define CTX_DEBUGBIT_PRIMARYAFFINITIZEFROMCRITICAL 0x00100000 +#define CTX_DEBUGBIT_PRIMARYSWITCHTOFAILED 0x00200000 +#define CTX_DEBUGBIT_HOLDINGUMSBLOCKEDCONTEXT 0x00400000 + +namespace Concurrency +{ +namespace details +{ + void SetContextDebugBits(::Concurrency::details::InternalContextBase *pContext, DWORD bits); +} // namespace details +} // namespace Concurrency +#endif // _DEBUG + +// Namespaces we use internally + +using namespace Concurrency; +using namespace Concurrency::details; + +// Internal Header Files (Both): +#include "utils.h" +#include "collections.h" +#include "Trace.h" + +// Internal Header Files (Resource Manager): +#include "rminternal.h" +#include "ExecutionResource.h" +#include "VirtualProcessorRoot.h" +#include "FreeVirtualProcessorRoot.h" +#include "HillClimbing.h" + +// Internal Header Files (Scheduler): +#include "Mailbox.h" +#include "WorkStealingQueue.h" +#include "StructuredWorkStealingQueue.h" +#include "workqueue.h" +#include "RealizedChore.h" + +#include "SearchAlgorithms.h" + +#include "VirtualProcessor.h" +#include "SchedulingNode.h" +#include "ThreadVirtualProcessor.h" + +#include "SubAllocator.h" +#include "ContextBase.h" +#include "SchedulerBase.h" +#include "InternalContextBase.h" +#include "SchedulingRing.h" +#include "ScheduleGroupBase.h" +#include "CacheLocalScheduleGroup.h" +#include "FairScheduleGroup.h" + +#include "ExternalContextBase.h" +#include "ThreadInternalContext.h" +#include "ThreadScheduler.h" + +#include "align.h" +#include "TaskCollection.h" +#include "SchedulerProxy.h" + +#include "WinRTWrapper.h" + +#include "ThreadProxy.h" +#include "FreeThreadProxy.h" +#include "Timer.h" + +#include "ThreadProxyFactory.h" +#include "ResourceManager.h" + +namespace Concurrency +{ +namespace details +{ + /// + /// A _Condition_variable which is explicitly aware of the Concurrency Runtime. + /// + /**/ + class _Condition_variable + { + public: + + /// + /// Constructs a new _Condition_variable. + /// + /**/ + _CONCRTIMP _Condition_variable(); + + /// + /// Destroys a _Condition_variable. + /// + /**/ + _CONCRTIMP ~_Condition_variable(); + + /// + /// Waits for the _Condition_variable to become signaled. The lock argument passed in is unlocked by the _Condition_variable + /// and relocked before the wait returns. + /// + /// + /// The critical_section to unlock before waiting and relock before the wait returns. + /// + /// + /**/ + _CONCRTIMP void wait(::Concurrency::critical_section& _Lck); + + /// + /// Waits for the _Condition_variable to become signaled. The lock argument passed in is unlocked by the _Condition_variable + /// and relocked before the wait returns. + /// + /// + /// The critical_section to unlock before waiting and relock before the wait returns. + /// + /// + /// A timeout, in milliseconds, for how long to wait for. + /// + /// + /**/ + _CONCRTIMP bool wait_for(::Concurrency::critical_section& _Lck, unsigned int _Timeout = COOPERATIVE_TIMEOUT_INFINITE); + + /// + /// Notify a single waiter of the _Condition_variable. + /// + /**/ + _CONCRTIMP void notify_one(); + + /// + /// Notify all the waiters of the _Condition_variable. + /// + /**/ + _CONCRTIMP void notify_all(); + + private: + + // Prevent bad usage of copy-constructor and copy-assignment + _Condition_variable(const _Condition_variable& _Event); + _Condition_variable& operator=(const _Condition_variable& _Event); + + void * volatile _M_pWaitChain; + ::Concurrency::critical_section _M_lock; + }; +} } // namespace Concurrency::details diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_hash.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_hash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4002fcf497a1311ccce1a99f08b76dc7cf53d355 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_hash.cpp @@ -0,0 +1,49 @@ +/*** +* ==++== +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +* ==--== +* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +* +* concurrent_hash.cpp +* +* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +****/ + + +#include "concrtinternal.h" +#include "internal_concurrent_hash.h" + +namespace Concurrency +{ + +namespace details +{ + +// An efficient implementation of the _Reverse function utilizes a 2^8 or 2^16 lookup table holding the +// bit-reversed values of [0..2^8 - 1] or [0..2^16 - 1] respectively. Those values can also be computed +// on the fly at a slightly higher cost. +const unsigned char _Byte_reverse_table[] = +{ + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF +}; + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_queue.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01f94f9a853b200e99d4f72514b117614746d015 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_queue.cpp @@ -0,0 +1,400 @@ +/*** +* ==++== +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* Microsoft would like to acknowledge that this concurrency data structure implementation +* is based on Intel's implementation in its Threading Building Blocks ("Intel Material"). +* +* ==--== +* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +* +* concurrent_queue.cpp +* +* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +****/ + +/* + Intel Material Copyright 2005-2008 Intel Corporation. All Rights Reserved. +*/ + + +#include "concrtinternal.h" +#include "concurrent_queue.h" +#include "cds_cache_aligned_allocator.h" +#include + +using namespace std; + +namespace Concurrency +{ + +namespace details +{ + + class _Micro_queue::_Push_finalizer + { + private: + _Ticket my_ticket; + _Micro_queue& my_queue; + public: + _Push_finalizer & operator = (const _Micro_queue::_Push_finalizer & other) = delete; + + _Push_finalizer( _Micro_queue& queue, _Ticket k ) + : my_ticket(k), my_queue(queue) + { + } + + ~_Push_finalizer() + { + my_queue._Tail_counter = my_ticket; + } + }; + + class _Micro_queue::_Pop_finalizer + { + private: + _Ticket my_ticket; + _Micro_queue& my_queue; + _Concurrent_queue_base::_Page* my_page; + _Concurrent_queue_base &base; + + public: + _Pop_finalizer & operator = (const _Micro_queue::_Pop_finalizer & other) = delete; + + _Pop_finalizer( _Micro_queue& queue, _Concurrent_queue_base& b, _Ticket k, _Concurrent_queue_base::_Page* p ) + : my_ticket(k), my_queue(queue), my_page(p), base(b) + { + } + + ~_Pop_finalizer() + { + _Concurrent_queue_base::_Page* p = my_page; + if( p ) + { + _SpinLock lock(my_queue._Page_mutex_flag); + + _Concurrent_queue_base::_Page* q = p->_Next; + my_queue._Head_page = q; + if( !q ) + { + my_queue._Tail_page = NULL; + } + } + + my_queue._Head_counter = my_ticket; + + if( p ) + base._Deallocate_page( p ); + } + }; + + + #pragma warning( push ) + // unary minus operator applied to unsigned type, result still unsigned + #pragma warning( disable: 4146 ) + + + static void* invalid_page; + + //------------------------------------------------------------------------ + // _Micro_queue + //------------------------------------------------------------------------ + void _Micro_queue::_Push( void* item, _Ticket k, _Concurrent_queue_base& base, void (_Concurrent_queue_base:: *moveOp)(_Concurrent_queue_base_v4::_Page&, size_t, void*)) + { + static _Concurrent_queue_base::_Page dummy = {static_cast<_Concurrent_queue_base::_Page*>((void*)1), 0}; + k &= -_Concurrent_queue_rep::_N_queue; + _Concurrent_queue_base::_Page* p = NULL; + size_t index = (k/_Concurrent_queue_rep::_N_queue & base._Items_per_page-1); + if( !index ) + { + try + { + p = base._Allocate_page(); + } catch (...) + { + // mark it so that no more pushes are allowed. + invalid_page = &dummy; + _SpinLock lock(_Page_mutex_flag); + + _Tail_counter = k+_Concurrent_queue_rep::_N_queue+1; + if( _Concurrent_queue_base::_Page* q = _Tail_page ) + q->_Next = static_cast<_Concurrent_queue_base::_Page*>(invalid_page); + else + _Head_page = static_cast<_Concurrent_queue_base::_Page*>(invalid_page); + _Tail_page = static_cast<_Concurrent_queue_base::_Page*>(invalid_page); + throw; + } + p->_Mask = 0; + p->_Next = NULL; + } + + { + _Push_finalizer finalizer( *this, k+_Concurrent_queue_rep::_N_queue ); + if( _Tail_counter!=k ) { + _SpinWaitBackoffNone spinWait; + do + { + spinWait._SpinOnce(); + // no memory. throws an exception + if( _Tail_counter&0x1 ) + throw std::bad_alloc(); + } while( _Tail_counter!=k ) ; + } + + if( p ) + { + _SpinLock lock(_Page_mutex_flag); + if( _Concurrent_queue_base::_Page* q = _Tail_page ) + q->_Next = p; + else + _Head_page = p; + _Tail_page = p; + } + else + { + p = _Tail_page; + } + + (base.*moveOp)(*p, index, item); + // If no exception was thrown, mark item as present. + p->_Mask |= size_t(1)<().allocate(1); + _CONCRT_ASSERT( (size_t)_My_rep % NFS_GetLineSize()==0 ); // alignment error + _CONCRT_ASSERT( (size_t)&_My_rep->_Head_counter % NFS_GetLineSize()==0 ); // alignment error + _CONCRT_ASSERT( (size_t)&_My_rep->_Tail_counter % NFS_GetLineSize()==0 ); // alignment error + _CONCRT_ASSERT( (size_t)&_My_rep->_Array % NFS_GetLineSize()==0 ); // alignment error + memset(_My_rep,0,sizeof(_Concurrent_queue_rep)); + this->_Item_size = _Item_size; + } + + _CONCRTIMP _Concurrent_queue_base_v4::~_Concurrent_queue_base_v4() + { + size_t nq = _My_rep->_N_queue; + for( size_t i=0; i_Array[i]._Tail_page==NULL ); // pages were not freed properly + cache_aligned_allocator<_Concurrent_queue_rep>().deallocate(_My_rep,1); + } + + _CONCRTIMP void _Concurrent_queue_base_v4::_Internal_swap( _Concurrent_queue_base_v4& other ) + { + if( _My_rep!=other._My_rep ) + { + std::swap(_My_rep, other._My_rep); + // do not need to swap _Items_per_page or _Item_size + // they should be same. + } + } + + _CONCRTIMP void _Concurrent_queue_base_v4::_Internal_push( const void* src ) + { + _Concurrent_queue_rep& r = *_My_rep; + _Ticket tail = r._Tail_counter++; + + r._Choose( tail )._Push( const_cast(src), tail, *this, + reinterpret_cast(&_Concurrent_queue_base_v4::_Copy_item)); + } + + _CONCRTIMP void _Concurrent_queue_base_v4::_Internal_move_push( void* src ) + { + _Concurrent_queue_rep& r = *_My_rep; + _Ticket tail = r._Tail_counter++; + + r._Choose( tail )._Push( src, tail, *this, &_Concurrent_queue_base_v4::_Move_item); + } + + _CONCRTIMP bool _Concurrent_queue_base_v4::_Internal_pop_if_present( void* dst ) + { + _Concurrent_queue_rep& r = *_My_rep; + _Ticket head; + + do + { + head = r._Head_counter; + for(;;) + { + if( head == r._Tail_counter ) + { + // Queue is empty + return false; + } + // Queue had item with ticket k when we looked. Attempt to get that item. + _Ticket oldHead=head; + head = r._Head_counter._CompareAndSwap( oldHead+1, oldHead ); + if( head==oldHead ) + break; + // Another thread snatched the item, retry. + } + } while( !r._Choose( head )._Pop( dst, head, *this ) ); + + return true; + } + + _CONCRTIMP size_t _Concurrent_queue_base_v4::_Internal_size() const + { + return static_cast(_My_rep->_Tail_counter-_My_rep->_Head_counter); + } + + _CONCRTIMP bool _Concurrent_queue_base_v4::_Internal_empty() const + { + _Ticket t0 = _My_rep->_Tail_counter; + _Ticket h = _My_rep->_Head_counter; + _Ticket t1 = _My_rep->_Tail_counter; // Load tail again to test consistency + + if (t0 == t1) { + // We got a consistent snapshot, so it was empty when we looked and saw the tail and head were equal. + return t0 == h; + } + + // t0 != t1, meaning some other thread must have pushed an item -- it was therefore not empty when we looked + return false; + + // ... Of course by the time we get here, the result is obsolete. + } + + _CONCRTIMP void _Concurrent_queue_base_v4::_Internal_finish_clear() + { + size_t nq = _My_rep->_N_queue; + for( size_t i=0; i_Array[i]._Tail_page; + _CONCRT_ASSERT( _My_rep->_Array[i]._Head_page==tp ); //at most one page should remain + if( tp!=NULL) + { + if( tp!=invalid_page ) + _Deallocate_page( tp ); + _My_rep->_Array[i]._Tail_page = NULL; + } + } + } + + _CONCRTIMP void _Concurrent_queue_base_v4::_Internal_throw_exception() const + { + throw bad_alloc(); + } + + //------------------------------------------------------------------------ + // _Concurrent_queue_iterator_rep + //------------------------------------------------------------------------ + class _Concurrent_queue_iterator_rep + { + public: + _Ticket _Head_counter; + const _Concurrent_queue_base& my_queue; + _Concurrent_queue_base::_Page* array[_Concurrent_queue_rep::_N_queue]; + _Concurrent_queue_iterator_rep( const _Concurrent_queue_base& queue ) + : _Head_counter(queue._My_rep->_Head_counter), + my_queue(queue) + { + const _Concurrent_queue_rep& rep = *queue._My_rep; + for( size_t k=0; k<_Concurrent_queue_rep::_N_queue; ++k ) + array[k] = rep._Array[k]._Head_page; + } + + _Concurrent_queue_iterator_rep & operator =(const _Concurrent_queue_iterator_rep &) = delete; + + // Get pointer to kth element + void* choose( size_t k ) + { + if( k==my_queue._My_rep->_Tail_counter ) + { + return NULL; + } + else + { + _Concurrent_queue_base::_Page* p = array[_Concurrent_queue_rep::_Index(k)]; + _CONCRT_ASSERT(p); + size_t i = k/_Concurrent_queue_rep::_N_queue & my_queue._Items_per_page-1; + return static_cast(static_cast(p+1)) + my_queue._Item_size*i; + } + } + }; + + //------------------------------------------------------------------------ + // concurrent_queue_iterator_base + //------------------------------------------------------------------------ + _CONCRTIMP _Concurrent_queue_iterator_base_v4::_Concurrent_queue_iterator_base_v4( const _Concurrent_queue_base& queue ) + { + _My_rep = cache_aligned_allocator<_Concurrent_queue_iterator_rep>().allocate(1); + new( _My_rep ) _Concurrent_queue_iterator_rep(queue); + _My_item = _My_rep->choose(_My_rep->_Head_counter); + } + + _CONCRTIMP void _Concurrent_queue_iterator_base_v4::_Assign( const concurrent_queue_iterator_base& other ) + { + if( _My_rep!=other._My_rep ) + { + if( _My_rep ) + { + cache_aligned_allocator<_Concurrent_queue_iterator_rep>().deallocate(_My_rep, 1); + _My_rep = NULL; + } + if( other._My_rep ) + { + _My_rep = cache_aligned_allocator<_Concurrent_queue_iterator_rep>().allocate(1); + new( _My_rep ) _Concurrent_queue_iterator_rep( *other._My_rep ); + } + } + _My_item = other._My_item; + } + + _CONCRTIMP void _Concurrent_queue_iterator_base_v4::_Advance() + { + _CONCRT_ASSERT( _My_item ); // attempt to increment iterator past end of queue + size_t k = _My_rep->_Head_counter; + const _Concurrent_queue_base& queue = _My_rep->my_queue; + _CONCRT_ASSERT( _My_item==_My_rep->choose(k) ); + size_t i = k/_Concurrent_queue_rep::_N_queue & queue._Items_per_page-1; + if( i==queue._Items_per_page-1 ) + { + _Concurrent_queue_base::_Page*& root = _My_rep->array[_Concurrent_queue_rep::_Index(k)]; + root = root->_Next; + } + _My_rep->_Head_counter = k+1; + _My_item = _My_rep->choose(k+1); + } + + _CONCRTIMP _Concurrent_queue_iterator_base_v4::~_Concurrent_queue_iterator_base_v4() + { + cache_aligned_allocator<_Concurrent_queue_iterator_rep>().deallocate(_My_rep, 1); + _My_rep = NULL; + } + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_vector.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_vector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..351f9841599d02c472ff615502f3dc1a16ddf64b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/concurrent_vector.cpp @@ -0,0 +1,609 @@ +/*** +* ==++== +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* Microsoft would like to acknowledge that this concurrency data structure implementation +* is based on Intel's implementation in its Threading Building Blocks ("Intel Material"). +* +* ==--== +* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +* +* concurrent_vector.cpp +* +* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +****/ + +/* + Intel Material Copyright 2005-2008 Intel Corporation. All Rights Reserved. +*/ + + +#include "concrtinternal.h" +#include "concurrent_vector.h" +#include "cds_cache_aligned_allocator.h" +#include + +using namespace std; + +namespace Concurrency +{ + +namespace details +{ + + class _Concurrent_vector_base_v4::_Helper + { + public: + // memory page size + static const _Size_type page_size = 4096; + + inline static bool incompact_predicate(_Size_type size) + { + return size < page_size || ((size-1)%page_size < page_size/2 && size < page_size * 128); + } + + inline static _Size_type find_segment_end(const _Concurrent_vector_base_v4 &v) + { + _Segment_index_t u = v._My_segment==(&(v._My_storage[0])) ? _Pointers_per_short_table + : _Pointers_per_long_table; + _Segment_index_t k = 0; + while( k < u && v._My_segment[k]._My_array ) + ++k; + return k; + } + + // assign first segment size. k - is index of last segment to be allocated, not a count of segments + static void assign_first_segment_if_necessary(_Concurrent_vector_base_v4 &v, _Segment_index_t k) + { + if( !v._My_first_block ) + { + v._My_first_block._CompareAndSwap(k+1, 0); // store number of segments + } + } + + inline static void *allocate_segment(_Concurrent_vector_base_v4 &v, _Size_type n) + { + void *_Ptr = v._My_vector_allocator_ptr(v, n); + if(!_Ptr) + _STD _Xbad_alloc(); + return _Ptr; + } + + // Publish segment so other threads can see it. + inline static void publish_segment( _Segment_t& s, void* rhs ) + { + _Subatomic_impl::_StoreWithRelease(s._My_array, rhs); + } + + inline static _Size_type enable_segment(_Concurrent_vector_base_v4 &v, _Size_type k, _Size_type element_size) + { + _CONCRT_ASSERT( !v._My_segment[k]._My_array ); // concurrent operation during growth? + if( !k ) + { + assign_first_segment_if_necessary(v, _Default_initial_segments-1); + try + { + publish_segment(v._My_segment[0], allocate_segment(v, _Segment_size(v._My_first_block) ) ); + } + catch(...) + { + // intercept exception here, assign _BAD_ALLOC_MARKER value, re-throw exception + publish_segment(v._My_segment[0], _BAD_ALLOC_MARKER); + throw; + } + return 2; + } + _Size_type m = _Segment_size(k); + + if( !v._My_first_block ) + SpinwaitWhileEq( v._My_first_block, _Segment_index_t(0) ); + + if( k < v._My_first_block ) + { + _Segment_t* s = v._My_segment; + // s[0]._My_array is changed only once ( 0 -> !0 ) and points to uninitialized memory + void *array0 = _Subatomic_impl::_LoadWithAquire(s[0]._My_array); + if( !array0 ) + { + details::SpinwaitWhileEq( s[0]._My_array, (void*)0 ); + array0 = _Subatomic_impl::_LoadWithAquire(s[0]._My_array); + } + if( array0 <= _BAD_ALLOC_MARKER ) // check for _BAD_ALLOC_MARKER of initial segment + { + publish_segment(s[k], _BAD_ALLOC_MARKER); // and assign _BAD_ALLOC_MARKER here + _STD _Xbad_alloc(); + } + publish_segment(s[k], + static_cast( static_cast(array0) + _Segment_base(k)*element_size ) ); + } + else + { + try + { + publish_segment(v._My_segment[k], allocate_segment(v, m)); + } + catch(...) + { + // intercept exception here, assign _BAD_ALLOC_MARKER value, re-throw exception + publish_segment(v._My_segment[k], _BAD_ALLOC_MARKER); + throw; + } + } + return m; + } + + inline static void extend_table_if_necessary(_Concurrent_vector_base_v4 &v, _Size_type k) + { + if(k >= _Pointers_per_short_table && v._My_segment == v._My_storage) + extend_segment_table(v); + } + + static void extend_segment_table(_Concurrent_vector_base_v4 &v) + { + _Segment_t* s = (_Segment_t*)NFS_Allocate( _Pointers_per_long_table, sizeof(_Segment_t), NULL ); + // if( !s ) throw bad_alloc() -- implemented in NFS_Allocate + memset( s, 0, _Pointers_per_long_table*sizeof(_Segment_t) ); + // If other threads are trying to set pointers in the short segment, wait for them to finish their + // assignments before we copy the short segment to the long segment. Note: grow_to_at_least depends on it. + for(_Segment_index_t i = 0; i < _Pointers_per_short_table; i++) + { + if(!v._My_storage[i]._My_array) + SpinwaitWhileEq(v._My_storage[i]._My_array, (void*)0); + } + + for( _Segment_index_t i = 0; i < _Pointers_per_short_table; i++) + s[i] = v._My_storage[i]; + if( v._My_segment._CompareAndSwap( s, v._My_storage ) != v._My_storage ) + NFS_Free( s ); + } + }; + + _CONCRTIMP _Concurrent_vector_base_v4::~_Concurrent_vector_base_v4() + { + _Segment_t* s = _My_segment; + if( s != _My_storage ) + { + // Clear short segment. + for( _Segment_index_t i = 0; i < _Pointers_per_short_table; i++) + _My_storage[i]._My_array = NULL; + _My_segment = _My_storage; + NFS_Free( s ); + } + } + + + _CONCRTIMP _Concurrent_vector_base_v4::_Segment_index_t __cdecl _Concurrent_vector_base_v4::_Segment_index_of( _Size_type _Index ) + { + return _Segment_index_t( Log2( _Index|1 ) ); + } + + + _CONCRTIMP _Concurrent_vector_base_v4::_Size_type _Concurrent_vector_base_v4::_Internal_capacity() const + { + return _Segment_base( _Helper::find_segment_end(*this) ); + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_throw_exception(_Size_type t) const + { + switch(t) + { + case 0: _STD _Xout_of_range("Index out of range"); + case 1: _STD _Xout_of_range("Index out of segments table range"); + case 2: _STD _Throw_range_error("Index is inside segment which failed to be allocated"); + } + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_reserve( _Size_type n, _Size_type element_size, _Size_type max_size ) + { + if( n>max_size ) + _STD _Xlength_error("argument to concurrent_vector::reserve() exceeds concurrent_vector::max_size()"); + + _Helper::assign_first_segment_if_necessary(*this, _Segment_index_of(n-1)); + _Segment_index_t k = _Helper::find_segment_end(*this); + try + { + for (; _Segment_base(k) < n; ++k) + { + _Helper::extend_table_if_necessary(*this, k); + _Helper::enable_segment(*this, k, element_size); + } + } + catch (...) + { + // repair and rethrow + _My_segment[k]._My_array = NULL; + throw; + } + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_copy( const _Concurrent_vector_base_v4& src, _Size_type element_size, _My_internal_array_op2 copy ) + { + _Size_type n = src._My_early_size; + _My_early_size = n; + _My_segment = _My_storage; + if( n ) + { + _Helper::assign_first_segment_if_necessary(*this, _Segment_index_of(n)); + _Size_type b; + for( _Segment_index_t k=0; (b=_Segment_base(k))= _Pointers_per_short_table) + || src._My_segment[k]._My_array <= _BAD_ALLOC_MARKER ) + { + _My_early_size = b; + break; + } + _Helper::extend_table_if_necessary(*this, k); + _Size_type m = _Helper::enable_segment(*this, k, element_size); + if( m > n-b ) + m = n-b; + copy( _My_segment[k]._My_array, src._My_segment[k]._My_array, m ); + } + } + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_assign( const _Concurrent_vector_base_v4& src, _Size_type element_size, _My_internal_array_op1 destroy, _My_internal_array_op2 assign, _My_internal_array_op2 copy ) + { + _Size_type n = src._My_early_size; + while( _My_early_size>n ) + { + _Segment_index_t k = _Segment_index_of( _My_early_size-1 ); + _Size_type b=_Segment_base(k); + _Size_type new_end = b>=n ? b : n; + _CONCRT_ASSERT( _My_early_size>new_end ); + if( _My_segment[k]._My_array <= _BAD_ALLOC_MARKER) // check vector was broken before + _STD _Xbad_alloc(); + // destructors are supposed to not throw any exceptions + destroy( (char*)_My_segment[k]._My_array+element_size*(new_end-b), _My_early_size-new_end ); + _My_early_size = new_end; + } + _Size_type dst_initialized_size = _My_early_size; + _My_early_size = n; + _Helper::assign_first_segment_if_necessary(*this, _Segment_index_of(n)); + _Size_type b; + for( _Segment_index_t k=0; (b=_Segment_base(k))= _Pointers_per_short_table) + || src._My_segment[k]._My_array <= _BAD_ALLOC_MARKER ) // if source is damaged + { + _My_early_size = b; + break; + } + _Size_type m = k? _Segment_size(k) : 2; + if( m > n-b ) m = n-b; + _Size_type a = 0; + if( dst_initialized_size>b ) + { + a = dst_initialized_size-b; + if( a>m ) + a = m; + assign( _My_segment[k]._My_array, src._My_segment[k]._My_array, a ); + m -= a; + a *= element_size; + } + if( m>0 ) + copy( (char*)_My_segment[k]._My_array+a, (char*)src._My_segment[k]._My_array+a, m ); + } + _CONCRT_ASSERT( src._My_early_size==n ); // detected use of ConcurrentVector::operator= with right side that was concurrently modified + } + + _CONCRTIMP void* _Concurrent_vector_base_v4::_Internal_push_back( _Size_type element_size, _Size_type& index ) + { + _Size_type tmp = _My_early_size++; + index = tmp; + _Segment_index_t k_old = _Segment_index_of( tmp ); + _Size_type base = _Segment_base(k_old); + _Helper::extend_table_if_necessary(*this, k_old); + _Segment_t& s = _My_segment[k_old]; + if ( !_Subatomic_impl::_LoadWithAquire(s._My_array) ) + { + // do not check for _BAD_ALLOC_MARKER because it's hard to recover after _BAD_ALLOC_MARKER correctly + if( base==tmp ) + _Helper::enable_segment(*this, k_old, element_size); + else + details::SpinwaitWhileEq( s._My_array, (void*)0 ); + } + if( s._My_array <= _BAD_ALLOC_MARKER ) // check for _BAD_ALLOC_MARKER + _STD _Xbad_alloc(); + _Size_type j_begin = tmp-base; + return (void*)((char*)s._My_array+element_size*j_begin); + } + + _CONCRTIMP _Concurrent_vector_base_v4::_Size_type _Concurrent_vector_base_v4::_Internal_grow_to_at_least_with_result( _Size_type new_size, _Size_type element_size, _My_internal_array_op2 init, const void *src ) + { + _Size_type e = _My_early_size; + while( e= _Pointers_per_short_table && _My_segment == _My_storage ) + { + details::SpinwaitWhileEq( _My_segment, _My_storage ); + i = _Pointers_per_short_table; // suppose short table is filled already + } + else + { + i = 0; + } + + while( i <= k_old ) + { + _Segment_t &s = _My_segment[i++]; + if( !s._My_array ) // concurrent changing of my_segment is ok due to wait in extend_segment_table() + { + details::SpinwaitWhileEq( s._My_array, (void*)0 ); + } + } + _CONCRT_ASSERT( _Internal_capacity() >= new_size ); + return e; + } + + _CONCRTIMP _Concurrent_vector_base_v4::_Size_type _Concurrent_vector_base_v4::_Internal_grow_by( _Size_type _Delta, _Size_type element_size, _My_internal_array_op2 init, const void *src ) + { + _Size_type result = _My_early_size._FetchAndAdd(_Delta); + _Internal_grow( result, result+_Delta, element_size, init, src ); + return result; + } + + _Concurrent_vector_base_v4::_Size_type _Concurrent_vector_base_v4::_Internal_grow_segment( const _Size_type start, _Size_type finish, _Size_type element_size, _Segment_t** ppSegment, _Size_type* pSegStart, _Size_type* pSegFinish ) + { + _Segment_index_t k_old = _Segment_index_of( start ); + _Size_type base = _Segment_base(k_old); + _Helper::extend_table_if_necessary(*this, k_old); + _Segment_t& s = _My_segment[k_old]; + if ( !_Subatomic_impl::_LoadWithAquire(s._My_array) ) + { + // do not check for _BAD_ALLOC_MARKER because it's hard to recover after _BAD_ALLOC_MARKER correctly + if( base==start ) + _Helper::enable_segment(*this, k_old, element_size); + else + details::SpinwaitWhileEq( s._My_array, (void*)0 ); + } + if( s._My_array <= _BAD_ALLOC_MARKER ) // check for _BAD_ALLOC_MARKER + _STD _Xbad_alloc(); + _Size_type n = k_old?_Segment_size(k_old):2; + *ppSegment = &s; + *pSegStart = start - base; + *pSegFinish = n > finish-base ? finish-base : n; + return base + *pSegFinish; + } + + void _Concurrent_vector_base_v4::_Internal_grow( const _Size_type start, _Size_type finish, _Size_type element_size, _My_internal_array_op2 init, const void *src ) + { + _CONCRT_ASSERT( start_My_array+element_size*j_begin), src, j_end-j_begin ); + } + catch (...) { + // Continue growing the remaining segments, zero-filling instead of initializing. + do + { + new_start = _Internal_grow_segment( new_start, finish, element_size, &pSegment, &j_begin, &j_end ); + memset( (void*)((char*)pSegment->_My_array+element_size*j_begin), 0, (j_end-j_begin) * element_size ); + } while (new_start < finish); + + throw; + } + } while( new_start < finish ); + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_resize( _Size_type new_size, _Size_type element_size, _Size_type max_size, _My_internal_array_op1 destroy, _My_internal_array_op2 init, const void* src) + { + _Size_type j = _My_early_size; + _My_early_size = new_size; + if( new_size > j ) // construct items + { + _Internal_reserve(new_size, element_size, max_size); + _Segment_index_t k = _Segment_index_of( j ); + _Size_type i = _My_first_block; // it should be read after call to reserve + if( k < i ) // process solid segment at a time + k = 0; + _Segment_index_t b = _Segment_base( k ); + new_size -= b; j -= b; // rebase as offsets from segment k + _Size_type sz = k ? b : _Segment_size( i ); // sz==b for k>0 + while( sz < new_size ) // work for more than one segment + { + void *array = _My_segment[k]._My_array; + if( array <= _BAD_ALLOC_MARKER ) + _STD _Xbad_alloc(); + init( (void*)((char*)array+element_size*j), src, sz-j ); + new_size -= sz; j = 0; // offsets from next segment + if( !k ) + { + k = i; + } + else + { + ++k; + sz <<= 1; + } + } + void *array = _My_segment[k]._My_array; + if( array <= _BAD_ALLOC_MARKER ) + _STD _Xbad_alloc(); + init( (void*)((char*)array+element_size*j), src, new_size-j ); + } + else + { + _Segment_index_t k = _Segment_index_of( new_size ); + _Size_type i = _My_first_block; + if( k < i ) // process solid segment at a time + k = 0; + _Segment_index_t b = _Segment_base( k ); + new_size -= b; j -= b; // rebase as offsets from segment k + _Size_type sz = k ? b : _Segment_size( i ); // sz==b for k>0 + while( sz < j ) // work for more than one segment + { + void *array = _My_segment[k]._My_array; + if( array > _BAD_ALLOC_MARKER ) + destroy( (void*)((char*)array+element_size*new_size), sz-new_size); + j -= sz; new_size = 0; + if( !k ) + { + k = i; + } + else + { + ++k; + sz <<= 1; + } + } + void *array = _My_segment[k]._My_array; + if( array > _BAD_ALLOC_MARKER ) + destroy( (void*)((char*)array+element_size*new_size), j-new_size); + } + } + + _CONCRTIMP _Concurrent_vector_base_v4::_Segment_index_t _Concurrent_vector_base_v4::_Internal_clear( _My_internal_array_op1 destroy ) + { + _CONCRT_ASSERT( _My_segment != NULL ); + const _Size_type k_end = _Helper::find_segment_end(*this); + _Size_type finish = _My_early_size; + // Set "_My_early_size" early, so that subscripting errors can be caught. + _My_early_size = 0; + while( finish > 0 ) + { + _Segment_index_t k_old = _Segment_index_of(finish-1); + _Size_type base = _Segment_base(k_old); + _Size_type j_end = finish-base; + finish = base; + if( k_old <= k_end ) + { + _Segment_t& s = _My_segment[k_old]; + _CONCRT_ASSERT( j_end ); + if( s._My_array > _BAD_ALLOC_MARKER) + destroy( s._My_array, j_end ); // destructors are supposed to not throw any exceptions + } + } + return k_end; + } + + _CONCRTIMP void *_Concurrent_vector_base_v4::_Internal_compact( _Size_type element_size, void *table, _My_internal_array_op1 destroy, _My_internal_array_op2 copy ) + { + const _Size_type my_size = _My_early_size; + const _Segment_index_t k_end = _Helper::find_segment_end(*this); + // number of segments to store existing items: 0=>0; 1,2=>1; 3,4=>2; [5-8]=>3; ... + const _Segment_index_t k_stop = my_size ? _Segment_index_of(my_size-1) + 1 : 0; + const _Segment_index_t first_block = _My_first_block; // number of merged segments; getting values from atomics + + _Segment_index_t k = first_block; + if(k_stop < first_block) + { + k = k_stop; + } + else + { + while (k < k_stop && _Helper::incompact_predicate(_Segment_size( k ) * element_size) ) + k++; + } + if(k_stop == k_end && k == first_block) + return NULL; + + _Segment_t *const segment_table = _My_segment; + _Internal_segments_table &old = *static_cast<_Internal_segments_table*>( table ); + memset(&old, 0, sizeof(old)); + + if ( k != first_block && k ) // first segment optimization + { + // exception can occur here + void *seg = old._Table[0] = _Helper::allocate_segment( *this, _Segment_size(k) ); + old._First_block = k; // fill info for freeing new segment if exception occurs + // copy items to the new segment + _Size_type my_segment_size = _Segment_size( first_block ); + for (_Segment_index_t i = 0, j = 0; i < k && j < my_size; j = my_segment_size) + { + _CONCRT_ASSERT( segment_table[i]._My_array > _BAD_ALLOC_MARKER ); + void *s = static_cast( static_cast(seg) + _Segment_base(i)*element_size ); + if(j + my_segment_size >= my_size) + my_segment_size = my_size - j; + // exception can occur here + copy( s, segment_table[i]._My_array, my_segment_size ); + my_segment_size = i? _Segment_size( ++i ) : _Segment_size( i = first_block ); + } + // commit the changes + memcpy(old._Table, segment_table, k * sizeof(_Segment_t)); + for (_Segment_index_t i = 0; i < k; i++) + { + segment_table[i]._My_array = static_cast( static_cast(seg) + _Segment_base(i)*element_size ); + } + old._First_block = first_block; _My_first_block = k; // now, first_block != _My_first_block + // destroy original copies + my_segment_size = _Segment_size( first_block ); // old.first_block actually + for (_Segment_index_t i = 0, j = 0; i < k && j < my_size; j = my_segment_size) + { + if(j + my_segment_size >= my_size) + my_segment_size = my_size - j; + // destructors are supposed to not throw any exceptions + destroy( old._Table[i], my_segment_size ); + my_segment_size = i? _Segment_size( ++i ) : _Segment_size( i = first_block ); + } + } + // free unnecessary segments allocated by reserve() call + if ( k_stop < k_end ) + { + old._First_block = first_block; + memcpy(old._Table+k_stop, segment_table+k_stop, (k_end-k_stop) * sizeof(_Segment_t)); + memset(segment_table+k_stop, 0, (k_end-k_stop) * sizeof(_Segment_t)); + if (!k) + _My_first_block = 0; + } + return table; + } + + _CONCRTIMP void _Concurrent_vector_base_v4::_Internal_swap(_Concurrent_vector_base_v4& v) + { + _Size_type my_sz = _My_early_size, v_sz = v._My_early_size; + if(!my_sz && !v_sz) + return; + + _Size_type tmp = _My_first_block; _My_first_block = v._My_first_block; v._My_first_block = tmp; + bool my_short = (_My_segment == _My_storage), v_short = (v._My_segment == v._My_storage); + if ( my_short && v_short ) // swap both tables + { + char tbl[_Pointers_per_short_table * sizeof(_Segment_t)]; + memcpy(tbl, _My_storage, _Pointers_per_short_table * sizeof(_Segment_t)); + memcpy(_My_storage, v._My_storage, _Pointers_per_short_table * sizeof(_Segment_t)); + memcpy(v._My_storage, tbl, _Pointers_per_short_table * sizeof(_Segment_t)); + } + else if ( my_short ) // my -> v + { + memcpy(v._My_storage, _My_storage, _Pointers_per_short_table * sizeof(_Segment_t)); + _My_segment = v._My_segment; v._My_segment = v._My_storage; + } + else if ( v_short ) // v -> my + { + memcpy(_My_storage, v._My_storage, _Pointers_per_short_table * sizeof(_Segment_t)); + v._My_segment = _My_segment; _My_segment = _My_storage; + } + else + { + _Segment_t *_Ptr = _My_segment; _My_segment = v._My_segment; v._My_segment = _Ptr; + } + _My_early_size = v_sz; v._My_early_size = my_sz; + } + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/event.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0887a93b91458ced4ccd8c2db1e6f30250a875df --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/event.cpp @@ -0,0 +1,1679 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// event.cpp +// +// This file includes two parts: event and _Condition_variable. +// The core implementations of events and _Condition_variable which understand the cooperative nature of +// the scheduler and are designed to be scalable. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + + +#include "concrtinternal.h" + +#pragma warning (disable : 4702) + +// +// NOTE: The design of the wait-for-multiple semantic tries to keep the following goals: +// +// - Single event waits (create/wait/set) are very efficient requiring few memory barriers and +// absolutely no shared locking. This is necessary to support utilizing the event for stolen chore +// signaling. Currently, there are N*2+1 memory barriers (where N is the number to grab/release +// a spin-lock). +// +// - Multiple event wait can be supported on the same Event type. There is (as yet) no bifurcation between +// an event that can be used in a WaitForMultiple and one that can't. +// +// - There are (few) shared locks between multiple events. +// +// This leads to a few unfortunate side effects in the implementation described below: +// +// - Each event has a spinlock which now guards its wait chains. No longer do we have a simple CAS loop +// for light-weight events. This will add extra memory barriers in the fast path (5 or 3 depending +// on the lock versus 2 in the prototype implementation). +// +// - Each wait-for-multiple requires a single heap allocation. With normal sized wait lists, this should +// come from the concurrent suballocator. +// +// - Wait-for-multiple on N events requires N spinlock acquisitions although the code is left open to the +// possibility of lock pooling on a granularity to be decided by the scheduler. + +namespace Concurrency +{ +namespace details +{ + + //************************************************************************** + // Shared Functionality: + // + // This functionality is shared between agents infrastructure in msvcp for timeouts + // there as well as in the eventing infrastructure here in msvcr for timeouts as well. + // This is an msvcr export to msvcp to keep a shared timer queue throughout ConcRT. + // + //************************************************************************** + + /// + /// Returns the demand initialized single timer queue used for event timeouts, timer agents, etc... + /// + HANDLE GetSharedTimerQueue() + { + // TimerQueue was needed for XP support + return NULL; + } + + //************************************************************************** + // Internal Prototypes and Definitions: + // + // These are purely internal to the event implementation are placed here in lieu + // of generally visible headers. + //************************************************************************** + + class EventWaitNode; + + /// + /// Represents a wait block. It is indirectly chained to an event via a Wait*Node. + /// + class WaitBlock + { + public: + + enum STATE {UNDECIDED, SKIP, DONT_SKIP}; + + /// + /// Wait block constructor + /// + WaitBlock() : m_pContext(NULL), m_smSkip_BlockUnblock(UNDECIDED) + { + m_pContext = Context::CurrentContext(); + } + + /// + /// Called when the wait is satisfied (the event is signaled). Note that the derived class may or may + /// not unblock depending on the exact wait semantics. + /// + /// + /// An indication of whether the event needs to track this node after a signal due to the potential + /// for a reset to impact the overall wait. + /// + virtual bool Satisfy(Context **pContextOut, EventWaitNode *pNode) = 0; + + /// + /// Called when the event is reset. A wait-all may need to adjust counters to prevent the wait from being + /// satisfied. + /// + /// + /// An indication of whether the wait node is still valid + /// + virtual bool Reset() = 0; + + /// + /// Called when the underlying event is being destroyed / rundown. Allows cleaning up of wait blocks. + /// + virtual void Destroy() = 0; + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the wait chain. + /// + virtual bool SweepWaitNode() = 0; + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the reset chain. + /// + virtual bool SweepResetNode() = 0; + + // The context which this wait must block/unblock. + Context *m_pContext; + + // Flag to decide on skipping a pair of block/unblock to avoid unblocking of a context blocked due + // to scoped lock and unblocking it via event's set operation, which is the wrong/mismatched reason for unblocking. + // Further comments in MultiWaitBlock::SingleSatisfy() method. + volatile long m_smSkip_BlockUnblock; + }; + + /// + /// Represents a wait on a single object (with or without a timer). + /// + class SingleWaitBlock : public WaitBlock + { + public: + + virtual bool Satisfy(Context **pContextOut, EventWaitNode *pNode); + virtual bool Reset(); + virtual void Destroy(); + virtual bool SweepWaitNode(); + virtual bool SweepResetNode(); + }; + + class MultiWaitBlock : public WaitBlock + { + public: + + // An indication of which object caused the wait to be satisfied. + EventWaitNode *m_pSatisfiedBy; + + // Timer queue timer. + HANDLE m_hTimer; + + // The final trigger count. + volatile long m_finalTrigger; + + // The number of things pointing at the wait block (wait nodes or timers). + size_t m_waiters; + + // When the count reaches the trigger limit, the wait block is satisfied. + volatile size_t m_triggerLimit{}; + + // The number of signaled objects + volatile size_t m_count; + + // The number of completed waiters (main counter of when the block can be freed) + volatile size_t m_completions; + + // An indication of whether this wait has a timeout or not. Timeouts are handled by a two stage + // wait (m_count -> m_finalTrigger). + bool m_fHasTimeout; + + // A variable that is set if there was a timeout associated with the wait block and the wait timed out. + // It is set either by the timer thread, or in the wait_for_* operation itself if the timeout was 0 and the wait was not satisfied + // when the wait_for_* method was invoked. + volatile bool m_fWaitTimedOut; + + /// + /// MultiWaitBlock constructor. + /// + MultiWaitBlock(size_t waitObjects, bool timeout, bool timer) + : m_pSatisfiedBy(NULL) + , m_hTimer(NULL) + , m_finalTrigger(0) + , m_waiters(waitObjects + static_cast(timer)) + , m_count(0) + , m_completions(0) + , m_fHasTimeout(timeout) + , m_fWaitTimedOut(false) + { + } + + /// + /// Called when a node (or something masquerading as such) is done with its reference on the block. + /// + void NotifyCompletedNode(); + + /// + /// Called when a timer on the wait block fires. + /// + static void CALLBACK DispatchEventTimer(PTP_CALLBACK_INSTANCE instance, void * pContext, PTP_TIMER timer); + + /// + /// Same as DispatchEventTimer, only used on WinXP platform. + /// + static void CALLBACK DispatchEventTimerXP(PVOID pContext, BOOLEAN timerOrWaitFired); + protected: + + virtual void SingleSatisfy(Context **pContextOut, EventWaitNode *pNode); + + }; + + class MultiWaitBlockHolder + { + public: + + MultiWaitBlockHolder(bool fWaitAll, size_t count, bool timeout, bool timer); + + ~MultiWaitBlockHolder(); + + void Release() + { + m_count++; + } + + MultiWaitBlock *GetWaitBlock() const + { + return m_pWaitBlock; + } + + EventWaitNode *GetWaitNode(size_t i) const + { + return reinterpret_cast (m_pMemBlock + m_blockSize + m_nodeSize * i); + } + + size_t GetIndexOfNode(EventWaitNode *pNode) const + { + return (size_t) (reinterpret_cast (pNode) - (m_pMemBlock + m_blockSize)) / m_nodeSize; + } + + private: + + size_t m_blockSize; + size_t m_nodeSize; + size_t m_totalBlockSize; + BYTE *m_pMemBlock; + MultiWaitBlock *m_pWaitBlock; + + size_t m_count; + size_t m_refs; + + }; + + class WaitAllBlock : public MultiWaitBlock + { + public: + + WaitAllBlock(size_t waitObjects, bool timeout, bool timer) : MultiWaitBlock(waitObjects, timeout, timer) + { + m_triggerLimit = waitObjects; + } + + virtual bool Satisfy(Context **pContextOut, EventWaitNode *pNode); + virtual bool Reset(); + virtual void Destroy(); + virtual bool SweepWaitNode(); + virtual bool SweepResetNode(); + }; + + class WaitAnyBlock : public MultiWaitBlock + { + public: + + WaitAnyBlock(size_t waitObjects, bool timeout, bool timer) : MultiWaitBlock(waitObjects, timeout, timer) + { + m_triggerLimit = 1; + } + + virtual bool Satisfy(Context **pContextOut, EventWaitNode *pNode); + virtual bool Reset(); + virtual void Destroy(); + virtual bool SweepWaitNode(); + virtual bool SweepResetNode(); + }; + + /// + /// An event wait node represents an abstract wait block which is chained to each event such that when the + /// event is signaled, the wait block is notified and performs the appropriate unblocking (or additional + /// waiting) required. + /// + class EventWaitNode + { + public: + + EventWaitNode* m_pNext{}; + WaitBlock *m_pWaitBlock; + + EventWaitNode(WaitBlock *pWaitBlock) noexcept : m_pWaitBlock(pWaitBlock) + { + } + + bool Satisfy(Context **pContextOut) + { + return m_pWaitBlock->Satisfy(pContextOut, this); + } + + bool Reset() + { + return m_pWaitBlock->Reset(); + } + + void Destroy() + { + m_pWaitBlock->Destroy(); + } + + bool SweepWaitNode() + { + return m_pWaitBlock->SweepWaitNode(); + } + + bool SweepResetNode() + { + return m_pWaitBlock->SweepResetNode(); + } + + }; + + EventWaitNode * Sweep(EventWaitNode *pNode, bool fWaitChain); + +} // namespace details + +// Details for _Condition_variable +namespace details +{ + /// + /// This is the wait-block design for handling two signal sources: + /// 1. signals fired by user + /// 2. signals fired by timer + /// If there is no timer in this block, the block will be allocated on + /// the stack, which will be finally destroyed when the context get released; + /// however, when it comes with the timer, the block will be allocated on + /// the heap, and 2 phases de-reference checks are required to *delete* this object. + /// + class TimedSingleWaitBlock : public SingleWaitBlock + { + // The event node nested in wait-block, + // which shares the lifetime with wait-block + EventWaitNode m_eventNode; + + HANDLE m_hTimer{}; + + const bool m_hasTimer; + + // The de-reference times + volatile long m_deRef; + + // The number of signaled objects + // It is used to determine who fires the signal first. + volatile long m_signalCounter; + + public: + TimedSingleWaitBlock & operator =(const TimedSingleWaitBlock &) = delete; + + // An indication of whether this wait has a timeout or not. + volatile bool m_fWaitTimedOut; + + virtual bool SweepWaitNode(); + + virtual void Destroy(); + + /// + /// Called when a timer on the wait-block fires. + /// + static void CALLBACK DispatchEventTimer(PTP_CALLBACK_INSTANCE instance, void * pContext, PTP_TIMER timer); + + /// + /// Same as DispatchEventTimer, only used on WinXP platform. + /// + static void CALLBACK DispatchEventTimerXP(PVOID pContext, BOOLEAN timerOrWaitFired); + + virtual bool Satisfy(Context **pContextOut, EventWaitNode *pNode); + + /// + /// TimedSingleWaitBlock constructor. + /// + TimedSingleWaitBlock(bool hasTimer) + : m_eventNode(nullptr) + , m_hasTimer(hasTimer) + , m_deRef(0) + , m_signalCounter(0) + , m_fWaitTimedOut(false) + { + m_eventNode.m_pWaitBlock = this; + } + + /// + /// Get the event node nested in the wait-block + /// + EventWaitNode *getEventNode() + { + return &m_eventNode; + } + + bool createTimer(unsigned int timerout) + { + if (m_hasTimer) + { + return (m_hTimer = RegisterAsyncTimerAndLoadLibrary(timerout, TimedSingleWaitBlock::DispatchEventTimer, this)) != nullptr; + } + return false; + } + + void destroyTimer(bool waitForOutstandingCallback) + { + if (m_hasTimer) + { + if (waitForOutstandingCallback && m_hTimer) + DeleteAsyncTimerAndUnloadLibrary(static_cast(m_hTimer)); + // If it's an async deletion (happens inside the callback) we don't do anything here, new callback handler will handle it. + } + } + }; + + /// + /// It will be called by two event sources : + /// 1. the timer, with argument *pNode* nullptr + /// 2. the user trigger, with *pNode* the address of the event node. + /// This function will take actions ONLY when FIRST time being called, + /// any further calls will be ignored with return value False. + /// If the first caller sets pContextOut nullptr, it will Unblock the + /// context immediately, otherwise, it will pass out the blocked context + /// by pContextOut. + /// + bool TimedSingleWaitBlock::Satisfy(Context **pContextOut, EventWaitNode *pNode) + { + if (InterlockedIncrement(&m_signalCounter) == 1) + { + // Timer will be destroyed when as soon as + // it is satisfied + destroyTimer(pNode != nullptr); + + // check who initiated this *Satisfy* + m_fWaitTimedOut = pNode == nullptr; + + if (pContextOut) + *pContextOut = m_pContext; + else + m_pContext->Unblock(); + + return true; + } + return false; + } + + /// + /// Delete the wait-block after 2 times de-reference. + /// If the block is allocated on the stack, it should only + /// be de-referenced once -- when he is removed from the + /// event list. + /// + void TimedSingleWaitBlock::Destroy() + { + if (InterlockedIncrement(&m_deRef) == 2) + delete this; + } + + /// + /// Clean the timed-out node. + /// + bool TimedSingleWaitBlock::SweepWaitNode() + { + if (m_fWaitTimedOut) + { + Destroy(); + return false; + } + return true; + } + + /// + /// Called when a timer on an condition variable is signaled. + /// + void TimedSingleWaitBlock::DispatchEventTimer(PTP_CALLBACK_INSTANCE instance, void * pContext, PTP_TIMER timer) + { + TimedSingleWaitBlock *pWaitBlock = reinterpret_cast (pContext); + if (pWaitBlock->Satisfy(nullptr, nullptr)) + { + // We need to release the timer and dereference the module at the very end of the callback. + UnRegisterAsyncTimerAndUnloadLibrary(instance, timer); + } + } + + void TimedSingleWaitBlock::DispatchEventTimerXP(LPVOID pContext, BOOLEAN) + { + TimedSingleWaitBlock *pWaitBlock = reinterpret_cast (pContext); + pWaitBlock->Satisfy(nullptr, nullptr); + // It does not need to de-reference anything. + } + + _Condition_variable::_Condition_variable() : + _M_pWaitChain(nullptr), _M_lock() + { + } + + _Condition_variable::~_Condition_variable() + { + // + // It's entirely possible that some other thread is currently executing inside ::set, and is currently holding the lock. + // Since the waiter that was woken up could destroy the event, either by deleting a heap allocated, or unwinding the + // stack, we need to let that other thread (that invoked ::set) get out of the lock before we proceed. + // + _M_lock._Flush_current_owner(); + + // release all contexts + notify_all(); + } + + /// + /// Fast method for waiting on _Condition_variable without timeout + /// + void _Condition_variable::wait(Concurrency::critical_section& _Lck) + { + // Please refers to the wait_for function + TimedSingleWaitBlock block(false); + + EventWaitNode *pEventNode = block.getEventNode(); + { + critical_section::scoped_lock lock(_M_lock); + pEventNode->m_pNext = Sweep(reinterpret_cast (_M_pWaitChain), true); + _M_pWaitChain = pEventNode; + _Lck.unlock(); + } + + Context::Block(); + _Lck.lock(); + } + + /// + /// Timed wait method + /// + bool _Condition_variable::wait_for(Concurrency::critical_section& _Lck, unsigned int _Timeout) + { + // If check special case for _Timeout for efficiency reason + if (_Timeout == 0) + return false; + else if (_Timeout == COOPERATIVE_TIMEOUT_INFINITE) + { + wait(_Lck); + return true; + } + + // Create timed node on heap, which will be destroyed when + // the de-reference counts 2. + TimedSingleWaitBlock *pBlock = _concrt_new TimedSingleWaitBlock(true); + EventWaitNode *pNode = pBlock->getEventNode(); + + // Commit to wait: + // Step 1: Chain itself on the event list, set the timer, + // and release the mutex. + // The _Lck must be unlocked after chaining, to protect the atomic. + { + + critical_section::scoped_lock lock(_M_lock); + + pNode->m_pNext = Sweep(reinterpret_cast (_M_pWaitChain), true); + _M_pWaitChain = pNode; + + if (!pBlock->createTimer(_Timeout)) + throw std::bad_alloc(); + + _Lck.unlock(); + } + + // Step 2: blocks itself + Context::Block(); + + // After being waken up, collect the result and de-reference itself. + bool res = !pBlock->m_fWaitTimedOut; + pBlock->Destroy(); + + // Re-acquire the mutex + _Lck.lock(); + + return res; + } + + /// + /// It only wake up one context if there are + /// some contexts waiting, otherwise, it does nothing. + /// + void _Condition_variable::notify_one() + { + // optimization for reducing unnecessary lock + if (!_M_pWaitChain) + return; + + critical_section::scoped_lock lock(_M_lock); + + EventWaitNode *p = reinterpret_cast (_M_pWaitChain); + EventWaitNode *np; + Context *cp = nullptr; + + // It iterates over the chain, and finds first + // wait-block not timed out yet. + while (p && !p->Satisfy(&cp)) + { + np = p->m_pNext; + p->Destroy(); + p = np; + } + + if (p) + { + // If it finds one available wait-block + _M_pWaitChain = p->m_pNext; + p->Destroy(); + + // Unblock() must be called after Destroy() + // since releasing context may invalidate the wait-block. + cp->Unblock(); + } + else + _M_pWaitChain = NULL; + } + + /// + /// It wakes up all contexts if there are + /// some contexts waiting, otherwise, it does nothing. + /// + void _Condition_variable::notify_all() + { + // optimization for reducing unnecessary lock + if (!_M_pWaitChain) + return; + EventWaitNode *p, *np; + { + critical_section::scoped_lock lock(_M_lock); + p = reinterpret_cast (_M_pWaitChain); + _M_pWaitChain = nullptr; + } + + // It is safe to go over the list without lock + // since the chain has been removed from the head. + while (p) + { + Context *cp = nullptr; + p->Satisfy(&cp); + np = p->m_pNext; + p->Destroy(); + + // Unblock() must be called after Destroy() + // since releasing context may invalidate the wait-block. + if (cp) + cp->Unblock(); + p = np; + } + } + +} + +/// +/// Constructs an event. +/// +event::event() : + _M_pWaitChain(EVENT_UNSIGNALED), + _M_pResetChain(NULL) +{ +} + +/// +/// Destroys an event. +/// +event::~event() +{ + // + // It's entirely possible that some other thread is currently executing inside ::set, and is currently holding the lock. + // Since the waiter that was woken up could destroy the event, either by deleting a heap allocated, or unwinding the + // stack, we need to let that other thread (that invoked ::set) get out of the lock before we proceed. + // + _M_lock._Flush_current_owner(); + + // + // Go through and make sure any event blocks are satisfied. One would expect items only on the reset list, + // but we'll handle both cases -- the runtime should not be leaking regardless. + // + EventWaitNode *pNext; + + EventWaitNode *pNode = reinterpret_cast (_M_pWaitChain); + if (pNode > EVENT_SIGNALED) + { + for(; pNode != NULL; pNode = pNext) + { + pNext = pNode->m_pNext; + if (pNode->Satisfy(NULL)) + { + pNode->Destroy(); + } + } + } + + for (pNode = reinterpret_cast (_M_pResetChain); pNode != NULL; pNode = pNext) + { + pNext = pNode->m_pNext; + pNode->Destroy(); + } +} + +/// +/// Waits on the specified event. +/// +size_t event::wait(unsigned int timeout) +{ + const EventWaitNode *pOldChain; + + // + // Waits with timeout fall back on the heavy weight "wait for multiple" mechanism. The only place + // we use a light-weight spin/stack semantic is with a single *WAIT*. + // + // We can specially handle a 0 timeout "check" here though. + // + if (timeout != COOPERATIVE_TIMEOUT_INFINITE) + { + if (timeout == 0) + { + if (reinterpret_cast (_M_pWaitChain) == EVENT_SIGNALED) + return 0; + else + return COOPERATIVE_WAIT_TIMEOUT; + } + + event *pThis = this; + return event::wait_for_multiple(&pThis, 1, true, timeout); + } + + // Spin wait (no yielding) for the event to be set. + _SpinWaitNoYield spinWait; + + do + { + pOldChain = reinterpret_cast (_M_pWaitChain); + if (pOldChain == EVENT_SIGNALED) + { + return 0; + } + + } while (spinWait._SpinOnce()); + + // + // Give up and block, first putting our context on a stack-based + // list of waiting contexts for this event. + // + SingleWaitBlock block; + EventWaitNode node(&block); + bool fSatisfied = false; + { + critical_section::scoped_lock lockGuard(_M_lock); + + if (_M_pWaitChain == EVENT_SIGNALED) + fSatisfied = true; + else + { + node.m_pNext = Sweep(reinterpret_cast (_M_pWaitChain), true); + _M_pWaitChain = &node; + } + } + + + if (!fSatisfied ) + { + bool bSkip = block.m_smSkip_BlockUnblock == WaitBlock::SKIP // Avoid unnecessary InterlockedCompareExchange for optimizing. + || InterlockedCompareExchange(&block.m_smSkip_BlockUnblock, WaitBlock::DONT_SKIP, WaitBlock::UNDECIDED) == WaitBlock::SKIP; + + if(!bSkip) + Context::Block(); + } + + return 0; +} + +/// +/// Resets the specified event. +/// +void event::reset() +{ + critical_section::scoped_lock lockGuard(_M_lock); + + if (_M_pWaitChain == EVENT_SIGNALED) + { + EventWaitNode *pRoot = NULL; + EventWaitNode *pNext = NULL; + + EventWaitNode *pNode = reinterpret_cast (_M_pResetChain); + _M_pResetChain = NULL; + + for (; pNode != NULL; pNode = pNext) + { + pNext = pNode->m_pNext; + if (pNode->Reset()) + { + // + // We need to shift this back to the wait list. The wait hasn't been satisfied and + // this reset impacts the block. + // + pNode->m_pNext = pRoot; + pRoot = pNode; + } + + } + + _M_pWaitChain = pRoot; + } +} + +/// +/// Sets the specified event. +/// +void event::set() +{ + Context **pContexts = NULL; + ULONG nodeCount = 0; + _MallocaArrayHolder mholder; + + { + critical_section::scoped_lock lockGuard(_M_lock); + + // + // Although it's not technically necessary to interlock this, it allows an optimization for light-weight events + // in that they are able to spin for a period before blocking. Without the fence here, they would not. + // + EventWaitNode *pOldChain; + pOldChain = reinterpret_cast ( + InterlockedExchangePointer (reinterpret_cast (&_M_pWaitChain), EVENT_SIGNALED) + ); + + if (pOldChain > EVENT_SIGNALED) + { + ASSERT(_M_pResetChain == NULL); + + EventWaitNode *pNext; + + // + // Note that the lock grabbed above is within the event, so it's entirely possible that the moment we unblock + // the context, the lock is gone. We also don't want to diddle in the scheduler lists while under a hot + // lock, so build the list of contexts to unblock, release the lock, and then diddle in the scheduler. + // + nodeCount = 0; + for (EventWaitNode *pNode = pOldChain; pNode != NULL; pNode = pNode->m_pNext) + nodeCount++; + + pContexts = mholder._InitOnRawMalloca(_malloca(sizeof (Context *) * nodeCount)); + nodeCount = 0; + + for (EventWaitNode *pNode = pOldChain; pNode != NULL; pNode = pNext) + { + // + // Need to cache the next pointer, since as soon as we unblock, + // the stack-based EventWaitNode may be deallocated. + // + pNext = pNode->m_pNext; + + Context *pContext; + if (pNode->Satisfy(&pContext)) + { + // + // If Satisfy returned true, we need to track the node as it's part of + // a wait-for-all and a reset on this event could impact it. + // + pNode->m_pNext = reinterpret_cast (_M_pResetChain); + + // + // Guarded via the spinlock. + // + _M_pResetChain = pNode; + } + + if (pContext != NULL) + pContexts[nodeCount++] = pContext; + } + } + } + + // + // Unblock contexts outside the given dispatch lock. + // + while(nodeCount-- > 0) + { + pContexts[nodeCount]->Unblock(); + } +} + + +#pragma warning(push) +#pragma warning(disable:26010) + +/// +/// Waits for multiple events to become signaled. +/// +/// +/// An array of events to wait upon +/// +/// +/// A count of events within the array +/// +/// +/// An indication of whether to wait for all events or just a single one +/// +_Use_decl_annotations_ +size_t event::wait_for_multiple(event** pEvents, size_t count, bool fWaitAll, unsigned int timeout) +{ + // + // Handle some trivial cases up front + // + if (pEvents == NULL) + { + throw std::invalid_argument("pEvents"); + } + + // + // Nothing to wait on. + // + if (count == 0) + return 0; + + // + // Optimize for any caller which decides to call this to wait on a single event. All waits with timeouts + // flow through here as we need the heavier weight mechanism. + // + if (count == 1 && (timeout == 0 || timeout == COOPERATIVE_TIMEOUT_INFINITE)) + { + if (pEvents[0] == NULL) + { + throw std::invalid_argument("pEvents"); + } + + return pEvents[0]->wait(timeout); + } + + for (size_t i = 0; i < count; i++) + { + if (pEvents[i] == NULL) + { + throw std::invalid_argument("pEvents"); + } + } + + MultiWaitBlockHolder waitBlock(fWaitAll, count, timeout != COOPERATIVE_TIMEOUT_INFINITE, (timeout != 0 && timeout != COOPERATIVE_TIMEOUT_INFINITE)); + MultiWaitBlock *pWaitBlock = waitBlock.GetWaitBlock(); + + // + // Chain to each event, carefully checking signal state for each as we go. Note that a wait + // any can be satisfied immediately if any fail due to an event already being signaled. In + // that case, we must carefully dispose the rest of the nodes and make sure the counters are + // appropriate for wait block disposal as the chained ones get dechained later on other event + // set/reset/destruction. + // + bool fSatisfied = false; + + for (size_t i = 0; i < count; i++) + { + event *pEvent = pEvents[i]; + + Context *pSatisfiedContext; + + critical_section::scoped_lock lockGuard(pEvent->_M_lock); + + EventWaitNode *pWaitNode = waitBlock.GetWaitNode(i); + waitBlock.Release(); + EventWaitNode *pOldChain = reinterpret_cast (pEvent->_M_pWaitChain); + + if (pOldChain == EVENT_SIGNALED) + { + // + // Event was signaled before we could add ourself to the wait list... We must be + // very careful here. For a "wait any", we are satisfied but need to take care + // to ensure that the heap blocks get appropriately freed and dechained. For a wait + // all, we need to chain to the reset list as it's possible that the event is reset + // before some other event that would satisfy the wait is signaled. + // + if (fWaitAll) + { + if (pWaitNode->Satisfy(&pSatisfiedContext)) + { + pWaitNode->m_pNext = Sweep(reinterpret_cast (pEvent->_M_pResetChain), false); + pEvent->_M_pResetChain = pWaitNode; + } + + if (pSatisfiedContext != NULL) + { + ASSERT(i == count - 1); + fSatisfied = true; + } + } + else + { + // + // The wait is satisfied. + // + pWaitNode->Satisfy(&pSatisfiedContext); + if(pSatisfiedContext != NULL) + fSatisfied = true; + for (size_t j = i + 1; j < count; j++) + { + pWaitNode = waitBlock.GetWaitNode(j); + waitBlock.Release(); + pWaitNode->Satisfy(&pSatisfiedContext); + ASSERT(pSatisfiedContext == NULL); + } + + break; + } + } + else + { + pWaitNode->m_pNext = Sweep(pOldChain, true); + pEvent->_M_pWaitChain = pWaitNode; + } + } + + if (!fSatisfied ) + { + + // + // For explanation of skipping Block/Unblock please see the comments in MultiWaitBlock::SingleSatisfy() method. + // + bool bSkip = pWaitBlock->m_smSkip_BlockUnblock == WaitBlock::SKIP // Avoid unnecessary InterlockedCompareExchange for optimizing. + || InterlockedCompareExchange(&pWaitBlock->m_smSkip_BlockUnblock, WaitBlock::DONT_SKIP, WaitBlock::UNDECIDED) == WaitBlock::SKIP; + + if( !bSkip ) + { + // + // Handle timeouts of zero specially. We don't want to block the thread. + // + if (timeout == 0) + { + if (InterlockedIncrement(&pWaitBlock->m_finalTrigger) == 1) + { + pWaitBlock->m_pSatisfiedBy = NULL; + fSatisfied = true; + pWaitBlock->m_fWaitTimedOut = true; + } + else + { + Context::Block(); + } + } + else + { + if (timeout != COOPERATIVE_TIMEOUT_INFINITE) + { + if (pWaitBlock->m_finalTrigger == 0) + { + if ((pWaitBlock->m_hTimer = RegisterAsyncTimerAndLoadLibrary(timeout, MultiWaitBlock::DispatchEventTimer, pWaitBlock)) == nullptr) + { + // + // Note that the thread is left in a state unexplicable by the scheduler here. It's quite possible someone ::Unblocks this context in + // the future. With this error, we make no attempt to unwind that. + // + throw std::bad_alloc(); + } + waitBlock.Release(); + } + } + Context::Block(); + } + } + } + return (pWaitBlock->m_pSatisfiedBy == NULL) ? COOPERATIVE_WAIT_TIMEOUT : waitBlock.GetIndexOfNode(pWaitBlock->m_pSatisfiedBy); +} + +#pragma warning(pop) + +namespace details +{ + /// + /// Constructs a holder for a single allocation wait block which gets split into a wait block and a series of wait nodes, + /// one per wait object. + /// + MultiWaitBlockHolder::MultiWaitBlockHolder(bool fWaitAll, size_t count, bool timeout, bool timer) : m_count(0) + { + // + // Allocate a single block comprised of all the wait nodes / block that we need to satisfy + // the wait for multiple. + // + m_blockSize = ALIGNED_SIZE(fWaitAll ? sizeof(WaitAllBlock) : sizeof(WaitAnyBlock), P2_ALIGN); + m_nodeSize = ALIGNED_SIZE(sizeof(EventWaitNode), P2_ALIGN); + m_totalBlockSize = m_blockSize + m_nodeSize * count; + + m_pMemBlock = _concrt_new BYTE[m_totalBlockSize]; + + m_pWaitBlock = reinterpret_cast (m_pMemBlock); + if (fWaitAll) + { + _Analysis_assume_(m_totalBlockSize >= sizeof(WaitAllBlock)); + new(m_pMemBlock) WaitAllBlock(count, timeout, timer); + } + else + { + _Analysis_assume_(m_totalBlockSize >= sizeof(WaitAnyBlock)); + new(m_pMemBlock) WaitAnyBlock(count, timeout, timer); + } + + BYTE *pWaitNodeAddr = m_pMemBlock + m_blockSize; + + for (size_t i = 0; i < count; i++) + { + new(pWaitNodeAddr) EventWaitNode(m_pWaitBlock); + pWaitNodeAddr += m_nodeSize; + } + + // + // The number of references on the block is the number of wait objects plus the timer plus one for + // the stack frame of the WaitForMultiple which initialized us. The block gets freed when NotifyCompletedNode + // is called m_refs number of times. This object is responsible, in normal cases, for releasing the single + // stack frame reference. It's also responsible for cleaning up and releasing any references that won't come + // from wait objects / timers due to exceptions thrown in the midst of setting up the wait. + // + m_refs = count + (timer ? 2 : 1); + + } + + /// + /// Destructor for the wait block holder. Releases any references on the block which will not come as the result + /// of a release. + /// + MultiWaitBlockHolder::~MultiWaitBlockHolder() + { + while(m_count++ < m_refs) + m_pWaitBlock->NotifyCompletedNode(); + } + + /// + /// Called in order to satisfy the wait. This handles a single wait/timer combination. Any multi-wait semantic + /// must override this and call the base class in order to present a single-wait semantic. + /// + void MultiWaitBlock::SingleSatisfy(Context **pContextOut, EventWaitNode *pNode) + { + // + // If there is a timeout, the timer may already have unblocked the context. + // + Context *pContext = m_pContext; + bool fSatisfied = true; + if (m_fHasTimeout) + { + if (InterlockedIncrement(&m_finalTrigger) != 1) + fSatisfied = false; + } + + if (fSatisfied) + { + // SingleSatisfy can be called with pNode set to NULL, but only when the wait has timed out. + ASSERT(pNode != NULL); + m_pSatisfiedBy = pNode; + + if (m_hTimer) + { + DeleteAsyncTimerAndUnloadLibrary(static_cast(m_hTimer)); + + // + // Now, we need to answer the question of whether the timer fired and incremented the + // trigger or not. That will answer the question of when we delete the wait block. + // + if (m_finalTrigger == 1) + NotifyCompletedNode(); + } + + // + // The wait_for_multiple() or wait() may be in the process of chaining the context to wait + // chain of the event. Before chaining it has taken a lock on the event. It is possible + // that the current context being unblocked (in this SingleSatisfy()) could be the one + // blocked because of the lock taken above. In this case m_fOkToUnblock flag was set to FALSE in + // wait_for_multiple() or wait() and so here(in set()) we should not Unblock() the context and also set + // a flag to not Block() the context in the wait_for_multiple(), for which m_fDoNotBlock flag + // is set here. This cancels out the Block() Unblock(). + // If we do not take this measure and Unblock if above situation occurs, then Context blocked on + // above lock will run, thus the critical region will be executed concurrently, which is + // disastrous. Also this (Unblocking here) could result in Unblock/Unblock sequence on a + // context which is illegal. + // + bool bSkip = !(pNode->m_pWaitBlock->m_smSkip_BlockUnblock == WaitBlock::DONT_SKIP // Avoid unnecessary InterlockedCompareExchange for optimizing. + || InterlockedCompareExchange(&pNode->m_pWaitBlock->m_smSkip_BlockUnblock, WaitBlock::SKIP, WaitBlock::UNDECIDED) == WaitBlock::DONT_SKIP); + + // + // It is *NOT* safe to touch the this pointer if bSkip is true, or right after the context is unblocked (if bSkip is false) since the context associated + // with this wait block could return from the wait, and destroy the wait block in the process. + // + if(bSkip) + { + if(pContextOut != NULL) + *pContextOut = NULL; // No context in list, hence no Unblocking in set() + } + else if (pContextOut != NULL) + *pContextOut = pContext; + else + pContext->Unblock(); + } + } + + void MultiWaitBlock::DispatchEventTimer(PTP_CALLBACK_INSTANCE instance, void * pContext, PTP_TIMER timer) + { + MultiWaitBlock *pWaitBlock = reinterpret_cast (pContext); + Context *pUnblockContext = NULL; + bool deleteTimer = false; + if (InterlockedIncrement(&pWaitBlock->m_finalTrigger) == 1) + { + pUnblockContext = pWaitBlock->m_pContext; + // Defer the timer deletion until the very end of this callback. + deleteTimer = true; + + // + // Note that after this point, m_hTimer is invalid. Only the entity that transitions m_finalTrigger + // to 1 is allowed to play with deleting the timer. + // + + // Mark the block as timed out. This will allow us to cleanup the wait nodes associated with this wait block + // the next time the event's wait and reset chains are swept. + pWaitBlock->m_fWaitTimedOut = true; + } + + if (pUnblockContext != NULL) + { + pWaitBlock->m_pSatisfiedBy = NULL; + pUnblockContext->Unblock(); + } + + pWaitBlock->NotifyCompletedNode(); + + if (deleteTimer) + { + UnRegisterAsyncTimerAndUnloadLibrary(instance, timer); + } + } + + /// + /// Called when a timer on an event is signaled. + /// + void MultiWaitBlock::DispatchEventTimerXP(LPVOID pContext, BOOLEAN) + { + MultiWaitBlock *pWaitBlock = reinterpret_cast (pContext); + Context *pUnblockContext = NULL; + + if (InterlockedIncrement(&pWaitBlock->m_finalTrigger) == 1) + { + pUnblockContext = pWaitBlock->m_pContext; + platform::__DeleteTimerQueueTimer(GetSharedTimerQueue(), pWaitBlock->m_hTimer, NULL); + + // + // Note that after this point, m_hTimer is invalid. Only the entity that transitions m_finalTrigger + // to 1 is allowed to play with deleting the timer. + // + + // Mark the block as timed out. This will allow us to cleanup the wait nodes associated with this wait block + // the next time the event's wait and reset chains are swept. + pWaitBlock->m_fWaitTimedOut = true; + } + + if (pUnblockContext != NULL) + { + pWaitBlock->m_pSatisfiedBy = NULL; + pUnblockContext->Unblock(); + } + + pWaitBlock->NotifyCompletedNode(); + + } + + /// + /// Called to indicate that the event wait has been satisfied. + /// + bool SingleWaitBlock::Satisfy(Context **pContextOut, EventWaitNode *pNode) + { + // + // For explanation of skipping Block/Unblock please see the comments in MultiWaitBlock::SingleSatisfy() method. + // + bool bSkip = !(pNode->m_pWaitBlock->m_smSkip_BlockUnblock == WaitBlock::DONT_SKIP // Avoid unnecessary InterlockedCompareExchange for optimizing. + || InterlockedCompareExchange(&pNode->m_pWaitBlock->m_smSkip_BlockUnblock, WaitBlock::SKIP, WaitBlock::UNDECIDED) == WaitBlock::DONT_SKIP ); + + if( bSkip ) + { + if(pContextOut) + *pContextOut = NULL; // No context in list, hence no Unblocking in set() + } + else if (pContextOut != NULL) + *pContextOut = m_pContext; + else + m_pContext->Unblock(); + + return false; + } + +#pragma warning(push) +#pragma warning(disable: 4702) + /// + /// Called to indicate that the event for a single wait has been reset. + /// + bool SingleWaitBlock::Reset() + { + ASSERT(false); + return false; + } + + /// + /// Called to indicate that the event node was on the rundown list at event destruction. + /// + void SingleWaitBlock::Destroy() + { + ASSERT(false); + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the wait chain. + /// + bool SingleWaitBlock::SweepWaitNode() + { + return true; + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the reset chain. + /// + bool SingleWaitBlock::SweepResetNode() + { + ASSERT(false); + return false; + } +#pragma warning(pop) + + void MultiWaitBlock::NotifyCompletedNode() + { + size_t waiters = m_waiters; + + // + // Once satisfied, we are responsible for incrementing the completion counter. When it hits + // the number of waiters, we can destroy the shared wait block. + // + if (InterlockedIncrementSizeT(&m_completions) == waiters + 1) + delete[] (reinterpret_cast (this)); + } + + /// + /// Called to indicate that an event for the wait-any has triggered and we should satisfy this + /// wait block. + /// + bool WaitAnyBlock::Satisfy(Context **pContextOut, EventWaitNode *pNode) + { + if (pContextOut != NULL) + *pContextOut = NULL; + + // + // NOTE: m_pWaitBlock is unsafe as soon as we increment the counter if we are not the entity + // to increment the counter to the wait limit. Cache everything up front! + // + ASSERT(m_triggerLimit == 1); + + size_t triggerCount = InterlockedIncrementSizeT(&m_count); + if (triggerCount == m_triggerLimit) + SingleSatisfy(pContextOut, pNode); + + NotifyCompletedNode(); + + // + // On a wait-any, we no longer need the wait node. The single wait block containing the node is + // freed by the last satisfied waiter. + // + return false; + } + + /// + /// Called to indicate that an event in the wait-any has reset. This is irrelevant to us. + /// + bool WaitAnyBlock::Reset() + { + ASSERT(false); + return false; + } + + /// + /// Called to indicate that an event with the node present on the rundown list is being + /// destroyed. This should never be called for a wait any. + /// + void WaitAnyBlock::Destroy() + { + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the wait chain. + /// + bool WaitAnyBlock::SweepWaitNode() + { + if (m_count >= m_triggerLimit || m_fWaitTimedOut) + { + Context *pContext; + // If the wait has timed out, go ahead and satisfy the block. Since the timer has already fired and woken up the context, + // we are not in danger of doing so. + Satisfy(&pContext, NULL); + ASSERT(pContext == NULL); + return false; + } + + return true; + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the reset chain. + /// + bool WaitAnyBlock::SweepResetNode() + { + ASSERT(false); + return false; + } + + /// + /// Called to indicate that an event for the wait-all has triggered and we should satisfy this + /// wait node. Note that this does *NOT* indicate that the wait should be satisfied yet. + /// + bool WaitAllBlock::Satisfy(Context **pContextOut, EventWaitNode *pNode) + { + if (pContextOut != NULL) + *pContextOut = NULL; + + ASSERT(m_triggerLimit >= 1); + + size_t triggerCount = InterlockedIncrementSizeT(&m_count); + if (triggerCount == m_triggerLimit) + { + SingleSatisfy(pContextOut, pNode); + NotifyCompletedNode(); + return false; + } + + return true; + + } + + /// + /// Called to indicate that an event which was previously signaled and counting towards a satisfied + /// wait all block has reset. + /// + bool WaitAllBlock::Reset() + { + size_t triggerLimit = m_triggerLimit; + + // + // Ensure that we never decrement once the wait is satisfied. We need to make sure that a reset subsequent + // just gets rid of the wait block. + // + size_t previousTriggerCount = m_count; + for(;;) + { + if (previousTriggerCount == triggerLimit) + break; + + size_t xchgCount = InterlockedCompareExchangeSizeT(&m_count, previousTriggerCount - 1, previousTriggerCount); + if (xchgCount == previousTriggerCount) + break; + + previousTriggerCount = xchgCount; + } + + if (previousTriggerCount == triggerLimit) + { + NotifyCompletedNode(); + return false; + } + + return true; + + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the wait chain. + /// + bool WaitAllBlock::SweepWaitNode() + { + ASSERT(m_count < m_triggerLimit); + if (m_fWaitTimedOut) + { + Context * pContext; + if (Satisfy(&pContext, NULL)) + Destroy(); + ASSERT(pContext == NULL); + return false; + } + return true; + } + + /// + /// Called in order to check whether a node is still alive or dead during a sweep of the reset chain. + /// + bool WaitAllBlock::SweepResetNode() + { + ASSERT(m_count <= m_triggerLimit); + if (m_count >= m_triggerLimit) + { + // + // The reset will clear us out. + // + Reset(); + return false; + } + else if (m_fWaitTimedOut) + { + Destroy(); + return false; + } + return true; + } + + /// + /// Called when an event with an all-node is destroyed with the event present on a rundown list, this + /// destroys the wait node and releases its shared reference on the wait block. + /// + void WaitAllBlock::Destroy() + { + NotifyCompletedNode(); + } + + /// + /// Called in order to sweep out unused entries from a given node list. This clears dead wait-for-all nodes + /// on a reset-list or dead wait-for-any nodes on the wait-list, as well as nodes associated with timed out wait blocks on both lists. + /// + /// + /// true if the wait chain of an event is being swept and false if the reset chain is being swept + /// + EventWaitNode * Sweep(EventWaitNode *pNode, bool fWaitChain) + { + EventWaitNode *pRoot = NULL; + EventWaitNode *pNext = NULL; + for (; pNode != NULL; pNode = pNext) + { + // Cache the next pointer since the sweep could destroy the swept node. + pNext = pNode->m_pNext; + + bool keepNode = fWaitChain ? pNode->SweepWaitNode() : pNode->SweepResetNode(); + if (keepNode) + { + pNode->m_pNext = pRoot; + pRoot = pNode; + } + } + + return pRoot; + } + +// +// A StructuredEvent is simply a pointer with a few distinguished values. A newly +// initialized StructuredEvent will be set to 0. A StructuredEvent that has one or more waiters +// on it, that is, contexts which called StructuredEvent::Wait before StructuredEvent::Set has +// signaled the StructuredEvent, will simply point to a linked list of those waiters, +// via stack-blocks so no heap allocation is required. A StructuredEvent that is +// signaled is set to 1. Once an event is signaled, it can be safely +// deallocated, even if StructuredEvent::Set is still running. +// + +// +// StructuredEvent - Synchronization object mediating access to the low-level context +// Block and Unblock APIs. +// +struct StructuredEventWaitNode +{ + StructuredEventWaitNode *m_next; + ::Concurrency::Context *m_context; +}; + +// +// Wait until the event is signaled (via some other context calling Set()) +// +void StructuredEvent::Wait() +{ + // + // Spin a short time waiting to be signaled before we block + // + void *oldPtr = m_ptr; + if (oldPtr == EVENT_SIGNALED) + return; + + _SpinWaitBackoffNone spinWait; + for (;;) + { + oldPtr = m_ptr; + if (oldPtr == EVENT_SIGNALED) + return; + + if ( !spinWait._SpinOnce()) + break; + } + + // + // Give up and block, first putting our context on a stack-based + // list of waiting contexts for this event + // + ::Concurrency::Context *context = SchedulerBase::FastCurrentContext(); + StructuredEventWaitNode node; + + node.m_context = context; + + for (;;) + { + node.m_next = (StructuredEventWaitNode*)oldPtr; + + void *xchgPtr = InterlockedCompareExchangePointer(&m_ptr, &node, oldPtr); + + if (xchgPtr == oldPtr) + break; + + oldPtr = xchgPtr; + + if (oldPtr == EVENT_SIGNALED) + { + // + // Event was signaled before we could add ourself to the wait + // list, so no need to block any longer + // + return; + } + } + + context->Block(); +} + +// +// Set the event as signaled, and unblock any other contexts waiting +// on the event. +// +void StructuredEvent::Set() +{ + void *oldPtr = m_ptr; + + // + // Mark the event signaled, and get the waiters list, if any + // + + for (;;) + { + void *xchgPtr = InterlockedCompareExchangePointer(&m_ptr, EVENT_SIGNALED, oldPtr); + + if (xchgPtr == oldPtr) + break; + + oldPtr = xchgPtr; + } + + // + // If the event had any waiters, then unblock them + // + if (oldPtr > EVENT_SIGNALED) + { + for (StructuredEventWaitNode *node = (StructuredEventWaitNode *)oldPtr, *next; node != NULL; node = next) + { + // + // Need to cache the next pointer, since as soon as we unblock, + // the stack-based StructuredEventWaitNode may be deallocated. + // + // Technically, there should be a memory fence after retrieving + // the next pointer, but practically it's unnecessary, as long + // as there is a locked operation inside the call to Unblock + // before the blocked context starts running. I don't think + // it's possible to write a scheduler unblock operation without + // needing a locked op, so I'm avoiding the extra cost per + // waiter here. + // + + next = node->m_next; + node->m_context->Unblock(); + } + } +} + +} // namespace details + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/location.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/location.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef1b234f985350d76a9bf367db99ff0e2cf76d38 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/location.cpp @@ -0,0 +1,158 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// location.cpp +// +// Implementation file of the metaphor for a location. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ + typedef BOOL (WINAPI *PFN_GetNumaNodeNumberFromHandle)(HANDLE, PUSHORT); + + /// + /// Constructs a specific location. + /// + _Use_decl_annotations_ + location::location(_Type _LocationType, unsigned int _Id, unsigned int _BindingId, void *_PBinding) : + _M_type(_LocationType), + _M_reserved(0), + _M_bindingId(_BindingId), + _M_pBinding(_PBinding) + { + // + // Guarantee order per union. + // + _M_ptr = NULL; + _M_id = _Id; + } + + /// + /// Returns a location which represents a given NUMA node. + /// + /// + /// The NUMA node number to construct a location for. + /// + /// + /// A location representing the NUMA node specified by the parameter. + /// + location location::from_numa_node(unsigned short _NumaNodeNumber) + { + ULONG highestNodeNumber = platform::__GetNumaHighestNodeNumber(); + + if (_NumaNodeNumber > highestNodeNumber) + { + throw invalid_operation(); + } + + return location(location::_NumaNode, _NumaNodeNumber, 0, NULL); + } + + /// + /// Determines whether two locations have an intersection. This is a fast intersection which avoids certain checks by knowing that + /// the *this* pointer is a virtual processor location for a validly bound virtual processor. + /// + /// + /// The location to intersect with this. + /// + /// + /// An indication as to whether the two locations intersect. + /// + bool location::_FastVPIntersects(const location& _Rhs) const + { + switch(_Rhs._M_type) + { + case _ExecutionResource: + return _M_id == _Rhs._M_id; + + case _NumaNode: + return _As()->GetOwningNode()->GetNumaNodeNumber() == (DWORD)_Rhs._M_id; + + case _SchedulingNode: + return static_cast(_As()->GetOwningNode()->Id()) == _Rhs._M_id; + + case _System: + return true; + + } + + return false; + } + + /// + /// Determines whether two locations have an intersection. This is a fast intersection which avoids certain checks by knowing that + /// the *this* pointer is a node for a validly bound node. + /// + /// + /// The location to intersect with this. + /// + /// + /// An indication as to whether the two locations intersect. + /// + bool location::_FastNodeIntersects(const location& _Rhs) const + { + switch(_Rhs._M_type) + { + case _ExecutionResource: + return _As()->ContainsResourceId(_Rhs._M_id); + + case _NumaNode: + return _As()->GetNumaNodeNumber() == (DWORD)_Rhs._M_id; + + case _SchedulingNode: + return _M_id == _Rhs._M_id; + + case _System: + return true; + } + + return false; + } + + /// + /// Returns a location representing the most specific place the calling thread is executing upon. + /// + location location::current() + { + location current; + + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + if (pCurrentContext != NULL && !pCurrentContext->IsExternal()) + { + InternalContextBase *pCtx = static_cast(pCurrentContext); + + pCtx->EnterCriticalRegion(); + VirtualProcessor *pVProc = pCtx->m_pVirtualProcessor; + current = location(location::_ExecutionResource, pVProc->GetExecutionResourceId(), pVProc->GetOwningNode()->GetScheduler()->Id(), pVProc); + pCtx->ExitCriticalRegion(); + } + + return current; + } + + location __cdecl location::_Current_node() + { + location current; + + ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext(); + if (pCurrentContext != NULL && !pCurrentContext->IsExternal()) + { + InternalContextBase *pCtx = static_cast(pCurrentContext); + + pCtx->EnterCriticalRegion(); + VirtualProcessor *pVProc = pCtx->m_pVirtualProcessor; + SchedulingNode *pNode = pVProc->GetOwningNode(); + current = location(location::_SchedulingNode, pNode->Id(), pNode->GetScheduler()->Id(), pNode); + pCtx->ExitCriticalRegion(); + } + + return current; + } +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4684d3370fdf3cb1ec194de8cfb036b509df35b1 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.cpp @@ -0,0 +1,12 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// pch.cpp +// +// PCH source for ConcRT +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.h new file mode 100644 index 0000000000000000000000000000000000000000..b3ddf0988d076a9282b80e56d5a37d63fa207263 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/pch.h @@ -0,0 +1,14 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// pch.h +// +// PCH header for ConcRT +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ppl.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ppl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a06c5d6c6f4c52fa4e1f6348cc99a957feb7d10 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ppl.cpp @@ -0,0 +1,62 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// ppl.cpp +// +// Utility routines for use in PPL. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +// Candidate primes... these must be sorted. Note that this isn't a complete list of primes, and is +// capped at reasonable level (e.g., a size of 281 means you expect to have about that many threads). +static const unsigned int g_getCombinableCandidatePrimes[] = { + 11, 19, 37, 67, 73, 151, 281 +}; + +namespace Concurrency +{ + +namespace details +{ + _CONCRTIMP size_t _GetCombinableSize() + { + unsigned int size = CurrentScheduler::GetNumberOfVirtualProcessors(); + if (size == static_cast(-1)) + { + // Choose a reasonable arbitrary (prime) size when ConcRT isn't around. + return 11; + } + + // ConcRT gave us the number of vprocs. + size *= 2; + for (unsigned int candidatePrime : g_getCombinableCandidatePrimes) + { + if (size < candidatePrime) + { + return candidatePrime; + } + } + + return g_getCombinableCandidatePrimes[sizeof(g_getCombinableCandidatePrimes) + / sizeof(g_getCombinableCandidatePrimes[0]) - 1]; + } +} // namespace details + +/// +/// Returns an indication of whether the task group which is currently executing inline on the current context +/// is in the midst of an active cancellation (or will be shortly). Note that if there is no task group currently +/// executing inline on the current context, false will be returned. +/// +_CONCRTIMP bool is_current_task_group_canceling() +{ + return Context::IsCurrentTaskCollectionCanceling(); +} + +} // namespace concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rminternal.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rminternal.h new file mode 100644 index 0000000000000000000000000000000000000000..c41063598a7161bd0c51dcca9baae4ff2bc8e522 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rminternal.h @@ -0,0 +1,732 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// rminternal.h +// +// Main internal header file for ConcRT's Resource Manager. +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +namespace Concurrency +{ +namespace details +{ + // The lowest two bits are used to determine the type of the pointer stored in the + // execution resource TLS slot (created in the RM). + static const size_t TlsResourceBitMask = 0x3; + static const size_t TlsResourceInResource = 0x0; + static const size_t TlsResourceInProxy = 0x1; + + // The RM has an array of processor nodes and cores representing the hardware topology on the machine. + // Every scheduler that asks for an allocation, gets it's own copy of this array of nodes/cores once they + // have been granted an allocation of cores by the RM, that is stored in the corresponding scheduler proxy. + + /// + /// An abstraction of a hardware affinity that understands how to deal with affinity on both Win7 and pre-Win7 + /// platforms. + /// + struct HardwareAffinity + { + public: + + /// + /// Construct an empty affinity. + /// + HardwareAffinity() + { + memset(&m_affinity, 0, sizeof(m_affinity)); + m_affinity.Group = 0; + m_affinity.Mask = 0; + } + + /// + /// Construct a hardware affinity from a given thread. + /// + HardwareAffinity(HANDLE hThread); + + /// + /// Construct a Win7 understood affinity. + /// + HardwareAffinity(USHORT processorGroup, ULONG_PTR affinityMask) + { + memset(&m_affinity, 0, sizeof(m_affinity)); + m_affinity.Group = processorGroup; + m_affinity.Mask = affinityMask; + } + + /// + /// Construct a pre-Win7 understood affinity. + /// + HardwareAffinity(DWORD_PTR affinityMask) + { + memset(&m_affinity, 0, sizeof(m_affinity)); + m_affinity.Group = 0; + m_affinity.Mask = affinityMask; + } + + /// + /// Copy construct an affinity. + /// + HardwareAffinity(const HardwareAffinity &src) + { + memcpy(&m_affinity, &src.m_affinity, sizeof(m_affinity)); + } + + /// + /// Compare two affinities + /// + bool operator==(const HardwareAffinity &rhs) + { + return (rhs.m_affinity.Group == m_affinity.Group && rhs.m_affinity.Mask == m_affinity.Mask); + } + + /// + /// Compare two affinities + /// + bool operator!=(const HardwareAffinity &rhs) + { + return !operator==(rhs); + } + + /// + /// Copy an affinity. + /// + HardwareAffinity& operator=(const HardwareAffinity &rhs) + { + m_affinity.Group = rhs.m_affinity.Group; + m_affinity.Mask = rhs.m_affinity.Mask; + return *this; + } + + /// + /// Return the group number. + /// + USHORT GetGroup() + { + return m_affinity.Group; + } + + /// + /// Return the group mask. + /// + KAFFINITY GetMask() + { + return m_affinity.Mask; + } + + /// + /// Modify the affinity to be the intersection of the existing affinity and the provided affinity. + /// + void IntersectWith(KAFFINITY affinity) + { + m_affinity.Mask &= affinity; + } + + /// + /// Applies this hardware affinity to a thread. + /// + /// + /// The thread handle to which to apply this affinity. + /// + void ApplyTo(HANDLE hThread); + + GROUP_AFFINITY m_affinity; + }; + + /// + /// Base class for description of a core or hardware thread. + /// + struct ProcessorCore + { + enum CoreState + { + // Initial state for all cores. + Unknown = 0, + + // A core that is not assigned to a scheduler proxy, either because the scheduler proxy did + // not ask for it (it already has what it desires), or because it is assigned to some other scheduler. + // This state is only used for core in a scheduler's local view of resources. + Unassigned, + + // The core is available and may be reserved for or allocated to a scheduler. + Available, + + // The core is reserved for a scheduler by the Resource Manager. This state is only used for core + // in a scheduler's local view of resources. + Reserved, + + // The core is allocated to a scheduler. Cores transition from Reserved to Allocated once the + // scheduler proxy has allocated execution resources or virtual processors for its scheduler. + Allocated, + + // When a scheduler releases a core for a different scheduler, it sets its core state to Stolen. + // This enables it to track the cores it has relinquished. If the core is not allocated to the + // receiving scheduler, it will revert back to Allocated for the scheduler proxy it came from. + Stolen, + + // A core is considered idle during dynamic core migration if the scheduler(s) that core is assigned + // to, have all vprocs de-activated. This state is only used for cores in the global map. + Idle + }; + + // 'Available' means available for assignment to a scheduler during the allocation calculation. + CoreState m_coreState; + + // The Resource Manager assigned identifier for the processor core. + unsigned int m_id; + + // The processor number in Win7 {group, processor number} id scheme. + BYTE m_processorNumber; + }; + + // Forward declaration. + struct GlobalNode; + class ResourceManager; + + /// + /// Representation of a processor core within the RM's global map of execution resources. Information in this struct + /// represents a systemwide view of the underlying hardware thread. + /// + struct GlobalCore : public ProcessorCore + { + // Back pointer to the node for topological enumeration. + GlobalNode *m_pOwningNode; + + // The number of schedulers that this core is assigned to. + unsigned int m_useCount; + + // Used to send notifications to qualifying schedulers regarding external subscription level changes. + LONG m_currentSubscriptionLevel; + LONG m_previousSubscriptionLevel; + + // This field is used during core migration to represent the number of schedulers that this core has been allocated + // to, that have also deactivated all virtual processors on the core, i.e. the number of schedulers that are 'idle' + // with respect to this core. When this is equal to the use count, the core is considered 'idle'. + unsigned int m_idleSchedulers; + + /// + /// Initializes a processor node. + /// + void Initialize(GlobalNode *pOwningNode, unsigned int id, BYTE processorNumber) + { + m_pTopologyObject = _concrt_new TopologyObject(this); + + m_pOwningNode = pOwningNode; + m_id = id; + m_processorNumber = processorNumber; + } + + ~GlobalCore() + { + delete m_pTopologyObject; + } + + //************************************************** + // Topology walking: + // + + // + // TRANSITION: This needs to be eliminated. There are a slew of memcpy and memset operations on GlobalCore and GlobalNode which + // assume this is how they initialize and copy the base class. We cannot add virtual methods on GlobalCore without cleaning ALL of that + // up. Hence, we heap alloc a side object until such time as it can be cleaned up. + // + struct TopologyObject : public ITopologyExecutionResource + { + GlobalCore *m_pCore; + + TopologyObject(GlobalCore *pCore) : m_pCore(pCore) + { + } + + /// + /// Returns an interface to the next execution resource in enumeration order. + /// + /// + /// An interface to the next execution resource in enumeration order. If there are no more nodes in enumeration order of the node to which + /// this execution resource belongs, this method will return NULL. + /// + /// + /// + /**/ + virtual ITopologyExecutionResource *GetNext() const; + + /// + /// Returns the resource manager's unique identifier for this execution resource. + /// + /// + /// The resource manager's unique identifier for this execution resource. + /// + /**/ + virtual unsigned int GetId() const + { + return m_pCore->m_id; + } + + } *m_pTopologyObject; + }; + + /// + /// Representation of a processor core within a scheduler proxy's local map of execution resources. Information in this struct + /// represents the schedulers utilization of the underlying hardware thread. + /// + struct SchedulerCore : public ProcessorCore + { + // When virtual processor roots are created for a scheduler proxy, or external threads are subscribed, the corresponding + // execution resources are inserted into this list. + List m_resources; + + // Each scheduler core has a pointer to the corresponding global core's use count. + unsigned int* m_pGlobalUseCountPtr{}; + + // This field represents the number of activated virtual processors and subscribed threads that a scheduler has + // on this core at any time. When a virtual processor root is deactivated, or when a thread subscription is released + // the count is decremented. The core is considered to be 'idle' in the scheduler it belongs to, if this value is 0. + volatile LONG m_subscriptionLevel{}; + + // Used to send notifications to qualifying schedulers regarding external subscription level changes. + LONG m_currentSubscriptionLevel{}; + LONG m_previousSubscriptionLevel{}; + + // The number of threads that were assigned to this core through initial allocation or core migration. + // Note that this is not necessarily equal to the number of roots in the m_resources list, since the list + // includes oversubscribed vproc roots as well. + unsigned int m_numAssignedThreads{}; + + // The total number of threads (running on vprocs and external) that require this core to be fixed. + unsigned int m_numFixedThreads{}; + + // The number of external threads that run on this core. + unsigned int m_numExternalThreads{}; + + // This is set to true for a scheduler proxy's core during static allocation or core migration if the subscription + // level on the core is found to be 0 when the Dynamic RM worker is executing. The subscription value can change + // as soon as it is captured, but the captured value is what is used for successive computation. + bool m_fIdleDuringDRM{}; + + // This is set to true for a scheduler proxy's core during core migration, if this is an borrowed core. + // An borrowed core is a core that is assigned to one or more different schedulers, but was found to be idle. + // The RM temporarily assigns idle resources to schedulers that need them. + bool m_fBorrowed{}; + + // This variable is set to true when a borrowed core is converted to a fixed core. When the core is unfixed, + // it is marked borrowed again. + bool m_fPreviouslyBorrowed{}; + + /// + /// Returns whether this core is fixed, i.e., cannot be removed by the RM. + /// + bool IsFixed() + { + return m_numFixedThreads > 0; + } + + /// + /// Returns whether this core is idle, i.e., its subscription level was 0 at the time it was retrieved by the RM. + /// Note that this state could change, but once we capture it, we consider it idle until the next time it is captured. + /// + bool IsIdle() + { + return m_fIdleDuringDRM; + } + + /// + /// Returns whether this core is borrowed, i.e., it was temporarily lent to this scheduler due to the owning + /// scheduler being idle on this core. + /// + bool IsBorrowed() + { + return m_fBorrowed; + } + }; + + /// + /// Base class for the description of a processor package or NUMA node. + /// + struct ProcessorNode + { + // The affinity mask of the node. + ULONG_PTR m_nodeAffinity; + + // The total number of cores in the node. + unsigned int m_coreCount; + + // The number cores that are available for allocation (cores whose state is ProcessorCore::Available) + unsigned int m_availableCores; + + // The group number in the Win7 {group, mask} id format. + unsigned int m_processorGroup; + + // The node id which maps to a scheduler node id. + unsigned int m_id; + + // The NUMA node to which this node belongs. + DWORD m_numaNodeNumber; + }; + + /// + /// Representation of a processor node within a scheduler proxy's local map of execution resources. Information in this struct + /// represents the schedulers utilization of the underlying node. + /// + struct SchedulerNode : public ProcessorNode + { + // A scratch field used during allocation. The allocation routine works by looking at cores with m_useCount=0, + // grabs all it can, then looks at m_useCount=1, then m_useCount=2, etc... During an allocation attempt at a particular + // use count, cores that were reserved at previous use counts are stored in m_reservedCores, and cores available at the + // current use count are stored in m_availableCores. A subset of the available cores may be reserved for the scheduler + // proxy. + unsigned int m_reservedCores; + + // number of cores allocated to the scheduler proxy (this field is only applicable to a scheduler proxy's nodes) + unsigned int m_allocatedCores; + + // The number of allocated cores that are borrowed. An borrowed core is a core that is assigned to + // one or more different schedulers, but was found to be idle. The RM temporarily assigns idle resources to + // schedulers that need them. + unsigned int m_numBorrowedCores; + + // The number of cores on this node that are considered fixed. Fixed cores cannot be removed by the RM during static/dynamic allocation. + unsigned int m_numFixedCores; + + // The number of cores in this node for the scheduler in question that were found to be idle during the dynamic RM phase. This is + // a scratch field, and the value is stale outside of dynamic RM phases. + unsigned int m_numDRMIdle; + + // The number of borrowed cores in this node for the scheduler in question that were found to be idle during the dynamic RM phase. + // This is a scratch field, and the value is stale outside of dynamic RM phases. + unsigned int m_numDRMBorrowedIdle; + + // The array of cores in this node. + SchedulerCore * m_pCores; + + /// + /// Returns the number of cores that were found to be idle. + /// + unsigned int GetNumIdleCores() + { + return m_numDRMIdle; + } + + /// + /// Returns the number of allocated cores in this node that are fixed - cannot be removed by dynamic RM. + /// + unsigned int GetNumFixedCores() + { + return m_numFixedCores; + } + + /// + /// Returns the number of movable cores within this node. + /// + unsigned int GetNumMigratableCores() + { + return m_allocatedCores - m_numFixedCores; + } + + /// + /// Returns the number of owned cores - cores that are not borrowed from a different scheduler. + /// + unsigned int GetNumOwnedCores() + { + return m_allocatedCores - m_numBorrowedCores; + } + + /// + /// Returns the number of non-borrowed, non-fixed cores. + unsigned int GetNumOwnedMigratableCores() + { + return m_allocatedCores - m_numBorrowedCores - m_numFixedCores; + } + + /// + /// Returns the number of borrowed cores - cores that were temporarily lent to this scheduler since the scheduler(s) they + /// were assigned to, were not using them. + /// + unsigned int GetNumBorrowedCores() + { + return m_numBorrowedCores; + } + + /// + /// Returns the number of borrowed cores that are idle. + /// + unsigned int GetNumBorrowedIdleCores() + { + return m_numDRMBorrowedIdle; + } + + /// + /// Returns the number of borrowed cores that are not idle. + /// + unsigned int GetNumBorrowedInUseCores() + { + ASSERT(m_numBorrowedCores >= m_numDRMBorrowedIdle); + return (m_numBorrowedCores - m_numDRMBorrowedIdle); + } + + /// + /// Deallocates memory allocated by the node. + /// + void Cleanup(void) + { + delete [] m_pCores; + } + }; + + /// + /// Representation of a processor node within the RM's global map of execution resources. Information in this struct + /// represents a systemwide view of the underlying node. + /// + struct GlobalNode : public ProcessorNode + { + // Back pointer to the RM for topological enumeration + ResourceManager *m_pRM; + + // A scratch field used during dynamic RM allocation, on the RM's global copy of nodes. Idle cores represents the number + // of cores on this node that are idle and can temporarily be assigned to another scheduler that needs cores. + unsigned int m_idleCores; + + // The array of cores in this node. + GlobalCore * m_pCores; + + /// + /// Initializes a processor node. + /// + // + // coreCount == 0 / baseProcNum == 0 is for regular topologies + // coreCount != 0 / baseProcNum != 0 is for fake / created topologies + // + void Initialize(ResourceManager *pRM, USHORT id, USHORT processorGroup, ULONG_PTR affinityMask, unsigned int coreCount = 0, unsigned int baseProcNum = 0) + { + m_pTopologyObject = _concrt_new TopologyObject(this); + + m_pRM = pRM; + m_id = id; + m_processorGroup = processorGroup; + m_nodeAffinity = affinityMask; + + if (coreCount == 0) + m_coreCount = NumberOfBitsSet(affinityMask); + else + m_coreCount = coreCount; + + m_availableCores = 0; + + m_pCores = _concrt_new GlobalCore[m_coreCount]; + memset(m_pCores, 0, m_coreCount * sizeof(GlobalCore)); + + for (unsigned int i = 0, j = 0; j < m_coreCount; ++i) + { + ASSERT(i < sizeof(ULONG_PTR) * 8); + + // Check if the LSB of the affinity mask is set. + if (coreCount != 0 || ((affinityMask & 1) != 0)) + { + // Bit 0 of the affinity mask corresponds to processor number 0, bit 1 to processor number 1, etc... + if (coreCount == 0) + m_pCores[j++].Initialize(this, (m_processorGroup << 8) + i, (BYTE)i); + else + #pragma warning(suppress: 6385) // False positive warning, VSO-1806798 + m_pCores[j++].Initialize(this, (m_processorGroup << 16) + (id << 8) + i, (BYTE)i + (BYTE)baseProcNum); + } + // Right shift the affinity by 1. + affinityMask >>= 1; + } + } + + /// + /// Returns the next core from pCore within the node. + /// + GlobalCore *GetNextGlobalCore(const GlobalCore *pCore) + { + unsigned int idx = (unsigned int)((pCore - m_pCores) + 1); + return ((idx < m_coreCount) ? &m_pCores[idx] : NULL); + } + + ~GlobalNode() + { + delete m_pTopologyObject; + } + + //************************************************** + // Topology Walking: + // + + // + // TRANSITION: This needs to be eliminated. There are a slew of memcpy and memset operations on GlobalCore and GlobalNode which + // assume this is how they initialize and copy the base class. We cannot add virtual methods on GlobalCore without cleaning ALL of that + // up. Hence, we heap alloc a side object until such time as it can be cleaned up. + // + struct TopologyObject : public ITopologyNode + { + GlobalNode *m_pNode; + + TopologyObject(GlobalNode *pNode) : m_pNode(pNode) + { + } + + /// + /// Returns an interface to the next node in enumeration order. + /// + /// + /// An interface to the next node in enumeration order. If there are no more nodes in enumeration order of the system topology, this method + /// will return NULL. + /// + /// + /// + /**/ + virtual ITopologyNode *GetNext() const; + + /// + /// Returns the resource manager's unique identifier for this node. + /// + /// + /// The resource manager's unique identifier for this node. + /// + /// + /// The Concurrency Runtime represents hardware threads on the system in groups of processor nodes. Nodes are usually derived from + /// the hardware topology of the system. For example, all processors on a specific socket or a specific NUMA node may belong to the + /// same processor node. The Resource Manager assigns unique identifiers to these nodes starting with 0 up to and including + /// nodeCount - 1, where nodeCount represents the total number of processor nodes on the system. + /// The count of nodes can be obtained from the function GetProcessorNodeCount. + /// + /**/ + virtual unsigned int GetId() const + { + return m_pNode->m_id; + } + + /// + /// Returns the Windows assigned NUMA node number to which this Resource Manager node belongs. + /// + /// + /// The Windows assigned NUMA node number to which this Resource Manager node belongs. + /// + /// + /// A thread proxy running on a virtual processor root belonging to this node will have affinity to at least the NUMA node level for the NUMA + /// node returned by this method. + /// + /**/ + virtual DWORD GetNumaNode() const + { + return m_pNode->m_numaNodeNumber; + } + + /// + /// Returns the number of execution resources grouped together under this node. + /// + /// + /// The number of execution resources grouped together under this node. + /// + /// + /**/ + virtual unsigned int GetExecutionResourceCount() const + { + return m_pNode->m_coreCount; + } + + /// + /// Returns the first execution resource grouped under this node in enumeration order. + /// + /// + /// The first execution resource grouped under this node in enumeration order. + /// + /// + /**/ + virtual ITopologyExecutionResource *GetFirstExecutionResource() const + { + return m_pNode->m_pCores->m_pTopologyObject; + } + } *m_pTopologyObject; + }; + + /// + /// Used to store information during static and dynamic allocation. + /// + struct AllocationData + { + // Index into an array of schedulers - used for sorting, etc. + unsigned int m_index; + + // Additional allocation to give to a scheduler after proportional allocation decisions are made. + unsigned int m_allocation; + + // Used to hold a scaled allocation value during proportional allocation. + double m_scaledAllocation; + + // The scheduler proxy this allocation data is for. + SchedulerProxy *m_pProxy; + + // Number of idle cores in a scheduler proxy during static allocation or dynamic core migration. + unsigned int m_numIdleCores; + + // Number of idle cores in a scheduler proxy during static allocation or dynamic core migration that are also borrowed. During core + // migration these cores are the first to go. + unsigned int m_numBorrowedIdleCores; + }; + + struct StaticAllocationData : public AllocationData + { + // A field used during static allocation to decide on an allocation proportional to each scheduler's desired value. + double m_adjustedDesired; + + // Tells if a thread subscription is a part of this static allocation request. + bool m_fNeedsExternalThreadAllocation; + + // Keeps track of stolen cores during static allocation. + unsigned int m_numCoresStolen; + }; + + struct DynamicAllocationData : public AllocationData + { + // This variable is toggled back in forth during dynamic migration to instruct the RM whether or not + // an exact fit allocation should be attempted - i.e. if a node has 3 available cores, but this scheduler proxy + // needs only 2, keep searching in case a later node is found with 2 available cores. + bool m_fExactFitAllocation; + + // Fully loaded is set to true when a scheduler is using all the cores that are allocated to it (no cores are idle) + // AND it has less than its desired number of cores. + bool m_fFullyLoaded; + + // Number suggested as an appropriate allocation for the scheduler proxy, by the hill climbing instance. + unsigned int m_suggestedAllocation; + +#if defined(CONCRT_TRACING) + unsigned int m_originalSuggestedAllocation; +#endif + + union + { +#pragma warning(push) +#pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union + // Struct used for a receiving proxy. + struct + { + // Number of nodes in the scheduler proxy that are partially allocated. + unsigned int m_numPartiallyFilledNodes; + + // As we go through dynamic allocation, the starting node index moves along the array of sorted nodes, + // in a scheduling proxy that is receiving cores. + unsigned int m_startingNodeIndex; + }; + // Struct used for a giving proxy. + struct + { + // Maximum number of borrowed idle cores this scheduler can give up. + unsigned int m_borrowedIdleCoresToMigrate; + + // Maximum number of borrowed in-use cores this scheduler can give up. + unsigned int m_borrowedInUseCoresToMigrate; + + // Maximum number of owned cores this scheduler can give up. + unsigned int m_ownedCoresToMigrate; + }; +#pragma warning(pop) + }; + }; +} // namespace details +}; // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rtlocks.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rtlocks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73a456366767b16acc44b1df9458a3ab98907c5b --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/rtlocks.cpp @@ -0,0 +1,1704 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// rtlocks.cpp +// +// Implementation file for locks used only within the runtime implementation. The locks +// themselves are expected to be dependent on the underlying platform definition. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +#pragma warning (disable : 4702) + +namespace Concurrency +{ +namespace details +{ + const unsigned int SPIN_COUNT = 4000; + + unsigned int _SpinCount::_S_spinCount = SPIN_COUNT; + + static const long NotTriggered = 0; + static const long TriggeredByUnblock = 1; + static const long TriggeredByTimeout = 2; + +#if defined(_DEBUG) + + #define DebugBitsNone 0 + #define DebugBitsMask 0xF0000000 + + /// + /// Returns a set of debug bits indicating where the lock was acquired. + /// + LONG GetDebugBits() + { + return DebugBitsNone; + } + + /// + /// Validates the lock conditions. + /// + void ValidateDebugBits(LONG dbgBits) + { + (dbgBits); + } +#endif // _DEBUG + + + + void _SpinCount::_Initialize() + { + _S_spinCount = (::Concurrency::GetProcessorCount() > 1) ? SPIN_COUNT : 0; + } + + unsigned int _SpinCount::_Value() + { + return _S_spinCount; + } + + // + // The non-reentrant lock for use with the thread-based implementation is defined as + // a 32-bit integer that is set to '1' when the lock is held, using interlocked + // APIs. + // + _NonReentrantBlockingLock::_NonReentrantBlockingLock() + { + static_assert(sizeof(CRITICAL_SECTION) <= sizeof(_M_criticalSection), "_M_critical section buffer too small"); + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + new(pCriticalSection) CRITICAL_SECTION; + platform::__InitializeCriticalSectionEx(pCriticalSection, _SpinCount::_S_spinCount); + } + + _NonReentrantBlockingLock::~_NonReentrantBlockingLock() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + DeleteCriticalSection(pCriticalSection); + } + + // + // Acquire the lock using an InterlockedExchange on _M_lock. After s_spinCount + // number of retries, it will begin calling sleep(0). + // + void _NonReentrantBlockingLock::_Acquire() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + EnterCriticalSection(pCriticalSection); + } + + void _NonReentrantLock::_DebugAcquire() + { +#if defined(_DEBUG) + LONG old; + LONG dbgBits = GetDebugBits(); + _SpinWaitBackoffNone spinWait(_Sleep0); + + for (;;) + { + // + // Under the debug build, verify lock sharing rules in the runtime by stealing high bits of the _M_lock field. + // This is purely for UMS so we don't run into people changing lock structures and inadvertently causing HARD TO FIND + // random deadlocks in UMS. + // + old = _M_Lock; + if ((old & 1) == 0) + { + LONG destVal = old | 1 | dbgBits; + LONG xchg = InterlockedCompareExchange(&_M_Lock, destVal, old); + + if (xchg == old) + { + ValidateDebugBits(destVal); + break; + } + } + + spinWait._SpinOnce(); + } +#endif // _DEBUG + } + + // + // Try to acquire the lock, does not spin if it is unable to acquire. + // + bool _NonReentrantBlockingLock::_TryAcquire() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + return TryEnterCriticalSection(pCriticalSection) != 0; + } + + bool _NonReentrantLock::_DebugTryAcquire() + { +#if defined(_DEBUG) + LONG dbgBits = GetDebugBits(); + LONG old = _M_Lock; + + if ((old & 1) == 0) + { + for(;;) + { + if ((old & 1) == 1) + break; + + LONG destVal = old | 1 | dbgBits; + LONG xchg = InterlockedCompareExchange(&_M_Lock, destVal, old); + if (xchg == old) + { + ValidateDebugBits(destVal); + return true; + } + + old = xchg; + } + } +#endif // _DEBUG + return false; + } + + // + // Release the lock, which can be safely done without a memory barrier + // + void _NonReentrantBlockingLock::_Release() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + LeaveCriticalSection(pCriticalSection); + } + +#define NULL_THREAD_ID -1L + + _ReentrantBlockingLock::_ReentrantBlockingLock() + { + static_assert(sizeof(CRITICAL_SECTION) <= sizeof(_M_criticalSection), "_M_critical section buffer too small"); + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + new(pCriticalSection) CRITICAL_SECTION; + platform::__InitializeCriticalSectionEx(pCriticalSection, _SpinCount::_S_spinCount); + } + + _ReentrantBlockingLock::~_ReentrantBlockingLock() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + DeleteCriticalSection(pCriticalSection); + } + + _ReentrantLock::_ReentrantLock() + { + _M_owner = NULL_THREAD_ID; + _M_recursionCount = 0; + } + + void _ReentrantBlockingLock::_Acquire() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + EnterCriticalSection(pCriticalSection); + } + + void _ReentrantLock::_Acquire() + { + LONG id = (LONG) GetCurrentThreadId(); + + LONG old; + _SpinWaitBackoffNone spinWait(_Sleep0); + +#if defined(_DEBUG) + LONG dbgBits = GetDebugBits(); +#endif // _DEBUG + + for (;;) + { + + old = InterlockedCompareExchange(&_M_owner, id, NULL_THREAD_ID); + + if ( old == NULL_THREAD_ID ) + { +#if defined(_DEBUG) + // + // Under the debug build, verify lock sharing rules in the runtime by stealing high bits of the _M_recursionCount field. + // This is purely for UMS so we don't run into people changing lock structures and inadvertently causing HARD TO FIND + // random deadlocks in UMS. + // + // This does mean you better not recursively acquire the lock more than a billion times ;) + // + _M_recursionCount = (_M_recursionCount & DebugBitsMask) | 1; +#else // _DEBUG + _M_recursionCount = 1; +#endif // _DEBUG + break; + } + else if ( old == id ) + { +#if defined(_DEBUG) + CONCRT_COREASSERT((_M_recursionCount & ~DebugBitsMask) < (DebugBitsMask - 2)); + _M_recursionCount = ((_M_recursionCount & ~DebugBitsMask) + 1) | (_M_recursionCount & DebugBitsMask) | dbgBits; +#else + _M_recursionCount++; +#endif // _DEBUG + break; + } + + spinWait._SpinOnce(); + } + +#if defined(_DEBUG) + ValidateDebugBits(_M_recursionCount); +#endif // _DEBUG + + } + + bool _ReentrantBlockingLock::_TryAcquire() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + return TryEnterCriticalSection(pCriticalSection) != 0; + } + + bool _ReentrantLock::_TryAcquire() + { +#if defined(_DEBUG) + LONG dbgBits = GetDebugBits(); +#endif // _DEBUG + + LONG id = (LONG) GetCurrentThreadId(); + + LONG old = InterlockedCompareExchange(&_M_owner, id, NULL_THREAD_ID); + + if ( old == NULL_THREAD_ID || old == id ) + { +#if defined(_DEBUG) + CONCRT_COREASSERT((_M_recursionCount & ~DebugBitsMask) < (DebugBitsMask - 2)); + _M_recursionCount = ((_M_recursionCount & ~DebugBitsMask) + 1) | (_M_recursionCount & DebugBitsMask) | dbgBits; +#else // !_DEBUG + _M_recursionCount++; +#endif + } + else + { + return false; + } + +#if defined(_DEBUG) + ValidateDebugBits(_M_recursionCount); +#endif // _DEBUG + + return true; + } + + void _ReentrantBlockingLock::_Release() + { + CRITICAL_SECTION * pCriticalSection = reinterpret_cast(_M_criticalSection); + LeaveCriticalSection(pCriticalSection); + } + + void _ReentrantLock::_Release() + { + if ( _M_owner != (LONG) GetCurrentThreadId() || _M_recursionCount < 1) + return; + +#if defined(_DEBUG) + if ( (_M_recursionCount & ~DebugBitsMask) < 1 ) +#else // !_DEBUG + if ( _M_recursionCount < 1 ) +#endif // _DEBUG + return; + + _M_recursionCount--; + +#if defined(_DEBUG) + if ( (_M_recursionCount & DebugBitsMask) == 0 ) +#else // !_DEBUG + if ( _M_recursionCount == 0 ) +#endif // DEBUG + { + _M_owner = NULL_THREAD_ID; + } + } + + // + // NonReentrant PPL Critical Section Wrapper + // + _NonReentrantPPLLock::_NonReentrantPPLLock() + { + } + + void _NonReentrantPPLLock::_Acquire(void* _Lock_node) + { + _M_criticalSection._Acquire_lock(_Lock_node, true); + } + + void _NonReentrantPPLLock::_Release() + { + _M_criticalSection.unlock(); + } + + // + // Reentrant PPL Critical Section Wrapper + // + _ReentrantPPLLock::_ReentrantPPLLock() + { + _M_owner = NULL_THREAD_ID; + _M_recursionCount = 0; + } + + void _ReentrantPPLLock::_Acquire(void* _Lock_node) + { + LONG id = (LONG) GetCurrentThreadId(); + + if ( _M_owner == id ) + { + _M_recursionCount++; + } + else + { + _M_criticalSection._Acquire_lock(_Lock_node, true); + _M_owner = id; + _M_recursionCount = 1; + } + } + + void _ReentrantPPLLock::_Release() + { + ASSERT(_M_owner == (LONG) GetCurrentThreadId()); + ASSERT(_M_recursionCount >= 1); + + _M_recursionCount--; + + if ( _M_recursionCount == 0 ) + { + _M_owner = NULL_THREAD_ID; + _M_criticalSection.unlock(); + } + } + + // + // A Non-Reentrant Reader-Writer spin lock, designed for rare writers. + // + // A writer request immediately blocks future readers and then waits until all current + // readers drain. A reader request does not block future writers and must wait until + // all writers are done, even those that cut in front In any race between requesting + // and reader and a writer, the writer always wins. + // + _ReaderWriterLock::_ReaderWriterLock() + : _M_state(_ReaderWriterLock::_Free), _M_numberOfWriters(0) + { + } + + // + // Acquires the RWLock for reading. Waits for the number of writers to drain. + // + void _ReaderWriterLock::_AcquireRead() + { +#if defined(_DEBUG) + LONG dbgBits = GetDebugBits(); + LONG val = _M_numberOfWriters; + + for(;;) + { + LONG xchgVal = InterlockedCompareExchange(&_M_numberOfWriters, val | dbgBits, val); + if (xchgVal == val) + break; + + val = xchgVal; + } +#endif // _DEBUG + + for (;;) + { + if (_M_numberOfWriters > 0) +#if defined(_DEBUG) + _WaitEquals(_M_numberOfWriters, 0, ~DebugBitsMask); +#else // !_DEBUG + _WaitEquals(_M_numberOfWriters, 0); +#endif // _DEBUG + int currentState = _M_state; + // Try to acquire read lock by incrementing the current State. + if (currentState != _Write && + InterlockedCompareExchange(&_M_state, currentState + 1, currentState) == currentState) + { +#if defined(_DEBUG) + ValidateDebugBits(_M_numberOfWriters); +#endif // _DEBUG + return; + } + } + } + + // + // Release read lock -- the last reader will decrement _M_state to _Free + // + void _ReaderWriterLock::_ReleaseRead() + { + ASSERT(_M_state >= _Read); + InterlockedDecrement(&_M_state); + } + + // + // Acquire write lock -- spin until there are no existing readers, no new readers will + // be added + // + void _ReaderWriterLock::_AcquireWrite() + { + InterlockedIncrement(&_M_numberOfWriters); + + for (;;) + { + if (InterlockedCompareExchange(&_M_state, _Write, _Free) == _Free) + { +#if defined(_DEBUG) + ValidateDebugBits(_M_numberOfWriters); +#endif // _DEBUG + return; + } + _WaitEquals(_M_state, _Free); + } + } + + // + // Release writer lock -- there can only be one active, but a bunch might be pending + // + void _ReaderWriterLock::_ReleaseWrite() + { + ASSERT(_M_state == _Write); +#if defined(_DEBUG) + ASSERT((_M_numberOfWriters & ~DebugBitsMask) > 0); +#else // !_DEBUG + ASSERT(_M_numberOfWriters > 0); +#endif // _DEBUG + + // The following assignment does not need to be interlocked, as the interlocked + // decrement can take care of the fence. + _M_state = _Free; + InterlockedDecrement(&_M_numberOfWriters); + } + + // + // Tries to acquire the write lock. Returns true if the lock was acquired. + // + bool _ReaderWriterLock::_TryAcquireWrite() + { + if (InterlockedCompareExchange(&_M_state, _Write, _Free) == _Free) + { + InterlockedIncrement(&_M_numberOfWriters); +#if defined(_DEBUG) + ValidateDebugBits(_M_numberOfWriters); +#endif // _DEBUG + return true; + } + return false; + } + + // Spin-Wait-Until variant -- spin for s_spinCount iterations, then Sleep(0) then repeat + // 10 times (tunable), thereafter we spin and Sleep(1) + void _ReaderWriterLock::_WaitEquals(volatile const LONG& location, LONG value, LONG mask) + { + unsigned int retries = 0; + int spinInterval = 10; // tuning + + for (;;) + { + if ((location & mask) == value) + return; + + YieldProcessor(); + + if (++retries >= _SpinCount::_S_spinCount) + { + if (spinInterval > 0) + { + --spinInterval; + platform::__Sleep(0); + } + else + platform::__Sleep(1); + retries = 0; + } + } + } + + // Guarantees that all writers are out of the lock. This does nothing if there are no pending writers. + void _ReaderWriterLock::_FlushWriteOwners() + { + // + // Ideally, if the read lock is held and we have pending writers, this would not need to grab the lock and release + // it; however -- we must guarantee that any writer which was in the lock as of this call is completely out + // of everything including _ReleaseWrite. Since the last thing which happens there is the decrement of _M_numberOfWriters, + // that is *currently* what we must key off. It's possible that after the change of _M_state to free there, a reader + // gets the lock because it was preempted after the initial check of _M_numberOfWriters which saw 0. Hence, we cannot + // rely on _M_state. + // + if (_M_numberOfWriters > 0) + { +#if defined(_DEBUG) + _WaitEquals(_M_numberOfWriters, 0, ~DebugBitsMask); +#else // !_DEBUG + _WaitEquals(_M_numberOfWriters, 0); +#endif // _DEBUG + } + } + + //*************************************************************************** + // Locking primitives and structures: + //*************************************************************************** + + // Reader-writer lock constants + + static const long RWLockWriterInterested = 0x1; // Writer interested or active + static const long RWLockWriterExclusive = 0x2; // Writer active, no reader entry + static const long RWLockReaderInterested = 0x4; // Reader interested but not active + static const long RWLockReaderCountIncrement = 0x8; // Reader count step (reader counter is scaled by it) + + /// + /// Node element used in the lock queues. + /// + class LockQueueNode + { + public: + + /// + /// Constructor for queue node. It keeps the context pointer in order + /// to block in a fashion visible to ConcRT. + /// + LockQueueNode(unsigned int timeout = COOPERATIVE_TIMEOUT_INFINITE) + : m_pNextNode(NULL), m_ticketState(StateIsBlocked), m_hTimer(NULL), m_trigger(NotTriggered), m_fTimedNodeInvalid(0) + { + m_pContext = SchedulerBase::CurrentContext(); + if (timeout != COOPERATIVE_TIMEOUT_INFINITE) + { + if ((m_hTimer = RegisterAsyncTimerAndLoadLibrary(timeout, LockQueueNode::DispatchNodeTimeoutTimer, this)) == nullptr) + { + // + // Note that the thread is left in a state unexplicable by the scheduler here. It's quite possible someone ::Unblocks this context in + // the future. With this error, we make no attempt to unwind that. + // + throw std::bad_alloc(); + } + } + } + + /// + /// Constructor for queue node. It keeps the context pointer in order + /// to block in a fashion visible to ConcRT. + /// + LockQueueNode(Context * pContext, unsigned int ticket) + : m_pContext(pContext), m_pNextNode(NULL), m_ticketState(ticket), m_hTimer(NULL), m_trigger(NotTriggered), m_fTimedNodeInvalid(0) + { + } + + /// + /// Waits until lock is available. + /// + /// + /// The number of the node that is currently owning the lock, or has last owned it. + /// + void Block(unsigned int currentTicketState = 0) + { + // Get the number of physical processors to determine the best spin times + unsigned int numberOfProcessors = Concurrency::GetProcessorCount(); + _CONCRT_ASSERT(numberOfProcessors > 0); + + // If the previous node is blocked then there is no need to spin and waste cycles + if (!IsPreviousBlocked()) + { + // If there is a race and the ticket is not valid then use the default spin + unsigned int placeInLine = IsTicketValid() ? ((m_ticketState >> NumberOfBooleanStates) - (currentTicketState >> NumberOfBooleanStates)) : 1; + _CONCRT_ASSERT(placeInLine > 0); + + // + // If the node is back in line by more than a processor count plus a threshold + // then simply don't spin and block immediately. Otherwise, progressively increase the + // amount of spin for the subsequent nodes until a double default spin count is reached. + // + if (placeInLine <= numberOfProcessors + TicketThreshold) + { + const unsigned int defaultSpin = _SpinCount::_Value(); + unsigned int totalSpin = defaultSpin + (defaultSpin * (placeInLine - 1)) / (numberOfProcessors + TicketThreshold); + + _SpinWaitNoYield spinWait; + spinWait._SetSpinCount(totalSpin); + + while (IsBlocked() && spinWait._SpinOnce()) + { + // _YieldProcessor is called inside _SpinOnce + } + } + } + + // + // After spin waiting for a while use the ConcRT blocking mechanism. It will return + // immediately if the unblock already happened. + // + m_pContext->Block(); + } + + /// + /// Notifies that lock is available without context blocking. + /// + void UnblockWithoutContext() + { + m_ticketState = m_ticketState & ~StateIsBlocked; + } + + /// + /// Compensate timer's unblock action, if necessary. + /// + void TryCompensateTimer() + { + // No matter the timer win the race or not, this thread always get unblocked (It actually never get blocked) + // However, if the timer win the race, we do need to compensate its context::unblock. + if (m_hTimer && InterlockedExchange(&m_trigger, TriggeredByUnblock) == TriggeredByTimeout) + { + // Timer won the race for the trigger and has unblocked this context - block to consume the unblock. + m_pContext->Block(); + // The thread that failed to trigger the waiting context needs to release the reference + DerefTimerNode(); + } + } + + /// + /// Notifies that lock is available. + /// + bool Unblock() + { + if (InterlockedCompareExchange(&m_trigger, TriggeredByUnblock, NotTriggered) == NotTriggered) + { + // The unblock has won the race (if this was a timed node) + UnblockWithoutContext(); + + // + // This call implies a fence which serves two purposes: + // a) it makes m_fIsBlocked visible sooner (in UnblockWithoutContext) + // b) it makes sure that we never block a context without unblocking it + // + m_pContext->Unblock(); + + return true; + } + + return false; + } + + /// + /// Waits until the next node is set. + /// + /// + /// The next node. + /// + LockQueueNode * WaitForNextNode() + { + LockQueueNode * pNextNode = m_pNextNode; + _SpinWaitBackoffNone spinWait; + + while (pNextNode == NULL) + { + // + // There in no context blocking here so continue to spin even if maximum + // spin is already reached. Since setting the tail and setting next pointer + // are back-to-back operations it is very likely that while loop will not take + // a long time. + // + spinWait._SpinOnce(); + pNextNode = m_pNextNode; + } + + return pNextNode; + } + + /// + /// Copies the contents of the passed in node to this node. + /// + /// + /// The node copy from. + /// + /// + /// Used only to transfer data to the internally allocated node. + /// + void Copy(LockQueueNode * pCopyFromNode) + { + _CONCRT_ASSERT(pCopyFromNode->IsTicketValid()); + _CONCRT_ASSERT(!pCopyFromNode->IsBlocked()); + + m_ticketState = pCopyFromNode->m_ticketState; + m_pNextNode = pCopyFromNode->m_pNextNode; + m_pContext = pCopyFromNode->m_pContext; + } + + /// + /// Estimates the position of this node in the node queue based on the previous node. + /// + /// + /// The node to get the base number from, if available. + /// + /// + /// Used only as a heuristic for critical section and writers in reader writer lock. + /// + void UpdateQueuePosition(LockQueueNode * pPreviousNode) + { + if (!IsTicketValid()) + { + // If the previous node has a valid ticket then this one will have it as well + if (pPreviousNode->IsTicketValid()) + { + unsigned int newState = (pPreviousNode->m_ticketState + TicketIncrement) & MaskBlockedStates; + _CONCRT_ASSERT((newState & StateIsTicketValid) != 0); + + // If the previous node is blocked then set this information on the current node to save the spin + // We disabled the IsSynchronouslyBlocked check for timed-node. It is designed for work around an AV caused by accessing + // deleted context (After timer unblocking the thread, the thread may already exited and deleted its external context). + if (pPreviousNode->IsBlocked() && (pPreviousNode->IsPreviousBlocked() || pPreviousNode->m_hTimer == nullptr && pPreviousNode->m_pContext->IsSynchronouslyBlocked())) + { + newState |= StateIsPreviousBlocked; + } + m_ticketState = m_ticketState | newState; + } + } + } + + /// + /// Estimates the state of this node based on the state of previous node. + /// + /// + /// The node to get the base from, if available. + /// + /// + /// Used only as a heuristic for readers in reader writer lock. + /// + void UpdateBlockingState(LockQueueNode * pPreviousNode) + { + // If the previous node is blocked then set this information on the current node to save the spin + // We don't need to check the m_hTimer here as UpdateQueuePosition because it is only used by read_write_lock, which does not have a timer. + if (pPreviousNode->IsBlocked() && (pPreviousNode->IsPreviousBlocked() || pPreviousNode->m_pContext->IsSynchronouslyBlocked())) + { + m_ticketState = m_ticketState | StateIsPreviousBlocked; + } + } + + /// + /// Timed waiting node (m_hTimer != nullptr) is allocated on the heap, and needs to be + /// released after use. + /// + /// + /// There are 2 references: + /// 1. The thread that waits on or attempts to wait on the block. + /// 2. The one who loses the race to trigger the waiting thread (this could be the timer callback, + /// the previous lock owner, or the waiting thread itself in the case where the lock was not already acquired). + /// + void DerefTimerNode() + { + if (m_hTimer && InterlockedIncrement(&m_fTimedNodeInvalid) == 2) + { + delete this; + } + } + + /// + /// Called when a timer on an event is signaled. + /// + static void CALLBACK DispatchNodeTimeoutTimer(PTP_CALLBACK_INSTANCE instance, void * pContext, PTP_TIMER timer) + { + LockQueueNode *pNode = reinterpret_cast (pContext); + + if (InterlockedCompareExchange(&pNode->m_trigger, TriggeredByTimeout, NotTriggered) == NotTriggered) + { + pNode->m_pContext->Unblock(); + } + else + { + // Unblock won the race, since we failed to trigger we're responsible for releasing the reference on the node. + pNode->DerefTimerNode(); + } + + // Always delete the timer + UnRegisterAsyncTimerAndUnloadLibrary(instance, timer); + } + + /// + /// Same as DispatchNodeTimeoutTimer, but used only for XP and MSDK + /// + static void CALLBACK DispatchNodeTimeoutTimerXP(PVOID pContext, BOOLEAN) + { + LockQueueNode *pNode = reinterpret_cast (pContext); + + // Always delete the timer + platform::__DeleteTimerQueueTimer(GetSharedTimerQueue(), pNode->m_hTimer, NULL); + + if (InterlockedCompareExchange(&pNode->m_trigger, TriggeredByTimeout, NotTriggered) == NotTriggered) + { + pNode->m_pContext->Unblock(); + } + else + { + // Unblock won the race, since we failed to trigger we're responsible for releasing the reference on the node. + pNode->DerefTimerNode(); + } + } + + private: + + friend class critical_section; + friend class reader_writer_lock; + + bool IsBlocked() + { + return (m_ticketState & StateIsBlocked) != 0; + } + + bool IsPreviousBlocked() + { + return (m_ticketState & StateIsPreviousBlocked) != 0; + } + + bool IsTicketValid() + { + return (m_ticketState & StateIsTicketValid) != 0; + } + + // Const statics needed for blocking heuristics + static const unsigned int TicketThreshold = 2; + static const unsigned int StateIsBlocked = 0x00000001; + static const unsigned int StateIsTicketValid = 0x00000002; + static const unsigned int StateIsPreviousBlocked = 0x00000004; + static const unsigned int MaskBlockedStates = ~(StateIsBlocked | StateIsPreviousBlocked); + static const unsigned int NumberOfBooleanStates = 0x00000003; + static const unsigned int TicketIncrement = 1 << NumberOfBooleanStates; + + Context * m_pContext; + LockQueueNode * volatile m_pNextNode; + volatile unsigned int m_ticketState; + // Timer handle (valid only for XP; on Vista and above, this handle only used as the indication of whether current node is a timed node. + HANDLE m_hTimer; + // The trigger - for timed waits, the unblock mechanism competes with the timer to trigger the thread attempting to acquire the lock. + // Note, the acquiring thread may fire the trigger itself if the lock is not held - this counts as a virtual 'unblock' + volatile long m_trigger; + volatile long m_fTimedNodeInvalid; + }; + + // + // A C++ holder for a Non-reentrant PPL lock. + // + _CONCRTIMP _NonReentrantPPLLock::_Scoped_lock::_Scoped_lock(_NonReentrantPPLLock & _Lock) : _M_lock(_Lock) + { + new(reinterpret_cast (_M_lockNode)) LockQueueNode; + _M_lock._Acquire(reinterpret_cast (_M_lockNode)); + } + + _CONCRTIMP _NonReentrantPPLLock::_Scoped_lock::~_Scoped_lock() + { + _M_lock._Release(); + } + + // + // A C++ holder for a Reentrant PPL lock. + // + _CONCRTIMP _ReentrantPPLLock::_Scoped_lock::_Scoped_lock(_ReentrantPPLLock & _Lock) : _M_lock(_Lock) + { + new(reinterpret_cast (_M_lockNode)) LockQueueNode; + _M_lock._Acquire(reinterpret_cast (_M_lockNode)); + } + + _CONCRTIMP _ReentrantPPLLock::_Scoped_lock::~_Scoped_lock() + { + _M_lock._Release(); + } + +} // namespace details + +/// +/// Constructs an critical section +/// +_CONCRTIMP critical_section::critical_section() : _M_pHead(NULL), _M_pTail(NULL) +{ + _CONCRT_ASSERT(sizeof(_M_activeNode) >= sizeof(LockQueueNode)); + + // Hide the inside look of LockQueueNode behind a char array big enough to keep 3 pointers + // This is why LockQueueNode is newed in place instead of a more traditional allocation. + new(reinterpret_cast(_M_activeNode)) LockQueueNode(NULL, LockQueueNode::StateIsTicketValid); +} + +/// +/// Destroys a critical section. It is expected that the lock is no longer held. +/// +_CONCRTIMP critical_section::~critical_section() +{ + _ASSERT_EXPR(_M_pHead == NULL, L"Lock was destructed while held"); +} + +/// +/// Gets a critical section handle. +/// +/// +/// A reference to this critical section. +/// +_CONCRTIMP critical_section::native_handle_type critical_section::native_handle() +{ + return *this; +} + +/// +/// Acquires this critical section. +/// +/// +/// Throws a improper_lock exception if the lock is acquired recursively +/// +_CONCRTIMP void critical_section::lock() +{ + LockQueueNode newNode; // Allocated on the stack and goes out of scope before unlock() + LockQueueNode * pNewNode = &newNode; + + // + // Acquire the lock node that was just created on the stack + // + _Acquire_lock(pNewNode, false); + + // + // At this point the context has exclusive ownership of the lock + // + + _Switch_to_active(pNewNode); +} + +/// +/// Tries to acquire the lock, does not block. +/// +/// +/// true if the lock is acquired, false otherwise +/// +_CONCRTIMP bool critical_section::try_lock() +{ + LockQueueNode newNode; // Allocated on the stack and goes out of scope before unlock() + LockQueueNode * pNewNode = &newNode; + LockQueueNode * pPreviousNode = reinterpret_cast(InterlockedCompareExchangePointer(&_M_pTail, pNewNode, NULL)); + + // Try and acquire this lock. If this CAS succeeds, then the lock has been acquired. + if (pPreviousNode == NULL) + { + _M_pHead = pNewNode; + pNewNode->UpdateQueuePosition(reinterpret_cast(_M_activeNode)); + pNewNode->UnblockWithoutContext(); + _Switch_to_active(pNewNode); + return true; + } + + return false; +} + +/// +/// Tries to acquire the lock for timeout number of milliseconds, does not block. +/// +/// +/// true if the lock is acquired, false otherwise +/// +_CONCRTIMP bool critical_section::try_lock_for(unsigned int timeout) +{ + LockQueueNode * pNewNode = new LockQueueNode(timeout); // Allocated on the heap + + // + // Acquire the lock node that was just created + // + if (_Acquire_lock(pNewNode, false)) + { + // + // At this point the context has exclusive ownership of the lock + // + _Switch_to_active(pNewNode); + pNewNode->DerefTimerNode(); + return true; + } + else + { + pNewNode->DerefTimerNode(); + return false; + } +} + +/// +/// Unlocks an acquired lock. +/// +_CONCRTIMP void critical_section::unlock() +{ + LockQueueNode * pCurrentNode = reinterpret_cast(_M_pHead); + + _ASSERT_EXPR(pCurrentNode != nullptr, L"Lock not being held"); + _ASSERT_EXPR(pCurrentNode->m_pContext == SchedulerBase::SafeFastCurrentContext(), L"Lock being held by different context"); + + // Reset the context on the active node to ensure that it is possible to detect the error case + // where the same context tries to enter the lock twice. (enjoy the fence below) + reinterpret_cast(&_M_activeNode)->m_pContext = nullptr; + + LockQueueNode * pNextNode = pCurrentNode->m_pNextNode; + + // This assignment must be put before ICEP(_M_pTail) because + // 1. It must be visible before ICEP(_M_pTail), and + // 2. It must be visible before unblock. + _M_pHead = pNextNode; + + // If we reach the end of the queue of waiters, we need to handle a potential race with new incoming waiters. + if (pNextNode == nullptr && reinterpret_cast(InterlockedCompareExchangePointer(&_M_pTail, nullptr, pCurrentNode)) != pCurrentNode) + { + // If someone is adding a context then wait until next node pointer is populated. + pNextNode = pCurrentNode->WaitForNextNode(); + // DO NOT try to combine this assignment with the one above by moving it out of and after the if statement. Moving it to after the if statement + // could lead to situations where the set of _M_pHead is not fenced. + _M_pHead = pNextNode; + } + + // It's no longer safe to touch pNextNode after it gets unblocked + while (pNextNode != nullptr && !pNextNode->Unblock()) + { + // The unblock could only have failed because the block is a timed block and was woken up by the timer. + pCurrentNode = pNextNode; + pNextNode = pCurrentNode->m_pNextNode; + + // This assignment must be put before ICEP(_M_pTail) below + _M_pHead = pNextNode; + + // If we reach the tail end of the waiters queue, we need to handle a potential race due to a new waiter being added to the tail. + if (pNextNode == nullptr && reinterpret_cast(InterlockedCompareExchangePointer(&_M_pTail, nullptr, pCurrentNode)) != pCurrentNode) + { + // If someone is adding a context then wait until next node pointer is populated. + pNextNode = pCurrentNode->WaitForNextNode(); + _M_pHead = pNextNode; + } + + // Since this was a timer node that was released by the timer firing we need to release our reference on it so it can be deleted. + pCurrentNode->DerefTimerNode(); + } +} + +/// +/// If no one owns the lock at the instant the API is called, it returns instantly. If there is an owner, +/// it performs a lock followed by an unlock. +/// +void critical_section::_Flush_current_owner() +{ + if (_M_pTail != NULL) + { + lock(); + unlock(); + } +} + +/// +/// Acquires this critical section given a specific node to lock. +/// +/// +/// The node that needs to own the lock. +/// +/// +/// Returns true if the lock was acquired, false if the timer woke us up. +/// +/// +/// Throws a improper_lock exception if the lock is acquired recursively +/// +bool critical_section::_Acquire_lock(void * _PLockingNode, bool _FHasExternalNode) +{ + LockQueueNode * pNewNode = reinterpret_cast(_PLockingNode); + LockQueueNode * pActiveNode = reinterpret_cast(&_M_activeNode); + + // Locks are non-reentrant, so throw if this condition is detected. + if (pNewNode->m_pContext == pActiveNode->m_pContext) + { + throw improper_lock("Lock already taken"); + } + + LockQueueNode * pPrevious = reinterpret_cast(InterlockedExchangePointer(&_M_pTail, pNewNode)); + + // No one held this critical section, so this context now acquired the lock + if (pPrevious == NULL) + { + _M_pHead = pNewNode; + + pNewNode->UpdateQueuePosition(pActiveNode); + pNewNode->UnblockWithoutContext(); + + // If this was a timed wait, we need to compensate for the fact that the timer callback may race with us, + // and try to unblock this context. If that happens we need to invoke Context::Block to consume the unblock + // or the state on the context will be invalid. + pNewNode->TryCompensateTimer(); + } + else + { + pNewNode->UpdateQueuePosition(pPrevious); + pPrevious->m_pNextNode = pNewNode; + + // NOT SAFE TO TOUCH pPrevious AFTER THE ASSIGNMENT ABOVE! + + pNewNode->Block(pActiveNode->m_ticketState); + + // Do another position estimation in case we missed the previous number due to race if we've acquired the lock. + if (pNewNode->m_trigger != TriggeredByTimeout) + { + pNewNode->UpdateQueuePosition(pActiveNode); + } + } + + // Since calls with external nodes will not call _Switch_to_active, make + // sure that we are setting the head and the active node properly. + if (_FHasExternalNode) + { + pActiveNode->Copy(pNewNode); + _M_pHead = pNewNode; + } + + // The block can be in the NotTriggered state if it is not a timed block and the lock was not already held. + return pNewNode->m_trigger != TriggeredByTimeout; +} + +/// +/// The acquiring node allocated on the stack never really owns the lock. The reason for that is that +/// it would go out of scope and its insides would not be visible in unlock() where it would potentially +/// need to unblock the next in the queue. Instead, its state is transferred to the internal +/// node which is used as a scratch node. +/// +/// +/// The node that needs to own the lock. +/// +void critical_section::_Switch_to_active(void * _PLockingNode) +{ + LockQueueNode * pLockingNode = reinterpret_cast(_PLockingNode); + LockQueueNode * pActiveNode = reinterpret_cast(&_M_activeNode); + + // + // Copy the contents of the node allocated on the stack which now owns the lock, so that we would + // have its information available during unlock. + // + pActiveNode->Copy(pLockingNode); + + // + // If someone is acquiring the critical_section then wait until next node pointer is populated. Otherwise, there will be no way + // to unblock that acquiring context after pLockingNode goes out of scope. + // + if (pActiveNode->m_pNextNode == NULL) + { + // + // If the compare-and-swap to active node succeeds that means that a new acquirer coming in will + // properly set the _M_pHead. Otherwise, it has to be set manually when next node is done. + // + if (reinterpret_cast(InterlockedCompareExchangePointer(&_M_pTail, pActiveNode, pLockingNode)) != pLockingNode) + { + pLockingNode->WaitForNextNode(); + + // + // During the initial copy the next pointer was not copied over and it has been populated in the meantime. + // This copy can now be safely performed because tail has moved, so next will point to the second element. + // + pActiveNode->Copy(pLockingNode); + } + } + + _CONCRT_ASSERT(_PLockingNode != _M_pTail); + + _M_pHead = pActiveNode; +} + +/// +/// Constructs a holder object and acquires the critical_section passed to it. +// If the critical_section is held by another thread this call will block. +/// +/// +/// Critical section to lock. +/// +critical_section::scoped_lock::scoped_lock(critical_section& _Critical_section) : _M_critical_section(_Critical_section) +{ + static_assert(sizeof(LockQueueNode) <= sizeof(_M_node), "_M_node buffer too small"); + LockQueueNode * pNewNode = reinterpret_cast(_M_node); + new(pNewNode) LockQueueNode; + _M_critical_section._Acquire_lock(pNewNode, true); +} + +/// +/// Destructs a holder object and releases the critical_section. +/// +critical_section::scoped_lock::~scoped_lock() +{ + _M_critical_section.unlock(); +} + +/// +/// Constructs a new reader_writer_lock object. +/// +_CONCRTIMP reader_writer_lock::reader_writer_lock() : _M_pReaderHead(NULL), _M_pWriterHead(NULL), _M_pWriterTail(NULL), _M_lockState(0) +{ + _CONCRT_ASSERT(sizeof(_M_activeWriter) >= sizeof(LockQueueNode)); + + // Hide the inside look of LockQueueNode behind a char array big enough to keep 3 pointers + // This is why LockQueueNode is newed in place instead of a more traditional allocation. + new(reinterpret_cast (_M_activeWriter)) LockQueueNode(NULL, LockQueueNode::StateIsTicketValid); +} + +/// +/// Destructs reader_writer_lock object. If lock is held during the destruction an exception is thrown. +/// +_CONCRTIMP reader_writer_lock::~reader_writer_lock() +{ + _ASSERT_EXPR(_M_lockState == 0, L"Lock was destructed while held"); + + // Since LockQueueNode has a trivial destructor, no need to call it here. If it ever becomes + // non-trivial then it would be called here instead of calling delete (since memory is allocated + // in the char array and will be reclaimed anyway when reader_writer_lock is destructed). +} + +/// +/// Writer entering the lock. If there are readers active they are immediately notified to finish +/// and relinquish the lock. +/// +/// +/// Writer blocks by doing spinning on a local variable. Writers are chained so that a writer +/// exiting the lock releases the next writer in line. +/// +_CONCRTIMP void reader_writer_lock::lock() +{ + LockQueueNode newWriterNode; // Allocated on the stack and goes out of scope before unlock() + LockQueueNode * pNewWriter = &newWriterNode; + + // + // Acquire the lock node that was just created on the stack + // + _Acquire_lock(pNewWriter, false); + + // + // At this point the writer has exclusive ownership of the lock + // + + _Switch_to_active(pNewWriter); +} + +/// +/// Try to take a writer lock. +/// +/// +/// true if the lock is immediately available and lock succeeded; false otherwise. +/// +_CONCRTIMP bool reader_writer_lock::try_lock() +{ + LockQueueNode newWriterNode; // Allocated on the stack and goes out of scope before unlock() + LockQueueNode * pNewWriter = &newWriterNode; + LockQueueNode * pPreviousWriter = reinterpret_cast(InterlockedCompareExchangePointer(&_M_pWriterTail, pNewWriter, NULL)); + + // Is this the only writer present? If yes, it will win over any new writer coming in. + if (pPreviousWriter == NULL) + { + _M_pWriterHead = pNewWriter; + + // Is there any active readers? If no, our lock succeeded. + if (InterlockedCompareExchange(&_M_lockState, (RWLockWriterInterested | RWLockWriterExclusive), 0) == 0) + { + pNewWriter->UpdateQueuePosition(reinterpret_cast(_M_activeWriter)); + pNewWriter->UnblockWithoutContext(); + _Switch_to_active(pNewWriter); + return true; + } + else + { + // Lock failed, but other writers may now be linked to this failed write attempt. + // Thus, unwind all the actions and leave the lock in a consistent state. + _Remove_last_writer(pNewWriter); + } + } + + return false; +} + +/// +/// Reader entering the lock. If there are writers active readers have to wait until they are done. +/// Reader simply registers an interest in the lock and waits for writers to release it. +/// +/// +/// Reader blocks by doing spinning on a local variable. All readers cache previous reader (if available) +/// locally, so they could all be unblocked once the lock is available. +/// +_CONCRTIMP void reader_writer_lock::lock_read() +{ + LockQueueNode newReaderNode; + LockQueueNode * pNewReader = &newReaderNode; + + // Locks are non-reentrant, so throw if this condition is detected. + if (pNewReader->m_pContext == reinterpret_cast(_M_activeWriter)->m_pContext) + { + throw improper_lock("Lock already taken as a writer"); + } + + LockQueueNode * pNextReader = reinterpret_cast(InterlockedExchangePointer(&_M_pReaderHead, pNewReader)); + + // + // If this is the only read that currently exists and there are no interested writers + // then unblock this read. + // + if (pNextReader == NULL) + { + if ((InterlockedOr(&_M_lockState, RWLockReaderInterested) & (RWLockWriterInterested | RWLockWriterExclusive)) == 0) + { + LockQueueNode * pHeadReader = reinterpret_cast(_Get_reader_convoy()); + + // + // If the new reader is still the head of the reader list that means that it is + // unblocking itself, in which case using UnblockWithoutContext will not include + // context unblocking. Otherwise, the full unblock/block mechanism is needed. + // + if (pHeadReader == pNewReader) + { + pHeadReader->UnblockWithoutContext(); + return; + } + + _CONCRT_ASSERT(pHeadReader != pNewReader); + pHeadReader->Unblock(); + } + } + else + { + pNewReader->UpdateBlockingState(pNextReader); + } + + pNewReader->Block(); + + // Unblock the reader that preceeded this one as a head or the list + if (pNextReader != NULL) + { + InterlockedExchangeAdd(&_M_lockState, RWLockReaderCountIncrement); + pNextReader->Unblock(); + } +} + +/// +/// Try to take a reader lock. +/// +/// +/// true if the lock is immediately available and lock succeeded; false otherwise. +/// +_CONCRTIMP bool reader_writer_lock::try_lock_read() +{ + long oldState = _M_lockState; + + // + // Try to increment the reader count while no writer is interested. + // + while ((oldState & (RWLockWriterInterested | RWLockWriterExclusive)) == 0) + { + if (InterlockedCompareExchange(&_M_lockState, oldState + RWLockReaderCountIncrement, oldState) == oldState) + { + return true; + } + oldState = _M_lockState; + } + + return false; +} + +/// +/// Unlock the lock based on who locked it, reader or writer. +/// +_CONCRTIMP void reader_writer_lock::unlock() +{ + if (_M_lockState >= RWLockReaderCountIncrement) + { + _Unlock_reader(); + } + else if ((_M_lockState & RWLockWriterExclusive) != 0) + { + _Unlock_writer(); + } + else + { + _ASSERT_EXPR(false, L"Lock not being held"); + } +} + +/// +/// Called for the first context in the writer queue. It sets the queue head and it tries to +/// claim the lock if readers are not active. +/// +/// +/// The first writer in the queue. +/// +bool reader_writer_lock::_Set_next_writer(void * _PWriter) +{ + _M_pWriterHead = _PWriter; + + if (((InterlockedOr(&_M_lockState, RWLockWriterInterested) & RWLockReaderInterested) == 0) && + (InterlockedOr(&_M_lockState, RWLockWriterExclusive) < RWLockReaderCountIncrement)) + { + return true; + } + + return false; +} + +/// +/// Called when writers are done with the lock, or when lock was free for claiming by +/// the first reader coming in. If in the meantime there are more writers interested +/// the list of readers is finalized and they are convoyed, while head of the list +/// is reset to NULL. +/// +/// +/// Pointer to the head of the reader list. +/// +void * reader_writer_lock::_Get_reader_convoy() +{ + // In one interlocked step, clear reader interested flag and increment the reader count. + long prevLockState = InterlockedExchangeAdd(&_M_lockState, RWLockReaderCountIncrement - RWLockReaderInterested); + + // + // If a lock is in the race between a reader and a writer allow this last reader batch + // to go through and then close the lock for the new incoming readers, granting + // exclusive access to writers. + // + if ((prevLockState & RWLockWriterInterested) != 0 && (prevLockState & RWLockWriterExclusive) == 0) + { + InterlockedOr(&_M_lockState, RWLockWriterExclusive); + } + + // Return the batch of readers to be unblocked + return reinterpret_cast(InterlockedExchangePointer(&_M_pReaderHead, NULL)); +} + +/// +/// Called from unlock() when a writer is holding the lock. Writer unblocks the next writer in the list +/// and is being retired. If there are no more writers, but there are readers interested, then readers +/// are unblocked. +/// +/// +/// If there wasn't for a race to add a writer while the last writer is unlocking the lock, there would be +/// no need for the writer structure in unlock. However, because of this race there is an ABA problem and +/// writer information had to be passed onto a scratch writer (_M_activeWriter), internal to the lock. +/// +void reader_writer_lock::_Unlock_writer() +{ + _CONCRT_ASSERT((_M_lockState & RWLockWriterExclusive) != 0); + _CONCRT_ASSERT(_M_pWriterHead != NULL); + + LockQueueNode * pCurrentNode = reinterpret_cast(_M_pWriterHead); + + _ASSERT_EXPR(pCurrentNode->m_pContext == SchedulerBase::SafeFastCurrentContext(), L"Lock being held by different writer"); + + LockQueueNode * pNextNode = pCurrentNode->m_pNextNode; + _M_pWriterHead = pNextNode; + + // Reset context on the active writer to ensure that it is possible to detect the error case + // where the same writer tries to enter the lock twice. + reinterpret_cast(&_M_activeWriter)->m_pContext = NULL; + + if (pNextNode != NULL) + { + pNextNode->Unblock(); + } + else + { + // If there are readers lined up, then unblock them + if ((InterlockedAnd(&_M_lockState, ~(RWLockWriterInterested | RWLockWriterExclusive)) & RWLockReaderInterested) != 0) + { + LockQueueNode * pHeadNode = reinterpret_cast(_Get_reader_convoy()); + pHeadNode->Unblock(); + } + + // Safely remove this writer, keeping in mind there might be a race for the queue tail. + _Remove_last_writer(pCurrentNode); + } +} + +/// +/// When last writer leaves the lock it needs to reset the tail to NULL so that the next coming +/// writer would know to try to grab the lock. If the CAS to NULL fails, then some other writer +/// managed to grab the tail before the reset, so this writer needs to wait until the link to +/// the next writer is complete before trying to release the next writer. +/// +/// +/// Last writer in the queue. +/// +void reader_writer_lock::_Remove_last_writer(void * _PWriter) +{ + // If someone is adding a writer then wait until next node pointer is populated. + if (reinterpret_cast(InterlockedCompareExchangePointer(&_M_pWriterTail, NULL, _PWriter)) != _PWriter) + { + LockQueueNode * pWriter = reinterpret_cast(_PWriter); + LockQueueNode * pNextWriter = pWriter->WaitForNextNode(); + + if (_Set_next_writer(pNextWriter)) + { + pNextWriter->Unblock(); + } + } +} + +/// +/// Acquires a write lock given a specific write node to lock. +/// +/// +/// The node that needs to own the lock. +/// +/// +/// Whether the node being locked is external to the reader_writer_lock. +/// +/// +/// Throws a improper_lock exception if the lock is acquired recursively +/// +void reader_writer_lock::_Acquire_lock(void * _PLockingNode, bool _FHasExternalNode) +{ + LockQueueNode * pNewWriter = reinterpret_cast(_PLockingNode); + LockQueueNode * pActiveWriter = reinterpret_cast(_M_activeWriter); + + // Locks are non-reentrant, so throw if this condition is detected. + if (pNewWriter->m_pContext == reinterpret_cast(pActiveWriter)->m_pContext) + { + throw improper_lock("Lock already taken"); + } + + LockQueueNode * pPreviousWriter = reinterpret_cast(InterlockedExchangePointer(&_M_pWriterTail, pNewWriter)); + + bool doNeedBlock = true; + + if (pPreviousWriter == NULL) + { + pNewWriter->UpdateQueuePosition(pActiveWriter); + + // This is the only write that currently exists + if (_Set_next_writer(pNewWriter)) + { + doNeedBlock = false; + pNewWriter->UnblockWithoutContext(); + } + } + else + { + pNewWriter->UpdateQueuePosition(pPreviousWriter); + pPreviousWriter->m_pNextNode = pNewWriter; + + // Note: pPreviousWriter is *unsafe* after the assignment above! + } + + // Don't block if the context unblocked itself already + if (doNeedBlock) + { + pNewWriter->Block(pActiveWriter->m_ticketState); + + // Do another position estimation in case we missed the previous number due to race + pNewWriter->UpdateQueuePosition(pActiveWriter); + } + + // Since calls with external nodes will not call _Switch_to_active, make + // sure that we are setting the head and the active node properly. + if (_FHasExternalNode) + { + pActiveWriter->Copy(pNewWriter); + // NOTE: The write to _M_pWriterHead below could be re-ordered on ARM64 with the writes within the ->Copy() above (when Copy is inlined). + // However, this is not an issue because _M_pWriterHead is not concurrently read when the lock has already been acquired by the writer + // (which is the case here). The read of _M_pWriterHead in _Unlock_reader can occur only when a writer is blocked or about to block. + _M_pWriterHead = pNewWriter; + } +} + +/// +/// The writer node allocated on the stack never really owns the lock. The reason for that is that +/// it would go out of scope and its insides would not be visible in unlock() where it would potentially +/// need to unblock the next writer in the queue. Instead, its state is transferred to the internal +/// writer node which is used as a scratch node. +/// +/// +/// The writer that needs to own the lock. +/// +void reader_writer_lock::_Switch_to_active(void * _PWriter) +{ + _CONCRT_ASSERT((_M_lockState & RWLockWriterExclusive) != 0); + + LockQueueNode * pWriter = reinterpret_cast(_PWriter); + LockQueueNode * pActiveWriter = reinterpret_cast(_M_activeWriter); + + // + // Copy the contents of the writer allocated on the stack which now owns the lock, so that we would + // have its information available during unlock. + // + pActiveWriter->Copy(pWriter); + + // + // If someone is adding a writer then wait until next node pointer is populated. Otherwise, there will be no way + // to unblock the next writer after newWriterNode goes out of scope. + // + if (pActiveWriter->m_pNextNode == NULL) + { + // + // If the compare-and-swap to active writer succeeds that means that a new writer coming in will call _Set_next_writer, which + // will properly set the _M_pWriterHead. Otherwise, it has to be set manually when next node is done. + // + if (reinterpret_cast(InterlockedCompareExchangePointer(&_M_pWriterTail, pActiveWriter, pWriter)) != pWriter) + { + pWriter->WaitForNextNode(); + + // + // During the initial copy the next pointer was not copied over and it has been populated in the meantime. + // This copy can now be safely performed because tail has moved, so next will point to the second element. + // + pActiveWriter->Copy(pWriter); + } + } + + _CONCRT_ASSERT(_PWriter != _M_pWriterTail); + // NOTE: The write to _M_pWriterHead below could be re-ordered on ARM64 with the writes within the ->Copy() above (when Copy is inlined). + // However, this is not an issue because _M_pWriterHead is not concurrently read when the lock has already been acquired by the writer + // (which is the case here). The read of _M_pWriterHead in _Unlock_reader can occur only when a writer is blocked or about to block. + _M_pWriterHead = pActiveWriter; +} + +/// +/// Called from unlock() when a reader is holding the lock. Reader count is decremented and if this +/// is the last reader it checks whether there are interested writers that need to be unblocked. +/// +void reader_writer_lock::_Unlock_reader() +{ + long resultState = InterlockedExchangeAdd(&_M_lockState, -RWLockReaderCountIncrement); + + // + // If this is the last reader and there are writers lined up then unblock them. However, + // if exclusive writer flag is not set, then writers will take care of themselves. + // + if ((resultState & (~RWLockReaderInterested)) == (RWLockReaderCountIncrement | RWLockWriterInterested | RWLockWriterExclusive)) + { + _CONCRT_ASSERT(_M_pWriterTail != NULL); + reinterpret_cast(_M_pWriterHead)->Unblock(); + } +} + +/// +/// Constructs a holder object and acquires the reader_writer_lock passed to it. +// If the reader_writer_lock is held by another thread this call will block. +/// +/// +/// Reader writer to lock. +/// +reader_writer_lock::scoped_lock::scoped_lock(reader_writer_lock& _Reader_writer_lock) : _M_reader_writer_lock(_Reader_writer_lock) +{ + static_assert(sizeof(LockQueueNode) <= sizeof(_M_writerNode), "_M_writerNode buffer too small"); + LockQueueNode * pNewWriterNode = reinterpret_cast(_M_writerNode); + new(pNewWriterNode) LockQueueNode; + _M_reader_writer_lock._Acquire_lock(pNewWriterNode, true); +} + +/// +/// Destructs a holder object and releases the reader_writer_lock. +/// +reader_writer_lock::scoped_lock::~scoped_lock() +{ + _M_reader_writer_lock.unlock(); +} + +/// +/// Constructs a holder object and acquires the reader_writer_lock passed to it. +// If the reader_writer_lock is held by another thread this call will block. +/// +/// +/// Reader Writer to lock. +/// +reader_writer_lock::scoped_lock_read::scoped_lock_read(reader_writer_lock& _Reader_writer_lock) : _M_reader_writer_lock(_Reader_writer_lock) +{ + _M_reader_writer_lock.lock_read(); +} + +/// +/// Destructs a holder object and releases the reader_writer_lock. +/// +reader_writer_lock::scoped_lock_read::~scoped_lock_read() +{ + _M_reader_writer_lock.unlock(); +} + +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/staticinits.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/staticinits.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61c9539dc2641d8f1a02dd71b90ec3afc5701e20 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/staticinits.cpp @@ -0,0 +1,52 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// staticinits.cpp +// +// A separate module for static fields and globals that need to be initialized in +// a special, compiler segment. This is done to ensure that these objects are initialized +// before any user code or third-party library code. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" + +namespace Concurrency +{ +namespace details +{ +#pragma warning(push) +#pragma warning(disable:4074) + +#pragma init_seg(compiler) + + // There shall be no dependency between the objects being initialized here. + // If they do we should have a StaticInitialize() method that invokes the + // initializers in the appropriate order. + + // From utils.cpp + volatile long Security::s_initialized = 0; + ULONG_PTR Security::s_cookie = Security::InitializeCookie(); + + // From SchedulerBase.cpp + // Define statics + _StaticLock SchedulerBase::s_schedulerLock; + _StaticLock SchedulerBase::s_defaultSchedulerLock; + + // A stack that holds free suballocators. + LockFreeStack SchedulerBase::s_subAllocatorFreePool; + + // From ResourceManager.cpp + _StaticLock ResourceManager::s_lock; + + // From Trace.cpp + _StaticLock Etw::s_lock; + +#pragma warning(pop) + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/targetver.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/targetver.h new file mode 100644 index 0000000000000000000000000000000000000000..ec962f871bf52b2eb6bbd23614cec5d70c8106b8 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/targetver.h @@ -0,0 +1,17 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +#pragma once + +// The following macros define the minimum required platform. The minimum required platform +// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run +// your application. The macros work by enabling all features available on platform versions up to and +// including the version specified. + +// Modify the following defines if you have to target a platform prior to the ones specified below. +// Refer to MSDN for the latest info on corresponding values for different platforms. +#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. +#endif diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f22b3eed2a60f6ed072e6b911ad8d583dd07e3a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.cpp @@ -0,0 +1,691 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// utils.cpp +// +// Utility routines for use in ConcRT. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#include "concrtinternal.h" +#include + +extern "C" IMAGE_DOS_HEADER __ImageBase; + +namespace Concurrency +{ +namespace details +{ + + /// + /// Default method for yielding during a spin wait + /// + void __cdecl _UnderlyingYield() + { + // Performs a yield appropriate to the scheduler. + ContextBase *pCurrentContext = SchedulerBase::SafeFastCurrentContext(); + if (pCurrentContext != NULL) + { + pCurrentContext->SpinYield(); + } + else + { + platform::__SwitchToThread(); + } + } + + /// + /// Returns the hardware concurrency available to the Concurrency Runtime, taking into account process affinity, or any restrictions + /// in place due to the set_task_execution_resource method. + /// + /// + /// This method is functionally equivalent to Concurrency::GetProcessorCount declared in concrtrm.h. It is surfaced in the details + /// namespace through concrt.h for use by code in headers that is part of the WINAPI_PARTITION App SDK, since all of concrtrm.h is unavailable + /// for WINAPI_PARTITION Apps. + /// + unsigned int __cdecl _GetConcurrency() + { + return ::Concurrency::details::ResourceManager::GetCoreCount(); + } + + /// + /// Use Sleep(0) to do the yield. + /// + void __cdecl _Sleep0() + { + platform::__Sleep(0); + } + + static bool g_TraceInitialized = false; + static int g_DesiredTraceLevel = 0; + static FILE* g_DebugOutFilePtr = stderr; + static int g_CommitFrequency = 50; + static unsigned __int64 g_TraceCount = 0; + + void _HyperNonReentrantLock::_Acquire() + { + ContextBase::StaticEnterHyperCriticalRegion(); + m_lock._Acquire(); + } + + bool _HyperNonReentrantLock::_TryAcquire() + { + ContextBase::StaticEnterHyperCriticalRegion(); + bool lockAcquired = m_lock._TryAcquire(); + if (!lockAcquired) + ContextBase::StaticExitHyperCriticalRegion(); + return lockAcquired; + } + + void _HyperNonReentrantLock::_Release() + { + m_lock._Release(); + ContextBase::StaticExitHyperCriticalRegion(); + } + + void _CriticalNonReentrantLock::_Acquire() + { + ContextBase::StaticEnterCriticalRegion(); + m_lock._Acquire(); + } + + bool _CriticalNonReentrantLock::_TryAcquire() + { + ContextBase::StaticEnterCriticalRegion(); + bool lockAcquired = m_lock._TryAcquire(); + if (!lockAcquired) + ContextBase::StaticExitCriticalRegion(); + return lockAcquired; + } + + void _CriticalNonReentrantLock::_Release() + { + m_lock._Release(); + ContextBase::StaticExitCriticalRegion(); + } + +#if defined(CONCRT_TRACING) + static bool + IsWhitespace( + wchar_t wch + ) + { + wchar_t buf[2]; + buf[0] = wch; + buf[1] = 0; + WORD type; +#pragma warning(push) +#pragma warning(disable: 25028) // use of function or parameters passed to function 'GetStringTypeExW' need to be reviewed -- it has been reviewed + if (!GetStringTypeExW(LOCALE_USER_DEFAULT, CT_CTYPE1, buf, 1, &type)) { + return false; + } +#pragma warning(pop) + return (type & C1_SPACE) != 0; + } + + static wchar_t * + SkipWhitespace( + _Out_writes_(count) wchar_t * ptr, + int count + ) + { + int i = 0; + while (i < count && ptr[i] != 0 && iswspace(ptr[i])) { + ++i; + } + return &ptr[i]; + } +#endif + + template + static const wchar_t * + StringToInt( + const wchar_t * ptr, + SignedInt * pvalue + ) + { + ASSERT(*ptr != L'\0'); + + bool negative; + if (*ptr == L'-') { + negative = true; + ++ptr; + } + else { + negative = false; + if (*ptr == L'+') { + ++ptr; + } + } + + if (*ptr < L'0' || *ptr > L'9') { + // No number present (possibly just a sign) + return NULL; + } + + UnsignedInt absval = 0; + do { + int digit = *ptr - L'0'; + if (absval > ui_max / 10 || + (absval == ui_max / 10 && + digit > ui_max % 10)) + { + // Unsigned overflow + return NULL; + } + absval = absval * 10 + digit; + ++ptr; + } while (*ptr >= L'0' && *ptr <= L'9'); + + SignedInt result = static_cast(absval); + if (negative) { + result = -result; + if (result > 0) { + // Signed underflow + return NULL; + } + } + else { + if (result < 0) { + // Signed overflow + return NULL; + } + } + + *pvalue = result; + return ptr; + } + +#if defined(CONCRT_TRACING) + static wchar_t * ReadEnvVar(const wchar_t * name, _Out_writes_(maxlen) wchar_t * buffer, DWORD maxlen) + { + DWORD len = GetEnvironmentVariableW(name, buffer, maxlen); + + if (len == 0) { + return NULL; + } + + if (len >= MAX_PATH) { + // name too long, just ignore it + return NULL; + } + + wchar_t * ptr = SkipWhitespace(buffer, maxlen); + if (*ptr == L'\0') { + return NULL; + } + + wchar_t * endptr = ptr + lstrlenW(ptr); + ASSERT(*endptr == L'\0'); + while (IsWhitespace(endptr[-1])) { + --endptr; + } + *endptr = L'\0'; + + ASSERT(*ptr != L'\0' && !IsWhitespace(*ptr)); + + return ptr; + } + + static int ProcessTraceValue(const wchar_t * ptr) + { + int value; + ptr = StringToInt(ptr, &value); + if (ptr == NULL || *ptr != L'\0') { + return 0; + } + return value; + } +#endif + + void InitializeUtilityRoutines() + { +#if defined(CONCRT_TRACING) + if (g_TraceInitialized) + { + return; + } + else + { + g_TraceInitialized = true; + } + + wchar_t buffer[MAX_PATH+1]; + // bits to match TRACE arenas + const wchar_t * ptr = ReadEnvVar(L"CONCRT_TRACE", buffer, DIM(buffer)); + if (ptr != NULL) + g_DesiredTraceLevel = ProcessTraceValue(buffer); + // when > 0, fflush every g_CommitFrequency TRACE statements, when <= 0 no flush + ptr = ReadEnvVar(L"CONCRT_COMMIT_FREQUENCY", buffer, DIM(buffer)); + if (ptr != NULL) + g_CommitFrequency = ProcessTraceValue(buffer); + else + g_CommitFrequency = 1; + // when not set will go to debug output, else stdout, stderr or filename + const wchar_t* pwszOutputFile = ReadEnvVar(L"CONCRT_TRACE_OUTPUT", buffer, DIM(buffer)); + if (pwszOutputFile != NULL) + { + if (wcsncmp(L"stdout", pwszOutputFile, MAX_PATH) == 0) + g_DebugOutFilePtr = stdout; + else if (wcsncmp(L"stderr", pwszOutputFile, MAX_PATH) == 0) + { + g_DebugOutFilePtr = stderr; + g_CommitFrequency = 0; + } + else + { + buffer[MAX_PATH] = 0; + errno_t errNo = 0; + if ((errNo = _wfopen_s(&g_DebugOutFilePtr, pwszOutputFile, L"w+tc")) != 0) + { + if (swprintf_s(buffer, MAX_PATH, L"Cannot open trace output: %S, errno=%d\n", pwszOutputFile, errNo) < 0) + // bad state -- try again w/o string + fprintf(stderr, "Cannot open trace output: errno=%d\n", errNo); + else + { + OutputDebugStringW(buffer); + fprintf(stderr, "Cannot open trace output: %S, errno=%d\n", pwszOutputFile, errNo); + } + // default to stderr + g_DebugOutFilePtr = stderr; + } + } + } +#endif + } + + void _ConcRT_CoreAssert(const char *, const char*, int) + { + // + // Nothing here can block in any way. + // + __debugbreak(); + } + + template + void + ConcRT_FillBuffer( + wchar_t (&buffer)[size], + const wchar_t * format, + va_list args + ) + { + // Format the prefix giving the current context, thread, and vproc IDs + int lenPrefix = 0; + ContextBase * pContext = SchedulerBase::SafeFastCurrentContext(); + if (pContext != NULL && pContext->GetScheduler() != NULL) { + lenPrefix = swprintf_s(buffer, size, L"[%d:%d:%d:%d(%d)] ", + pContext->GetVirtualProcessorId(), + pContext->GetId(), + pContext->GetScheduleGroupId(), + pContext->ScheduleGroupRefCount(), + GetCurrentThreadId()); + if (lenPrefix < 0) { + // Error in swprintf_s, don't bother with a prefix + lenPrefix = 0; + } + } + + // Format the trace message + vswprintf_s(buffer + lenPrefix, + DIM(buffer) - lenPrefix, + format, args); + + // Append the trailing newline if missing + int lenBuffer = static_cast(wcslen(buffer)); + if (lenBuffer > 0 && buffer[lenBuffer - 1] != L'\n') + { + if (lenBuffer < DIM(buffer) - 1) + { + buffer[lenBuffer] = L'\n'; + buffer[lenBuffer + 1] = L'\0'; + } + else + { + buffer[lenBuffer - 1] = L'\n'; + } + } + } + + // Trace -- Used for tracing and debugging + void + _ConcRT_Trace( + int trace_level, + const wchar_t * format, + ... + ) + { + InitializeUtilityRoutines(); + + // Check if tracing is disabled + if ((g_DesiredTraceLevel & trace_level) == 0) { + return; + } + + wchar_t buffer[1024+1]; + + va_list args; + va_start(args, format); + ConcRT_FillBuffer(buffer, format, args); + va_end(args); + + buffer[1024] = 0; + + if (g_DebugOutFilePtr != NULL) + { + fwprintf(g_DebugOutFilePtr, buffer); + if (g_CommitFrequency > 0 && (g_TraceCount++ % g_CommitFrequency) == 0) + fflush(g_DebugOutFilePtr); + } + else + { + OutputDebugStringW(buffer); + } + } + + // + // _SpinLock + // + _CONCRTIMP _SpinLock::_SpinLock(volatile long& flag) + : _M_flag(flag) + { + if ( _InterlockedCompareExchange(&_M_flag, 1, 0) != 0 ) + { + _SpinWaitBackoffNone spinWait; + do + { + spinWait._SpinOnce(); + } while ( _InterlockedCompareExchange(&_M_flag, 1, 0) != 0 ); + } + } + + _CONCRTIMP _SpinLock::~_SpinLock() + { + _InterlockedExchange(&_M_flag, 0); + } + + + + _CONCRTIMP unsigned long Log2(size_t n) { + unsigned long r; +#if defined(_WIN64) + // CodeQL [SM02313] r is always initialized: the only caller (concurrent_vector.cpp) always passes non-zero n + _BitScanReverse64(&r, n); +#else + // CodeQL [SM02313] r is always initialized: the only caller (concurrent_vector.cpp) always passes non-zero n + _BitScanReverse(&r, n); +#endif + return r; + } + + + // Globals used for ConcRT shutdown + volatile LONG LoadLibraryCount = 0; + HMODULE HostModule = NULL; + + // + // Adds a reference on a DLL where ConcRT is hosted, if it is a DLL, otherwise does nothing. + // This is used to shutdown ConcRT on our own terms and not be forced into a difficult synchronous + // shutdown by user's call to FreeLibrary. Note that this does not matter if a process shutdown + // happens because all threads and ConcRT along with them are rudely terminated by the OS. + // + void ReferenceLoadLibrary() + { +#if !defined(_ONECORE) + HMODULE currentModuleHandle = (HMODULE) &__ImageBase; + HMODULE currentExeHandle = GetModuleHandle(NULL); + + // Do this only if ConcRT is hosted inside a DLL + if (currentModuleHandle != currentExeHandle) + { + WCHAR wcDllPath[MAX_PATH]; + + auto nameSize = GetModuleFileNameW(currentModuleHandle, wcDllPath, MAX_PATH); + // GetModuleFileNameW will truncate module name and return MAX_PATH if the module name is too long. + if (nameSize != 0 && nameSize != MAX_PATH) + { + HostModule = LoadLibraryExW(wcDllPath, NULL, 0); + } + else + { + throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError())); + } + } +#endif // _ONECORE + } + + // + // Adds a reference to a host module and then creates the thread. First reference is managed by LoadLibrary, + // and all subsequent ones are reference counted internally to avoid LoadLibrary call overhead. + // + HANDLE LoadLibraryAndCreateThread + ( + LPSECURITY_ATTRIBUTES lpThreadAttributes, + SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, + DWORD dwCreationFlags, + LPDWORD lpThreadId + ) + { + // A caller higher up in the chain may retry the thread creation to provide resilience against thread creation failures. + // If thread creation fails we must be careful to undo any state changes we've made. Currently there are none. + HANDLE threadHandle = platform::__CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); + + if (threadHandle != NULL) + { + // Make sure that library (DLL) is not unloaded while ConcRT threads are still running. It is safe to do this after the + // thread is created, since the created threads block until they are resumed at a later point after this call returns, and + // we are guaranteed that they will not exit until after we've returned. + if (InterlockedIncrement(&LoadLibraryCount) == 1) + { + ReferenceLoadLibrary(); + SchedulerBase::ReferenceStaticOneShot(); + } + } + + return threadHandle; + } + + // + // Removes a reference count on a host module and in the case of last reference frees the library. + // + void FreeLibraryAndDestroyThread(DWORD exitCode) + { + // If this is the last ConcRT thread leaving the process try to cleanup + if (InterlockedDecrement(&LoadLibraryCount) == 0) + { + SchedulerBase::CheckOneShotStaticDestruction(); + +#if !defined(_ONECORE) + // If this is a DLL release the last LoadLibrary reference + if (HostModule != NULL) + { + FreeLibraryAndExitThread(HostModule, exitCode); + } +#else + (exitCode); +#endif // _ONECORE + } + } + + void UnRegisterAsyncWaitAndUnloadLibrary(PTP_CALLBACK_INSTANCE instance, PTP_WAIT waiter) + { + CONCRT_COREASSERT(instance != nullptr && waiter != nullptr); + SetThreadpoolWait(waiter, nullptr, nullptr); + CloseThreadpoolWait(waiter); + SchedulerBase::CheckOneShotStaticDestruction(); + + if (HostModule != nullptr) + { + FreeLibraryWhenCallbackReturns(instance, HostModule); + } + } + + PTP_WAIT RegisterAsyncWaitAndLoadLibrary(HANDLE waitingEvent, PTP_WAIT_CALLBACK callback, PVOID data) + { + // Use default global thread pool + PTP_WAIT waiter = CreateThreadpoolWait(callback, data, nullptr); + + if (waiter == nullptr) + { + return nullptr; + } + + // Add reference to the library + ReferenceLoadLibrary(); + SchedulerBase::ReferenceStaticOneShot(); + + SetThreadpoolWait(waiter, waitingEvent, nullptr); + return waiter; + } + + /// + /// This method is used if the timer is being destroyed from outside of one of its callbacks. It waits for + /// outstanding callbacks before closing the timer + /// + void DeleteAsyncTimerAndUnloadLibrary(PTP_TIMER timer) + { + CONCRT_COREASSERT(timer != nullptr); + SetThreadpoolTimer(timer, 0, 0, 0); + WaitForThreadpoolTimerCallbacks(timer, true); + CloseThreadpoolTimer(timer); + +#if !defined(_ONECORE) + SchedulerBase::CheckOneShotStaticDestruction(); + + if (HostModule != nullptr) + { + FreeLibrary(HostModule); + } +#endif // !defined(_ONECORE) + } + + /// + /// This method is used if the timer is being destroyed from within one of its callbacks. It cannot wait + /// for outstanding callbacks + /// + void UnRegisterAsyncTimerAndUnloadLibrary(PTP_CALLBACK_INSTANCE instance, PTP_TIMER timer) + { + CONCRT_COREASSERT(instance != nullptr && timer != nullptr); + SetThreadpoolTimer(timer, 0, 0, 0); + CloseThreadpoolTimer(timer); + +#if !defined(_ONECORE) + SchedulerBase::CheckOneShotStaticDestruction(); + + if (HostModule != nullptr) + { + FreeLibraryWhenCallbackReturns(instance, HostModule); + } +#endif // !defined(_ONECORE) + } + + PTP_TIMER RegisterAsyncTimerAndLoadLibrary(DWORD timeoutms, PTP_TIMER_CALLBACK callback, PVOID data, bool recurring) + { + // Use default global thread pool + PTP_TIMER timer = CreateThreadpoolTimer(callback, data, nullptr); + + if (timer == nullptr) + { + return nullptr; + } + +#if !defined(_ONECORE) + // Add reference to the library + ReferenceLoadLibrary(); + SchedulerBase::ReferenceStaticOneShot(); +#endif // !defined(_ONECORE) + + FILETIME time = {0}; + // Convert 100 ns unit into 1 ms unit. + // Negative here means FILETIME is a time span (instead of time point). + reinterpret_cast(time) = -static_cast(timeoutms) * 10000; + + SetThreadpoolTimer(timer, &time, recurring ? timeoutms : 0, 0); + return timer; + } + +// We will use the GS cookie as a starting point +extern "C" uintptr_t __security_cookie; + + // + // Initializes the cookie used to encode global data + // + ULONG_PTR Security::InitializeCookie() + { + CONCRT_COREASSERT(Security::s_initialized == 0); + Security::s_initialized = 1; + + // Take advantage of ASLR and per-process cookie + ULONG_PTR cookie = (ULONG_PTR)::EncodePointer((PVOID)&Security::s_cookie); + + // security cookie should be initialized before us. + cookie ^= (ULONG_PTR)__security_cookie; + +#if !defined(_ONECORE) + + // Add other randomization factors such as the thread creation time. + + FILETIME creationTime; + FILETIME notused; + + if (GetThreadTimes(GetCurrentThread(), &creationTime, ¬used, ¬used, ¬used)) + { +#if defined(_WIN64) + ULARGE_INTEGER ul; + + ul.LowPart = creationTime.dwLowDateTime; + ul.HighPart = creationTime.dwHighDateTime; + cookie ^= ul.QuadPart; +#else + cookie ^= creationTime.dwLowDateTime; + cookie ^= creationTime.dwHighDateTime; +#endif // _WIN64 + } +#endif // _ONECORE + + return cookie; + } + + // + // Encode the given pointer value + // + PVOID Security::EncodePointer(PVOID ptr) + { + CONCRT_COREASSERT(Security::s_initialized != 0); + return (PVOID)((ULONG_PTR)(ptr) ^ Security::s_cookie); + } + + // + // Decode the given pointer value + // + PVOID Security::DecodePointer(PVOID ptr) + { + return EncodePointer(ptr); + } + +} // namespace details +} // namespace Concurrency + +// +// ConcRT static cleanup: +// +extern "C" +void __cdecl _concrt_static_cleanup(void); + +_CRTALLOC(".CRT$XPB") static _PVFV pterm = _concrt_static_cleanup; + +extern "C" +void __cdecl _concrt_static_cleanup(void) +{ + // Cleanup the TLS unless inside an EXE + if (HostModule != NULL) + { + SchedulerBase::CheckOneShotStaticDestruction(); + } +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3fac9962d0ec49a6aedd666857ea808834697d11 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/utils.h @@ -0,0 +1,826 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// utils.h +// +// Header file containing the utility routine declarations. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +#pragma once + +//************************************************************************** +// Previously Public Macro Definitions: +//************************************************************************** + +// Enable tracing mechanisms +#if defined(_DEBUG) && defined(CONCRT_TRACING) +# define CONCRT_TRACE(...) ::Concurrency::details::_ConcRT_Trace(__VA_ARGS__) +#else +# define CONCRT_TRACE(...) ((void)0) +#endif + +#if defined(_DEBUG) +# define CONCRT_COREASSERT(x) (((x) ? ((void)0) : ::Concurrency::details::_ConcRT_CoreAssert(#x, __FILE__, __LINE__)), __assume(x)) +#else +# define CONCRT_COREASSERT(x) _CONCRT_ASSERT(x) +#endif + +#if defined(_DEBUG) +# define CONCRT_VERIFY(x) _CONCRT_ASSERT(x) +#else +# define CONCRT_VERIFY(x) (__assume(x), ((void)x)) +#endif + +// +// MTRACE: +// +// Memory tracing for UMS debugging (since it's nigh impossible elsewhere). This should be improved once the scheduler is "stable". Right now, +// buffers are interlocked incremented. +// +#define MTRACE_EVT_AFFINITIZED 1 +#define MTRACE_EVT_ADDEDTORUNNABLES 2 +#define MTRACE_EVT_UMSBLOCKED 3 +#define MTRACE_EVT_CRITICALBLOCK 4 +#define MTRACE_EVT_PULLEDFROMCOMPLETION 5 +#define MTRACE_EVT_SWITCHTO_BLOCKING 6 +#define MTRACE_EVT_SWITCHTO_IDLE 7 +#define MTRACE_EVT_SWITCHTO_YIELDING 8 +#define MTRACE_EVT_SWITCHTO_NESTING 9 +#define MTRACE_EVT_CONTEXT_RELEASED 10 +#define MTRACE_EVT_CONTEXT_ACQUIRED 11 +#define MTRACE_EVT_SFW_FOUND 12 +#define MTRACE_EVT_SFW_FOUNDBY 13 +#define MTRACE_EVT_CRITICALNOTIFY 14 +#define MTRACE_EVT_SUTNOTIFY 15 +#define MTRACE_EVT_BLOCKUNBLOCKRACE 16 +#define MTRACE_EVT_DEACTIVATE 17 +#define MTRACE_EVT_ACTIVATE 18 +#define MTRACE_EVT_INVERTED_ADDEDTORUNNABLES 19 +#define MTRACE_EVT_CLAIMEDOWNERSHIP 20 +#define MTRACE_EVT_MADEAVAILABLE 21 +#define MTRACE_EVT_AVAILABLEVPROCS 22 +#define MTRACE_EVT_SWITCHTO 23 +#define MTRACE_EVT_WOKEAFTERDEACTIVATE 24 +#define MTRACE_EVT_RMAWAKEN 25 +#define MTRACE_EVT_ACTIVATED 26 +#define MTRACE_EVT_SEARCHEDLOCALRUNNABLES 27 +#define MTRACE_EVT_RESTARTRAMBLING 28 +#define MTRACE_EVT_STARTRAMBLING 29 +#define MTRACE_EVT_STOPRAMBLING 30 +#define MTRACE_EVT_SFW_NEXTLOOP 31 +#define MTRACE_EVT_UPDATERAMBLING_RING 32 +#define MTRACE_EVT_UPDATERAMBLING_RESETRING 33 +#define MTRACE_EVT_UPDATERAMBLING_ALLVPROCS 34 +#define MTRACE_EVT_RETURNTOPRIMARY_BLOCKED 35 +#define MTRACE_EVT_RETURNTOPRIMARY_YIELD 36 +#define MTRACE_EVT_EXECUTE 37 +#define MTRACE_EVT_EXECUTEFAIL 38 +#define MTRACE_EVT_RETIRE 39 +#define MTRACE_EVT_ORIGINALCOMPLETION 40 +#define MTRACE_EVT_CONTEXTPOOLED 41 +#define MTRACE_EVT_CONTEXTUNPOOLED 42 +#define MTRACE_EVT_CONTEXTUNBOUND 43 +#define MTRACE_EVT_REFERENCE 44 +#define MTRACE_EVT_DEREFERENCE 45 +#define MTRACE_EVT_GROUPSWAP 46 +#define MTRACE_EVT_WORKITEMDEREFERENCE 47 +#define MTRACE_EVT_ADDUNREALIZED 48 +#define MTRACE_EVT_POPUNREALIZED 49 +#define MTRACE_EVT_EXECUTEUNREALIZED 50 +#define MTRACE_EVT_TOKENRESOLVE 51 +#define MTRACE_EVT_CHANGEAFFINITYSTATE 52 +#define MTRACE_EVT_ACKNOWLEDGEAFFINITYMESSAGE 53 +#define MTRACE_EVT_POSTAFFINITYMESSAGE 54 +#define MTRACE_EVT_SFW_SEARCHPHASE 55 +#define MTRACE_EVT_SFW_BIASGROUP 56 +#define MTRACE_EVT_SFW_SEGMENT 57 +#define MTRACE_EVT_SFW_SKIPSEGMENT 58 +#define MTRACE_EVT_SFW_RUNNABLES 59 +#define MTRACE_EVT_SFW_REALIZED 60 +#define MTRACE_EVT_SFW_UNREALIZED 61 +#define MTRACE_EVT_ADDLWT 62 +#define MTRACE_EVT_ADDRUNNABLE 63 +#define MTRACE_EVT_INITIALIZED 64 +#define MTRACE_EVT_TICKETEXERCISE 65 +#define MTRACE_EVT_SCHEDULEDTHROTTLER 66 +#define MTRACE_EVT_THROTTLERDISPATCH 67 +#define MTRACE_EVT_CREATEDTHROTTLEDCONTEXT 68 +#define MTRACE_EVT_NOTIFYTHROTTLEDCONTEXT 69 +#define MTRACE_EVT_PHASEONESHUTDOWN 70 +#define MTRACE_EVT_PHASETWOSHUTDOWN 71 +#define MTRACE_EVT_FINALIZATION 72 +#define MTRACE_EVT_EVENTHANDLERSDESTROYED 73 +#define MTRACE_EVT_VPROCACTIVE 74 +#define MTRACE_EVT_VPROCIDLE 75 +#define MTRACE_EVT_DEFERREDCONTEXT 76 +#define MTRACE_EVT_SCHEDULERSWEEP 77 +#define MTRACE_EVT_GETINTERNALCONTEXT 78 +#define MTRACE_EVT_GETINTERNALCONTEXTNOTHROTTLE 79 +#define MTRACE_EVT_RIP 80 +#define MTRACE_EVT_CTXFLAGS 81 +#define MTRACE_EVT_SFW_END 82 +#define MTRACE_EVT_CHOREMAILED 83 +#define MTRACE_EVT_MAILDEQUEUE 84 +#define MTRACE_EVT_SLOTCLAIM 85 +#define MTRACE_EVT_AFFINITYEXECUTED 86 +#define MTRACE_EVT_TAGAFFINITY 87 +#define MTRACE_EVT_STEALUNREALIZED 88 +#define MTRACE_EVT_VIEWWSQ 89 +#define MTRACE_EVT_SLOTCLAIMFAILED 90 +#define MTRACE_EVT_PERIODICSCAN 91 +#define MTRACE_EVT_PRIORITYBOOST 92 +#define MTRACE_EVT_MARK 93 +#define MTRACE_EVT_PRIORITYPULL 94 +#define MTRACE_EVT_PERIODICSCANNED 95 +#define MTRACE_EVT_CREATESEGMENT 96 +#define MTRACE_EVT_DESTROYSEGMENT 97 +#define MTRACE_EVT_SEARCHINGTRUE 98 +#define MTRACE_EVT_SEARCHINGFALSE 99 +#define MTRACE_EVT_LISTENINGTRUE 100 +#define MTRACE_EVT_LISTENINGFALSE 101 + + +#define VMTRACE(traceevt, ctx, vp, data) +#define CMTRACE(traceevt, ctx, vp, data) +#define VCMTRACE(traceevt, ctx, vp, data) +#define OMTRACE(traceevt, obj, ctx, vp, data) +#define CCMTRACE(traceevt, data) +#define CCMSTRACE(traceevt, data) +#define RVMTRACE(traceevt, ctx, vp, data) +#define RPMTRACE(traceevt, ctx, vp, data) +#define RVPMTRACE(traceevt, ctx, vp, data) + + +#define CONCRT_TRACE_ALL 0xFFFF +#define CONCRT_TRACE_SCHEDULER 0x0001 +#define CONCRT_TRACE_MSG 0x0002 +#define CONCRT_TRACE_SGROUP 0x0004 +#define CONCRT_TRACE_SCHEDULER_INSTANCE 0x0008 +#define CONCRT_TRACE_COLLECTIONS 0x0010 +#define CONCRT_TRACE_EVENT 0x0020 +#define CONCRT_TRACE_CHORES 0x0040 +#define CONCRT_TRACE_WORKQUEUE 0x0080 +#define CONCRT_TRACE_UNIT 0x0100 +#define CONCRT_TRACE_HILLCLIMBING 0x0200 +#define CONCRT_TRACE_DYNAMIC_RM 0x0400 + +// Various macros are defined in public headers as CONCRT_whatever. Define +// them here without the CONCRT_ prefix for use in the internal implementation. + +#define TRACE CONCRT_TRACE +#define TRACE_ALL CONCRT_TRACE_ALL +#define TRACE_SCHEDULER CONCRT_TRACE_SCHEDULER +#define TRACE_MSG CONCRT_TRACE_MSG +#define TRACE_SGROUP CONCRT_TRACE_SGROUP +#define TRACE_SCHEDULER_INSTANCE CONCRT_TRACE_SCHEDULER_INSTANCE +#define TRACE_COLLECTIONS CONCRT_TRACE_COLLECTIONS +#define TRACE_EVENT CONCRT_TRACE_EVENT +#define TRACE_CHORES CONCRT_TRACE_CHORES +#define TRACE_WORKQUEUE CONCRT_TRACE_WORKQUEUE +#define TRACE_UNIT CONCRT_TRACE_UNIT + +// Useful Macros + +#define UNREACHED 0 + +#define KB 1024 +#define DEFAULTCONTEXTSTACKSIZE (64 * KB) + +#define WIDEN2(str) L ## str +#define WIDEN(str) WIDEN2(str) + +#define __WFILE__ WIDEN(__FILE__) + +#define DIM(array) (sizeof(array) / sizeof(array[0])) + +// Ensure we use the intrinsic forms of Interlocked* APIs + +#undef InterlockedAnd +#undef InterlockedCompareExchange +#undef InterlockedDecrement +#undef InterlockedExchange +#undef InterlockedExchangeAdd +#undef InterlockedIncrement +#undef InterlockedOr +#undef InterlockedXor + +#define InterlockedAnd _InterlockedAnd +#define InterlockedCompareExchange _InterlockedCompareExchange +#define InterlockedDecrement _InterlockedDecrement +#define InterlockedExchange _InterlockedExchange +#define InterlockedExchangeAdd _InterlockedExchangeAdd +#define InterlockedIncrement _InterlockedIncrement +#define InterlockedOr _InterlockedOr +#define InterlockedXor _InterlockedXor + +#ifdef _M_X64 +# undef InterlockedAnd64 +# undef InterlockedOr64 +# undef InterlockedXor64 +# undef InterlockedIncrement64 +# define InterlockedAnd64 _InterlockedAnd64 +# define InterlockedOr64 _InterlockedOr64 +# define InterlockedXor64 _InterlockedXor64 +# define InterlockedIncrement64 _InterlockedIncrement64 +#endif + +#if defined(_M_ARM64) || defined(_M_X64) || defined(_M_IX86) +#define USE_ICX64 1 +# undef InterlockedCompareExchange64 +# define InterlockedCompareExchange64 _InterlockedCompareExchange64 +#else +#undef USE_ICX64 +#endif + +#undef InterlockedCompareExchangePointer +#undef InterlockedExchangePointer + +#define InterlockedCompareExchangePointer _InterlockedCompareExchangePointer +#define InterlockedExchangePointer _InterlockedExchangePointer + +#undef InterlockedIncrementSizeT +#undef InterlockedDecrementSizeT +#undef InterlockedCompareExchangeSizeT + +#ifdef _WIN64 +#define InterlockedIncrementSizeT(x) (size_t)(InterlockedIncrement64(reinterpret_cast((x)))) +#define InterlockedDecrementSizeT(x) (size_t)(InterlockedDecrement64(reinterpret_cast((x)))) +#define InterlockedCompareExchangeSizeT(x,y,z) (size_t)(InterlockedCompareExchange64(reinterpret_cast((x)), (LONGLONG)((y)), (LONGLONG)((z)))) +#else +#define InterlockedIncrementSizeT(x) (size_t)(InterlockedIncrement(reinterpret_cast((x)))) +#define InterlockedDecrementSizeT(x) (size_t)(InterlockedDecrement(reinterpret_cast((x)))) +#define InterlockedCompareExchangeSizeT(x,y,z) (size_t)(InterlockedCompareExchange(reinterpret_cast((x)), (LONG)((y)), (LONG)((z)))) +#endif + + +namespace Concurrency +{ +namespace details +{ + bool + FORCEINLINE + SafeInterlockedIncrement ( + _Inout_ LONG volatile *Addend + ) + { + LONG Old; + + do { + Old = *Addend; + if (Old == 0) + return false; + } while (_InterlockedCompareExchange(Addend, + Old + 1, + Old) != Old); + + return true; + } + + #if defined(_M_ARM64) || defined(_M_ARM64EC) + inline __int64 _ReadTimeStampCounter() + { + __int64 tsc; + QueryPerformanceCounter((LARGE_INTEGER*)&tsc); + return tsc; + } + #else + #define _ReadTimeStampCounter() __rdtsc() + #endif + + // For HillClimbing + + inline double GetCurrentHiRezTime() + { + static LARGE_INTEGER qpcFreq; + if (0 == qpcFreq.QuadPart) + { + QueryPerformanceFrequency(&qpcFreq); + } + + LARGE_INTEGER time; + QueryPerformanceCounter(&time); + + return (double)time.QuadPart / (double)qpcFreq.QuadPart; + } + + template + T sign(T val) + { + if (val == 0) + { + return 0; + } + return val > 0 ? 1 : -1; + } + + USHORT + inline + NumberOfBitsSet( + _In_ ULONG_PTR mask + ) + { + USHORT count = 0; + + while (mask != 0) + { + ++count; + mask &= (mask - 1); + } + return count; + } + + _CONCRTIMP void _ConcRT_Trace(int trace_level, const wchar_t * format, ...); + _CONCRTIMP void _ConcRT_CoreAssert(const char* value, const char* filename, int lineno); + _CONCRTIMP void _ConcRT_VMTrace(int traceevt, void *pCtx, void *pVp, ULONG_PTR data); + _CONCRTIMP void _ConcRT_CMTrace(int traceevt, void *pCtx, void *pVp, ULONG_PTR data); + _CONCRTIMP void _ConcRT_CCMTrace(int traceevt, ULONG_PTR data); + _CONCRTIMP void _ConcRT_CCMSTrace(int traceevt, ULONG_PTR data); + _CONCRTIMP void _ConcRT_RVMTrace(int traceevt, void *pCtx, void *pVp, ULONG_PTR data); + _CONCRTIMP void _ConcRT_RPMTrace(int traceevt, void *pCtx, void *pVp, ULONG_PTR data); + + void InitializeUtilityRoutines(); + + /// + /// Static methods related to security such as encode/decode pointer + /// + class Security + { + public: + + static ULONG_PTR s_cookie; + static volatile long s_initialized; + + static ULONG_PTR InitializeCookie(); + + static PVOID EncodePointer(PVOID ptr); + static PVOID DecodePointer(PVOID ptr); + }; + + /// + /// Use Sleep(0) to do the yield. + /// + void __cdecl _Sleep0(); + + /// + /// Spin WHILE the value of the variable is equal to a given value. + /// _Ty and _U should be comparable types + /// + template + static inline void SpinwaitWhileEq( volatile _Ty& location, _U value ) + { + _SpinWaitBackoffNone spinWait; + while( location==value ) + { + spinWait._SpinOnce(); + } + } + + /// + /// Spin UNTIL the value of the variable is equal to a given value. + /// _Ty and _U should be comparable types + /// + template + static inline void SpinwaitUntilEq( volatile _Ty& location, const _U value ) + { + _SpinWaitBackoffNone spinWait; + while( location!=value ) + { + spinWait._SpinOnce(); + } + } + + /// + /// Spin UNTIL the value of the variable is equal to a given value. + /// Uses Sleep(0) to yield + /// + void + inline + SpinUntilValueEquals( + _In_ LONG volatile * Address, + _In_ LONG Value + ) + { + if (*Address != Value) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + } while (*Address != Value); + } + } + + /// + /// Spin UNTIL the specified bits are set + /// Uses Sleep(0) to yield + /// + LONG + inline + SpinUntilBitsSet( + _In_ LONG volatile * Address, + _In_ LONG Bits + ) + { + LONG val = *Address; + if ((val & Bits) != Bits) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + val = *Address; + } while ((val & Bits) != Bits); + } + return val; + } + + /// + /// Spin UNTIL the specified bits are reset. + /// Uses Sleep(0) to yield + /// + LONG + inline + SpinUntilBitsReset( + _In_ LONG volatile * Address, + _In_ LONG Bits + ) + { + LONG val = *Address; + if ((val & Bits) != 0) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + val = *Address; + } while ((val & Bits) != 0); + } + return val; + } + + /// + /// This non-reentrant lock is a pure spin lock and is intended for use in situations + /// where it is known that the lock will not be taken recursively, and can thus be more + /// efficiently implemented. + /// + class _NonReentrantLock + { + public: + /// + /// Constructor for _NonReentrantLock + /// + _NonReentrantLock() + : _M_Lock(0) + { + } + + /// + /// Acquire the lock, spin if necessary + /// + void _Acquire() + { +#if defined(_DEBUG) + _DebugAcquire(); +#else // !_DEBUG + + if (InterlockedExchange(&_M_Lock, 1) != 0) + { + _SpinWaitBackoffNone spinWait(_Sleep0); + + do + { + spinWait._SpinOnce(); + } + while (InterlockedExchange(&_M_Lock, 1) != 0); + } + +#endif // !_DEBUG + } + + /// + /// Tries to acquire the lock, does not spin. + /// Returns true if the lock is taken, false otherwise + /// + bool _TryAcquire() + { +#if defined(_DEBUG) + return _DebugTryAcquire(); +#else // !_DEBUG + return (_M_Lock == 0 && InterlockedExchange(&_M_Lock, 1) == 0); +#endif // _DEBUG + } + + /// + /// Releases the lock + /// + void _Release() + { +#if defined(_DEBUG) + _M_Lock = _M_Lock & ~1; +#else // !_DEBUG + _M_Lock = 0; +#endif // _DEBUG + } + + bool _IsLockHeld() const + { + return (_M_Lock != 0); + } + + /// + /// An exception safe RAII wrapper. + /// + class _Scoped_lock + { + public: + explicit _Scoped_lock(_NonReentrantLock& _Lock) : _M_lock(_Lock) + { + _M_lock._Acquire(); + } + + ~_Scoped_lock() + { + _M_lock._Release(); + } + private: + _NonReentrantLock& _M_lock; + + _Scoped_lock(const _Scoped_lock&); // no copy constructor + _Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator + }; + + private: + // The lock being held + volatile long _M_Lock; + + bool _DebugTryAcquire(); + void _DebugAcquire(); + }; + + /// + /// A variant of _NonReentrantLock which ensures that the lock is taken in a hyper critical region. + /// + class _HyperNonReentrantLock + { + public: + void _Acquire(); + bool _TryAcquire(); + void _Release(); + + bool _IsLockHeld() const + { + return m_lock._IsLockHeld(); + } + + /// + /// An exception safe RAII wrapper. + /// + class _Scoped_lock + { + public: + explicit _Scoped_lock(_HyperNonReentrantLock& _Lock) : _M_lock(_Lock) + { + _M_lock._Acquire(); + } + + ~_Scoped_lock() + { + _M_lock._Release(); + } + private: + _HyperNonReentrantLock& _M_lock; + + _Scoped_lock(const _Scoped_lock&); // no copy constructor + _Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator + }; + + private: + _NonReentrantLock m_lock; + }; + + /// + /// A variant of _NonReentrantLock which ensures that the lock is taken in a critical region. + /// + class _CriticalNonReentrantLock + { + public: + void _Acquire(); + bool _TryAcquire(); + void _Release(); + + bool _IsLockHeld() const + { + return m_lock._IsLockHeld(); + } + + /// + /// An exception safe RAII wrapper. + /// + class _Scoped_lock + { + public: + explicit _Scoped_lock(_CriticalNonReentrantLock& _Lock) : _M_lock(_Lock) + { + _M_lock._Acquire(); + } + + ~_Scoped_lock() + { + _M_lock._Release(); + } + private: + _CriticalNonReentrantLock& _M_lock; + + _Scoped_lock(const _Scoped_lock&); // no copy constructor + _Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator + }; + + private: + _NonReentrantLock m_lock; + }; + + + typedef _NonReentrantLock _StaticLock; + + + // Wrapper around _BitScanReverse (for concurrent_vector) + _CONCRTIMP unsigned long Log2(size_t); + + // ************************************************** + // Safe Points: + // + // Pre-declare structures used for safe points. These must be defined early due to usage within collections and other utilities. + // + // A safe point is defined as a region past which every virtual processor is guaranteed to have made a particular observation. Operations + // subject to safe points are usually defined as two phase operations where phase 1 of an operation is performed, and phase 2 is registered + // to occur at the next safe point. The actual safe point may occur an **ARBITRARY** amount of time later. If a given virtual processor + // is sleeping, it may not make the observation until it awakens, is retired, or the scheduler finalizes. Likewise, if a given virtual processor + // is performing work which is not cooperatively blocking, it may not make the observation until the next cooperative event. Thus, the operation + // performed at a safe point must not be performance critical relative to when it was scheduled. + // + // The typical uses of safe points are things like deferred deletions from lock free lists. For example, an element may be removed from + // a ListArray as phase 1 and deleted on reaching the next safe point as phase 2. This guarantees that every virtual processor has observed + // the removal and isn't touching the element. + // + // Each virtual processor contains a SafePointMarker which performs necessary data versioning for this mechanism to work. + // + // ******************** READ THIS NOW ******************** + // + // Safe points are observations by virtual processors, not every context running on the scheduler. While this distinction does not matter so much + // on the thread scheduler, it is **EXTREMELY IMPORTANT** on the UMS scheduler. As such, the usage of safe points to guard an operation X must follow + // a set of rules: + // + // - The operation X must be inclusively bound by a critical region on the UMS scheduler. + // + // As an example, consider lock-free traversal of a ListArray. Internal contexts traverse list array objects without regard to the state of + // the objects. The ListArray code frees objects at safe points. The safe point is guarding the reference of ListArray objects. Therefore, + // the entire region from inclusively between saying p = ListArray[x] and the last dereference of p must be bounded by a critical region. + // + // As a second example, detached work stealing queues release their reference on their schedule group at retirement at a safe point. Code which + // steals from a detached work stealing queue does not put a new reference on the schedule group until calling WorkItem::TransferReferences. The + // safe point is guarding the region between the steal and the placement of the reference. Therefore, the entire region inclusively between + // WorkQueue::Steal... and WorkItem::TransferReferences must be inclusively bounded by a critical region. + // + + template class SQueue; + + /// + /// An intrusive object which is inserted into the list of work a scheduler must invoke on the next safe point. + /// + class SafePointInvocation + { + public: + + typedef void (*InvocationFunction)(void *); + + /// + /// Registers a particular function to be called with particular data when a given scheduler reaches the next safe point + /// after the call is made. This is an intrusive invocation with the current SafePointInvocation class incurring no heap + /// allocations. + /// + /// + /// The function which will be invoked at the next safe point + /// + /// + /// User specified data. + /// + /// + /// The scheduler on which to wait for a safe point to invoke pInvocationFunction. + /// + void InvokeAtNextSafePoint(InvocationFunction pInvocationFunction, void *pData, SchedulerBase *pScheduler); + + private: + + friend class SchedulerBase; + template friend class SQueue; + + /// + /// The invocation of the callback for this particular registration. + /// + void Invoke() + { + m_pInvocation(m_pData); + } + + // The client invocation function + InvocationFunction m_pInvocation; + + // The client data + void *m_pData; + + // The data version for this safe point. + ULONG m_safePointVersion; + + // The queue linkage (spin-lock guarded) + SafePointInvocation *m_pNext; + + }; + + /// + /// This performs all version tracking for a particular virtual processor. Only the scheduler touches this data structure. + /// + class SafePointMarker + { + public: + + /// + /// Construct a new safe point marker. + /// + SafePointMarker() + { + Reset(); + } + + /// + /// Reset a safe point marker. + /// + void Reset() + { + // + // Zero is a special key indicating that it has made no data observations. + // + m_lastObservedVersion = 0; + } + + private: + + friend class SchedulerBase; + + // The last observed version of data. + ULONG m_lastObservedVersion; + }; + + /// + /// Adds a reference to a host module and then creates the thread. First reference is managed by LoadLibrary, + /// and all subsequent ones are reference counted internally to avoid LoadLibrary call overhead. + /// + HANDLE LoadLibraryAndCreateThread + ( + LPSECURITY_ATTRIBUTES lpThreadAttributes, + SIZE_T dwStackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + LPVOID lpParameter, + DWORD dwCreationFlags, + LPDWORD lpThreadId + ); + + /// + /// Removes a reference count on a host module and in the case of last reference frees the library. + /// + void FreeLibraryAndDestroyThread(DWORD exitCode); + + /// + /// Adds a reference to a host module and then create a async waiter in global threadpool that listens to the waitingEvent. + /// + PTP_WAIT RegisterAsyncWaitAndLoadLibrary(HANDLE waitingEvent, PTP_WAIT_CALLBACK callback, PVOID data); + + /// + /// Removes the async waiter from the global threadpool and the reference count on a host module when the callback returns. + /// + void UnRegisterAsyncWaitAndUnloadLibrary(PTP_CALLBACK_INSTANCE instance, PTP_WAIT waiter); + + /// + /// Adds a reference to a host module and then create a async timer in global threadpool that listens to the waitingEvent. + /// + PTP_TIMER RegisterAsyncTimerAndLoadLibrary(DWORD timeoutms, PTP_TIMER_CALLBACK callback, PVOID data, bool recurring = false); + + /// + /// Removes the async timer from the global threadpool and the reference count on a host module when the callback returns. + /// + void UnRegisterAsyncTimerAndUnloadLibrary(PTP_CALLBACK_INSTANCE instance, PTP_TIMER timer); + + /// + /// Removes the async timer, reference count on a host module, and wait for the callback returns. + /// + void DeleteAsyncTimerAndUnloadLibrary(PTP_TIMER timer); + +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/workqueue.h b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/workqueue.h new file mode 100644 index 0000000000000000000000000000000000000000..0c5e878bb9c27eb4b8d4b4692e9f5ba1e691cc34 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/workqueue.h @@ -0,0 +1,339 @@ +// ==++== +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// ==--== +// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ +// +// workqueue.h +// +// Work stealing queues pair implementation. +// +// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +namespace Concurrency +{ +namespace details +{ +#define QUEUE_ATTACHED 0 +#define QUEUE_DETACHED 1 + + /// + /// The work queue is a pair of bound work stealing queues, one structured and one unstructured, that + /// can be associated with a context. + /// +#pragma warning(push) +#pragma warning(disable: 4324) // structure was padded due to alignment specifier + class WorkQueue + { + public: + + /// + /// Constructs a new work queue. + /// + WorkQueue(); + + // + // Queue Reuse: + // + + /// + /// Informs the WSQ what context it's attached to in a synchronized manner. + /// + void LockedSetOwningContext(ContextBase *pOwningContext) + { + m_lock._Acquire(); + m_pOwningContext = pOwningContext; + m_lock._Release(); + } + + /// + /// Informs the WSQ what context it's attached to. + /// + void SetOwningContext(ContextBase *pOwningContext) + { + m_pOwningContext = pOwningContext; + } + + // + // Structured Parallelism: + // + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue + /// + /// + /// The mailbox slot into which the specified chore has already been queued for explicit affinitization. The slot can be an empty + /// slot if the chore was not queued anywhere. + /// + void PushStructured(_UnrealizedChore *pChore, Mailbox<_UnrealizedChore>::Slot affinitySlot) + { + m_structuredQueue.Push(pChore, affinitySlot); + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for structured parallelism. + /// + /// + /// The chore to push onto the structured work stealing queue + /// + void PushStructured(_UnrealizedChore *pChore) + { + m_structuredQueue.Push(pChore); + } + + /// + /// Pops the topmost chore from the work stealing queue for unstructured parallelism. Failure + /// to pop typically indicates stealing. + /// + /// + /// An unrealized chore from the structured work stealing queue or NULL if none is present + /// + _UnrealizedChore* PopStructured() + { + return m_structuredQueue.Pop(); + } + + /// + /// Returns whether the structured work stealing queue is empty. + /// + bool IsStructuredEmpty() const + { + return m_structuredQueue.Empty(); + } + + // + // Unstructured Parallelism: + // + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. The returned + /// value is a cookie which can be used in a call to TryPopUnstructured. + /// + /// + /// The chore to push onto the unstructured work stealing queue + /// + /// + /// The mailbox slot into which the specified chore has already been queued for explicit affinitization. The slot can be an empty + /// slot if the chore was not queued anywhere. + /// + /// + /// A cookie which can be used to identify the chore for a later TryPopUnstructured call + /// + int PushUnstructured(_UnrealizedChore *pChore, Mailbox<_UnrealizedChore>::Slot affinitySlot) + { + return m_unstructuredQueue.Push(pChore, affinitySlot); + } + + /// + /// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism. The returned + /// value is a cookie which can be used in a call to TryPopUnstructured. + /// + /// + /// The chore to push onto the unstructured work stealing queue + /// + /// + /// A cookie which can be used to identify the chore for a later TryPopUnstructured call + /// + int PushUnstructured(_UnrealizedChore *pChore) + { + return m_unstructuredQueue.Push(pChore); + } + + /// + /// Attempts to pop the chore specified by a cookie value from the unstructured work stealing queue. Failure + /// to pop typically indicates stealing. + /// + /// + /// A cookie returned from PushUnstructured indicating the chore to attempt to pop from + /// the unstructured work stealing queue + /// + /// + /// The specified unrealized chore (as indicated by cookie) or NULL if it could not be popped from + /// the work stealing queue + /// + _UnrealizedChore *TryPopUnstructured(int cookie) + { + return m_unstructuredQueue.TryPop(cookie); + } + + /// + /// Attempts to steal an unrealized chore from the unstructured work stealing queue. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + /// + /// An unrealized chore stolen from the work stealing queues or NULL if no such chore can be stolen + /// + _UnrealizedChore *Steal(bool fForceStealLocalized); + + /// + /// Attempts to steal an unrealized chore from the unstructured work stealing queue. + /// + /// + /// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location + /// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there + /// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox. + /// + /// + /// The try lock was successfully acquired. + /// + /// + /// An unrealized chore stolen from the work stealing queues or NULL if no such chore can be stolen + /// + _UnrealizedChore *TryToSteal(bool fForceStealLocalized, bool& fSuccessfullyAcquiredLock); + + /// + /// Returns whether the unstructured work stealing queue is empty. + /// + bool IsUnstructuredEmpty() const + { + return m_unstructuredQueue.Empty(); + } + + /// + /// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them + /// based on the result of a callback. + /// + /// + /// The predicate for things to call pSweepFn on. + /// + /// + /// The data for the predicate and sweep callback + /// + /// + /// The sweep function + /// + void SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate, + void *pData, + WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn); + + /// + /// Called in order to mark this work queue as detached so that we know how far it's legal to steal up the work + /// queue should it become reattached to context with active cancellation. + /// + void MarkDetachment() + { + // + // We only detach unstructured queues. + // + m_unstructuredQueue.MarkDetachment(); + } + + // + // Both: + // + + /// + /// Returns the id of the work queue. + /// + unsigned int Id() const { return m_id; } + + /// + /// Returns whether the both work stealing queues are empty. + /// + bool IsEmpty() const + { + return m_structuredQueue.Empty() && m_unstructuredQueue.Empty(); + } + + /// + /// Sets the queue to a detached state. + /// + void SetDetached(bool fDetached) + { + if (fDetached) + MarkDetachment(); + + InterlockedExchange(&m_detachmentState, fDetached ? QUEUE_DETACHED : QUEUE_ATTACHED); + } + + /// + /// Queries whether the queue is detached. + /// + bool IsDetached() const + { + return (m_detachmentState == QUEUE_DETACHED); + } + + /// + /// Causes a detached work queue to release its reference on the passed-in schedule group and remove itself from that schedule group's + /// list of work queues at the next available safe point. + /// + void RetireAtSafePoint(ScheduleGroupSegmentBase *pSegment); + + /// + /// Causes a detached work queue to redetach due to roll-back of retirement at the next available safe point. + /// + void RedetachFromScheduleGroupAtSafePoint(ScheduleGroupSegmentBase *pSegment); + + /// + /// Indicates whether the steal lock is held. + /// + bool IsLockHeld() const + { + return m_lock._IsLockHeld(); + } + + private: + friend class ContextBase; + friend class ScheduleGroupBase; + friend class ScheduleGroupSegmentBase; + template friend class ListArray; + template friend void _InternalDeleteHelper(T*); + + // structured work stealing + StructuredWorkStealingQueue<_UnrealizedChore, _CriticalNonReentrantLock> m_structuredQueue; + + // Intrusive links for list array. + SLIST_ENTRY m_listArrayFreeLink{}; + + // The safe point invocation which will perform a release of schedule group held by a detached WSQ. + SafePointInvocation m_detachmentSafePoint{}; + + // Tracking for detachment + ListArrayInlineLink m_detachment; + volatile long m_detachmentState; + ScheduleGroupSegmentBase *m_pDetachedSegment{}; + + // The unique identifier for the work queue. This is the final level of binding between a task collection and a work queue. + unsigned int m_id; + + // The index this workqueue appears at in its list array + int m_listArrayIndex{}; + + // The context which owns the WSQ. NOTE: Any utilization of this must be capture/use as it will change outside the scope + // of the WSQ list lock. + ContextBase *m_pOwningContext; + + // Unstructured work stealing + WorkStealingQueue<_UnrealizedChore, _CriticalNonReentrantLock> m_unstructuredQueue; + + // External lock for unstructured work stealing + _CriticalNonReentrantLock m_lock; + + // Reinitialize a work queue pulled from a free pool + void Reinitialize(); + + // steal helper + _UnrealizedChore *UnlockedSteal(bool fForceStealLocalized); + + /// + /// Retires the detached work queue. + /// + static void StaticRetire(WorkQueue *pQueue); + + /// + /// Places the work queue back in a detached state on roll back. + /// + static void StaticRedetachFromScheduleGroup(WorkQueue *pQueue); + }; +#pragma warning(pop) +} // namespace details +} // namespace Concurrency diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/alloca16.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/alloca16.asm new file mode 100644 index 0000000000000000000000000000000000000000..3df015fd9f0ba15b42c36f68348bb26de9b9cdca --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/alloca16.asm @@ -0,0 +1,71 @@ + page ,132 + title alloca16 - aligned C stack checking routine +;*** +;chkstk.asm - aligned C stack checking routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Provides 16 and 8 bit aligned alloca routines. +; +;******************************************************************************* + +.xlist + include vcruntime.inc +.list + +extern _chkstk:near + +; size of a page of memory + + CODESEG + +page +;*** +; _alloca_probe_16, _alloca_probe_8 - align allocation to 16/8 byte boundary +; +;Purpose: +; Adjust allocation size so the ESP returned from chkstk will be aligned +; to 16/8 bit boundary. Call chkstk to do the real allocation. +; +;Entry: +; EAX = size of local frame +; +;Exit: +; Adjusted EAX. +; +;Uses: +; EAX +; +;******************************************************************************* + +public _alloca_probe_8 + +_alloca_probe_16 proc ; 16 byte aligned alloca + + push ecx + lea ecx, [esp] + 8 ; TOS before entering this function + sub ecx, eax ; New TOS + and ecx, (16 - 1) ; Distance from 16 bit align (align down) + add eax, ecx ; Increase allocation size + sbb ecx, ecx ; ecx = 0xFFFFFFFF if size wrapped around + or eax, ecx ; cap allocation size on wraparound + pop ecx ; Restore ecx + jmp _chkstk + +alloca_8: ; 8 byte aligned alloca +_alloca_probe_8 = alloca_8 + + push ecx + lea ecx, [esp] + 8 ; TOS before entering this function + sub ecx, eax ; New TOS + and ecx, (8 - 1) ; Distance from 8 bit align (align down) + add eax, ecx ; Increase allocation Size + sbb ecx, ecx ; ecx = 0xFFFFFFFF if size wrapped around + or eax, ecx ; cap allocation size on wraparound + pop ecx ; Restore ecx + jmp _chkstk + +_alloca_probe_16 endp + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chandler4.c b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chandler4.c new file mode 100644 index 0000000000000000000000000000000000000000..ffd77889dd3c71da1952d6987e714716435be110 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chandler4.c @@ -0,0 +1,580 @@ +/*** +*chandler4.c - Structured Exception Handling part of _except_handler4 +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Defines _except_handler4, the language specific handler for structured +* exception handling on x86. First created for Visual C++ 2005, replacing +* _except_handler3, with the addition of security cookie checks. +* +* For the CRT DLL, this actually defines _except_handler4_common, which +* performs the real processing for chandler4gs.c's stub routine +* _except_handler4. We need a stub that is linked statically into an +* image, so it can access the image-local global security cookie. But all +* it needs to do is pass through to this code, sending in the address of +* the global cookie and the image's __security_check_cookie routine. This +* larger routine can then be placed in the CRT DLL. +* +*******************************************************************************/ + +#include +#include + +// copied from ntxcapi.h +#define EXCEPTION_UNWINDING 0x2 // Unwind is in progress +#define EXCEPTION_EXIT_UNWIND 0x4 // Exit unwind is in progress +#define EXCEPTION_STACK_INVALID 0x8 // Stack out of limits or unaligned +#define EXCEPTION_NESTED_CALL 0x10 // Nested exception handler call +#define EXCEPTION_TARGET_UNWIND 0x20 // Target unwind in progress +#define EXCEPTION_COLLIDED_UNWIND 0x40 // Collided exception handler call + +#define EXCEPTION_UNWIND (EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND | \ + EXCEPTION_TARGET_UNWIND | EXCEPTION_COLLIDED_UNWIND) + +#define IS_UNWINDING(Flag) ((Flag & EXCEPTION_UNWIND) != 0) +#define IS_DISPATCHING(Flag) ((Flag & EXCEPTION_UNWIND) == 0) +#define IS_TARGET_UNWIND(Flag) (Flag & EXCEPTION_TARGET_UNWIND) + +BEGIN_PRAGMA_OPTIMIZE_ENABLE("t", DevDivVSO:162582, "This file is performance-critical and should always be optimized for speed") + +/* + * Define __except filter/handler and __finally handler function types. + */ + +typedef LONG (__cdecl *PEXCEPTION_FILTER_X86)(void); +typedef void (__cdecl *PEXCEPTION_HANDLER_X86)(void); +typedef void (__fastcall *PTERMINATION_HANDLER_X86)(BOOL); + +/* + * Define type of pointer to __security_check_cookie. + */ + +typedef void (__fastcall *PCOOKIE_CHECK)(UINT_PTR); + +/* + * The function-specific scope table pointed to by the on-stack exception + * registration record. This describes the nesting structure of __try blocks + * in the function, the location of all __except filters, __except blocks, and + * __finally blocks, and the data required to check the security cookies in + * the function + */ + +typedef struct _EH4_SCOPETABLE_RECORD +{ + ULONG EnclosingLevel; + PEXCEPTION_FILTER_X86 FilterFunc; + union + { + PEXCEPTION_HANDLER_X86 HandlerAddress; + PTERMINATION_HANDLER_X86 FinallyFunc; + } u; +} EH4_SCOPETABLE_RECORD, *PEH4_SCOPETABLE_RECORD; + +typedef struct _EH4_SCOPETABLE +{ + ULONG GSCookieOffset; + ULONG GSCookieXOROffset; + ULONG EHCookieOffset; + ULONG EHCookieXOROffset; + EH4_SCOPETABLE_RECORD ScopeRecord[1]; +} EH4_SCOPETABLE, *PEH4_SCOPETABLE; + +#define NO_GS_COOKIE ((ULONG)-2) + +#define TOPMOST_TRY_LEVEL ((ULONG)-2) + +/* + * The exception registration record stored in the stack frame. The linked + * list of registration records goes through the EXCEPTION_REGISTRATION_RECORD + * sub-struct, so some fields here are at negative offsets with regards to + * the registration record pointer we are passed. + */ + +typedef struct _EH4_EXCEPTION_REGISTRATION_RECORD +{ + PVOID SavedESP; + PEXCEPTION_POINTERS ExceptionPointers; + EXCEPTION_REGISTRATION_RECORD SubRecord; + UINT_PTR EncodedScopeTable; + ULONG TryLevel; +} EH4_EXCEPTION_REGISTRATION_RECORD, *PEH4_EXCEPTION_REGISTRATION_RECORD; + +/* + * External dependencies not found in headers. + */ + +#pragma warning(disable: 4132) // communal object is intentionally const +void (__cdecl * const _pDestructExceptionObject)( + PEXCEPTION_RECORD pExcept, + int fThrowNotAllowed + ); + +#define EH_EXCEPTION_NUMBER ('msc' | 0xE0000000) + +extern LONG __fastcall +_EH4_CallFilterFunc( + _In_ PEXCEPTION_FILTER_X86 FilterFunc, + _In_ PCHAR FramePointer + ); + +extern void __declspec(noreturn) __fastcall +_EH4_TransferToHandler( + _In_ PEXCEPTION_HANDLER_X86 HandlerAddress, + _In_ PCHAR FramePointer + ); + +extern void __fastcall +_EH4_GlobalUnwind2( + _In_opt_ PEXCEPTION_REGISTRATION_RECORD EstablisherFrame, + _In_opt_ PEXCEPTION_RECORD ExceptionRecord + ); + +extern void __fastcall +_EH4_LocalUnwind( + _In_ PEXCEPTION_REGISTRATION_RECORD EstablisherFrame, + _In_ ULONG TargetLevel, + _In_ PCHAR FramePointer, + _In_ PUINT_PTR CookiePointer + ); + +#pragma warning(disable: 4100) // ignore unreferenced formal parameters + +#ifdef _M_HYBRID_X86_ARM64 + +#pragma intrinsic(_HybridGenerateThunks) + +// +// Generate wrappers for routines implemented in asm. +// + +LONG __fastcall +_EH4_CallFilterFunc( + PEXCEPTION_FILTER_X86 FilterFunc, + PCHAR FramePointer + ) +{ + _HybridGenerateThunks((void *)_EH4_CallFilterFunc, 1); + return 0; +} + +void __declspec(noreturn) __fastcall +_EH4_TransferToHandler( + PEXCEPTION_HANDLER_X86 HandlerAddress, + PCHAR FramePointer + ) +{ + _HybridGenerateThunks((void *)_EH4_TransferToHandler, 1); +} + +void __fastcall +_EH4_GlobalUnwind2( + PEXCEPTION_REGISTRATION_RECORD EstablisherFrame, + PEXCEPTION_RECORD ExceptionRecord + ) +{ + _HybridGenerateThunks((void *)_EH4_GlobalUnwind2, 1); +} + +void __fastcall +_EH4_LocalUnwind( + PEXCEPTION_REGISTRATION_RECORD EstablisherFrame, + ULONG TargetLevel, + PCHAR FramePointer, + PUINT_PTR CookiePointer + ) +{ + _HybridGenerateThunks((void *)_EH4_LocalUnwind, 1); +} + +#endif + +extern void +__except_validate_context_record( + _In_ PCONTEXT ContextRecord + ); + +/*** +*ValidateLocalCookies - perform local cookie validation during SEH processing +* +*Purpose: +* Perform the security checks for _except_handler4. +* +*Entry: +* CookieCheckFunction - (CRT DLL only) pointer to __security_check_cookie in +* the target image +* ScopeTable - pointer to the unencoded scope table from the exception +* registration record +* FramePointer - EBP frame pointer for the function that established the +* exception registration record +* +*Return: +* If the security checks fail, the process is terminated via a Watson dump. +* +*******************************************************************************/ + +static __declspec(guard(ignore)) void +ValidateLocalCookies( +#if defined(CRTDLL) + IN PCOOKIE_CHECK CookieCheckFunction, +#endif + IN PEH4_SCOPETABLE ScopeTable, + _When_(ScopeTable->GSCookieOffset >= ScopeTable->EHCookieOffset, + _In_reads_bytes_(ScopeTable->GSCookieOffset + sizeof(UINT_PTR))) + _When_(ScopeTable->GSCookieOffset < ScopeTable->EHCookieOffset, + _In_reads_bytes_(ScopeTable->EHCookieOffset + sizeof(UINT_PTR))) + PCHAR FramePointer + ) +{ + UINT_PTR GSCookie; + UINT_PTR EHCookie; + + if (ScopeTable->GSCookieOffset != NO_GS_COOKIE) + { + GSCookie = *(PUINT_PTR)(FramePointer + ScopeTable->GSCookieOffset); + GSCookie ^= (UINT_PTR)(FramePointer + ScopeTable->GSCookieXOROffset); +#if defined(CRTDLL) + _GUARD_CHECK_ICALL(CookieCheckFunction); + (*CookieCheckFunction)(GSCookie); +#else + __security_check_cookie(GSCookie); +#endif + } + + EHCookie = *(PUINT_PTR)(FramePointer + ScopeTable->EHCookieOffset); + EHCookie ^= (UINT_PTR)(FramePointer + ScopeTable->EHCookieXOROffset); +#if defined(CRTDLL) + _GUARD_CHECK_ICALL(CookieCheckFunction); + (*CookieCheckFunction)(EHCookie); +#else + __security_check_cookie(EHCookie); +#endif +} + +/*** +*_except_handler4 - (non-CRT DLL only) SEH handler with security cookie checks +* +*_except_handler4_common - (CRT DLL only) actual SEH implementation called by +* _except_handler4 stub +* +*Purpose: +* Implement structured exception handling for functions which have __try/ +* __except/__finally. This version of SEH also performs security cookie +* checks to detect buffer overruns which potentially corrupt the on-stack +* exception handling data, terminating the process before such corruption +* can be exploited. +* +* Call exception and termination handlers as necessary, based on the current +* execution point within the function. +* +*Entry: +* CookiePointer - (CRT DLL only) pointer to the global security cookie to be +* used to decode the scope table pointer in the exception registration +* record +* CookieCheckFunction - (CRT DLL only) pointer to __security_check_cookie in +* the calling image +* ExceptionRecord - pointer to the exception being dispatched +* EstablisherFrame - pointer to the on-stack exception registration record +* for this function +* ContextRecord - pointer to a context record for the point of exception +* DispatcherContext - pointer to the exception dispatcher or unwind +* dispatcher context +* +*Return: +* If the security checks fail, the process is terminated via a Watson dump. +* +* If an exception is being dispatched and the exception is handled by an +* __except filter for this exception frame, then this function does not +* return. Instead, it calls RtlUnwind and transfers control to the __except +* block corresponding to the accepting __except filter. Otherwise, an +* exception disposition of continue execution or continue search is returned. +* +* If an unwind is being dispatched, then each termination handler (__finally) +* is called and a value of continue search is returned. +* +*******************************************************************************/ + +#if defined(_M_IX86) && !defined(CRTDLL) && !defined(_M_HYBRID) +// Filter incorrect x86 floating point exceptions, unless linkopt that provides an empty filter is available. +#pragma comment(linker, "/alternatename:__filter_x86_sse2_floating_point_exception=__filter_x86_sse2_floating_point_exception_default") +#endif + +DECLSPEC_GUARD_SUPPRESS +EXCEPTION_DISPOSITION +#if !defined(CRTDLL) +_except_handler4( +#else +_except_handler4_common( + IN PUINT_PTR CookiePointer, + IN PCOOKIE_CHECK CookieCheckFunction, +#endif + IN PEXCEPTION_RECORD ExceptionRecord, + IN PEXCEPTION_REGISTRATION_RECORD EstablisherFrame, + IN OUT PCONTEXT ContextRecord, + IN OUT PVOID DispatcherContext + ) +{ + PEH4_EXCEPTION_REGISTRATION_RECORD RegistrationNode; + PCHAR FramePointer; + PEH4_SCOPETABLE ScopeTable; + ULONG TryLevel; + ULONG EnclosingLevel; + EXCEPTION_POINTERS ExceptionPointers; + PEH4_SCOPETABLE_RECORD ScopeTableRecord; + PEXCEPTION_FILTER_X86 FilterFunc; + LONG FilterResult; + BOOLEAN Revalidate = FALSE; + EXCEPTION_DISPOSITION Disposition = ExceptionContinueSearch; + +#ifdef _M_HYBRID_X86_ARM64 + + // + // Ensure that this function is implemented as guest code so that there are + // no dynamic EH registration nodes added for push thunk frames. + // + +#if defined(CRTDLL) + _HybridGenerateThunks((void *)_except_handler4_common, 1); +#else + _HybridGenerateThunks((void *)_except_handler4, 1); +#endif +#endif + +#if defined(_M_IX86) && !defined(CRTDLL) && !defined(_M_HYBRID) + ExceptionRecord->ExceptionCode = _filter_x86_sse2_floating_point_exception(ExceptionRecord->ExceptionCode); +#endif + + // + // We are passed a registration record which is a field offset from the + // start of our true registration record. + // + + RegistrationNode = + (PEH4_EXCEPTION_REGISTRATION_RECORD) + ( (PCHAR)EstablisherFrame - + FIELD_OFFSET(EH4_EXCEPTION_REGISTRATION_RECORD, SubRecord) ); + + // + // The EBP frame pointer in the function corresponding to the registration + // record will be immediately following the record. If the function uses + // FPO, this is a "virtual" frame pointer outside of exception handling, + // but it's still the EBP value set when calling into the handlers or + // filters. + // + + FramePointer = (PCHAR)(RegistrationNode + 1); + + // + // Retrieve the scope table pointer, which encodes where we find the local + // security cookies within the function's frame, as well as how the guarded + // blocks in the target function are laid out. This pointer was XORed with + // the image-local global security cookie when originally stored, to avoid + // attacks which spoof the table to address valid local cookies elsewhere + // on the stack. + // + +#if defined(CRTDLL) + ScopeTable = (PEH4_SCOPETABLE) + (RegistrationNode->EncodedScopeTable ^ *CookiePointer); +#else + ScopeTable = (PEH4_SCOPETABLE) + (RegistrationNode->EncodedScopeTable ^ __security_cookie); +#endif + + // + // Perform the initial security cookie validation. + // + + ValidateLocalCookies( +#if defined(CRTDLL) + CookieCheckFunction, +#endif + ScopeTable, + FramePointer + ); + + __except_validate_context_record(ContextRecord); + + // + // Security checks have passed, begin actual exception handling. + // + + if (IS_DISPATCHING(ExceptionRecord->ExceptionFlags)) + { + // + // An exception dispatch is in progress. First build the + // EXCEPTION_POINTERS record queried by the _exception_info intrinsic + // and save it in the exception registration record so the __except + // filter can find it. + // + + ExceptionPointers.ExceptionRecord = ExceptionRecord; + ExceptionPointers.ContextRecord = ContextRecord; + RegistrationNode->ExceptionPointers = &ExceptionPointers; + + // + // Scan the scope table and call the appropriate __except filters until + // we find one that accepts the exception. + // + + for (TryLevel = RegistrationNode->TryLevel; + TryLevel != TOPMOST_TRY_LEVEL; + TryLevel = EnclosingLevel) + { + ScopeTableRecord = &ScopeTable->ScopeRecord[TryLevel]; + FilterFunc = ScopeTableRecord->FilterFunc; + EnclosingLevel = ScopeTableRecord->EnclosingLevel; + + if (FilterFunc != NULL) + { + // + // The current scope table record is for an __except. + // Call the __except filter to see if we've found an + // accepting handler. + // + + FilterResult = _EH4_CallFilterFunc(FilterFunc, FramePointer); + Revalidate = TRUE; + + // + // If the __except filter returned a negative result, then + // dismiss the exception. If it returned a positive result, + // unwind to the accepting exception handler. Otherwise keep + // searching for an exception filter. + // + + if (FilterResult < 0) + { + Disposition = ExceptionContinueExecution; + break; + } + else if (FilterResult > 0) + { +#if !defined(_NTSUBSET_) + // + // If we're handling a thrown C++ exception, let the C++ + // exception handler destruct the thrown object. This call + // is through a function pointer to avoid linking to the + // C++ EH support unless it's already present. Don't call + // the function pointer unless it's in read-only memory. + // + + if (ExceptionRecord->ExceptionCode == EH_EXCEPTION_NUMBER && + _pDestructExceptionObject != NULL && + _IsNonwritableInCurrentImage((PBYTE)&_pDestructExceptionObject)) + { + (*_pDestructExceptionObject)(ExceptionRecord, TRUE); + } +#endif // !defined(_NTSUBSET_) + + + + // + // Unwind all registration nodes below this one, then unwind + // the nested __try levels. + // + _EH4_GlobalUnwind2( + &RegistrationNode->SubRecord, + ExceptionRecord + ); + + if (RegistrationNode->TryLevel != TryLevel) + { + _EH4_LocalUnwind( + &RegistrationNode->SubRecord, + TryLevel, + FramePointer, +#if defined(CRTDLL) + CookiePointer +#else + &__security_cookie +#endif + ); + } + + // + // Set the __try level to the enclosing level, since it is + // the enclosing level, if any, that guards the __except + // handler. + // + + RegistrationNode->TryLevel = EnclosingLevel; + + // + // Redo the security checks, in case any __except filters + // or __finally handlers have caused overruns in the target + // frame. + // + + ValidateLocalCookies( +#if defined(CRTDLL) + CookieCheckFunction, +#endif + ScopeTable, + FramePointer + ); + + // + // Call the __except handler. This call will not return. + // The __except handler will reload ESP from the + // registration record upon entry. The EBP frame pointer + // for the handler is directly after the registration node. + // + + _EH4_TransferToHandler( + ScopeTableRecord->u.HandlerAddress, + FramePointer + ); + } + } + } + } + else + { + // + // An exception unwind is in progress, and this isn't the target of the + // unwind. Unwind any active __try levels in this function, calling + // the applicable __finally handlers. + // + + if (RegistrationNode->TryLevel != TOPMOST_TRY_LEVEL) + { + _EH4_LocalUnwind( + &RegistrationNode->SubRecord, + TOPMOST_TRY_LEVEL, + FramePointer, +#if defined(CRTDLL) + CookiePointer +#else + &__security_cookie +#endif + ); + Revalidate = TRUE; + } + } + + // + // If we called any __except filters or __finally handlers, then redo the + // security checks, in case those funclets have caused overruns in the + // target frame. + // + + if (Revalidate) + { + ValidateLocalCookies( +#if defined(CRTDLL) + CookieCheckFunction, +#endif + ScopeTable, + FramePointer + ); + } + + // + // Continue searching for exception or termination handlers in previous + // registration records higher up the stack, or resume execution if we're + // here because an __except filter returned a negative result. + // + + return Disposition; +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chkstk.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chkstk.asm new file mode 100644 index 0000000000000000000000000000000000000000..6e3bb904482a58408790545a836bcd828fc16e87 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/chkstk.asm @@ -0,0 +1,104 @@ + page ,132 + title chkstk - C stack checking routine +;*** +;chkstk.asm - C stack checking routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Provides support for automatic stack checking in C procedures +; when stack checking is enabled. +; +;******************************************************************************* + +.xlist + include vcruntime.inc +.list + +; size of a page of memory + +_PAGESIZE_ equ 1000h + + + CODESEG + +page +;*** +;_chkstk - check stack upon procedure entry +; +;Purpose: +; Provide stack checking on procedure entry. Method is to simply probe +; each page of memory required for the stack in descending order. This +; causes the necessary pages of memory to be allocated via the guard +; page scheme, if possible. In the event of failure, the OS raises the +; _XCPT_UNABLE_TO_GROW_STACK exception. +; +; NOTE: Currently, the (EAX < _PAGESIZE_) code path falls through +; to the "lastpage" label of the (EAX >= _PAGESIZE_) code path. This +; is small; a minor speed optimization would be to special case +; this up top. This would avoid the painful save/restore of +; ecx and would shorten the code path by 4-6 instructions. +; +;Entry: +; EAX = size of local frame +; +;Exit: +; ESP = new stackframe, if successful +; +;Uses: +; EAX +; +;Exceptions: +; _XCPT_GUARD_PAGE_VIOLATION - May be raised on a page probe. NEVER TRAP +; THIS!!!! It is used by the OS to grow the +; stack on demand. +; _XCPT_UNABLE_TO_GROW_STACK - The stack cannot be grown. More precisely, +; the attempt by the OS memory manager to +; allocate another guard page in response +; to a _XCPT_GUARD_PAGE_VIOLATION has +; failed. +; +;******************************************************************************* + +public _alloca_probe + +_chkstk proc + +_alloca_probe = _chkstk + + push ecx + +; Calculate new TOS. + + lea ecx, [esp] + 8 - 4 ; TOS before entering function + size for ret value + sub ecx, eax ; new TOS + +; Handle allocation size that results in wraparound. +; Wraparound will result in StackOverflow exception. + + sbb eax, eax ; 0 if CF==0, ~0 if CF==1 + not eax ; ~0 if TOS did not wrapped around, 0 otherwise + and ecx, eax ; set to 0 if wraparound + + mov eax, esp ; current TOS + and eax, not ( _PAGESIZE_ - 1) ; Round down to current page boundary + +cs10: + cmp ecx, eax ; Is new TOS + jb short cs20 ; in probed page? + mov eax, ecx ; yes. + pop ecx + xchg esp, eax ; update esp + mov eax, dword ptr [eax] ; get return address + mov dword ptr [esp], eax ; and put it at new TOS + ret + +; Find next lower page and probe +cs20: + sub eax, _PAGESIZE_ ; decrease by PAGESIZE + test dword ptr [eax],eax ; probe page. + jmp short cs10 + +_chkstk endp + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/dllsupp.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/dllsupp.asm new file mode 100644 index 0000000000000000000000000000000000000000..3915e4035c028568c91415a253b3f531fc418d9a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/dllsupp.asm @@ -0,0 +1,28 @@ +;*** +;dllsupp.asm - Definitions of public constants +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Provides definitions for public constants (absolutes) that are +; 'normally' defined in objects in the C library, but must be defined +; here for clients of the CRT DLL. These constants are: +; +; _except_list +; _ldused +; +;******************************************************************************* + + .686 + .model flat,c + +; offset, with respect to FS, of pointer to currently active exception handler. +; referenced by compiler generated code for SEH and by _setjmp(). + + public _except_list +_except_list equ 0 + + public _ldused +_ldused equ 9876h + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg2.c b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg2.c new file mode 100644 index 0000000000000000000000000000000000000000..e5cd90195c8500e937687dbfaf70d199eaac4892 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg2.c @@ -0,0 +1,122 @@ +/*** +*ehprolg2.c - Defines _EH_prolog2 compiler helper +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* EH prologue helper function for an aligned stack. +****/ + +#pragma warning(disable:4733) // ignore unsafe FS:0 modifications +/*** +*void _EH_prolog2(alignment) - set up aligned stack with EH frame +* +*Purpose: +* Sets up an aligned frame for a C++ EH function with unwinds, by +* creating a link in the __except_list, setting EBX as the frame +* parameter pointer, and EBP as the frame base pointer. +* +*Entry: +* EAX = address of EH handler thunk +* Incoming stack frame has: +* [ESP + 8] = callee's return address +* [ESP + 4] = stack alignment requirement +* [ESP + 0] = _EH_prolog2's return address +* +*Exit: +* EAX = destroyed +* EBX = pointer to callee's parameters +* EBP = aligned pointer to callee's locals +* ESP = EBP - 12 +* FS:[0] = set to EBP-8 to create new link in EH chain +* Stack frame has been set up as follows: +* [EBX + 4] = (entry [ESP+8]) callee's return address +* [EBX + 0] = saved EBX +* padding to align stack (if needed) +* [EBP + 4] = callee's return address (from [EBX+4]) +* [EBP + 0] = saved EBP +* [EBP - 4] = EH record state index, initialized to -1 +* [EBP - 8] = address of EH handler thunk +* [EBP - 12] = saved FS:[0] +* +*Exceptions: +* +*******************************************************************************/ + +#ifdef __cplusplus +extern "C" +#endif +void __declspec(naked) _EH_prolog2(void) +{ + /* + * We want to generate a frame that is equivalent to + * push ebx + * ebx = esp + * sub esp, 8 + * and esp, ~alignment + * add esp, 4 + * push ebp + * ebp = esp + * mov [ebp+4], [ebx+4] + * [EH record] + */ + + __asm { + ; stack has: + ; alignment + ; ret addr <== esp + + push ecx ; save ecx + ; with ret addr == sub esp, 8 + + ; stack has: + ; alignment + ; ret addr + ; saved ecx <== esp + + mov ecx, [esp+8] ; get alignment + + mov [esp+8], ebx ; save ebx over alignment + lea ebx, [esp+8] ; set param pointer + + ; stack has: + ; saved ebx <== ebx + ; ret addr + ; saved ecx <== esp + + neg ecx ; create alignment mask + and esp, ecx ; align stack + + mov ecx, [ebx-8] ; restore ecx since it will be in the same + ; location we want to store ebp if no + ; padding is inserted (esp is aligned at and) + + mov [esp], ebp ; save ebp + mov ebp, esp ; initialize ebp + + ; stack has + ; saved ebx <== ebx + ; ret addr + ; [padding] + ; saved ebp <== ebp, esp + + push -1 ; create EH record + push eax + mov eax,fs:[00000000] + push eax + mov dword ptr fs:[0],esp + + push ecx ; we need this again + + mov eax, [ebx-4] ; get helper return address + + mov ecx, [ebx+4] ; copy orig function caller return address + mov [ebp+4], ecx ; (for ebp-based stack walks) + + pop ecx ; we are done + + push eax ; eax has return address + + ret + } +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3.c b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3.c new file mode 100644 index 0000000000000000000000000000000000000000..6df4e9dfdf215a5d3486bda9b2a0ee9df4cbfe6e --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3.c @@ -0,0 +1,612 @@ +/*** +*ehprolg3.c - Define the _EH_prolog3* compiler helpers for unaligned frames +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* EH prologue helpers for the EH security cookie cases, where the cookie +* must be initialized before the EH node is installed. Also defines the +* complementary EH epilogue helpers. +* +* The helpers should be compiled /Gy, at least in retail CRTs, so they +* will be compiled as comdats, and only the ones used will be pulled into +* a release build. +* +* These helpers are for setting up normal frames which do not require +* 8-byte (or more) alignment of the local stack allocation. +* +* There are 4 different prologue helpers, to deal with the various +* combinations of a 12-byte -vs- 16-byte exception registration node and +* the presence or absence of a /GS local security cookie. +* +* _EH_prolog3 +* _EH_prolog3_catch +* _EH_prolog3_GS +* _EH_prolog3_catch_GS +* +* There are 3 different epilogue helpers: +* +* _EH_epilog3 +* _EH_epilog3_GS +* _EH_epilog3_catch_GS +****/ + +#include + +/* + * Ignore warnings about unreferenced formal parameters and unsafe FS:0 + * assignments. + */ + +#pragma warning(disable:4100 4733) +/*** +*_EH_prolog3 - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 12-byte EH node (function has unwinds, no catch blocks) +* + does not have a local /GS cookie +* + uses an EBP frame (no FPO) +* + does not need dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* +* Incoming stack frame has: +* [ESP+8] callee's return address +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3's return address +* +*Exit: +* EAX = destroyed +* EBP = ESP on entry + 4 +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBP+4] (entry [ESP+8]) callee's return address +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* ... +* [EBP-12-N] base of locals allocation +* [EBP-16-N] saved EBX +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3( + unsigned long LocalAllocation + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr <== ESP + + push eax ; save handler thunk address in its proper + ; final position, free EAX for use + push fs:[0] ; set link to next node in EH chain + + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr + ; handler thunk address + ; saved FS:[0] <== ESP + + lea eax, [esp+12] ; calculate return value for EBP + sub esp, [esp+12] ; allocate locals allocation area + push ebx ; save the callee saves except for EBP + push esi + push edi + mov [eax], ebp ; save old EBP in final location + mov ebp, eax ; establish new EBP frame pointer + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; ret addr + ; handler thunk address + ; saved FS:[0] + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH cookie + push eax + push [ebp-4] ; move the return address to its final position + mov dword ptr [ebp-4], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; initial EH state index of -1 + ; handler thunk address + ; saved FS:[0] + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_catch - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 16-byte EH node (function has catch blocks) +* + does not have a local /GS cookie +* + uses an EBP frame (no FPO) +* + does not need dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This includes 4 bytes for the 4th field (the saved ESP) in the EH +* registration node. +* +* Incoming stack frame has: +* [ESP+8] callee's return address +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_catch's return address +* +*Exit: +* EAX = destroyed +* EBP = ESP on entry + 4 +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBP+4] (entry [ESP+8]) callee's return address +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved final ESP return value +* ... +* [EBP-12-N] base of locals allocation +* [EBP-16-N] saved EBX +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_catch( + unsigned long LocalAllocation + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr <== ESP + + push eax ; save handler thunk address in its proper + ; final position, free EAX for use + push fs:[0] ; set link to next node in EH chain + + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr + ; handler thunk address + ; saved FS:[0] <== ESP + + lea eax, [esp+12] ; calculate return value for EBP + sub esp, [esp+12] ; allocate end of EH node and the locals + ; allocation area + push ebx ; save the callee saves except for EBP + push esi + push edi + mov [eax], ebp ; save old EBP in final location + mov ebp, eax ; establish new EBP frame pointer + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; ret addr + ; handler thunk address + ; saved FS:[0] + ; (uninitialized) saved ESP field of EH node + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH cookie + push eax + mov [ebp-16], esp ; initialize the EH node's saved ESP field + push [ebp-4] ; move the return address to its final position + mov dword ptr [ebp-4], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; initial EH state index of -1 + ; handler thunk address + ; saved FS:[0] + ; saved ESP field of EH node + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_GS - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 12-byte EH node (function has unwinds, no catch blocks) +* + has a local /GS cookie +* + uses an EBP frame (no FPO) +* + does not need dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This includes 4 bytes for the GS cookie. +* +* Incoming stack frame has: +* [ESP+8] callee's return address +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_GS's return address +* +*Exit: +* EAX = destroyed +* EBP = ESP on entry + 4 +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBP+4] (entry [ESP+8]) callee's return address +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] local GS cookie, XORed with value of EBP on exit +* ... +* [EBP-12-N] base of locals allocation +* [EBP-16-N] saved EBX +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_GS( + unsigned long LocalAllocation + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr <== ESP + + push eax ; save handler thunk address in its proper + ; final position, free EAX for use + push fs:[0] ; set link to next node in EH chain + + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr + ; handler thunk address + ; saved FS:[0] <== ESP + + lea eax, [esp+12] ; calculate return value for EBP + sub esp, [esp+12] ; allocate space for the GS cookie, and the + ; locals allocation area + push ebx ; save the callee saves except for EBP + push esi + push edi + mov [eax], ebp ; save old EBP in final location + mov ebp, eax ; establish new EBP frame pointer + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; ret addr + ; handler thunk address + ; saved FS:[0] + ; (uninitialized) local GS security cookie + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH and GS cookies + push eax + mov [ebp-16], eax + push [ebp-4] ; move the return address to its final position + mov dword ptr [ebp-4], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; initial EH state index of -1 + ; handler thunk address + ; saved FS:[0] + ; saved ESP field of EH node + ; local GS security cookie + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_catch_GS - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 16-byte EH node (function has catch blocks) +* + has a local /GS cookie +* + uses an EBP frame (no FPO) +* + does not need dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This includes 4 bytes for the 4th field (the saved ESP) in the EH +* registration node, and 4 bytes for the GS cookie. +* +* Incoming stack frame has: +* [ESP+8] callee's return address +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_catch_GS's return address +* +*Exit: +* EAX = destroyed +* EBP = ESP on entry + 4 +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBP+4] (entry [ESP+8]) callee's return address +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved final ESP return value +* [EBP-20] local GS cookie, XORed with value of EBP on exit +* ... +* [EBP-12-N] base of locals allocation +* [EBP-16-N] saved EBX +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_catch_GS( + unsigned long LocalAllocation + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr <== ESP + + push eax ; save handler thunk address in its proper + ; final position, free EAX for use + push fs:[0] ; set link to next node in EH chain + + ; stack has: + ; callee's return addr + ; allocation size + ; ret addr + ; handler thunk address + ; saved FS:[0] <== ESP + + lea eax, [esp+12] ; calculate return value for EBP + sub esp, [esp+12] ; allocate end of EH node, space for the GS + ; cookie, and the locals allocation area + push ebx ; save the callee saves except for EBP + push esi + push edi + mov [eax], ebp ; save old EBP in final location + mov ebp, eax ; establish new EBP frame pointer + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; ret addr + ; handler thunk address + ; saved FS:[0] + ; (uninitialized) saved ESP field of EH node + ; (uninitialized) local GS security cookie + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH and GS cookies + push eax + mov [ebp-20], eax + mov [ebp-16], esp ; initialize the EH node's saved ESP field + push [ebp-4] ; move the return address to its final position + mov dword ptr [ebp-4], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBP <== EBP + ; initial EH state index of -1 + ; handler thunk address + ; saved FS:[0] + ; saved ESP field of EH node + ; local GS security cookie + ; locals allocation area + ; saved EBX + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_epilog3 - Tear down C++ EH call frame variation +* +*Purpose: +* Destroy a call frame set up by _EH_prolog3 or _EH_prolog3_catch. +* +*Entry: +* ESP = value it had on return from _EH_prolog3 or _EH_prolog3_catch +* EBP = value it had on return from _EH_prolog3 or _EH_prolog3_catch +* +*Exit: +* ESP = pointer to the callee's return address +* EBX, ESI, EDI, EBP restored from frame +* ECX destroyed +* All other registers except CC preserved +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_epilog3( + void + ) +{ + __asm + { + mov ecx, [ebp-12] ; remove EH node from EH chain + mov fs:[0], ecx + pop ecx ; save return address + pop edi ; pop and ignore the EH cookie + pop edi ; restore callee-saves + pop esi + pop ebx + mov esp, ebp ; free stack + pop ebp ; restore frame pointer + push ecx ; push return address + ret 0 + } +} + +/*** +*_EH_epilog3_GS - Tear down C++ EH call frame variation +* +*Purpose: +* Destroy a call frame set up by _EH_prolog3_GS, after first checking that +* the local /GS security cookie is correct. +* +*Entry: +* ESP = value it had on return from _EH_prolog3_GS +* EBP = value it had on return from _EH_prolog3_GS +* GS cookie located at EBP-16 +* +*Exit: +* ESP = pointer to the callee's return address +* EBX, ESI, EDI, EBP restored from frame +* ECX destroyed +* All other registers except CC preserved +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_epilog3_GS( + void + ) +{ + __asm + { + mov ecx, [ebp-16] ; rematerialize the global cookie and check + xor ecx, ebp ; * its validity + call __security_check_cookie + jmp _EH_epilog3 ; go tear down the frame + } +} + +/*** +*_EH_epilog3_catch_GS - Tear down C++ EH call frame variation +* +*Purpose: +* Destroy a call frame set up by _EH_prolog3_catch_GS, after first checking +* that the local /GS security cookie is correct. +* +*Entry: +* ESP = value it had on return from _EH_prolog3_catch_GS +* EBP = value it had on return from _EH_prolog3_catch_GS +* GS cookie located at EBP-20 +* +*Exit: +* ESP = pointer to the callee's return address +* EBX, ESI, EDI, EBP restored from frame +* ECX destroyed +* All other registers except CC preserved +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_epilog3_catch_GS( + void + ) +{ + __asm + { + mov ecx, [ebp-20] ; rematerialize the global cookie and check + xor ecx, ebp ; * its validity + call __security_check_cookie + jmp _EH_epilog3 ; go tear down the frame + } +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3a.c b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3a.c new file mode 100644 index 0000000000000000000000000000000000000000..43e924a80fee3fef9b9ae41815ee28b69fa8cecb --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolg3a.c @@ -0,0 +1,858 @@ +/*** +*ehprolg3a.c - Define the _EH_prolog3* compiler helpers for aligned frames +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* EH prologue helpers for the EH security cookie cases, where the cookie +* must be initialized before the EH node is installed. Also defines the +* complementary EH epilogue helpers. +* +* The helpers should be compiled /Gy, at least in retail CRTs, so they +* will be compiled as comdats, and only the ones used will be pulled into +* a release build. +* +* These helpers are for setting up dynamically aligned frames, where the +* local stack allocation must be 8-byte (or better) aligned, either for +* performance reasons (making sure doubles don't cross cache lines) or +* correctness (making sure some SSE types don't cross cache lines). +* +* There are 4 different prologue helpers, to deal with the various +* combinations of a 12-byte -vs- 16-byte exception registration node and +* the presence or absence of a /GS local security cookie. +* +* _EH_prolog3_align +* _EH_prolog3_catch_align +* _EH_prolog3_GS_align +* _EH_prolog3_catch_GS_align +* +* There are 2 different epilogue helpers: +* +* _EH_epilog3_align +* _EH_epilog3_GS_align +****/ + +#include + +/* + * Ignore warnings about unreferenced formal parameters and unsafe FS:0 + * assignments. + */ + +#pragma warning(disable:4100 4733) + +/*** +*_EH_prolog3_align - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 12-byte EH node (function has unwinds, no catch blocks) +* + does not have a local /GS cookie +* + uses an EBX/EBP frame (no FPO) +* + needs dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This is the space required after EBX is pushed below the EH node. +* Alignment = alignment requirement. +* +* Incoming stack frame has: +* [ESP+12] callee's return address +* [ESP+8] alignment requirement +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_align's return address +* +*Exit: +* EAX = destroyed +* EBX = ESP on entry + 4 (pointer to callee's parameters) +* EBP = aligned pointer to callee's locals +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBX+4] (entry [ESP+12]) callee's return address +* [EBX+0] saved EBX +* padding to align stack (if needed) +* [EBP+4] callee's return address (copy of entry [ESP+12]) +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved value of EBX on exit +* padding to realign stack (if needed) +* ... +* [EBP-16-N] base of locals allocation +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_align( + unsigned long LocalAllocation, + unsigned long Alignment + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; alignment requirement + ; allocation size + ; ret addr <== ESP + + push ecx ; we need an extra reg, so save ECX + mov ecx, [esp+12] ; get the alignment requirement + mov [esp+12], ebx ; save EBX in its final position + lea ebx, [esp+12] ; * and set the new EBX for addressing params + push eax ; save the handler thunk addr, free EAX for use + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; allocation size + ; ret addr + ; saved ECX + ; handler thunk addr <== ESP + ; + ; Now calculate the aligned stack pointer, which will be returned in + ; EBP. Depending on the padding required, it will point at the ret + ; addr in the above stack, or somewhere below that. + + lea eax, [esp+8] + neg ecx + and eax, ecx + lea esp, [eax-8] + + ; ESP now points at or below its position in the previous comment, + ; and ESP+8 has the required alignment. Everything below the saved + ; EBX is potentially overlapped by the aligned stack frame we're about + ; to create, so move those items to safety. + + mov eax, [ebx-16] ; the handler thunk address can be moved into + mov [esp], eax ; * its final position (might not move) + mov eax, [ebx-8] ; copy down the ret addr + push eax + mov eax, [ebx-4] ; get the allocation size for later + mov ecx, [ebx-12] ; restore the original ECX + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; (uninitialized) saved EBP (aligned stack location) + ; (uninitialized) EH state index + ; handler thunk addr + ; ret addr <== ESP + + mov [esp+12], ebp ; save old EBP and set new EBP frame pointer + lea ebp, [esp+12] ; * for addressing locals + mov dword ptr [esp+8], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr <== ESP + + push ebx ; save copy of EBX at EBP-16 for funclet use + sub esp, eax ; allocate the locals allocation space + push esi ; save callee-saved regs + push edi + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; saved value of EBX on exit + ; locals allocation area + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH cookie + push eax + mov eax, [ebx+4] ; copy callee's return addr above saved EBP + mov [ebp+4], eax ; * so EBP-based stackwalks work better + push [ebp-12] ; move the return address to final position + mov eax, fs:[0] ; set link to next node in EH chain + mov [ebp-12], eax + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; saved FS:[0] + ; saved value of EBX on exit + ; locals allocation area + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_catch_align - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 16-byte EH node (function has catch blocks) +* + does not have a local /GS cookie +* + uses an EBX/EBP frame (no FPO) +* + needs dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This is the space required after EBX is pushed below the EH node. +* Alignment = alignment requirement. +* +* Incoming stack frame has: +* [ESP+12] callee's return address +* [ESP+8] alignment requirement +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_catch_align's return address +* +*Exit: +* EAX = destroyed +* EBX = ESP on entry + 4 (pointer to callee's parameters) +* EBP = aligned pointer to callee's locals +* ESP = EBP on exit - 32 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBX+4] (entry [ESP+12]) callee's return address +* [EBX+0] saved EBX +* padding to align stack (if needed) +* [EBP+4] callee's return address (copy of entry [ESP+12]) +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved final ESP return value +* [EBP-20] saved value of EBX on exit +* padding to realign stack (if needed) +* ... +* [EBP-20-N] base of locals allocation +* [EBP-24-N] saved ESI +* [EBP-28-N] saved EDI +* [EBP-32-N] local EH cookie, XORed with value of EBP on exit +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_catch_align( + unsigned long LocalAllocation, + unsigned long Alignment + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; alignment requirement + ; allocation size + ; ret addr <== ESP + + push ecx ; we need an extra reg, so save ECX + mov ecx, [esp+12] ; get the alignment requirement + mov [esp+12], ebx ; save EBX in its final position + lea ebx, [esp+12] ; * and set the new EBX for addressing params + push eax ; save the handler thunk addr, free EAX for use + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; allocation size + ; ret addr + ; saved ECX + ; handler thunk addr <== ESP + ; + ; Now calculate the aligned stack pointer, which will be returned in + ; EBP. Depending on the padding required, it will point at the ret + ; addr in the above stack, or somewhere below that. + + lea eax, [esp+8] + neg ecx + and eax, ecx + lea esp, [eax-8] + + ; ESP now points at or below its position in the previous comment, + ; and ESP+8 has the required alignment. Everything below the saved + ; EBX is potentially overlapped by the aligned stack frame we're about + ; to create, so move those items to safety. + + mov eax, [ebx-16] ; the handler thunk address can be moved into + mov [esp], eax ; * its final position (might not move) + mov eax, [ebx-8] ; copy down the ret addr + push eax + mov eax, [ebx-4] ; get the allocation size for later + mov ecx, [ebx-12] ; restore the original ECX + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; (uninitialized) saved EBP (aligned stack location) + ; (uninitialized) EH state index + ; handler thunk addr + ; ret addr <== ESP + + mov [esp+12], ebp ; save old EBP and set new EBP frame pointer + lea ebp, [esp+12] ; * for addressing locals + mov dword ptr [esp+8], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr <== ESP + + push ecx ; save space for saved ESP field of EH node + push ebx ; save copy of EBX at EBP-20 for funclet use + sub esp, eax ; allocate the locals allocation space + push esi ; save callee-saved regs + push edi + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; (uninitialized) saved ESP field of EH node + ; saved value of EBX on exit + ; locals allocation area + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH cookie + push eax + mov [ebp-16], esp ; initialize the EH node's saved ESP field + mov eax, [ebx+4] ; copy callee's return addr above saved EBP + mov [ebp+4], eax ; * so EBP-based stackwalks work better + push [ebp-12] ; move the return address to final position + mov eax, fs:[0] ; set link to next node in EH chain + mov [ebp-12], eax + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; saved FS:[0] + ; saved ESP field of EH node + ; saved value of EBX on exit + ; locals allocation area + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_GS_align - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 12-byte EH node (function has unwinds, no catch blocks) +* + has a local /GS cookie +* + uses an EBX/EBP frame (no FPO) +* + needs dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This is the space required after EBX is pushed below the EH node. +* Alignment = alignment requirement. +* +* Incoming stack frame has: +* [ESP+12] callee's return address +* [ESP+8] alignment requirement +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_GS_align's return address +* +*Exit: +* EAX = destroyed +* EBX = ESP on entry + 4 (pointer to callee's parameters) +* EBP = aligned pointer to callee's locals +* ESP = EBP on exit - 28 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBX+4] (entry [ESP+12]) callee's return address +* [EBX+0] saved EBX +* padding to align stack (if needed) +* [EBP+4] callee's return address (copy of entry [ESP+12]) +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved value of EBX on exit +* padding to realign stack (if needed) +* [EBP-???] local GS cookie, XORed with value of EBP on exit +* ... +* [EBP-16-N] base of locals allocation +* [EBP-20-N] saved ESI +* [EBP-24-N] saved EDI +* [EBP-28-N] local EH cookie, XORed with value of EBP on exit +* +* The local GS cookie will be placed just below the first alignment point at +* or below EBP-16. That is, it is stored at [((EBP-16) & -Alignment)-4]. +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_GS_align( + unsigned long LocalAllocation, + unsigned long Alignment + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; alignment requirement + ; allocation size + ; ret addr <== ESP + + push ecx ; we need an extra reg, so save ECX + mov ecx, [esp+12] ; get the alignment requirement + mov [esp+12], ebx ; save EBX in its final position + lea ebx, [esp+12] ; * and set the new EBX for addressing params + push eax ; save the handler thunk addr, free EAX for use + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; allocation size + ; ret addr + ; saved ECX + ; handler thunk addr <== ESP + ; + ; Now calculate the aligned stack pointer, which will be returned in + ; EBP. Depending on the padding required, it will point at the ret + ; addr in the above stack, or somewhere below that. + + lea eax, [esp+8] + neg ecx + and eax, ecx + lea esp, [eax-8] + + ; ESP now points at or below its position in the previous comment, + ; and ESP+8 has the required alignment. Everything below the saved + ; EBX is potentially overlapped by the aligned stack frame we're about + ; to create, so move those items to safety. + + mov eax, [ebx-16] ; the handler thunk address can be moved into + mov [esp], eax ; * its final position (might not move) + mov eax, [ebx-8] ; copy down the ret addr + push eax + mov eax, [ebx-12] ; copy down the original ECX + push eax + mov eax, [ebx-4] ; get the allocation size for later + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; (uninitialized) saved EBP (aligned stack location) + ; (uninitialized) EH state index + ; handler thunk addr + ; ret addr + ; saved ECX <== ESP + + mov [esp+16], ebp ; save old EBP and set new EBP frame pointer + lea ebp, [esp+16] ; * for addressing locals + mov dword ptr [esp+12], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; saved ECX <== ESP + + and ecx, esp ; get address of realignment point + sub esp, eax ; allocate the locals allocation space + push esi ; save callee-saved regs + push edi + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; saved ECX + ; ... possible padding to realign stack ... <== ECX (aligned) + ; (uninitialized) local GS security cookie + ; locals allocation area + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH and GS cookies + push eax + mov [ecx-4], eax + mov ecx, [ebp-16] ; restore the original ECX + mov [ebp-16], ebx ; save copy of EBX for funclet use + mov eax, [ebx+4] ; copy callee's return addr above saved EBP + mov [ebp+4], eax ; * so EBP-based stackwalks work better + push [ebp-12] ; move the return address to final position + mov eax, fs:[0] ; set link to next node in EH chain + mov [ebp-12], eax + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; saved FS:[0] + ; saved value of EBX on exit + ; ... possible padding to realign stack ... + ; local GS security cookie + ; locals allocation area + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_prolog3_catch_GS_align - Set up C++ EH call frame variation +* +*Purpose: +* Sets up the call frame for a C++ EH function that: +* + uses a 16-byte EH node (function has catch blocks) +* + has a local /GS cookie +* + uses an EBX/EBP frame (no FPO) +* + needs dynamic stack alignment +* +*Entry: +* EAX = address of EH handler thunk. +* LocalAllocation = local stack allocation requirement (hereafter, 'N'). +* This is the space required after EBX is pushed below the EH node. +* Alignment = alignment requirement. +* +* Incoming stack frame has: +* [ESP+12] callee's return address +* [ESP+8] alignment requirement +* [ESP+4] local stack allocation requirement +* [ESP+0] _EH_prolog3_catch_GS_align's return address +* +*Exit: +* EAX = destroyed +* EBX = ESP on entry + 4 (pointer to callee's parameters) +* EBP = aligned pointer to callee's locals +* ESP = EBP on exit - 32 - N +* All other registers except CC preserved +* +* FS:[0] = set to EBP on exit - 12 to create new link in the EH chain +* +* Stack frame has been set up as follows: +* [EBX+4] (entry [ESP+12]) callee's return address +* [EBX+0] saved EBX +* padding to align stack (if needed) +* [EBP+4] callee's return address (copy of entry [ESP+12]) +* [EBP+0] saved EBP +* [EBP-4] EH record state index, initialized to -1 +* [EBP-8] address of EH handler thunk +* [EBP-12] saved FS:[0] +* [EBP-16] saved final ESP return value +* [EBP-20] saved value of EBX on exit +* padding to realign stack (if needed) +* [EBP-???] local GS cookie, XORed with value of EBP on exit +* ... +* [EBP-20-N] base of locals allocation +* [EBP-24-N] saved ESI +* [EBP-28-N] saved EDI +* [EBP-32-N] local EH cookie, XORed with value of EBP on exit +* +* The local GS cookie will be placed just below the first alignment point at +* or below EBP-16. That is, it is stored at [((EBP-16) & -Alignment)-4]. +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_prolog3_catch_GS_align( + unsigned long LocalAllocation, + unsigned long Alignment + ) +{ + __asm + { + ; stack has: + ; callee's return addr + ; alignment requirement + ; allocation size + ; ret addr <== ESP + + push ecx ; we need an extra reg, so save ECX + mov ecx, [esp+12] ; get the alignment requirement + mov [esp+12], ebx ; save EBX in its final position + lea ebx, [esp+12] ; * and set the new EBX for addressing params + push eax ; save the handler thunk addr, free EAX for use + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; allocation size + ; ret addr + ; saved ECX + ; handler thunk addr <== ESP + ; + ; Now calculate the aligned stack pointer, which will be returned in + ; EBP. Depending on the padding required, it will point at the ret + ; addr in the above stack, or somewhere below that. + + lea eax, [esp+8] + neg ecx + and eax, ecx + lea esp, [eax-8] + + ; ESP now points at or below its position in the previous comment, + ; and ESP+8 has the required alignment. Everything below the saved + ; EBX is potentially overlapped by the aligned stack frame we're about + ; to create, so move those items to safety. + + mov eax, [ebx-16] ; the handler thunk address can be moved into + mov [esp], eax ; * its final position (might not move) + mov eax, [ebx-8] ; copy down the ret addr + push eax + mov eax, [ebx-12] ; copy down the original ECX + push eax + mov eax, [ebx-4] ; get the allocation size for later + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; (uninitialized) saved EBP (aligned stack location) + ; (uninitialized) EH state index + ; handler thunk addr + ; ret addr + ; saved ECX <== ESP + + mov [esp+16], ebp ; save old EBP and set new EBP frame pointer + lea ebp, [esp+16] ; * for addressing locals + mov dword ptr [esp+12], -1 ; initialize the EH state index + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; saved ECX <== ESP + + push ebx ; save copy of EBX at EBP-16 for funclet use + and ecx, esp ; get address of realignment point + sub esp, eax ; allocate the locals allocation space + push esi ; save callee-saved regs + push edi + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; (uninitialized) callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; ret addr + ; saved ECX + ; saved value of EBX on exit + ; ... possible padding to realign stack ... <== ECX (aligned) + ; (uninitialized) local GS security cookie + ; locals allocation area + ; saved ESI + ; saved EDI <== ESP + + mov eax, __security_cookie + xor eax, ebp ; generate local EH and GS cookies + push eax + mov [ecx-4], eax + mov ecx, [ebp-16] ; restore the original ECX + mov [ebp-16], esp ; initialize the EH node's saved ESP field + mov eax, [ebx+4] ; copy callee's return addr above saved EBP + mov [ebp+4], eax ; * so EBP-based stackwalks work better + push [ebp-12] ; move the return address to final position + mov eax, fs:[0] ; set link to next node in EH chain + mov [ebp-12], eax + + ; stack has: + ; callee's return addr + ; saved EBX <== EBX + ; ... possible padding to align stack ... + ; callee's return addr + ; saved EBP <== EBP (aligned stack location) + ; initial EH state index of -1 + ; handler thunk addr + ; saved FS:[0] + ; saved ESP field of EH node + ; saved value of EBX on exit + ; ... possible padding to realign stack ... + ; local GS security cookie + ; locals allocation area + ; saved ESI + ; saved EDI + ; local EH security cookie + ; ret addr <== ESP + + lea eax, [ebp-12] ; all done - link in the EH node + mov fs:[0], eax + + ret + } +} + +/*** +*_EH_epilog3_align - Tear down C++ EH call frame variation +* +*Purpose: +* Destroy a call frame set up by _EH_prolog3_align or _EH_prolog3_catch_align. +* +*Entry: +* ESP = value it had on return from _EH_prolog3_align or +* _EH_prolog3_catch_align +* EBP = value it had on return from _EH_prolog3_align or +* _EH_prolog3_catch_align +* EBX = value it had on return from _EH_prolog3_align or +* _EH_prolog3_catch_align +* +*Exit: +* ESP = pointer to the callee's return address +* EBX, ESI, EDI, EBP restored from frame +* ECX destroyed +* All other registers except CC preserved +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_epilog3_align( + void + ) +{ + __asm + { + mov ecx, [ebp-12] ; remove EH node from EH chain + mov fs:[0], ecx + pop ecx ; save return address + pop edi ; pop and ignore the EH cookie + pop edi ; restore callee-saves + pop esi + mov esp, ebp ; free aligned stack + pop ebp ; restore local frame pointer + mov esp, ebx ; free unaligned stack + pop ebx ; restore parameter frame pointer + push ecx ; push return address + ret 0 + } +} + +/*** +*_EH_epilog3_GS_align - Tear down C++ EH call frame variation +* +*Purpose: +* Destroy a call frame set up by _EH_prolog3_GS_align or +* _EH_prolog3_catch_align, after first checking that the local /GS security +* cookie is correct. +* +* This helper version does not load the cookie itself because it doesn't +* know where it's located. It would need to be passed the alignment to know +* that, so it might as well be passed the cookie value directly. +* +*Entry: +* ESP = value it had on return from _EH_prolog3_GS +* EBP = value it had on return from _EH_prolog3_GS +* EBX = value it had on return from _EH_prolog3_GS +* ECX = GS cookie from callee's frame +* +*Exit: +* ESP = pointer to the callee's return address +* EBX, ESI, EDI, EBP restored from frame +* ECX destroyed +* All other registers except CC preserved +* +*******************************************************************************/ + +extern void __declspec(naked) +_EH_epilog3_GS_align( + void + ) +{ + __asm + { + xor ecx, ebp ; rematerialize the global cookie and + call __security_check_cookie ; * check its validity + jmp _EH_epilog3_align ; go tear down the frame + } +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolog.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolog.asm new file mode 100644 index 0000000000000000000000000000000000000000..fbda43be327046695ec9d498c3e858f81ee38742 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ehprolog.asm @@ -0,0 +1,36 @@ +;*** +;ehprolog.asm - defines __EH_prolog +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; EH prolog helper function. Sets up the frame for a C++ EH function +; with unwinds, by creating a link in the __except_list, and by setting +; up EBP as frame base pointer. +; +;******************************************************************************* + title ehprolog.asm + .386 + +.model FLAT + +ASSUME FS : NOTHING + +PUBLIC __EH_prolog + +.code + +__EH_prolog PROC NEAR + push -1 ; State index + push eax ; Push address of handler thunk + mov eax, DWORD PTR fs:[0] + push eax ; List link + mov eax, DWORD PTR [esp+12] ; Load return address + mov DWORD PTR fs:[0], esp + mov DWORD PTR [esp+12], ebp ; Save old ebp on the stack + lea ebp, DWORD PTR [esp+12] ; Set ebp to the base of the frame + push eax ; Push return addr on top of the stack + ret 0 ; JMP [eax] would be bad on P6 +__EH_prolog ENDP + +END diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/except.inc b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/except.inc new file mode 100644 index 0000000000000000000000000000000000000000..ae7adbf1942551f2d5aff5a300bd352a5b255085 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/except.inc @@ -0,0 +1,85 @@ +;*** +;except.inc - definitions for exception handling +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Structure and constant definitions used by exception handling code. +; +;******************************************************************************* + +; structure used by SEH support function and intrinsics. the information +; passed by the OS exception dispatcher is repackaged in this form by the +; runtime (_except_handler()). + +__EXCEPTION_INFO_PTRS struc + preport dd ? + pcontext dd ? +__EXCEPTION_INFO_PTRS ends + + +; exception registration record structure. + +__EXCEPTIONREGISTRATIONRECORD struc + prev_structure dd ? + ExceptionHandler dd ? + ExceptionFilter dd ? + FilterFrame dd ? + PExceptionInfoPtrs dd ? +__EXCEPTIONREGISTRATIONRECORD ends + +; size of exception registration record in double words + +DWORDS_IN_XREGREC equ 5 + + +; exception report record + +__EXCEPTIONREPORTRECORD struc + ExceptionNum dd ? + fHandlerFlags dd ? + ExceptionReportRecord dd ? + ExceptionAddress dd ? + cParameters dd ? + ExceptionInfo dd 4 dup (?) +__EXCEPTIONREPORTRECORD ends + + +; setjmp/longjmp buffer (i.e., structure underlying jmp_buf array) + +_JMP_BUF struc + ebpsave dd ? + ebxsave dd ? + edisave dd ? + esisave dd ? + espsave dd ? + retsave dd ? + xcptsave dd ? +_JMP_BUF ends + + +; exceptions corresponding to C runtime errors (these are explicitly +; referenced in the startup code) + +_XCPT_UNABLE_TO_GROW_STACK equ 080010001h +_XCPT_INTEGER_DIVIDE_BY_ZERO equ 0C000009Bh +_XCPT_NONCONTINUABLE_EXCEPTION equ 0C0000024h +_XCPT_INVALID_DISPOSITION equ 0C0000025h +_XCPT_SIGABRT equ 020000001h + + +; unwind settings in fHandlerFlags + +_EH_UNWINDING equ 2 +_EH_EXIT_UNWIND equ 4 +UNWIND equ _EH_UNWINDING OR _EH_EXIT_UNWIND + + +; return values (to the exception dispatcher) + +IFDEF _WIN32 + +_XCPT_CONTINUE_SEARCH equ 000000001h +_XCPT_CONTINUE_EXECUTION equ 000000000h + +ENDIF diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/exsup.inc b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/exsup.inc new file mode 100644 index 0000000000000000000000000000000000000000..02072314c5a8f4cc4e0c082f01aa6c99194a6940 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/exsup.inc @@ -0,0 +1,94 @@ +;*** +;exsup.inc +; +; Copyright (C) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Common data structures & definitions for exsup.asm and other +; Structured Exception Handling support modules. +; +;****************************************************************************** + + +;handler dispositions +DISPOSITION_DISMISS equ 0 +DISPOSITION_CONTINUE_SEARCH equ 1 +DISPOSITION_NESTED_EXCEPTION equ 2 +DISPOSITION_COLLIDED_UNWIND equ 3 + +;filter return codes +FILTER_ACCEPT equ 1 +FILTER_DISMISS equ -1 +FILTER_CONTINUE_SEARCH equ 0 + +;handler flags settings.. +EXCEPTION_UNWINDING equ 2 +EXCEPTION_EXIT_UNWIND equ 4 +EXCEPTION_UNWIND_CONTEXT equ EXCEPTION_UNWINDING OR EXCEPTION_EXIT_UNWIND +EXCEPTION_STACK_INVALID equ 8 + +TRYLEVEL_NONE equ -1 +TRYLEVEL_INVALID equ -2 + +;callback interface codes (minimal required set) +CB_GET_MAX_CODE equ 0 +CB_DO_LOCAL_UNWIND equ 1 +CB_GET_FRAME_EBP equ 2 +CB_GET_SCOPE_INDEX equ 3 +CB_GET_SCOPE_DATA equ 4 +MAX_CALLBACK_CODE equ 4 + +;typedef struct _EXCEPTION_REGISTRATION PEXCEPTION_REGISTRATION; +;struct _EXCEPTION_REGISTRATION{ +; struct _EXCEPTION_REGISTRATION *prev; +; void (*handler)(PEXCEPTION_RECORD, PEXCEPTION_REGISTRATION, PCONTEXT, PEXCEPTION_RECORD); +; struct scopetable_entry *scopetable; +; int trylevel; +; int _ebp; +; PEXCEPTION_POINTERS xpointers; +;}; +_EXCEPTION_REGISTRATION struc + prev dd ? + handler dd ? +_EXCEPTION_REGISTRATION ends + +;setjmp/longjmp buffer +_JMP_BUF struc + saved_ebp dd ? + saved_ebx dd ? + saved_edi dd ? + saved_esi dd ? + saved_esp dd ? + saved_return dd ? + saved_xregistration dd ? + saved_trylevel dd ? + ; following only found in C9.0 or later jmp_buf + version_cookie dd ? + unwind_func dd ? + unwind_data dd 6 dup(?) +_JMP_BUF ends + +; Cookie placed in the jmp_buf to identify the new, longer form +JMPBUF_COOKIE equ 'VC20' +JMPBUF_CHPE_COOKIE equ 'ephC' + +; Offset of TryLevel in a C8.0 SEH registration node +C8_TRYLEVEL equ 12 + +; NLG struct (debugging info) +; +; struct { +; unsigned long dwSig; +; unsigned long uoffDestination; +; unsigned long dwCode; +; unsigned long uoffFramePointer; +; } _NLG_Destination = {EH_MAGIC_NUMBER1,0,0,0}; + +MAGIC_NUMBER1 equ 019930520h + +_NLG_INFO struc + dwSig dd MAGIC_NUMBER1 + uoffDestination dd 0 + dwCode dd 0 + uoffFramePointer dd 0 +_NLG_INFO ends diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldiv.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldiv.asm new file mode 100644 index 0000000000000000000000000000000000000000..e915a4ed4c2d15154a5ddb63f97413e898bfda31 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldiv.asm @@ -0,0 +1,203 @@ + title lldiv - signed long divide routine +;*** +;lldiv.asm - signed long divide routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the signed long divide routine +; __alldiv +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;lldiv - signed long divide +; +;Purpose: +; Does a signed long divide of the arguments. Arguments are +; not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the quotient (dividend/divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_alldiv PROC NEAR +.FPO (3, 4, 0, 0, 0, 0) + + push edi + push esi + push ebx + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a/b will +; generate a call to lldiv(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; | EDI | +; |---------------| +; | ESI | +; |---------------| +; ESP---->| EBX | +; ----------------- +; + +DVND equ [esp + 16] ; stack address of dividend (a) +DVSR equ [esp + 24] ; stack address of divisor (b) + + +; Determine sign of the result (edi = 0 if result is positive, non-zero +; otherwise) and make operands positive. + + xor edi,edi ; result sign assumed positive + + mov eax,HIWORD(DVND) ; hi word of a + or eax,eax ; test to see if signed + jge short L1 ; skip rest if a is already positive + inc edi ; complement result sign flag + mov edx,LOWORD(DVND) ; lo word of a + neg eax ; make a positive + neg edx + sbb eax,0 + mov HIWORD(DVND),eax ; save positive value + mov LOWORD(DVND),edx +L1: + mov eax,HIWORD(DVSR) ; hi word of b + or eax,eax ; test to see if signed + jge short L2 ; skip rest if b is already positive + inc edi ; complement the result sign flag + mov edx,LOWORD(DVSR) ; lo word of a + neg eax ; make b positive + neg edx + sbb eax,0 + mov HIWORD(DVSR),eax ; save positive value + mov LOWORD(DVSR),edx +L2: + +; +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; +; NOTE - eax currently contains the high order word of DVSR +; + + or eax,eax ; check to see if divisor < 4194304K + jnz short L3 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; eax <- high order bits of quotient + mov ebx,eax ; save high bits of quotient + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; eax <- low order bits of quotient + mov edx,ebx ; edx:eax <- quotient + jmp short L4 ; set sign, restore stack and return + +; +; Here we do it the hard way. Remember, eax contains the high word of DVSR +; + +L3: + mov ebx,eax ; ebx:ecx <- divisor + mov ecx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L5: + shr ebx,1 ; shift divisor right one bit + rcr ecx,1 + shr edx,1 ; shift dividend right one bit + rcr eax,1 + or ebx,ebx + jnz short L5 ; loop until divisor < 4194304K + div ecx ; now divide, ignore remainder + mov esi,eax ; save quotient + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mul dword ptr HIWORD(DVSR) ; QUOT * HIWORD(DVSR) + mov ecx,eax + mov eax,LOWORD(DVSR) + mul esi ; QUOT * LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L6 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we are ok, otherwise +; subtract one (1) from the quotient. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L6 ; if result > original, do subtract + jb short L7 ; if result < original, we are ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L7 ; if less or equal we are ok, else subtract +L6: + dec esi ; subtract 1 from quotient +L7: + xor edx,edx ; edx:eax <- quotient + mov eax,esi + +; +; Just the cleanup left to do. edx:eax contains the quotient. Set the sign +; according to the save value, cleanup the stack, and return. +; + +L4: + dec edi ; check to see if result is negative + jnz short L8 ; if EDI == 0, result should be negative + neg edx ; otherwise, negate the result + neg eax + sbb edx,0 + +; +; Restore the saved registers and return. +; + +L8: + pop ebx + pop esi + pop edi + + ret 16 + +_alldiv ENDP + +end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldvrm.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldvrm.asm new file mode 100644 index 0000000000000000000000000000000000000000..471487e30150eb3dc2b79c58c902a02054fe680c --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lldvrm.asm @@ -0,0 +1,249 @@ + title lldvrm - signed long divide and remainder routine +;*** +;lldvrm.asm - signed long divide and remainder routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the signed long divide and remainder routine +; __alldvrm +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;lldvrm - signed long divide and remainder +; +;Purpose: +; Does a signed long divide and remainder of the arguments. Arguments are +; not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the quotient (dividend/divisor) +; EBX:ECX contains the remainder (divided % divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_alldvrm PROC NEAR +.FPO (3, 4, 0, 0, 1, 0) + + push edi + push esi + push ebp + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a/b will +; generate a call to alldvrm(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; | EDI | +; |---------------| +; | ESI | +; |---------------| +; ESP---->| EBP | +; ----------------- +; + +DVND equ [esp + 16] ; stack address of dividend (a) +DVSR equ [esp + 24] ; stack address of divisor (b) + + +; Determine sign of the quotient (edi = 0 if result is positive, non-zero +; otherwise) and make operands positive. +; Sign of the remainder is kept in ebp. + + xor edi,edi ; result sign assumed positive + xor ebp,ebp ; result sign assumed positive + + mov eax,HIWORD(DVND) ; hi word of a + or eax,eax ; test to see if signed + jge short L1 ; skip rest if a is already positive + inc edi ; complement result sign flag + inc ebp ; complement result sign flag + mov edx,LOWORD(DVND) ; lo word of a + neg eax ; make a positive + neg edx + sbb eax,0 + mov HIWORD(DVND),eax ; save positive value + mov LOWORD(DVND),edx +L1: + mov eax,HIWORD(DVSR) ; hi word of b + or eax,eax ; test to see if signed + jge short L2 ; skip rest if b is already positive + inc edi ; complement the result sign flag + mov edx,LOWORD(DVSR) ; lo word of a + neg eax ; make b positive + neg edx + sbb eax,0 + mov HIWORD(DVSR),eax ; save positive value + mov LOWORD(DVSR),edx +L2: + +; +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; +; NOTE - eax currently contains the high order word of DVSR +; + + or eax,eax ; check to see if divisor < 4194304K + jnz short L3 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; eax <- high order bits of quotient + mov ebx,eax ; save high bits of quotient + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; eax <- low order bits of quotient + mov esi,eax ; ebx:esi <- quotient +; +; Now we need to do a multiply so that we can compute the remainder. +; + mov eax,ebx ; set up high word of quotient + mul dword ptr LOWORD(DVSR) ; HIWORD(QUOT) * DVSR + mov ecx,eax ; save the result in ecx + mov eax,esi ; set up low word of quotient + mul dword ptr LOWORD(DVSR) ; LOWORD(QUOT) * DVSR + add edx,ecx ; EDX:EAX = QUOT * DVSR + jmp short L4 ; complete remainder calculation + +; +; Here we do it the hard way. Remember, eax contains the high word of DVSR +; + +L3: + mov ebx,eax ; ebx:ecx <- divisor + mov ecx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L5: + shr ebx,1 ; shift divisor right one bit + rcr ecx,1 + shr edx,1 ; shift dividend right one bit + rcr eax,1 + or ebx,ebx + jnz short L5 ; loop until divisor < 4194304K + div ecx ; now divide, ignore remainder + mov esi,eax ; save quotient + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mul dword ptr HIWORD(DVSR) ; QUOT * HIWORD(DVSR) + mov ecx,eax + mov eax,LOWORD(DVSR) + mul esi ; QUOT * LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L6 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we are ok, otherwise +; subtract one (1) from the quotient. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L6 ; if result > original, do subtract + jb short L7 ; if result < original, we are ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L7 ; if less or equal we are ok, else subtract +L6: + dec esi ; subtract 1 from quotient + sub eax,LOWORD(DVSR) ; subtract divisor from result + sbb edx,HIWORD(DVSR) +L7: + xor ebx,ebx ; ebx:esi <- quotient + +L4: +; +; Calculate remainder by subtracting the result from the original dividend. +; Since the result is already in a register, we will do the subtract in the +; opposite direction and negate the result if necessary. +; + + sub eax,LOWORD(DVND) ; subtract dividend from result + sbb edx,HIWORD(DVND) + +; +; Now check the result sign flag to see if the result is supposed to be positive +; or negative. It is currently negated (because we subtracted in the 'wrong' +; direction), so if the sign flag is set we are done, otherwise we must negate +; the result to make it positive again. +; + + dec ebp ; check result sign flag + jns short L9 ; result is ok, set up the quotient + neg edx ; otherwise, negate the result + neg eax + sbb edx,0 + +; +; Now we need to get the quotient into edx:eax and the remainder into ebx:ecx. +; +L9: + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi + +; +; Just the cleanup left to do. edx:eax contains the quotient. Set the sign +; according to the save value, cleanup the stack, and return. +; + + dec edi ; check to see if result is negative + jnz short L8 ; if EDI == 0, result should be negative + neg edx ; otherwise, negate the result + neg eax + sbb edx,0 + +; +; Restore the saved registers and return. +; + +L8: + pop ebp + pop esi + pop edi + + ret 16 + +_alldvrm ENDP + +end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llmul.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llmul.asm new file mode 100644 index 0000000000000000000000000000000000000000..edf1c05b007982722ffdde4038239f89d70528fa --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llmul.asm @@ -0,0 +1,100 @@ + title llmul - long multiply routine +;*** +;llmul.asm - long multiply routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Defines long multiply routine +; Both signed and unsigned routines are the same, since multiply's +; work out the same in 2's complement +; creates the following routine: +; __allmul +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;llmul - long multiply routine +; +;Purpose: +; Does a long multiply (same for signed/unsigned) +; Parameters are not changed. +; +;Entry: +; Parameters are passed on the stack: +; 1st pushed: multiplier (QWORD) +; 2nd pushed: multiplicand (QWORD) +; +;Exit: +; EDX:EAX - product of multiplier and multiplicand +; NOTE: parameters are removed from the stack +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_allmul PROC NEAR +.FPO (0, 4, 0, 0, 0, 0) + +A EQU [esp + 4] ; stack address of a +B EQU [esp + 12] ; stack address of b + +; +; AHI, BHI : upper 32 bits of A and B +; ALO, BLO : lower 32 bits of A and B +; +; ALO * BLO +; ALO * BHI +; + BLO * AHI +; --------------------- +; + + mov eax,HIWORD(A) + mov ecx,HIWORD(B) + or ecx,eax ;test for both hiwords zero. + mov ecx,LOWORD(B) + jnz short hard ;both are zero, just mult ALO and BLO + + mov eax,LOWORD(A) + mul ecx + + ret 16 ; callee restores the stack + +hard: + push ebx +.FPO (1, 4, 0, 0, 0, 0) + +; must redefine A and B since esp has been altered + +A2 EQU [esp + 8] ; stack address of a +B2 EQU [esp + 16] ; stack address of b + + mul ecx ;eax has AHI, ecx has BLO, so AHI * BLO + mov ebx,eax ;save result + + mov eax,LOWORD(A2) + mul dword ptr HIWORD(B2) ;ALO * BHI + add ebx,eax ;ebx = ((ALO * BHI) + (AHI * BLO)) + + mov eax,LOWORD(A2) ;ecx = BLO + mul ecx ;so edx:eax = ALO*BLO + add edx,ebx ;now edx has all the LO*HI stuff + + pop ebx + + ret 16 ; callee restores the stack + +_allmul ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llrem.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llrem.asm new file mode 100644 index 0000000000000000000000000000000000000000..d421a1019bcdad17f9e6f75db270d5b8ed77ad78 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llrem.asm @@ -0,0 +1,210 @@ + title llrem - signed long remainder routine +;*** +;llrem.asm - signed long remainder routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the signed long remainder routine +; __allrem +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;llrem - signed long remainder +; +;Purpose: +; Does a signed long remainder of the arguments. Arguments are +; not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the remainder (dividend%divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_allrem PROC NEAR +.FPO (2, 4, 0, 0, 0, 0) + + push ebx + push edi + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a%b will +; generate a call to lrem(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; | EBX | +; |---------------| +; ESP---->| EDI | +; ----------------- +; + +DVND equ [esp + 12] ; stack address of dividend (a) +DVSR equ [esp + 20] ; stack address of divisor (b) + + +; Determine sign of the result (edi = 0 if result is positive, non-zero +; otherwise) and make operands positive. + + xor edi,edi ; result sign assumed positive + + mov eax,HIWORD(DVND) ; hi word of a + or eax,eax ; test to see if signed + jge short L1 ; skip rest if a is already positive + inc edi ; complement result sign flag bit + mov edx,LOWORD(DVND) ; lo word of a + neg eax ; make a positive + neg edx + sbb eax,0 + mov HIWORD(DVND),eax ; save positive value + mov LOWORD(DVND),edx +L1: + mov eax,HIWORD(DVSR) ; hi word of b + or eax,eax ; test to see if signed + jge short L2 ; skip rest if b is already positive + mov edx,LOWORD(DVSR) ; lo word of b + neg eax ; make b positive + neg edx + sbb eax,0 + mov HIWORD(DVSR),eax ; save positive value + mov LOWORD(DVSR),edx +L2: + +; +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; +; NOTE - eax currently contains the high order word of DVSR +; + + or eax,eax ; check to see if divisor < 4194304K + jnz short L3 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; edx <- remainder + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; edx <- final remainder + mov eax,edx ; edx:eax <- remainder + xor edx,edx + dec edi ; check result sign flag + jns short L4 ; negate result, restore stack and return + jmp short L8 ; result sign ok, restore stack and return + +; +; Here we do it the hard way. Remember, eax contains the high word of DVSR +; + +L3: + mov ebx,eax ; ebx:ecx <- divisor + mov ecx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L5: + shr ebx,1 ; shift divisor right one bit + rcr ecx,1 + shr edx,1 ; shift dividend right one bit + rcr eax,1 + or ebx,ebx + jnz short L5 ; loop until divisor < 4194304K + div ecx ; now divide, ignore remainder + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mov ecx,eax ; save a copy of quotient in ECX + mul dword ptr HIWORD(DVSR) + xchg ecx,eax ; save product, get quotient in EAX + mul dword ptr LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L6 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we are ok, otherwise +; subtract the original divisor from the result. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L6 ; if result > original, do subtract + jb short L7 ; if result < original, we are ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L7 ; if less or equal we are ok, else subtract +L6: + sub eax,LOWORD(DVSR) ; subtract divisor from result + sbb edx,HIWORD(DVSR) +L7: + +; +; Calculate remainder by subtracting the result from the original dividend. +; Since the result is already in a register, we will do the subtract in the +; opposite direction and negate the result if necessary. +; + + sub eax,LOWORD(DVND) ; subtract dividend from result + sbb edx,HIWORD(DVND) + +; +; Now check the result sign flag to see if the result is supposed to be positive +; or negative. It is currently negated (because we subtracted in the 'wrong' +; direction), so if the sign flag is set we are done, otherwise we must negate +; the result to make it positive again. +; + + dec edi ; check result sign flag + jns short L8 ; result is ok, restore stack and return +L4: + neg edx ; otherwise, negate the result + neg eax + sbb edx,0 + +; +; Just the cleanup left to do. edx:eax contains the quotient. +; Restore the saved registers and return. +; + +L8: + pop edi + pop ebx + + ret 16 + +_allrem ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshl.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshl.asm new file mode 100644 index 0000000000000000000000000000000000000000..2d25bef61ed405b88fe6f36ba82b5ebd9567b5ea --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshl.asm @@ -0,0 +1,80 @@ + title llshl - long shift left +;*** +;llshl.asm - long shift left +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; define long shift left routine (signed and unsigned are same) +; __allshl +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;llshl - long shift left +; +;Purpose: +; Does a Long Shift Left (signed and unsigned are identical) +; Shifts a long left any number of bits. +; +;Entry: +; EDX:EAX - long value to be shifted +; CL - number of bits to shift by +; +;Exit: +; EDX:EAX - shifted value +; +;Uses: +; CL is destroyed. +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_allshl PROC NEAR +.FPO (0, 0, 0, 0, 0 ,0) + +; +; Handle shifts of 64 or more bits (all get 0) +; + cmp cl, 64 + jae short RETZERO + +; +; Handle shifts of between 0 and 31 bits +; + cmp cl, 32 + jae short MORE32 + shld edx,eax,cl + shl eax,cl + ret + +; +; Handle shifts of between 32 and 63 bits +; +MORE32: + mov edx,eax + xor eax,eax + and cl,31 + shl edx,cl + ret + +; +; return 0 in edx:eax +; +RETZERO: + xor eax,eax + xor edx,edx + ret + +_allshl ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshr.asm new file mode 100644 index 0000000000000000000000000000000000000000..22f813f8f9d590b983492a388d4affeddbcb56c7 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/llshr.asm @@ -0,0 +1,81 @@ + title llshr - long shift right +;*** +;llshr.asm - long shift right +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; define signed long shift right routine +; __allshr +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;llshr - long shift right +; +;Purpose: +; Does a signed Long Shift Right +; Shifts a long right any number of bits. +; +;Entry: +; EDX:EAX - long value to be shifted +; CL - number of bits to shift by +; +;Exit: +; EDX:EAX - shifted value +; +;Uses: +; CL is destroyed. +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_allshr PROC NEAR +.FPO (0, 0, 0, 0, 0, 0) + +; +; Handle shifts of 64 bits or more (if shifting 64 bits or more, the result +; depends only on the high order bit of edx). +; + cmp cl,64 + jae short RETSIGN + +; +; Handle shifts of between 0 and 31 bits +; + cmp cl, 32 + jae short MORE32 + shrd eax,edx,cl + sar edx,cl + ret + +; +; Handle shifts of between 32 and 63 bits +; +MORE32: + mov eax,edx + sar edx,31 + and cl,31 + sar eax,cl + ret + +; +; Return double precision 0 or -1, depending on the sign of edx +; +RETSIGN: + sar edx,31 + mov eax,edx + ret + +_allshr ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lowhelpr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lowhelpr.asm new file mode 100644 index 0000000000000000000000000000000000000000..91d7da397704bcc0f5be92f3e3629fb58d37de80 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/lowhelpr.asm @@ -0,0 +1,94 @@ +;*** +;lowhelpr.asm +; +; Copyright (C) Microsoft Corporation. All rights reserved. +; +;Purpose: +; Contains _CallSettingFrame(), which must be in asm for NLG purposes. +; +;Notes: +; +;******************************************************************************* + title lowhelpr.asm + +.xlist + include vcruntime.inc + include exsup.inc +.list + +EXTERN _NLG_Notify:NEAR +EXTERN _NLG_Notify1:NEAR +PUBLIC _CallSettingFrame +PUBLIC _NLG_Return +extern _NLG_Destination:_NLG_INFO + + +CODESEG + +;//////////////////////////////////////////////////////////////////////////// +;/ +;/ _CallSettingFrame - sets up EBP and calls the specified funclet. Restores +;/ EBP on return. +;/ +;/ Return value is return value of funclet (whatever is in EAX). +;/ + + + public _CallSettingFrame + +_CallSettingFrame proc stdcall, funclet:IWORD, pRN:IWORD, dwInCode:DWORD + ; FPO = 0 dwords locals allocated in prolog + ; 3 dword parameters + ; 8 bytes in prolog + ; 4 registers saved (includes locals to work around debugger bug) + ; 1 EBP is used + ; 0 frame type = FPO + .FPO (0,3,8,4,1,0) + + sub esp,4 + push ebx + push ecx + mov eax,pRN + add eax,0Ch ; sizeof(EHRegistrationNode) -- assumed to equal 0Ch + mov dword ptr [ebp-4],eax + mov eax,funclet + push ebp ; Save our frame pointer + push dwInCode + mov ecx,dwInCode + mov ebp,dword ptr [ebp-4] ; Load target frame pointer + call _NLG_Notify1 ; Notify debugger + push esi + push edi + call eax ; Call the funclet +_NLG_Return:: + pop edi + pop esi + mov ebx,ebp + pop ebp + mov ecx,dwInCode + push ebp + mov ebp,ebx + cmp ecx, 0100h + jne _NLG_Continue + mov ecx, 02h +_NLG_Continue: + push ecx + call _NLG_Notify1 ; Notify debugger yet again + pop ebp ; Restore our frame pointer + pop ecx + pop ebx + ret 0Ch +_CallSettingFrame ENDP + + +; +; SafeSEH stubs, declared here, in assembler language, so that they may be +; added to the SafeSEH handler list (which cannot be done from native C). +; +EXTERN _CatchGuardHandler:PROC +EXTERN _TranslatorGuardHandler:PROC + +.SafeSEH _CatchGuardHandler +.SafeSEH _TranslatorGuardHandler + + END diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memchr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memchr.asm new file mode 100644 index 0000000000000000000000000000000000000000..5f6625ea484889e5d57b2e85a69295fce07b0d1a --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memchr.asm @@ -0,0 +1,180 @@ + page ,132 + title memchr - search memory for a given character +;*** +;memchr.asm - search block of memory for a given character +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines memchr() - search memory until a character is +; found or a limit is reached. +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + +page +;*** +;char *memchr(buf, chr, cnt) - search memory for given character. +; +;Purpose: +; Searched at buf for the given character, stopping when chr is +; first found or cnt bytes have been searched through. +; +; Algorithm: +; char * +; memchr (buf, chr, cnt) +; char *buf; +; int chr; +; unsigned cnt; +; { +; while (cnt && *buf++ != c) +; cnt--; +; return(cnt ? --buf : NULL); +; } +; +;Entry: +; char *buf - memory buffer to be searched +; char chr - character to search for +; unsigned cnt - max number of bytes to search +; +;Exit: +; returns pointer to first occurrence of chr in buf +; returns NULL if chr not found in the first cnt bytes +; +;Uses: +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + + public memchr +memchr proc \ + buf:ptr byte, \ + chr:byte, \ + cnt:dword + + OPTION PROLOGUE:NONE, EPILOGUE:NONE + + .FPO ( 0, 1, 0, 0, 0, 0 ) + + mov eax,[esp+0ch] ; eax = count + push ebx ; Preserve ebx + + test eax,eax ; check if count=0 + jz short retnull ; if count=0, leave + + mov edx,[esp+8] ; edx = buffer + xor ebx,ebx + + mov bl,[esp+0ch] ; bl = search char + + test edx,3 ; test if string is aligned on 32 bits + jz short main_loop_start + +str_misaligned: ; simple byte loop until string is aligned + mov cl,byte ptr [edx] + add edx,1 + xor cl,bl + je short found + sub eax,1 ; counter-- + jz short retnull + test edx,3 ; already aligned ? + jne short str_misaligned + +main_loop_start: + sub eax,4 + jb short tail_less_then_4 + +; set all 4 bytes of ebx to [value] + push edi ; Preserve edi + mov edi,ebx ; edi=0/0/0/char + shl ebx,8 ; ebx=0/0/char/0 + add ebx,edi ; ebx=0/0/char/char + mov edi,ebx ; edi=0/0/char/char + shl ebx,10h ; ebx=char/char/0/0 + add ebx,edi ; ebx = all 4 bytes = [search char] + jmp short main_loop_entry ; ecx >=0 + +return_from_main: + pop edi + +tail_less_then_4: + add eax,4 + jz retnull + +tail_loop: ; 0 < eax < 4 + mov cl,byte ptr [edx] + add edx,1 + xor cl,bl + je short found + sub eax,1 + jnz short tail_loop +retnull: + pop ebx + ret ; _cdecl return + +main_loop: + sub eax,4 + jb short return_from_main +main_loop_entry: + mov ecx,dword ptr [edx] ; read 4 bytes + + xor ecx,ebx ; ebx is byte\byte\byte\byte + mov edi,7efefeffh + + add edi,ecx + xor ecx,-1 + + xor ecx,edi + add edx,4 + + and ecx,81010100h + je short main_loop + +; found zero byte in the loop? +char_is_found: + mov ecx,[edx - 4] + xor cl,bl ; is it byte 0 + je short byte_0 + xor ch,bl ; is it byte 1 + je short byte_1 + shr ecx,10h ; is it byte 2 + xor cl,bl + je short byte_2 + xor ch,bl ; is it byte 3 + je short byte_3 + jmp short main_loop ; taken if bits 24-30 are clear and bit + ; 31 is set + +byte_3: + pop edi ; restore edi +found: + lea eax,[edx - 1] + pop ebx ; restore ebx + ret ; _cdecl return + +byte_2: + lea eax,[edx - 2] + pop edi + pop ebx + ret ; _cdecl return + +byte_1: + lea eax,[edx - 3] + pop edi + pop ebx + ret ; _cdecl return + +byte_0: + lea eax,[edx - 4] + pop edi ; restore edi + pop ebx ; restore ebx + ret ; _cdecl return + +memchr endp + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memcpy.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memcpy.asm new file mode 100644 index 0000000000000000000000000000000000000000..0be54ed471984879075ca5123a6fb5683ddabd1c --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memcpy.asm @@ -0,0 +1,726 @@ + page ,132 + title memcpy - Copy source memory bytes to destination +;*** +;memcpy.asm - contains memcpy and memmove routines +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; memcpy() copies a source memory buffer to a destination buffer. +; Overlapping buffers are not treated specially, so propagation may occur. +; memmove() copies a source memory buffer to a destination buffer. +; Overlapping buffers are treated specially, to avoid propagation. +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + .xmm + +M_EXIT macro + ret ; _cdecl return + endm ; M_EXIT + +PALIGN_memcpy macro d +MovPalign&d&: + movdqa xmm1,xmmword ptr [esi-d] + lea esi, byte ptr [esi-d] + + align @WordSize + +PalignLoop&d&: + movdqa xmm3,xmmword ptr [esi+10h] + sub ecx,30h + movdqa xmm0,xmmword ptr [esi+20h] + movdqa xmm5,xmmword ptr [esi+30h] + lea esi, xmmword ptr [esi+30h] + cmp ecx,30h + movdqa xmm2,xmm3 + + palignr xmm3,xmm1,d + + movdqa xmmword ptr [edi],xmm3 + movdqa xmm4,xmm0 + + palignr xmm0,xmm2,d + + movdqa xmmword ptr [edi+10h],xmm0 + movdqa xmm1,xmm5 + + palignr xmm5,xmm4,d + + movdqa xmmword ptr [edi+20h],xmm5 + lea edi, xmmword ptr [edi+30h] + jae PalignLoop&d& + lea esi, xmmword ptr [esi+d] + + endm ; PALIGN_memcpy + + CODESEG + + extrn __isa_available:dword + extrn __isa_enabled:dword + extrn __favor:dword + +page +;*** +;memcpy - Copy source buffer to destination buffer +; +;Purpose: +; memcpy() copies a source memory buffer to a destination memory buffer. +; This routine does NOT recognize overlapping buffers, and thus can lead +; to propagation. +; For cases where propagation must be avoided, memmove() must be used. +; +; Algorithm: +; +; Same as memmove. See Below +; +; +;memmove - Copy source buffer to destination buffer +; +;Purpose: +; memmove() copies a source memory buffer to a destination memory buffer. +; This routine recognize overlapping buffers to avoid propagation. +; For cases where propagation is not a problem, memcpy() can be used. +; +; Algorithm: +; +; void * memmove(void * dst, void * src, size_t count) +; { +; void * ret = dst; +; +; if (dst <= src || dst >= (src + count)) { +; /* +; * Non-Overlapping Buffers +; * copy from lower addresses to higher addresses +; */ +; while (count--) +; *dst++ = *src++; +; } +; else { +; /* +; * Overlapping Buffers +; * copy from higher addresses to lower addresses +; */ +; dst += count - 1; +; src += count - 1; +; +; while (count--) +; *dst-- = *src--; +; } +; +; return(ret); +; } +; +; +;Entry: +; void *dst = pointer to destination buffer +; const void *src = pointer to source buffer +; size_t count = number of bytes to copy +; +;Exit: +; Returns a pointer to the destination buffer in AX/DX:AX +; +;Uses: +; CX, DX +; +;Exceptions: +;******************************************************************************* + +ifdef MEM_MOVE + _MEM_ equ +else ; MEM_MOVE + _MEM_ equ +endif ; MEM_MOVE + +% public _MEM_ +_MEM_ proc \ + dst:ptr byte, \ + src:ptr byte, \ + count:IWORD + + ; destination pointer + ; source pointer + ; number of bytes to copy + + OPTION PROLOGUE:NONE, EPILOGUE:NONE + + push edi ; save edi + push esi ; save esi + +; size param/4 prolog byte #reg saved + .FPO ( 0, 3 , $-_MEM_ , 2, 0, 0 ) + + mov esi,[esp + 010h] ; esi = source + mov ecx,[esp + 014h] ; ecx = number of bytes to move + mov edi,[esp + 0Ch] ; edi = dest + +; +; Check for overlapping buffers: +; If (dst <= src) Or (dst >= src + Count) Then +; Do normal (Upwards) Copy +; Else +; Do Downwards Copy to avoid propagation +; + + mov eax,ecx ; eax = byte count + + mov edx,ecx ; edx = byte count + add eax,esi ; eax = point past source end + + cmp edi,esi ; dst <= src ? + jbe short CopyUp ; no overlap: copy toward higher addresses + + cmp edi,eax ; dst < (src + count) ? + jb CopyDown ; overlap: copy toward lower addresses + +; +; Buffers do not overlap, copy toward higher addresses. +; +CopyUp: + cmp ecx, 020h + jb CopyUpDwordMov ; size smaller than 32 bytes, use dwords + cmp ecx, 080h + jae CopyUpLargeMov ; if greater than or equal to 128 bytes, use Enhanced fast Strings + bt __isa_enabled, __ISA_AVAILABLE_SSE2 + jc XmmCopySmallTest + jmp Dword_align + +CopyUpLargeMov: + bt __favor, __FAVOR_ENFSTRG ; check if Enhanced Fast Strings is supported + jnc CopyUpSSE2Check ; if not, check for SSE2 support + rep movsb + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi + pop edi + M_EXIT + +; +; Check if source and destination are equally aligned. +; +CopyUpSSE2Check: + mov eax,edi + xor eax,esi + test eax,15 + jne AtomChk ; Not aligned go check Atom + bt __isa_enabled, __ISA_AVAILABLE_SSE2 + jc XmmCopy ; yes, go SSE2 copy (params already set) +AtomChk: + ; Is Atom supported? + bt __favor, __FAVOR_ATOM + jnc Dword_align ; no,jump + + ; check if dst is 4 byte aligned + test edi, 3 + jne Dword_align + + ; check if src is 4 byte aligned + test esi, 3 + jne Dword_align_Ok + +; A software pipelining vectorized memcpy loop using PALIGN instructions + +; (1) copy the first bytes to align dst up to the nearest 16-byte boundary +; 4 byte align -> 12 byte copy, 8 byte align -> 8 byte copy, 12 byte align -> 4 byte copy +PalignHead4: + bt edi, 2 + jae PalignHead8 + mov eax, dword ptr [esi] + sub ecx, 4 + lea esi, byte ptr [esi+4] + mov dword ptr [edi], eax + lea edi, byte ptr [edi+4] + +PalignHead8: + bt edi, 3 + jae PalignLoop + movq xmm1, qword ptr [esi] + sub ecx, 8 + lea esi, byte ptr [esi+8] + movq qword ptr [edi], xmm1 + lea edi, byte ptr [edi+8] + +;(2) Use SSE palign loop +PalignLoop: + test esi, 7 + je MovPalign8 + bt esi, 3 + jae MovPalign4 + +PALIGN_memcpy 12 + jmp PalignTail + +PALIGN_memcpy 8 + jmp PalignTail + +PALIGN_memcpy 4 + +;(3) Copy the tailing bytes. +PalignTail: + cmp ecx,10h + jb PalignTail4 + movdqu xmm1,xmmword ptr [esi] + sub ecx, 10h + lea esi, xmmword ptr [esi+10h] + movdqa xmmword ptr [edi],xmm1 + lea edi, xmmword ptr [edi+10h] + jmp PalignTail + +PalignTail4: + bt ecx, 2 + jae PalignTail8 + mov eax, dword ptr [esi] + sub ecx,4 + lea esi, byte ptr [esi+4] + mov dword ptr [edi], eax + lea edi, byte ptr [edi+4] + +PalignTail8: + bt ecx, 3 + jae PalignTailLE3 + movq xmm1, qword ptr [esi] + sub ecx,8 + lea esi, byte ptr [esi+8] + movq qword ptr [edi], xmm1 + lea edi, byte ptr [edi+8] + +PalignTailLE3: + mov eax, dword ptr TrailingUpVec[ecx*4] + jmp eax + +; The algorithm for forward moves is to align the destination to a dword +; boundary and so we can move dwords with an aligned destination. This +; occurs in 3 steps. +; +; - move x = ((4 - Dest & 3) & 3) bytes +; - move y = ((L-x) >> 2) dwords +; - move (L - x - y*4) bytes +; + +Dword_align: + test edi,11b ; check if destination is dword aligned + jz short Dword_align_Ok ; if destination not dword aligned already, it should be aligned + +Dword_up_align_loop: + mov al, byte ptr [esi] + mov byte ptr [edi], al + dec ecx + add esi, 1 + add edi, 1 + test edi, 11b + jnz Dword_up_align_loop +Dword_align_Ok: + mov edx, ecx + cmp ecx, 32 + jb CopyUpDwordMov + shr ecx,2 + rep movsd ; move all of our dwords + and edx,11b ; trailing byte count + jmp dword ptr TrailingUpVec[edx*4] ; process trailing bytes + +; +; Code to do optimal memory copies for non-dword-aligned destinations. +; + +; The following length check is done for two reasons: +; +; 1. to ensure that the actual move length is greater than any possible +; alignment move, and +; +; 2. to skip the multiple move logic for small moves where it would +; be faster to move the bytes with one instruction. +; + + + align @WordSize +ByteCopyUp: + jmp dword ptr TrailingUpVec[ecx*4+16] ; process just bytes + + +;----------------------------------------------------------------------------- + + align @WordSize +TrailingUpVec dd TrailingUp0, TrailingUp1, TrailingUp2, TrailingUp3 + + align @WordSize +TrailingUp0: + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + ; spare + M_EXIT + + align @WordSize +TrailingUp1: + mov al,[esi] ; get byte from source + ; spare + mov [edi],al ; put byte in destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + align @WordSize +TrailingUp2: + mov al,[esi] ; get first byte from source + ; spare + mov [edi],al ; put first byte into destination + mov al,[esi+1] ; get second byte from source + mov [edi+1],al ; put second byte into destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + align @WordSize +TrailingUp3: + mov al,[esi] ; get first byte from source + ; spare + mov [edi],al ; put first byte into destination + mov al,[esi+1] ; get second byte from source + mov [edi+1],al ; put second byte into destination + mov al,[esi+2] ; get third byte from source + mov [edi+2],al ; put third byte into destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + +;----------------------------------------------------------------------------- +;----------------------------------------------------------------------------- +;----------------------------------------------------------------------------- + +; Copy down to avoid propagation in overlapping buffers. + align @WordSize +CopyDown: +; inserting check for size. For < 16 bytes, use dwords without checking for alignment + + lea esi, [esi+ecx] ; esi, edi pointing to the end of the buffer + lea edi, [edi+ecx] + cmp ecx, 32 + jb CopyDownSmall + bt __isa_enabled, __ISA_AVAILABLE_SSE2 + jc XmmMovLargeAlignTest +; See if the destination start is dword aligned + + test edi,11b ; Test if dword aligned + jz CopyDownAligned ; If not, jump + +CopyDownNotAligned: + mov edx,edi ; get destination offset + and edx, 11b + sub ecx, edx +CopyDownAlignLoop: + mov al, byte ptr [esi-1] + mov byte ptr[edi-1], al + dec esi + dec edi + sub edx, 1 + jnz CopyDownAlignLoop + +CopyDownAligned: + cmp ecx,32 ; test if small enough for unwind copy + jb CopyDownSmall ; if so, then jump + mov edx, ecx + shr ecx,2 ; shift down to dword count + and edx,11b ; trailing byte count + sub esi, 4 + sub edi, 4 ; setting up src, dest registers + std ; set direction flag + rep movsd ; move all of dwords at once + cld ; clear direction flag back + + jmp dword ptr TrailingDownVec[edx*4]; process trailing bytes + + +;----------------------------------------------------------------------------- + + align @WordSize +TrailingDownVec dd TrailingDown0, TrailingDown1, TrailingDown2, TrailingDown3 + + align @WordSize +TrailingDown0: + mov eax,[esp + 0Ch] ; return original destination pointer + ; spare + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + align @WordSize +TrailingDown1: + mov al,[esi+3] ; get byte from source + ; spare + mov [edi+3],al ; put byte in destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + align @WordSize +TrailingDown2: + mov al,[esi+3] ; get first byte from source + ; spare + mov [edi+3],al ; put first byte into destination + mov al,[esi+2] ; get second byte from source + mov [edi+2],al ; put second byte into destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + align @WordSize +TrailingDown3: + mov al,[esi+3] ; get first byte from source + ; spare + mov [edi+3],al ; put first byte into destination + mov al,[esi+2] ; get second byte from source + mov [edi+2],al ; put second byte into destination + mov al,[esi+1] ; get third byte from source + mov [edi+1],al ; put third byte into destination + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + +; Copy overlapping buffers using XMM registers +XmmMovLargeAlignTest: + test edi, 0Fh ; check if it's 16-byte aligned + jz XmmMovLargeLoop +XmmMovAlignLoop: + dec ecx + dec esi + dec edi + mov al, [esi] + mov [edi], al + test edi, 0Fh + jnz XmmMovAlignLoop + +XmmMovLargeLoop: + cmp ecx, 128 + jb XmmMovSmallTest + sub esi, 128 + sub edi, 128 + movdqu xmm0, xmmword ptr[esi] + movdqu xmm1, xmmword ptr[esi+16] + movdqu xmm2, xmmword ptr[esi+32] + movdqu xmm3, xmmword ptr[esi+48] + movdqu xmm4, xmmword ptr[esi+64] + movdqu xmm5, xmmword ptr[esi+80] + movdqu xmm6, xmmword ptr[esi+96] + movdqu xmm7, xmmword ptr[esi+112] + movdqu xmmword ptr[edi], xmm0 + movdqu xmmword ptr[edi+16], xmm1 + movdqu xmmword ptr[edi+32], xmm2 + movdqu xmmword ptr[edi+48], xmm3 + movdqu xmmword ptr[edi+64], xmm4 + movdqu xmmword ptr[edi+80], xmm5 + movdqu xmmword ptr[edi+96], xmm6 + movdqu xmmword ptr[edi+112], xmm7 + sub ecx, 128 + test ecx, 0FFFFFF80h + jnz XmmMovLargeLoop + + +XmmMovSmallTest: + cmp ecx, 32 ; if lesser than 32, use dwords + jb CopyDownSmall + +XmmMovSmallLoop: + sub esi, 32 + sub edi, 32 + movdqu xmm0, xmmword ptr[esi] + movdqu xmm1, xmmword ptr[esi+16] + movdqu xmmword ptr[edi], xmm0 + movdqu xmmword ptr[edi+16], xmm1 + sub ecx, 32 + test ecx, 0FFFFFFE0h + jnz XmmMovSmallLoop + +CopyDownSmall: + test ecx, 0FFFFFFFCh ; mask the bytes + jz CopyDownByteTest +CopyDownDwordLoop: + sub edi, 4 + sub esi, 4 + mov eax, [esi] + mov [edi], eax + sub ecx, 4 + test ecx, 0FFFFFFFCh + jnz CopyDownDwordLoop +CopyDownByteTest: + test ecx, ecx + jz CopyDownReturn +CopyDownByteLoop: + sub edi, 1 + sub esi, 1 + mov al, [esi] + mov [edi], al + sub ecx, 1 + jnz CopyDownByteLoop +CopyDownReturn: + mov eax,[esp + 0Ch] ; return original destination pointer + ; spare + pop esi ; restore esi + pop edi ; restore edi + M_EXIT + + +; Using XMM registers for non-overlapping buffers + +align 16 +XmmCopy: + mov eax, esi + and eax, 0Fh + ; eax = src and dst alignment (src mod 16) + test eax, eax + jne XmmCopyUnaligned + + ; in: + ; edi = dst (16 byte aligned) + ; esi = src (16 byte aligned) + ; ecx = len is >= (128 - head alignment bytes) + ; do block copy using SSE2 stores +XmmCopyAligned: + mov edx, ecx + and ecx, 7Fh + shr edx, 7 + je XmmCopySmallTest + ; ecx = loop count + ; edx = remaining copy length + +; Copy greater than or equal to 128 bytes using XMM registers +align 16 +XmmCopyLargeLoop: + movdqa xmm0,xmmword ptr [esi] + movdqa xmm1,xmmword ptr [esi + 10h] + movdqa xmm2,xmmword ptr [esi + 20h] + movdqa xmm3,xmmword ptr [esi + 30h] + movdqa xmmword ptr [edi],xmm0 + movdqa xmmword ptr [edi + 10h],xmm1 + movdqa xmmword ptr [edi + 20h],xmm2 + movdqa xmmword ptr [edi + 30h],xmm3 + movdqa xmm4,xmmword ptr [esi + 40h] + movdqa xmm5,xmmword ptr [esi + 50h] + movdqa xmm6,xmmword ptr [esi + 60h] + movdqa xmm7,xmmword ptr [esi + 70h] + movdqa xmmword ptr [edi + 40h],xmm4 + movdqa xmmword ptr [edi + 50h],xmm5 + movdqa xmmword ptr [edi + 60h],xmm6 + movdqa xmmword ptr [edi + 70h],xmm7 + lea esi,[esi + 80h] + lea edi,[edi + 80h] + dec edx + jne XmmCopyLargeLoop + +; Copy lesser than 128 bytes +XmmCopySmallTest: + test ecx, ecx + je CopyUpReturn + + ; ecx = length (< 128 bytes) + mov edx, ecx + shr edx, 5 ; check if there are 32 bytes that can be set + test edx, edx + je CopyUpDwordMov + ; if > 16 bytes do a loop (16 bytes at a time) + ; edx - loop count + ; edi = dst + ; esi = src + +align 16 +XmmCopySmallLoop: + movdqu xmm0, xmmword ptr [esi] + movdqu xmm1, xmmword ptr [esi + 10h] + movdqu xmmword ptr [edi], xmm0 + movdqu xmmword ptr [edi + 10h], xmm1 + lea esi, [esi + 20h] + lea edi, [edi + 20h] + dec edx + jne XmmCopySmallLoop + +CopyUpDwordMov: + + ; last 1-32 bytes: step back according to dst and src alignment and do a 16-byte copy + ; esi = src + ; eax = src alignment (set at the start of the procedure and preserved up to here) + ; edi = dst + ; ecx = remaining len + and ecx, 1Fh + je CopyUpReturn +CopyUpDwordTest: + mov eax, ecx ; save remaining len and calc number of dwords + shr ecx, 2 + je CopyUpByteTest ; if none try bytes +CopyUpDwordLoop: + mov edx, dword ptr [esi] + mov dword ptr [edi], edx + add edi, 4 + add esi, 4 + sub ecx, 1 + jne CopyUpDwordLoop +CopyUpByteTest: + mov ecx, eax + and ecx, 03h + je CopyUpReturn ; if none return +CopyUpByteLoop: + mov al, byte ptr [esi] + mov byte ptr [edi], al + inc esi + inc edi + dec ecx + jne CopyUpByteLoop +align 16 +CopyUpReturn: + ; return dst + mov eax,[esp + 0Ch] ; return original destination pointer + pop esi + pop edi + M_EXIT + + +; dst addr is not 16 byte aligned +align 16 +XmmCopyUnaligned: + +; copy the first the first 1-15 bytes to align both src and dst up to the nearest 16-byte boundary: + +; in +; esi = src +; edi = dst +; eax = src and dst alignment +; ecx = length + + mov edx, 010h + sub edx, eax ; calculate number of bytes to get it aligned + sub ecx, edx ; calc new length and save it + push ecx + mov eax, edx ; save alignment byte count for dwords + mov ecx, eax ; set ecx to rep count + and ecx, 03h + je XmmAlignDwordTest ; if no bytes go do dwords +XmmAlignByte: + mov dl, byte ptr [esi] ; move the bytes + mov byte ptr [edi], dl + inc esi ; increment the addresses + inc edi + dec ecx ; decrement the counter + jne XmmAlignByte +XmmAlignDwordTest: + shr eax, 2 ; get dword count + je XmmAlignAdjustCnt ; if none go to main loop +XmmAlignDwordLoop: + mov edx, dword ptr [esi] ; move the dwords + mov dword ptr [edi], edx + lea esi, [esi+4] ; increment the addresses + lea edi, [edi+4] + dec eax ; decrement the counter + jne XmmAlignDwordLoop +XmmAlignAdjustCnt: + pop ecx ; retrieve the adjusted length + jmp XmmCopyAligned + + +_MEM_ endp + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memmove.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memmove.asm new file mode 100644 index 0000000000000000000000000000000000000000..7a2fca1a4a095d06b3e16c37039409b7758ed453 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memmove.asm @@ -0,0 +1,16 @@ +;*** +;memmove.asm - +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; memmove() copies a source memory buffer to a destination buffer. +; Overlapping buffers are treated specially, to avoid propagation. +; +; NOTE: This stub module scheme is compatible with NT build +; procedure. +; +;******************************************************************************* + +MEM_MOVE EQU 1 +INCLUDE memcpy.asm diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memset.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memset.asm new file mode 100644 index 0000000000000000000000000000000000000000..669251585e57111ce7757a66b89cbd204fcb7d5f --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/memset.asm @@ -0,0 +1,195 @@ + page ,132 + title memset - set sections of memory all to one byte +;*** +;memset.asm - set a section of memory to all one byte +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; contains the memset() routine +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + .xmm + +page +;*** +;char *memset(dst, value, count) - sets "count" bytes at "dst" to "value" +; +;Purpose: +; Sets the first "count" bytes of the memory starting +; at "dst" to the character value "value". +; +; Algorithm: +; char * +; memset (dst, value, count) +; char *dst; +; char value; +; unsigned int count; +; { +; char *start = dst; +; +; while (count--) +; *dst++ = value; +; return(start); +; } +; +;Entry: +; char *dst - pointer to memory to fill with value +; char value - value to put in dst bytes +; int count - number of bytes of dst to fill +; +;Exit: +; returns dst, with filled bytes +; +;Uses: +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + + extrn __isa_available:dword + extrn __isa_enabled:dword + extrn __favor:dword + + public memset +memset proc \ + dst:ptr byte, \ + value:byte, \ + count:dword + + OPTION PROLOGUE:NONE, EPILOGUE:NONE + + .FPO ( 0, 3, 0, 0, 0, 0 ) + + mov ecx, [esp + 0ch] ; the number of bytes to be set + movzx eax, byte ptr[esp + 08h] ; the value to be stored + mov edx, edi ; saving non-volatile edi + mov edi, [esp + 04h]; the dest pointer + test ecx, ecx; 0 ? + jz toend; if so, nothing to do + imul eax, 01010101h + cmp ecx, 020h; < 32 bytes use SmallMov + jbe SmallMov + cmp ecx, 080h; For copies 32 < length < 128 + jb XmmMovSmall + bt __favor, __FAVOR_ENFSTRG + jnc XMMMov; no jump + +; Enhanced Fast Strings + + rep stosb ; store the values in the destination buffer + mov eax, dword ptr[esp + 04h] ; return the original destination pointer + mov edi, edx ; restoring non-volatile edi + ret +; XMM register usage + +XMMMov : + bt __isa_enabled, __ISA_AVAILABLE_SSE2 + jnc SmallMov ; if yes, use xmm large block set + movd xmm0, eax + pshufd xmm0, xmm0, 0 + + add ecx, edi ; ecx points to end of buffer + movups [edi], xmm0 + add edi, 16 ; point to next xmmword + and edi, -16 ; align xmmword ptr + sub ecx, edi ; ecx is offset to end of buffer + + cmp ecx, 080h + jbe XmmMovSmall + +align 16 +LargeRangeBytes : + movdqa [edi], xmm0 + movdqa [edi + 010h], xmm0 + movdqa [edi + 020h], xmm0 + movdqa [edi + 030h], xmm0 + movdqa [edi + 040h], xmm0 + movdqa [edi + 050h], xmm0 + movdqa [edi + 060h], xmm0 + movdqa [edi + 070h], xmm0 + lea edi, [edi + 080h] + sub ecx, 080h + test ecx, 0FFFFFF00h + jnz LargeRangeBytes + jmp XmmSmallLoop + + +; Do not require 16-byte alignment for sizes lesser than 128 bytes when using XMM registers +XmmMovSmall : + bt __isa_enabled, __ISA_AVAILABLE_SSE2 + jnc SmallMov ; if yes, use xmm large block set + movd xmm0, eax + pshufd xmm0, xmm0, 0 + +align 16 + +XmmSmallLoop : + cmp ecx, 32 + jb XMMTrailingBytes +MidRangeBytes : + movdqu [edi], xmm0 + movdqu [edi + 010h], xmm0 + + add edi, 020h + sub ecx, 020h + cmp ecx, 32 ; checking number of 32 byte blocks left + jnb MidRangeBytes + + test ecx, 01Fh ; check to see if there are bytes left + jz toend + +XMMTrailingBytes: +; Remaining bytes written with two stores that may overlap instead of 1 byte at a time + lea edi, [edi + ecx - 020h] + movdqu [edi], xmm0 + movdqu [edi + 010h], xmm0 + mov eax, dword ptr [esp + 04h] ; return the original destination pointer + mov edi, edx ; restoring non-volatile edi + ret + +; Copying less than or equal to 32 bytes + +SmallMov: + test ecx, 03h ; check if there are bytes that can be stored + jz DwordTest + +ByteLoop: + mov [edi], al + inc edi + sub ecx, 1 + test ecx, 03h + jnz ByteLoop + +DwordTest: + test ecx, 04h ; checking if there are dword blocks that can be set + jz QwordTest + mov [edi], eax + add edi, 4 + sub ecx, 4 +QwordTest: + test ecx, 0FFFFFFF8h + jz toend +align 16 +QwordLoop: + mov [edi], eax + mov [edi + 04h], eax + add edi, 8 + sub ecx, 8 + test ecx, 0FFFFFFF8h + jnz QwordLoop + +toend: + mov eax, dword ptr[esp + 04h] ; return the original destination pointer + mov edi, edx ; restore non-volatile edi + ret + +memset endp + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/mm.inc b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/mm.inc new file mode 100644 index 0000000000000000000000000000000000000000..16a27b99e3c97734c067c7f488646dbdc82ea516 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/mm.inc @@ -0,0 +1,16 @@ +;*** +;mm.inc - macros to write memory model dependent code +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; This file contains definitions of a number of macros which +; make the writing of memory model dependent code for the +; 386 a little easier and more portable. +; +;******************************************************************************* + +; Big/Little Endian Definitions for Long Integers + +LOWORD equ [0] +HIWORD equ [4] diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strchr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strchr.asm new file mode 100644 index 0000000000000000000000000000000000000000..c53293e026f6c370e79c3feaa8f1535486d18507 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strchr.asm @@ -0,0 +1,194 @@ + page ,132 + title strchr - search string for given character +;*** +;strchr.asm - search a string for a given character +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines strchr() - search a string for a character +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + +page +;*** +;char *strchr(string, chr) - search a string for a character +; +;Purpose: +; Searches a string for a given character, which may be the +; null character '\0'. +; +; Algorithm: +; char * +; strchr (string, chr) +; char *string, chr; +; { +; while (*string && *string != chr) +; string++; +; if (*string == chr) +; return(string); +; return((char *)0); +; } +; +;Entry: +; char *string - string to search in +; char chr - character to search for +; +;Exit: +; returns pointer to the first occurrence of c in string +; returns NULL if chr does not occur in string +; +;Uses: +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + + align 16 + public strchr, __from_strstr_to_strchr +strchr proc \ + string:ptr byte, \ + chr:byte + + OPTION PROLOGUE:NONE, EPILOGUE:NONE + + .FPO ( 0, 2, 0, 0, 0, 0 ) + +; Include SSE2 code path for platforms that support it. + include strchr_sse.inc + + xor eax,eax + mov al,[esp + 8] ; al = chr (search char) + +__from_strstr_to_strchr label proc + + push ebx ; PRESERVE EBX + mov ebx,eax ; ebx = 0/0/0/chr + shl eax,8 ; eax = 0/0/chr/0 + mov edx,[esp + 8] ; edx = buffer + test edx,3 ; test if string is aligned on 32 bits + jz short main_loop_start + +str_misaligned: ; simple byte loop until string is aligned + mov cl,[edx] + add edx,1 + cmp cl,bl + je short found_bx + test cl,cl + jz short retnull_bx + test edx,3 ; now aligned ? + jne short str_misaligned + +main_loop_start: ; set all 4 bytes of ebx to [chr] + or ebx,eax ; ebx = 0/0/chr/chr + push edi ; PRESERVE EDI + mov eax,ebx ; eax = 0/0/chr/chr + shl ebx,10h ; ebx = chr/chr/0/0 + push esi ; PRESERVE ESI + or ebx,eax ; ebx = all 4 bytes = [chr] + +; in the main loop (below), we are looking for chr or for EOS (end of string) + +main_loop: + mov ecx,[edx] ; read dword (4 bytes) + mov edi,7efefeffh ; work with edi & ecx for looking for chr + + mov eax,ecx ; eax = dword + mov esi,edi ; work with esi & eax for looking for EOS + + xor ecx,ebx ; eax = dword xor chr/chr/chr/chr + add esi,eax + + add edi,ecx + xor ecx,-1 + + xor eax,-1 + xor ecx,edi + + xor eax,esi + add edx,4 + + and ecx,81010100h ; test for chr + jnz short chr_is_found ; chr probably has been found + + ; chr was not found, check for EOS + + and eax,81010100h ; is any flag set ?? + jz short main_loop ; EOS was not found, go get another dword + + and eax,01010100h ; is it in high byte? + jnz short retnull ; no, definitely found EOS, return failure + + and esi,80000000h ; check was high byte 0 or 80h + jnz short main_loop ; it just was 80h in high byte, go get + ; another dword +retnull: + pop esi + pop edi +retnull_bx: + pop ebx + xor eax,eax + ret ; _cdecl return + +found_bx: + lea eax,[edx - 1] + pop ebx ; restore ebx + ret ; _cdecl return + +chr_is_found: + mov eax,[edx - 4] ; let's look one more time on this dword + cmp al,bl ; is chr in byte 0? + je short byte_0 + test al,al ; test if low byte is 0 + je retnull + cmp ah,bl ; is it byte 1 + je short byte_1 + test ah,ah ; found EOS ? + je retnull + shr eax,10h ; is it byte 2 + cmp al,bl + je short byte_2 + test al,al ; if in al some bits were set, bl!=bh + je retnull + cmp ah,bl + je short byte_3 + test ah,ah + jz retnull + jmp short main_loop ; neither chr nor EOS found, go get + ; another dword +byte_3: + pop esi + pop edi + lea eax,[edx - 1] + pop ebx ; restore ebx + ret ; _cdecl return + +byte_2: + lea eax,[edx - 2] + pop esi + pop edi + pop ebx + ret ; _cdecl return + +byte_1: + lea eax,[edx - 3] + pop esi + pop edi + pop ebx + ret ; _cdecl return + +byte_0: + lea eax,[edx - 4] + pop esi ; restore esi + pop edi ; restore edi + pop ebx ; restore ebx + ret ; _cdecl return + +strchr endp + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strrchr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strrchr.asm new file mode 100644 index 0000000000000000000000000000000000000000..17ed1cf65ba7899a25503827690ed84bea2be8e0 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strrchr.asm @@ -0,0 +1,98 @@ + page ,132 + title strrchr - find last occurrence of character in string +;*** +;strrchr.asm - find last occurrence of character in string +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines strrchr() - find the last occurrence of a given character +; in a string. +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + +page +;*** +;char *strrchr(string, ch) - find last occurrence of ch in string +; +;Purpose: +; Finds the last occurrence of ch in string. The terminating +; null character is used as part of the search. +; +; Algorithm: +; char * +; strrchr (string, ch) +; char *string, ch; +; { +; char *start = string; +; +; while (*string++) +; ; +; while (--string != start && *string != ch) +; ; +; if (*string == ch) +; return(string); +; return(NULL); +; } +; +;Entry: +; char *string - string to search in +; char ch - character to search for +; +;Exit: +; returns a pointer to the last occurrence of ch in the given +; string +; returns NULL if ch does not occur in the string +; +;Uses: +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + + public strrchr +strrchr proc \ + uses edi, \ + string:ptr byte, \ + chr:byte + +; .FPO (cdwLocals, cdwParams, cbProlog, cbRegs, fUseBP, cbFrame) + .FPO ( 0, 2, 0, 0, 0, 0 ) + +; Include SSE2/SSE4.2 code paths for platforms that support them. + include strrchr_sse.inc + + mov edi,[string] ; di = string + xor eax,eax ; al=null byte + or ecx,-1 ; cx = -1 +repne scasb ; find the null & count bytes + add ecx,1 ; cx=-byte count (with null) + neg ecx ; cx=+byte count (with null) + sub edi,1 ; di points to terminal null + mov al,chr ; al=search byte + std ; count 'down' on string this time +repne scasb ; find that byte + add edi,1 ; di points to byte which stopped scan + + cmp [edi],al ; see if we have a hit + je short returndi ; yes, point to byte + + xor eax,eax ; no, return NULL + jmp short toend ; do return sequence + +returndi: + mov eax,edi ; ax=pointer to byte + +toend: + cld + + ret ; _cdecl return + +strrchr endp + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strstr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strstr.asm new file mode 100644 index 0000000000000000000000000000000000000000..d9399c7aac4801180b3e3d0fa4e158ab238bc0ba --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/strstr.asm @@ -0,0 +1,179 @@ + page ,132 + title strstr - search for one string inside another +;*** +;strstr.asm - search for one string inside another +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines strstr() - search for one string inside another +; +;******************************************************************************* + + .xlist + include vcruntime.inc + .list + +page +;*** +;char *strstr(str1, str2) - search for str2 in str1 +; +;Purpose: +; finds the first occurrence of str2 in str1 +; +;Entry: +; char *str1 - string to search in +; char *str2 - string to search for +; +;Exit: +; returns a pointer to the first occurrence of string2 in +; string1, or NULL if string2 does not occur in string1 +; +;Uses: +; +;Exceptions: +; +;******************************************************************************* + + +__from_strstr_to_strchr proto + + CODESEG + + public strstr + +strstr proc \ + str1:ptr byte, \ + str2:ptr byte + + OPTION PROLOGUE:NONE, EPILOGUE:NONE + + mov ecx,[esp + 8] ; str2 (the string to be searched for) + mov eax,[esp + 4] ; str1 (the string to be searched) + + push edi ; Preserve edi, ebx and esi + push ebx + push esi + +; .FPO (cdwLocals, cdwParams, cbProlog, cbRegs, fUseBP, cbFrame) + .FPO ( 0, 2, $-strstr, 3, 0, 0 ) + +; Include SSE2/SSE4.2 code paths for platforms that support them. + include strstr_sse.inc + + mov dl,[ecx] ; dl contains first char from str2 + + mov edi,eax ; str1 (the string to be searched) + + test dl,dl ; is str2 empty? + jz empty_str2 + + mov dh,[ecx + 1] ; second char from str2 + test dh,dh ; is str2 a one-character string? + jz strchr_call ; if so, go use strchr code + +; length of str2 is now known to be > 1 (used later) +; dl contains first char from str2 +; dh contains second char from str2 +; edi holds str1 + +findnext: + mov esi,edi ; esi = edi = pointers to somewhere in str1 + mov ecx,[esp + 14h] ; str2 + +;use edi instead of esi to eliminate AGI + mov al,[edi] ; al is next char from str1 + + add esi,1 ; increment pointer into str1 + + cmp al,dl + je first_char_found + + test al,al ; end of str1? + jz not_found ; yes, and no match has been found + +loop_start: + mov al,[esi] ; put next char from str1 into al + add esi,1 ; increment pointer in str1 +in_loop: + cmp al,dl + je first_char_found + + test al,al ; end of str1? + jnz loop_start ; no, go get another char from str1 + +not_found: + pop esi + pop ebx + pop edi + xor eax,eax + ret + +; recall that dh contains the second char from str2 + +first_char_found: + mov al,[esi] ; put next char from str1 into al + add esi,1 + + cmp al,dh ; compare second chars + jnz in_loop ; no match, continue search + +two_first_chars_equal: + lea edi,[esi - 1] ; store position of last read char in str1 + +compare_loop: + mov ah,[ecx + 2] ; put next char from str2 into ah + test ah,ah ; end of str2? + jz match ; if so, then a match has been found + + mov al,[esi] ; get next char from str1 + add esi,2 ; bump pointer into str1 by 2 + + cmp al,ah ; are chars from str1 and str2 equal? + jne findnext ; no + +; do one more iteration + + mov al,[ecx + 3] ; put the next char from str2 into al + test al,al ; end of str2 + jz match ; if so, then a match has been found + + mov ah,[esi - 1] ; get next char from str1 + add ecx,2 ; bump pointer in str1 by 2 + cmp al,ah ; are chars from str1 and str2 equal? + je compare_loop + +; no match. test some more chars (to improve execution time for bad strings). + + jmp findnext + +; str2 string contains only one character so it's like the strchr function + +strchr_call: + xor eax,eax + pop esi + pop ebx + pop edi + mov al,dl + jmp __from_strstr_to_strchr + +; +; +; Match! Return (ebx - 1) +; +match: + lea eax,[edi - 1] + pop esi + pop ebx + pop edi + ret + +empty_str2: ; empty target string, return src (ANSI mandated) + mov eax,edi + pop esi + pop ebx + pop edi + ret + +strstr endp + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/trnsctrl.cpp b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/trnsctrl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9311c78644fcbba82cda0003032db08eb13194dc --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/trnsctrl.cpp @@ -0,0 +1,796 @@ +/*** +*trnsctrl.cpp - Routines for doing control transfers +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Routines for doing control transfers; written using inline +* assembly in naked functions. Contains the public routine +* _CxxFrameHandler, the entry point for the frame handler +****/ + +#include +#include +#include +#include +#include +#include +#include + +#include "../ehhelpers.h" + +#include + +#pragma warning(disable: 4100) // unreferenced formal parameter +#pragma warning(disable: 4731) // ignore EBP mod in inline-asm warning +#pragma warning(disable: 4733) // ignore unsafe FS:0 modifications +#pragma warning(disable: 4740) // control flow in asm suppresses global optimization + + + +// copied from ntxcapi.h +#define EXCEPTION_UNWINDING 0x2 // Unwind is in progress +#define EXCEPTION_EXIT_UNWIND 0x4 // Exit unwind is in progress +#define EXCEPTION_STACK_INVALID 0x8 // Stack out of limits or unaligned +#define EXCEPTION_NESTED_CALL 0x10 // Nested exception handler call +#define EXCEPTION_TARGET_UNWIND 0x20 // Target unwind in progress +#define EXCEPTION_COLLIDED_UNWIND 0x40 // Collided exception handler call + +#define EXCEPTION_UNWIND (EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND | \ + EXCEPTION_TARGET_UNWIND | EXCEPTION_COLLIDED_UNWIND) + +#define IS_UNWINDING(Flag) ((Flag & EXCEPTION_UNWIND) != 0) +#define IS_DISPATCHING(Flag) ((Flag & EXCEPTION_UNWIND) == 0) +#define IS_TARGET_UNWIND(Flag) (Flag & EXCEPTION_TARGET_UNWIND) + +#define pFrameInfoChain (*((FRAMEINFO **) &(RENAME_BASE_PTD(__vcrt_getptd)()->_pFrameInfoChain))) + +///////////////////////////////////////////////////////////////////////////// +// +// _JumpToContinuation - sets up EBP and jumps to specified code address. +// +// Does not return. +// +// NT leaves a marker registration node at the head of the list, under the +// assumption that RtlUnwind will remove it. As it happens, we need to keep +// it in case of a rethrow (see below). We only remove the current head +// (assuming it is NT's), because there may be other nodes that we still +// need. +// + +void __stdcall _JumpToContinuation( + void *target, // The funclet to call + EHRegistrationNode *pRN // Registration node, represents location of frame +) { + EHTRACE_FMT1("Transfer to 0x%p", target); + long targetEBP; + +#if !CC_EXPLICITFRAME + targetEBP = (long)pRN + FRAME_OFFSET; +#else + targetEBP = pRN->frame; +#endif + + __asm { + // + // Unlink NT's marker node: + // + mov ebx, FS:[0] + mov eax, [ebx] + mov FS:[0], eax + + // + // Transfer control to the continuation point + // + mov eax, target // Load target address + mov ebx, pRN + mov ebp, targetEBP // Load target frame pointer + mov esp, [ebx-4] // Restore target esp + jmp eax // Call the funclet + } + } + + + +///////////////////////////////////////////////////////////////////////////// +// +// _UnwindNestedFrames - Call RtlUnwind, passing the address after the call +// as the continuation address. +// +// Win32 assumes that after a frame has called RtlUnwind, it will never return +// to the dispatcher. +// +// Let me explain: +// When the dispatcher calls a frame handler while searching +// for the appropriate handler, it pushes an extra guard registration node +// onto the list. When the handler returns to the dispatcher, the dispatcher +// assumes that its node is at the head of the list, restores esp from the +// address of the head node, and then unlinks that node from the chain. +// However, if RtlUnwind removes ALL nodes below the specified node, including +// the dispatcher's node, so without intervention the result is that the +// current subject node gets popped from the list, and the stack pointer gets +// reset to somewhere within the frame of that node, which is totally bogus +// (this last side effect is not a problem, because esp is then immediately +// restored from the ebp chain, which is still valid). +// +// So: +// To get around this, WE ASSUME that the registration node at the head of +// the list is the dispatcher's marker node (which it is in NT 1.0), and +// we keep a handle to it when we call RtlUnwind, and then link it back in +// after RtlUnwind has done its stuff. That way, the dispatcher restores +// its stack exactly as it expected to, and leave our registration node alone. +// +// What happens if there is an exception during the unwind? +// We can't put a registration node here, because it will be removed +// immediately. +// +// RtlUnwind: +// RtlUnwind is evil. It trashes all the registers except EBP and ESP. +// Because of that, EBX, ESI, and EDI must be preserved by this function, +// and the compiler may not assume that any callee-save register can be used +// across the call to RtlUnwind. To accomplish the former, inline-asm code +// here uses EBX, ESI, and EDI, so they will be saved in the prologue. For +// the latter, optimizations are disabled for the duration of this function. +// + +BEGIN_PRAGMA_OPTIMIZE_DISABLE("g", DevDivVSO:162582, "RtlUnwind does not preserve registers (see above)") + +void __stdcall _UnwindNestedFrames( + EHRegistrationNode *pRN, // Unwind up to (but not including) this frame + EHExceptionRecord *pExcept // The exception that initiated this unwind +) { + void* pReturnPoint; + EHRegistrationNode *pDispatcherRN; // Magic! + + __asm { + // + // Save the dispatcher's marker node + // + // NOTE: RtlUnwind will trash the callee-save regs EBX, ESI, and EDI. + // We explicitly use them here in the inline-asm so they get preserved + // and restored by the function prologue/epilogue. + // + mov esi, dword ptr FS:[0] // use ESI + mov pDispatcherRN, esi + } + + __asm mov pReturnPoint, offset ReturnPoint +#pragma warning(push) +#pragma warning(disable: 6387) // TRANSITION, VSO-1801835 + RtlUnwind(pRN, pReturnPoint, (PEXCEPTION_RECORD)pExcept, nullptr); +#pragma warning(pop) + +ReturnPoint: + + PER_FLAGS(pExcept) &= ~EXCEPTION_UNWINDING; // Clear the 'Unwinding' flag + // in case exception is rethrown + __asm { + // + // Re-link the dispatcher's marker node + // + mov edi, dword ptr FS:[0] // Get the current head (use EDI) + mov ebx, pDispatcherRN // Get the saved head (use EBX) + mov [ebx], edi // Link saved head to current head + mov dword ptr FS:[0], ebx // Make saved head current head + } + + return; + } + +END_PRAGMA_OPTIMIZE() + +// +// This is a backwards-compatibility entry point. All new code must go to __CxxFrameHandler2 +// +extern "C" _VCRTIMP __declspec(naked) DECLSPEC_GUARD_SUPPRESS EXCEPTION_DISPOSITION __cdecl __CxxFrameHandler( +/* + EAX=FuncInfo *pFuncInfo, // Static information for this frame +*/ + EHExceptionRecord *pExcept, // Information for this exception + EHRegistrationNode *pRN, // Dynamic information for this frame + void *pContext, // Context info (we don't care what's in it) + DispatcherContext *pDC // More dynamic info for this frame (ignored on Intel) +) { + FuncInfo *pFuncInfo; + EXCEPTION_DISPOSITION result; + + __asm { + // + // Standard function prolog + // + push ebp + mov ebp, esp + sub esp, __LOCAL_SIZE + push ebx + push esi + push edi + cld // A bit of paranoia -- Our code-gen assumes this + + // + // Save the extra parameter + // + mov pFuncInfo, eax + } + + EHTRACE_FMT1("pRN = 0x%p", pRN); + + result = __InternalCxxFrameHandlerWrapper( pExcept, pRN, (PCONTEXT)pContext, pDC, pFuncInfo, 0, nullptr, FALSE ); + + EHTRACE_HANDLER_EXIT(result); + + __asm { + pop edi + pop esi + pop ebx + mov eax, result + mov esp, ebp + pop ebp + ret 0 + } +} + +// +// __CxxFrameHandler3 - Real entry point to the runtime +// __CxxFrameHandler2 is an alias for __CxxFrameHandler3 +// since they are compatible in VC version of CRT +// These function should be separated out if a change makes +// __CxxFrameHandler3 incompatible with __CxxFrameHandler2 +// +extern "C" _VCRTIMP __declspec(naked) DECLSPEC_GUARD_SUPPRESS EXCEPTION_DISPOSITION __cdecl __CxxFrameHandler3( +/* + EAX=FuncInfo *pFuncInfo, // Static information for this frame +*/ + EHExceptionRecord *pExcept, // Information for this exception + EHRegistrationNode *pRN, // Dynamic information for this frame + void *pContext, // Context info (we don't care what's in it) + DispatcherContext *pDC // More dynamic info for this frame (ignored on Intel) +) { + FuncInfo *pFuncInfo; + EXCEPTION_DISPOSITION result; + + __asm { + // + // Standard function prolog + // + push ebp + mov ebp, esp + sub esp, __LOCAL_SIZE + push ebx + push esi + push edi + cld // A bit of paranoia -- Our code-gen assumes this + + // + // Save the extra parameter + // + mov pFuncInfo, eax + } + + EHTRACE_FMT1("pRN = 0x%p", pRN); + + result = __InternalCxxFrameHandlerWrapper( pExcept, pRN, (PCONTEXT)pContext, pDC, pFuncInfo, 0, nullptr, FALSE ); + + EHTRACE_HANDLER_EXIT(result); + + __asm { + pop edi + pop esi + pop ebx + mov eax, result + mov esp, ebp + pop ebp + ret 0 + } +} + +// +// __CxxFrameHandler2 - Remove after compiler is updated +// +extern "C" _VCRTIMP __declspec(naked) DECLSPEC_GUARD_SUPPRESS EXCEPTION_DISPOSITION __cdecl __CxxFrameHandler2( +/* + EAX=FuncInfo *pFuncInfo, // Static information for this frame +*/ + EHExceptionRecord *pExcept, // Information for this exception + EHRegistrationNode *pRN, // Dynamic information for this frame + void *pContext, // Context info (we don't care what's in it) + DispatcherContext *pDC // More dynamic info for this frame (ignored on Intel) +) { + FuncInfo *pFuncInfo; + EXCEPTION_DISPOSITION result; + + __asm { + // + // Standard function prolog + // + push ebp + mov ebp, esp + sub esp, __LOCAL_SIZE + push ebx + push esi + push edi + cld // A bit of paranoia -- Our code-gen assumes this + + // + // Save the extra parameter + // + mov pFuncInfo, eax + } + + EHTRACE_FMT1("pRN = 0x%p", pRN); + + result = __InternalCxxFrameHandlerWrapper( pExcept, pRN, (PCONTEXT)pContext, pDC, pFuncInfo, 0, nullptr, FALSE ); + + EHTRACE_HANDLER_EXIT(result); + + __asm { + pop edi + pop esi + pop ebx + mov eax, result + mov esp, ebp + pop ebp + ret 0 + } +} + +extern "C" void +__except_validate_jump_buffer ( + _In_ _JUMP_BUFFER *JumpBuffer + ); + +///////////////////////////////////////////////////////////////////////////// +// +// __CxxLongjmpUnwind - Entry point for local unwind required by longjmp +// when setjmp used in same function as C++ EH. +// + +extern "C" DECLSPEC_GUARD_SUPPRESS void __stdcall __CxxLongjmpUnwind( + _JUMP_BUFFER *jbuf +) { + __except_validate_jump_buffer(jbuf); + + RENAME_EH_EXTERN(__FrameHandler3)::FrameUnwindToState((EHRegistrationNode *)jbuf->Registration, + (DispatcherContext*)nullptr, + (FuncInfo *)jbuf->UnwindData[0], + (__ehstate_t)jbuf->TryLevel); +} + +///////////////////////////////////////////////////////////////////////////// +// +// _CallCatchBlock2 - The nitty-gritty details to get the catch called +// correctly. +// +// We need to guard the call to the catch block with a special registration +// node, so that if there is an exception which should be handled by a try +// block within the catch, we handle it without unwinding the SEH node +// in CallCatchBlock. +// + +struct CatchGuardRN { + EHRegistrationNode *pNext; // Frame link + void *pFrameHandler; // Frame Handler + UINT_PTR RandomCookie; // __security_cookie XOR node address + FuncInfo *pFuncInfo; // Static info for subject function + EHRegistrationNode *pRN; // Dynamic info for subject function + int CatchDepth; // How deeply nested are we? + }; + +extern "C" EXCEPTION_DISPOSITION __cdecl _CatchGuardHandler( EHExceptionRecord*, CatchGuardRN *, void *, void * ); + +__declspec(guard(ignore)) void *_CallCatchBlock2( + EHRegistrationNode *pRN, // Dynamic info of function with catch + FuncInfo *pFuncInfo, // Static info of function with catch + void *handlerAddress, // Code address of handler + int CatchDepth, // How deeply nested in catch blocks are we? + unsigned long NLGCode +) { + // + // First, create and link in our special guard node: + // + CatchGuardRN CGRN = { nullptr, + (void*)_CatchGuardHandler, + __security_cookie ^ (UINT_PTR)&CGRN, + pFuncInfo, + pRN, + CatchDepth + 1 + }; + + __asm { + mov eax, FS:[0] // Fetch frame list head + mov CGRN.pNext, eax // Link this node in + lea eax, CGRN // Put this node at the head + mov FS:[0], eax + } + + // + // Call the catch + // + void *continuationAddress = _CallSettingFrame( handlerAddress, pRN, NLGCode ); + + // + // Unlink our registration node + // + __asm { + mov eax, CGRN.pNext // Get parent node + mov FS:[0], eax // Put it at the head + } + + return continuationAddress; + } + + +///////////////////////////////////////////////////////////////////////////// +// +// _CatchGuardHandler - frame handler for the catch guard node. +// +// This function will attempt to find a handler for the exception within +// the current catch block (ie any nested try blocks). If none is found, +// or the handler rethrows, returns ExceptionContinueSearch; otherwise does +// not return. +// +// Does nothing on an unwind. +// + +extern "C" EXCEPTION_DISPOSITION __cdecl _CatchGuardHandler( + EHExceptionRecord *pExcept, // Information for this exception + CatchGuardRN *pRN, // The special marker frame + void *pContext, // Context info (we don't care what's in it) + void * // (ignored) +) { + EHTRACE_FMT1("pRN = 0x%p", pRN); + __asm cld; // Our code-gen assumes this + + // + // Validate our registration record, to secure against hacker attacks. + // + + __security_check_cookie(pRN->RandomCookie ^ (UINT_PTR)pRN); + + EXCEPTION_DISPOSITION result = + __InternalCxxFrameHandlerWrapper( pExcept, + pRN->pRN, + (PCONTEXT)pContext, + nullptr, + pRN->pFuncInfo, + pRN->CatchDepth, + (EHRegistrationNode*)pRN, + FALSE ); + EHTRACE_HANDLER_EXIT(result); + return result; + } + + +///////////////////////////////////////////////////////////////////////////// +// +// CallSEHTranslator - calls the SEH translator, and handles the translation +// exception. +// +// Assumes that a valid translator exists. +// +// Method: +// Sets up a special guard node, whose handler handles the translation +// exception, and remembers NT's marker node (See _UnwindNestedFrames above). +// If the exception is not fully handled, the handler returns control to here, +// so that this function can return to resume the normal search for a handler +// for the original exception. +// +// Returns: TRUE if translator had a translation (handled or not) +// FALSE if there was no translation +// Does not return if translation was fully handled +// +// Note: +// This is also called in a special mode from _TranslatorGuardHandler +// to return the address of the continuation point, ExceptionContinuation, +// a label inside CallSEHTranslator. We used to keep this address in the +// TranslatorGuardRN, but that opens a security hole by allowing a buffer +// overrun exploit to overwrite an EH registration record and fill in the +// continuation point to vector wherever desired. +// +// The special mode is detected by a first argument having the value 0x123. +// That is never a legitimate pointer and unambiguously indicates a special +// case call. The 2nd arg in this case is treated as a void** to be used to +// return the continuation address. +// + +struct TranslatorGuardRN /*: CatchGuardRN */ { + EHRegistrationNode *pNext; // Frame link + void *pFrameHandler; // Frame Handler + UINT_PTR RandomCookie; // __security_cookie XOR node address + FuncInfo *pFuncInfo; // Static info for subject function + EHRegistrationNode *pRN; // Dynamic info for subject function + int CatchDepth; // How deeply nested are we? + EHRegistrationNode *pMarkerRN; // Marker for parent context + void *ESP; // ESP within CallSEHTranslator + void *EBP; // EBP within CallSEHTranslator + BOOL DidUnwind; // True if this frame was unwound + }; + +extern "C" EXCEPTION_DISPOSITION __cdecl _TranslatorGuardHandler( EHExceptionRecord*, TranslatorGuardRN *, void *, void * ); + +#define CSET_SPECIAL ((EHExceptionRecord *)0x123) + +BEGIN_PRAGMA_OPTIMIZE_DISABLE("g", DOLPH:3322, "Uninvestigated issue from Visual C++ 2.0") + +#if defined(_M_IX86) && !defined(CRTDLL) && !defined(_M_HYBRID) +// Filter incorrect x86 floating point exceptions, unless linkopt that provides an empty filter is available. +#pragma comment(linker, "/alternatename:__filter_x86_sse2_floating_point_exception=__filter_x86_sse2_floating_point_exception_default") +#endif + +__declspec(guard(ignore)) BOOL _CallSETranslator( + EHExceptionRecord *pExcept, // The exception to be translated + EHRegistrationNode *pRN, // Dynamic info of function with catch + void *pContext, // Context info (we don't care what's in it) + DispatcherContext *pDC, // More dynamic info of function with catch (ignored) + FuncInfo *pFuncInfo, // Static info of function with catch + int CatchDepth, // How deeply nested in catch blocks are we? + EHRegistrationNode *pMarkerRN // Marker for parent context +) { + // + // Process special case calling request - return address of internal + // continuation label through pRN (which is actually a void** in this case) + // + if (pExcept == CSET_SPECIAL) { + __asm { + mov eax, offset ExceptionContinuation + mov ecx, pRN + mov [ecx], eax + } + return TRUE; + } + + // + // Create and link in our special guard node: + // + TranslatorGuardRN TGRN = { nullptr, // Frame link + (void*)_TranslatorGuardHandler, + __security_cookie ^ (UINT_PTR)&TGRN, + pFuncInfo, + pRN, + CatchDepth, + pMarkerRN, + nullptr, // ESP + nullptr, // EBP + FALSE // DidUnwind + }; + + __asm { + // + // Fill in the blanks: + // + mov TGRN.ESP, esp + mov TGRN.EBP, ebp + + // + // Link this node in: + // + mov eax, FS:[0] // Fetch frame list head + mov TGRN.pNext, eax // Link this node in + lea eax, TGRN // Put this node at the head + mov FS:[0], eax + } + +#if defined(_M_IX86) && !defined(CRTDLL) && !defined(_M_HYBRID) + // Translate exception code for SSE exceptions + PER_CODE(pExcept) = _filter_x86_sse2_floating_point_exception(PER_CODE(pExcept)); +#endif + + // + // Call the translator; assume it will give a translation. + // + BOOL DidTranslate = TRUE; + _EXCEPTION_POINTERS pointers = { + (PEXCEPTION_RECORD)pExcept, + (PCONTEXT)pContext }; + + _se_translator_function pSETranslator; + pSETranslator = __pSETranslator; + _GUARD_CHECK_ICALL((uintptr_t)pSETranslator); + pSETranslator(PER_CODE(pExcept), &pointers); + + // + // If translator returned normally, that means it didn't translate the + // exception. + // + DidTranslate = FALSE; + + // + // Here's where we pick up if the translator threw something. + // Note that ESP and EBP were restored by our frame handler. + // +ExceptionContinuation: + + if (TGRN.DidUnwind) { + // + // If the translated exception was partially handled (ie caught but + // rethrown), then the frame list has the NT guard for the translation + // exception context instead of the one for the original exception + // context. Correct that sequencing problem. Note that our guard + // node was unlinked by RtlUnwind. + // + __asm { + mov ebx, FS:[0] // Get the node below the (bad) NT marker + mov eax, [ebx] // (it was the target of the unwind) + mov ebx, TGRN.pNext // Get the node we saved (the 'good' marker) + mov [ebx], eax // Link the good node to the unwind target + mov FS:[0], ebx // Put the good node at the head of the list + } + } + else { + // + // Translator returned normally or translation wasn't handled. + // unlink our registration node and exit + // + __asm { + mov eax, TGRN.pNext // Get parent node + mov FS:[0], eax // Put it at the head + } + } + + return DidTranslate; + } + +END_PRAGMA_OPTIMIZE() + +///////////////////////////////////////////////////////////////////////////// +// +// _TranslatorGuardHandler - frame handler for the translator guard node. +// +// On search: +// This frame handler will check if there is a catch at the current level +// for the translated exception. If there is no handler or the handler +// did a re-throw, control is transferred back into CallSEHTranslator, based +// on the values saved in the registration node. +// +// Does not return. +// +// On unwind: +// Sets the DidUnwind flag in the registration node, and returns. +// +extern "C" EXCEPTION_DISPOSITION __cdecl _TranslatorGuardHandler( + EHExceptionRecord *pExcept, // Information for this exception + TranslatorGuardRN *pRN, // The translator guard frame + void *pContext, // Context info (we don't care what's in it) + void * // (ignored) +) { + EHTRACE_FMT1("pRN = 0x%p", pRN); + __asm cld; // Our code-gen assumes this + + // + // Validate our registration record, to secure against hacker attacks. + // + + __security_check_cookie(pRN->RandomCookie ^ (UINT_PTR)pRN); + + if (IS_UNWINDING(PER_FLAGS(pExcept))) + { + pRN->DidUnwind = TRUE; + EHTRACE_HANDLER_EXIT(ExceptionContinueSearch); + return ExceptionContinueSearch; + } + else { + // + // Check for a handler: + // + __InternalCxxFrameHandlerWrapper( pExcept, pRN->pRN, (PCONTEXT)pContext, nullptr, pRN->pFuncInfo, pRN->CatchDepth, pRN->pMarkerRN, TRUE ); + + if (!pRN->DidUnwind) { + // + // If no match was found, unwind the context of the translator + // + _UnwindNestedFrames( (EHRegistrationNode*)pRN, pExcept ); + } + + // + // Transfer control back to establisher: + // + + void *pContinue; + _CallSETranslator(CSET_SPECIAL, (EHRegistrationNode *)&pContinue, + nullptr, nullptr, nullptr, 0, nullptr); + EHTRACE_FMT1("Transfer to establisher @ 0x%p", pContinue); + + __asm { + mov eax, pContinue + mov ebx, pRN // Get address of registration node + mov esp, [ebx]TranslatorGuardRN.ESP + mov ebp, [ebx]TranslatorGuardRN.EBP + jmp eax + } + + // Unreached. + return ExceptionContinueSearch; + } + } + + +///////////////////////////////////////////////////////////////////////////// +// +// GetRangeOfTrysToCheck - determine which try blocks are of interest, given +// the current catch block nesting depth. We only check the trys at a single +// depth. +// +// Returns: +// Address of first try block of interest is returned +// pStart and pEnd get the indices of the range in question +// +RENAME_EH_EXTERN(__FrameHandler3)::TryBlockMap::IteratorPair RENAME_EH_EXTERN(__FrameHandler3)::GetRangeOfTrysToCheck( + RENAME_EH_EXTERN(__FrameHandler3)::TryBlockMap &TryBlockMap, + __ehstate_t curState, + DispatcherContext * /*pDC*/, + FuncInfo * pFuncInfo, + int CatchDepth +) { + TryBlockMapEntry *pEntry = FUNC_PTRYBLOCK(*pFuncInfo, 0); + unsigned start = FUNC_NTRYBLOCKS(*pFuncInfo); + unsigned end = start; + unsigned end1 = end; + + while (CatchDepth >= 0) { + _VCRT_VERIFY(start != -1); + start--; + if ( TBME_HIGH(pEntry[start]) < curState && curState <= TBME_CATCHHIGH(pEntry[start]) + || (start == -1) + ) { + CatchDepth--; + end = end1; + end1 = start; + } + } + + ++start; // We always overshoot by 1 (we may even wrap around) + _VCRT_VERIFY(end <= FUNC_NTRYBLOCKS(*pFuncInfo) && start <= end); + auto iterStart = TryBlockMap::iterator(TryBlockMap, start); + auto iterEnd = TryBlockMap::iterator(TryBlockMap, end); + + return TryBlockMap::IteratorPair(iterStart, iterEnd); +} + + +///////////////////////////////////////////////////////////////////////////// +// +// _CreateFrameInfo - Save the frame information for this scope just before +// calling the catch block. Put it at the head of the linked list. For +// x86, all we need to save is the pointer to the exception object, so we +// can determine when that object is no longer used by any nested catch +// handler and can thus be destroyed on exiting from a catch. +// +// Returns: +// Pointer to the frame info (the first input argument). +// +extern "C" _VCRTIMP FRAMEINFO * __cdecl _CreateFrameInfo( + FRAMEINFO * pFrameInfo, + PVOID pExceptionObject +) { + pFrameInfo->pExceptionObject = pExceptionObject; + pFrameInfo->pNext = pFrameInfoChain; + pFrameInfoChain = pFrameInfo; + return pFrameInfo; +} + +///////////////////////////////////////////////////////////////////////////// +// +// _FindAndUnlinkFrame - Remove the frame information for this scope that was +// inserted by _CreateFrameInfo. This should be the first frame in the list +// (Ideally), but fibers deviate from ideal situation. +// +extern "C" _VCRTIMP void __cdecl _FindAndUnlinkFrame( + FRAMEINFO * pFrameInfo +) { + if (pFrameInfo == pFrameInfoChain) { + pFrameInfoChain = pFrameInfo->pNext; + return; + } else { + for (FRAMEINFO *pCurFrameInfo = pFrameInfoChain; + pCurFrameInfo->pNext; + pCurFrameInfo = pCurFrameInfo->pNext) + { + if (pFrameInfo == pCurFrameInfo->pNext) { + pCurFrameInfo->pNext = pFrameInfo->pNext; + return; + } + } + } + + // Should never be reached. + abort(); +} diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldiv.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldiv.asm new file mode 100644 index 0000000000000000000000000000000000000000..070119cbb212f753458d5836dc73210e4e81c840 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldiv.asm @@ -0,0 +1,159 @@ + title ulldiv - unsigned long divide routine +;*** +;ulldiv.asm - unsigned long divide routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the unsigned long divide routine +; __aulldiv +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;ulldiv - unsigned long divide +; +;Purpose: +; Does a unsigned long divide of the arguments. Arguments are +; not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the quotient (dividend/divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_aulldiv PROC NEAR +.FPO (2, 4, 0, 0, 0, 0) + + push ebx + push esi + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a/b will +; generate a call to uldiv(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; | EBX | +; |---------------| +; ESP---->| ESI | +; ----------------- +; + +DVND equ [esp + 12] ; stack address of dividend (a) +DVSR equ [esp + 20] ; stack address of divisor (b) + +; +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; + + mov eax,HIWORD(DVSR) ; check to see if divisor < 4194304K + or eax,eax + jnz short L1 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; get high order bits of quotient + mov ebx,eax ; save high bits of quotient + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; get low order bits of quotient + mov edx,ebx ; edx:eax <- quotient hi:quotient lo + jmp short L2 ; restore stack and return + +; +; Here we do it the hard way. Remember, eax contains DVSRHI +; + +L1: + mov ecx,eax ; ecx:ebx <- divisor + mov ebx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L3: + shr ecx,1 ; shift divisor right one bit; hi bit <- 0 + rcr ebx,1 + shr edx,1 ; shift dividend right one bit; hi bit <- 0 + rcr eax,1 + or ecx,ecx + jnz short L3 ; loop until divisor < 4194304K + div ebx ; now divide, ignore remainder + mov esi,eax ; save quotient + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mul dword ptr HIWORD(DVSR) ; QUOT * HIWORD(DVSR) + mov ecx,eax + mov eax,LOWORD(DVSR) + mul esi ; QUOT * LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L4 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we are ok, otherwise +; subtract one (1) from the quotient. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L4 ; if result > original, do subtract + jb short L5 ; if result < original, we are ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L5 ; if less or equal we are ok, else subtract +L4: + dec esi ; subtract 1 from quotient +L5: + xor edx,edx ; edx:eax <- quotient + mov eax,esi + +; +; Just the cleanup left to do. edx:eax contains the quotient. +; Restore the saved registers and return. +; + +L2: + + pop esi + pop ebx + + ret 16 + +_aulldiv ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldvrm.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldvrm.asm new file mode 100644 index 0000000000000000000000000000000000000000..624c305f0202107f0c857af155ac02f22f609324 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ulldvrm.asm @@ -0,0 +1,186 @@ + title ulldvrm - unsigned long divide and remainder routine +;*** +;ulldvrm.asm - unsigned long divide and remainder routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the unsigned long divide and remainder routine +; __aulldvrm +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;ulldvrm - unsigned long divide and remainder +; +;Purpose: +; Does a unsigned long divide and remainder of the arguments. Arguments +; are not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the quotient (dividend/divisor) +; EBX:ECX contains the remainder (divided % divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_aulldvrm PROC NEAR +.FPO (1, 4, 0, 0, 0, 0) + + push esi + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a/b will +; generate a call to aulldvrm(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; ESP---->| ESI | +; ----------------- +; + +DVND equ [esp + 8] ; stack address of dividend (a) +DVSR equ [esp + 16] ; stack address of divisor (b) + +; +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; + + mov eax,HIWORD(DVSR) ; check to see if divisor < 4194304K + or eax,eax + jnz short L1 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; get high order bits of quotient + mov ebx,eax ; save high bits of quotient + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; get low order bits of quotient + mov esi,eax ; ebx:esi <- quotient + +; +; Now we need to do a multiply so that we can compute the remainder. +; + mov eax,ebx ; set up high word of quotient + mul dword ptr LOWORD(DVSR) ; HIWORD(QUOT) * DVSR + mov ecx,eax ; save the result in ecx + mov eax,esi ; set up low word of quotient + mul dword ptr LOWORD(DVSR) ; LOWORD(QUOT) * DVSR + add edx,ecx ; EDX:EAX = QUOT * DVSR + jmp short L2 ; complete remainder calculation + +; +; Here we do it the hard way. Remember, eax contains DVSRHI +; + +L1: + mov ecx,eax ; ecx:ebx <- divisor + mov ebx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L3: + shr ecx,1 ; shift divisor right one bit; hi bit <- 0 + rcr ebx,1 + shr edx,1 ; shift dividend right one bit; hi bit <- 0 + rcr eax,1 + or ecx,ecx + jnz short L3 ; loop until divisor < 4194304K + div ebx ; now divide, ignore remainder + mov esi,eax ; save quotient + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mul dword ptr HIWORD(DVSR) ; QUOT * HIWORD(DVSR) + mov ecx,eax + mov eax,LOWORD(DVSR) + mul esi ; QUOT * LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L4 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we are ok, otherwise +; subtract one (1) from the quotient. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L4 ; if result > original, do subtract + jb short L5 ; if result < original, we are ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L5 ; if less or equal we are ok, else subtract +L4: + dec esi ; subtract 1 from quotient + sub eax,LOWORD(DVSR) ; subtract divisor from result + sbb edx,HIWORD(DVSR) +L5: + xor ebx,ebx ; ebx:esi <- quotient + +L2: +; +; Calculate remainder by subtracting the result from the original dividend. +; Since the result is already in a register, we will do the subtract in the +; opposite direction and negate the result. +; + + sub eax,LOWORD(DVND) ; subtract dividend from result + sbb edx,HIWORD(DVND) + neg edx ; otherwise, negate the result + neg eax + sbb edx,0 + +; +; Now we need to get the quotient into edx:eax and the remainder into ebx:ecx. +; + mov ecx,edx + mov edx,ebx + mov ebx,ecx + mov ecx,eax + mov eax,esi +; +; Just the cleanup left to do. edx:eax contains the quotient. +; Restore the saved registers and return. +; + + pop esi + + ret 16 + +_aulldvrm ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullrem.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullrem.asm new file mode 100644 index 0000000000000000000000000000000000000000..8a921177995a2a2dd898a9d7ea814f25c199959f --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullrem.asm @@ -0,0 +1,164 @@ + title ullrem - unsigned long remainder routine +;*** +;ullrem.asm - unsigned long remainder routine +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; defines the unsigned long remainder routine +; __aullrem +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;ullrem - unsigned long remainder +; +;Purpose: +; Does a unsigned long remainder of the arguments. Arguments are +; not changed. +; +;Entry: +; Arguments are passed on the stack: +; 1st pushed: divisor (QWORD) +; 2nd pushed: dividend (QWORD) +; +;Exit: +; EDX:EAX contains the remainder (dividend%divisor) +; NOTE: this routine removes the parameters from the stack. +; +;Uses: +; ECX +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_aullrem PROC NEAR +.FPO (1, 4, 0, 0, 0, 0) + + push ebx + +; Set up the local stack and save the index registers. When this is done +; the stack frame will look as follows (assuming that the expression a%b will +; generate a call to ullrem(a, b)): +; +; ----------------- +; | | +; |---------------| +; | | +; |--divisor (b)--| +; | | +; |---------------| +; | | +; |--dividend (a)-| +; | | +; |---------------| +; | return addr** | +; |---------------| +; ESP---->| EBX | +; ----------------- +; + +DVND equ [esp + 8] ; stack address of dividend (a) +DVSR equ [esp + 16] ; stack address of divisor (b) + +; Now do the divide. First look to see if the divisor is less than 4194304K. +; If so, then we can use a simple algorithm with word divides, otherwise +; things get a little more complex. +; + + mov eax,HIWORD(DVSR) ; check to see if divisor < 4194304K + or eax,eax + jnz short L1 ; nope, gotta do this the hard way + mov ecx,LOWORD(DVSR) ; load divisor + mov eax,HIWORD(DVND) ; load high word of dividend + xor edx,edx + div ecx ; edx <- remainder, eax <- quotient + mov eax,LOWORD(DVND) ; edx:eax <- remainder:lo word of dividend + div ecx ; edx <- final remainder + mov eax,edx ; edx:eax <- remainder + xor edx,edx + jmp short L2 ; restore stack and return + +; +; Here we do it the hard way. Remember, eax contains DVSRHI +; + +L1: + mov ecx,eax ; ecx:ebx <- divisor + mov ebx,LOWORD(DVSR) + mov edx,HIWORD(DVND) ; edx:eax <- dividend + mov eax,LOWORD(DVND) +L3: + shr ecx,1 ; shift divisor right one bit; hi bit <- 0 + rcr ebx,1 + shr edx,1 ; shift dividend right one bit; hi bit <- 0 + rcr eax,1 + or ecx,ecx + jnz short L3 ; loop until divisor < 4194304K + div ebx ; now divide, ignore remainder + +; +; We may be off by one, so to check, we will multiply the quotient +; by the divisor and check the result against the original dividend +; Note that we must also check for overflow, which can occur if the +; dividend is close to 2**64 and the quotient is off by 1. +; + + mov ecx,eax ; save a copy of quotient in ECX + mul dword ptr HIWORD(DVSR) + xchg ecx,eax ; put partial product in ECX, get quotient in EAX + mul dword ptr LOWORD(DVSR) + add edx,ecx ; EDX:EAX = QUOT * DVSR + jc short L4 ; carry means Quotient is off by 1 + +; +; do long compare here between original dividend and the result of the +; multiply in edx:eax. If original is larger or equal, we're ok, otherwise +; subtract the original divisor from the result. +; + + cmp edx,HIWORD(DVND) ; compare hi words of result and original + ja short L4 ; if result > original, do subtract + jb short L5 ; if result < original, we're ok + cmp eax,LOWORD(DVND) ; hi words are equal, compare lo words + jbe short L5 ; if less or equal we're ok, else subtract +L4: + sub eax,LOWORD(DVSR) ; subtract divisor from result + sbb edx,HIWORD(DVSR) +L5: + +; +; Calculate remainder by subtracting the result from the original dividend. +; Since the result is already in a register, we will perform the subtract in +; the opposite direction and negate the result to make it positive. +; + + sub eax,LOWORD(DVND) ; subtract original dividend from result + sbb edx,HIWORD(DVND) + neg edx ; and negate it + neg eax + sbb edx,0 + +; +; Just the cleanup left to do. dx:ax contains the remainder. +; Restore the saved registers and return. +; + +L2: + + pop ebx + + ret 16 + +_aullrem ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullshr.asm b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullshr.asm new file mode 100644 index 0000000000000000000000000000000000000000..a5125c2cbcc086fa85b8859a0c5117cab235d5d4 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/ullshr.asm @@ -0,0 +1,81 @@ + title ullshr - long shift right +;*** +;ullshr.asm - long shift right +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; define unsigned long shift right routine +; __aullshr +; +;******************************************************************************* + + +.xlist +include vcruntime.inc +include mm.inc +.list + +;*** +;ullshr - long shift right +; +;Purpose: +; Does a unsigned Long Shift Right +; Shifts a long right any number of bits. +; +;Entry: +; EDX:EAX - long value to be shifted +; CL - number of bits to shift by +; +;Exit: +; EDX:EAX - shifted value +; +;Uses: +; CL is destroyed. +; +;Exceptions: +; +;******************************************************************************* + + CODESEG + +_aullshr PROC NEAR +.FPO (0, 0, 0, 0, 0, 0) + +; +; Handle shifts of 64 bits or more (if shifting 64 bits or more, the result +; depends only on the high order bit of edx). +; + cmp cl,64 + jae short RETZERO + +; +; Handle shifts of between 0 and 31 bits +; + cmp cl, 32 + jae short MORE32 + shrd eax,edx,cl + shr edx,cl + ret + +; +; Handle shifts of between 32 and 63 bits +; +MORE32: + mov eax,edx + xor edx,edx + and cl,31 + shr eax,cl + ret + +; +; return 0 in edx:eax +; +RETZERO: + xor eax,eax + xor edx,edx + ret + +_aullshr ENDP + + end diff --git a/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/vcruntime.inc b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/vcruntime.inc new file mode 100644 index 0000000000000000000000000000000000000000..ea726cebeaba04ebd03aba43731edf94e475aad7 --- /dev/null +++ b/msvc/VC/Tools/MSVC/14.50.35717/crt/src/i386/vcruntime.inc @@ -0,0 +1,338 @@ +;*** +;vcruntime.inc - multi-model assembly macros for interfacing to HLLs +; +; Copyright (c) Microsoft Corporation. All rights reserved. +; +;Purpose: +; This file defines the current memory model being used. +; +;******************************************************************************* + +;============================================================================== +; +;Use the following defines to control processor/segment model +; +; default is -DI86 -Dmem_S +; +;============================================================================== +; +;The following variables are defined by this file: +; cpu 86, 286, or 386 +; mmodel english name of the memory model, i.e. "Medium" +; ISIZE, LSIZE, NSIZE size of ints, longs, shorts +; FLTSIZE, DBLSIZE, LDBLSIZE size of float, double, long double +; +;The following macros allow easy writing of combined 16/32 bit code: +; +; 16/32 bit registers: +; rax, rbx, rcx, rdx, expand to native registers (rax = eax or ax) +; rsi, rdi, rsp, rbp +; CBI convert byte to int (al to rax) +; Numeric type instructions: +; IWORD, LWORD, SWORD data type of int, long, short +; DFLOAT, DDOUBLE, DLDOUBLE define float, double, long double +; +;The following utility macros are provided: +; codeseg define/declare code segment +; error stop assembly with message +; display display a message, unless QUIET defined +; _if cond assemble instruction only if cond is TRUE +; _ife cond assemble instruction only if cond is FALSE +; _ifd symbol assemble instruction only if symbol defined +; _ifnd symbol assemble instruction only if symbol not defined +; +; lab LabelName assembles to "LabelName:" If DEBUG is defined +; LabelName is made public +; +; JS* (ex. JSE,JSZ,JSB ...) assemble to "je short","jz short","jb short" +; +; Cmacro look alikes +; static* Name, InitialValue, Repeat defines a static variable of type * +; global* Name, InitialValue, Repeat defines a global variable of type * +; label* Name, {PUBLIC,PASCAL,C} defines a label of type * +; +;============================================================================== + +; error - Output message and generate error + +error MACRO msg +if2 ;; only on pass 2 can we generate errors + %out ********************************************************** + %out *** E r r o r -- msg + %out ********************************************************** + .err +endif + ENDM + +; display msg - Output message unless QUIET defined + +display MACRO msg +ifndef QUIET ;; only when quiet flag not set +if1 ;; and on pass 1, then display message + %out msg +endif +endif + ENDM + +; One line conditionals: +; here we create the capability of writing code lines like +; +; _if sizeD as opposed to if sizeD +; push ds +; endif + +_if MACRO cond,text + if cond + text + endif + ENDM + +_ife MACRO cond,text + ife cond + text + endif + ENDM + +_ifd MACRO cond,text + ifdef cond + text + endif + ENDM + +_ifnd MACRO cond,text + ifndef cond + text + endif + ENDM + +; Process processor arguments + + .686 + +; Set memory model + + .model flat, C + +; Define registers: +; Instead of using the "word" registers directly, we will use a set of +; text equates. This will allow you to use the native word size instead of +; hard coded to 16 bit words. We also have some instruction equates for +; instruction with the register type hard coded in. + + rax equ + rbx equ + rcx equ + rdx equ + rdi equ + rsi equ + rbp equ + rsp equ + + CBI equ ; convert byte to int (al to rax) + +; The next set of equates deals with the size of SHORTS, INTS, LONGS, and +; pointers. + + ; parameters and locals + IWORD equ + + ; sizes for fixing SP, stepping through tables, etc. + ISIZE equ 4 + +; Float/double definitions +; (currently the same for 16- and 32-bit segments) + +FLTSIZE equ 4 ; float +DBLSIZE equ 8 ; double +LDBLSIZE equ 10 ; long double + +DFLOAT equ
+DDOUBLE equ +DLDOUBLE equ
+ +; codeseg - Define/declare the standard code segment. Maps to the proper +; form of the .code directive. +; +; Input: +; +; Output: +; .code _TEXT ; for large code models +; .code ; for small code models +; assume cs:FLAT ; for 386 +; assume ds:FLAT ; for 386 +; assume es:FLAT ; for 386 +; assume ss:FLAT ; for 386 +; + +codeseg MACRO + + .code + + assume ds:FLAT + assume es:FLAT + assume ss:FLAT + + ENDM + +; Define named constants for ISA levels. + +__ISA_AVAILABLE_X86 equ 0 +__ISA_AVAILABLE_SSE2 equ 1 +__ISA_AVAILABLE_SSE42 equ 2 +__ISA_AVAILABLE_AVX equ 3 +__ISA_AVAILABLE_ENFSTRG equ 4 +__ISA_AVAILABLE_AVX2 equ 5 +__ISA_AVAILABLE_AVX512 equ 6 + +; Define named constants for inverted ISA extension support bits + +__IA_SUPPORT_VECTOR128 equ 01h ; Vector lengths up to 128 bits supported (SSE2 if __avx10_version = 0) +__IA_SUPPORT_VECTOR256 equ 02h ; Vector lengths up to 256 bits supported (AVX2 if __avx10_version = 0) +__IA_SUPPORT_VECTOR512 equ 04h ; Vector lengths up to 512 bits supported (AVX-512 if __avx10_version = 0) +__IA_SUPPORT_AVX10 equ 08h ; AVX10 support +__IA_SUPPORT_SSE42 equ 10h ; SSE4.2 support (scalar and 128-bit) +__IA_SUPPORT_SV128X equ 20h ; AVX512 or AVX10.1 support (scalar and 128-bit) +__IA_SUPPORT_AVX10_2 equ 40h ; AVX10.2 support (scalar and 128-bit) +__IA_SUPPORT_APX equ 80h ; APX support +__IA_SUPPORT_FP16 equ 01000000h ; FP16 support + +; Define named constants for favor + +__FAVOR_ATOM equ 0 +__FAVOR_ENFSTRG equ 1 + +;*************************************************************** +;* +;* Debug lab macro +;* +;*************************************************************** + +lab macro name +ifdef DEBUG + public pascal name ;; define label public for Symdeb +endif +name: + endm + + +;*************************************************************** +;* +;* Conditional jump short macros +;* +;*************************************************************** + + + irp x, +JS&x equ + endm + + +;*************************************************************** +;* +;* Global data definition macros +;* +;* Usage: +;* globalI Name, InitialValue, Repeat +;* +;*************************************************************** + + +MakeGlobal macro suffix, DataType ;; makes all of the global* macros + +global&suffix macro name, data, rep +public name +ifb + _repeat = 1 +else + _repeat = (rep) +endif + +name &DataType _repeat dup( data ) + endm + + endm + + + MakeGlobal T, dt ; globalT + MakeGlobal Q, dq ; globalQ + MakeGlobal D, dd ; globalD + MakeGlobal W, dw ; globalW + MakeGlobal B, db ; globalB + +;*************************************************************** +;* +;* Static data definition macros +;* +;* Usage: +;* staticI Name, InitialValue, Repeat +;* +;*************************************************************** + + +MakeStatic macro suffix, DataType ;; makes all of the static* macros + +static&suffix macro name, data, rep + +ifdef DEBUG + public pascal name ;; make statics public if DEBUG +endif + +ifb + _repeat = 1 +else + _repeat = (rep) +endif + +name &DataType _repeat dup( data ) + endm + + endm + + + MakeStatic T, dt ; staticT + MakeStatic Q, dq ; staticQ + MakeStatic D, dd ; staticD + MakeStatic W, dw ; staticW + MakeStatic B, db ; staticB + +;*************************************************************** +;* +;* Label definition macros +;* +;* Usage: +;* labelI Name, {PUBLIC, PASCAL, C} +;* +;*************************************************************** + +__MakePublic macro name, option ;; decides if a label should be +ifidni