Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Agent.cpp +426 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.cpp +99 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.h +159 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Chores.cpp +376 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Context.cpp +180 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.cpp +1341 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.h +1147 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CurrentScheduler.cpp +236 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Exceptions.cpp +554 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.cpp +222 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.h +204 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.cpp +325 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.h +384 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.cpp +107 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.h +199 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.cpp +216 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.h +139 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.cpp +347 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.h +112 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.cpp +892 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.h +410 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.cpp +0 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.h +627 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Mailbox.h +591 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.cpp +921 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.h +206 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.cpp +28 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.h +73 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.cpp +0 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.h +826 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.cpp +870 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.h +654 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.cpp +0 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.h +1691 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerPolicyBase.cpp +437 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.cpp +1237 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.h +647 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.cpp +294 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.h +251 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.cpp +73 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.h +255 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.cpp +1659 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.h +767 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/StructuredWorkStealingQueue.h +414 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.cpp +379 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.h +200 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.cpp +0 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.h +241 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollectionBase.cpp +236 -0
- msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.cpp +23 -0
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Agent.cpp
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Agent.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing code for the agent creation APIs.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
#include <agents.h>
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
|
| 20 |
+
// A Filter function for a filter_block to check if the Agent has completed
|
| 21 |
+
bool _IsDone(agent_status const &status)
|
| 22 |
+
{
|
| 23 |
+
return status == agent_done || status == agent_canceled;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// A Filter function for a filter_block to check if the Agent has started (or completed)
|
| 27 |
+
bool _IsStarted(agent_status const &status)
|
| 28 |
+
{
|
| 29 |
+
return _IsDone(status) || status == agent_started;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
/// <summary>
|
| 33 |
+
/// Creates an agent within the default scheduler, and places it any schedule
|
| 34 |
+
/// group of the scheduler's choosing.
|
| 35 |
+
/// </summary>
|
| 36 |
+
agent::agent() :
|
| 37 |
+
_M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(NULL), _M_pScheduleGroup(NULL)
|
| 38 |
+
{
|
| 39 |
+
_Trace_agents(AGENTS_EVENT_CREATE,
|
| 40 |
+
details::_Trace_agents_get_id(this),
|
| 41 |
+
details::_Trace_agents_get_id(this));
|
| 42 |
+
|
| 43 |
+
send<agent_status> (_M_status, agent_created);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
/// <summary>
|
| 47 |
+
/// Create an agent within the specified scheduler, in a schedule group of the
|
| 48 |
+
/// scheduler's choosing.
|
| 49 |
+
/// </summary>
|
| 50 |
+
agent::agent(Scheduler& pScheduler) :
|
| 51 |
+
_M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(&pScheduler), _M_pScheduleGroup(NULL)
|
| 52 |
+
{
|
| 53 |
+
_Trace_agents(AGENTS_EVENT_CREATE,
|
| 54 |
+
details::_Trace_agents_get_id(this),
|
| 55 |
+
details::_Trace_agents_get_id(this));
|
| 56 |
+
|
| 57 |
+
send<agent_status> (_M_status, agent_created);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/// <summary>
|
| 61 |
+
/// Create an agent within the specified schedule group. The scheduler is implied
|
| 62 |
+
/// by the schedule group.
|
| 63 |
+
/// </summary>
|
| 64 |
+
agent::agent(ScheduleGroup& pGroup) :
|
| 65 |
+
_M_fStartable(TRUE), _M_fCancelable(TRUE), _M_pScheduler(NULL), _M_pScheduleGroup(&pGroup)
|
| 66 |
+
{
|
| 67 |
+
_Trace_agents(AGENTS_EVENT_CREATE,
|
| 68 |
+
details::_Trace_agents_get_id(this),
|
| 69 |
+
details::_Trace_agents_get_id(this));
|
| 70 |
+
|
| 71 |
+
send<agent_status> (_M_status, agent_created);
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/// <summary>
|
| 75 |
+
/// Cleans up any resources that may have been created by the Agent.
|
| 76 |
+
/// </summary>
|
| 77 |
+
agent::~agent()
|
| 78 |
+
{
|
| 79 |
+
_Trace_agents(AGENTS_EVENT_DESTROY, details::_Trace_agents_get_id(this));
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/// <returns>
|
| 83 |
+
/// Returns a message source that can pass messages about the current state of the agent
|
| 84 |
+
/// </returns>
|
| 85 |
+
ISource<agent_status> * agent::status_port()
|
| 86 |
+
{
|
| 87 |
+
return &_M_status;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
/// <returns>
|
| 91 |
+
/// Returns the current state of the agent. Note that this returned state could change
|
| 92 |
+
/// immediately after being returned.
|
| 93 |
+
/// </returns>
|
| 94 |
+
agent_status agent::status()
|
| 95 |
+
{
|
| 96 |
+
return receive<agent_status>(_M_status);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
/// <summary>
|
| 100 |
+
/// Moves an Agent from the agent_created state to the agent_runnable state, and schedules it for execution.
|
| 101 |
+
/// </summary>
|
| 102 |
+
/// <returns>
|
| 103 |
+
/// true if the agent started correctly, false otherwise
|
| 104 |
+
/// </returns>
|
| 105 |
+
bool agent::start()
|
| 106 |
+
{
|
| 107 |
+
if(_M_status.value() != agent_created)
|
| 108 |
+
{
|
| 109 |
+
return false;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
//
|
| 113 |
+
// Check if the agent is Startable. If the agent had already called start() or
|
| 114 |
+
// this variable was set to FALSE in cancel(), return false.
|
| 115 |
+
//
|
| 116 |
+
if(InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) == FALSE)
|
| 117 |
+
{
|
| 118 |
+
return false;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
_Trace_agents(AGENTS_EVENT_SCHEDULE, details::_Trace_agents_get_id(this));
|
| 122 |
+
send<agent_status> (_M_status, agent_runnable);
|
| 123 |
+
|
| 124 |
+
TaskProc proc = &Concurrency::agent::_Agent_task_wrapper;
|
| 125 |
+
if(_M_pScheduleGroup != NULL)
|
| 126 |
+
{
|
| 127 |
+
_M_pScheduleGroup->ScheduleTask(proc, this);
|
| 128 |
+
}
|
| 129 |
+
else if(_M_pScheduler != NULL)
|
| 130 |
+
{
|
| 131 |
+
_M_pScheduler->ScheduleTask(proc, this);
|
| 132 |
+
}
|
| 133 |
+
else
|
| 134 |
+
{
|
| 135 |
+
CurrentScheduler::ScheduleTask(proc, this);
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
return true;
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
/// <summary>
|
| 142 |
+
/// Moves an agent into the done state, indicating the completion of the agent
|
| 143 |
+
/// </summary>
|
| 144 |
+
/// <returns>
|
| 145 |
+
/// true if the agent is moved to the agent_done state, false otherwise
|
| 146 |
+
/// </returns>
|
| 147 |
+
bool agent::done()
|
| 148 |
+
{
|
| 149 |
+
//
|
| 150 |
+
// current status
|
| 151 |
+
//
|
| 152 |
+
agent_status currentStatus = this->status();
|
| 153 |
+
|
| 154 |
+
//
|
| 155 |
+
// Indicate that the agent can no longer be started.
|
| 156 |
+
//
|
| 157 |
+
if (InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) != TRUE)
|
| 158 |
+
{
|
| 159 |
+
//
|
| 160 |
+
// agent is either canceled, started or completed run.
|
| 161 |
+
//
|
| 162 |
+
currentStatus = receive<agent_status>(_M_status, _IsStarted);
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
//
|
| 166 |
+
// Agent is not cancelable anymore.
|
| 167 |
+
//
|
| 168 |
+
InterlockedExchange(&_M_fCancelable, FALSE);
|
| 169 |
+
|
| 170 |
+
//
|
| 171 |
+
// Transition to agent_done state if it not already in one of
|
| 172 |
+
// the terminal states.
|
| 173 |
+
//
|
| 174 |
+
if ((currentStatus != agent_canceled) && (currentStatus != agent_done))
|
| 175 |
+
{
|
| 176 |
+
send<agent_status> (_M_status, agent_done);
|
| 177 |
+
|
| 178 |
+
return true;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
return false;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
/// <summary>
|
| 185 |
+
/// Moves an agent from the agent_created or agent_runnable to the agent_canceled state.
|
| 186 |
+
/// </summary>
|
| 187 |
+
/// <returns>
|
| 188 |
+
/// true if the agent was canceled correctly, false otherwise
|
| 189 |
+
/// </returns>
|
| 190 |
+
bool agent::cancel()
|
| 191 |
+
{
|
| 192 |
+
//
|
| 193 |
+
// In case this agent has been canceled before it was even started
|
| 194 |
+
// mark it as no longer Startable and send a agent_canceled message to the
|
| 195 |
+
// status port
|
| 196 |
+
//
|
| 197 |
+
if(InterlockedCompareExchange(&_M_fStartable, FALSE, TRUE) == TRUE)
|
| 198 |
+
{
|
| 199 |
+
send<agent_status> (_M_status, agent_canceled);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
//
|
| 203 |
+
// Check to see if the agent is still Cancelable. Agents are initialized
|
| 204 |
+
// m_fCancelable == TRUE, and set to false either here in cancel(), so
|
| 205 |
+
// cancel() will not be called twice, or in the LWT, once the execution
|
| 206 |
+
// of the Agent task has begun.
|
| 207 |
+
//
|
| 208 |
+
if(InterlockedCompareExchange(&_M_fCancelable, FALSE, TRUE) == TRUE)
|
| 209 |
+
{
|
| 210 |
+
// Wait for the agent to reach a canceled state state
|
| 211 |
+
receive<agent_status>(_M_status, _IsDone);
|
| 212 |
+
|
| 213 |
+
// The above InterlockedCompareExchange marked this agent for cancellation
|
| 214 |
+
// When the LWT that has been spun up tries to execute the task, it will
|
| 215 |
+
// find it has been canceled and will propagate out the canceled state to
|
| 216 |
+
// the state buffer.
|
| 217 |
+
return true;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
return false;
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
// Private helper class to order an input array of agents. This is used by
|
| 225 |
+
// wait_for_all and wait_for_one to create an array of appropriate order nodes.
|
| 226 |
+
// The template _OrderNode specifies an _Order_node_base that accepts agent_status.
|
| 227 |
+
// For example, _Reserving_node<agent_status>
|
| 228 |
+
template<class _OrderNode>
|
| 229 |
+
class _OrderBlock
|
| 230 |
+
{
|
| 231 |
+
public:
|
| 232 |
+
|
| 233 |
+
// Constructs an orderBlock which has an array of ordernodes connected to the agents.
|
| 234 |
+
// The ordernodes are given a filter method to filter out non-terminal agent states
|
| 235 |
+
_OrderBlock(size_t _Count, agent ** _PAgents, ITarget<size_t> * _PTarget) : _M_count(_Count)
|
| 236 |
+
{
|
| 237 |
+
// Create an array of order nodes
|
| 238 |
+
_M_ppNodes = _concrt_new _OrderNode*[_M_count];
|
| 239 |
+
for (size_t i = 0; i < _M_count; i++)
|
| 240 |
+
{
|
| 241 |
+
_M_ppNodes[i] = _concrt_new _OrderNode(_PAgents[i]->status_port(), i, _PTarget, _IsDone);
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
// Destroys the block
|
| 246 |
+
~_OrderBlock()
|
| 247 |
+
{
|
| 248 |
+
for (size_t i = 0; i < _M_count; i++)
|
| 249 |
+
{
|
| 250 |
+
delete _M_ppNodes[i];
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
delete [] _M_ppNodes;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// Retrieve the agent status for the agent at the given index
|
| 257 |
+
agent_status _Status(size_t _Index)
|
| 258 |
+
{
|
| 259 |
+
_CONCRT_ASSERT(_M_ppNodes[_Index]->has_value());
|
| 260 |
+
|
| 261 |
+
return _M_ppNodes[_Index]->value();
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
private:
|
| 265 |
+
|
| 266 |
+
// Number of order nodes
|
| 267 |
+
size_t _M_count;
|
| 268 |
+
|
| 269 |
+
// Array of order nodes
|
| 270 |
+
_OrderNode ** _M_ppNodes;
|
| 271 |
+
};
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
/// <summary>
|
| 275 |
+
/// Wait for an agent to complete its task. A task is completed when it enters the agent_canceled,
|
| 276 |
+
/// or agent_done states.
|
| 277 |
+
/// </summary>
|
| 278 |
+
agent_status agent::wait(_Inout_ agent * pAgent, unsigned int timeout)
|
| 279 |
+
{
|
| 280 |
+
if(pAgent == NULL)
|
| 281 |
+
{
|
| 282 |
+
throw std::invalid_argument("pAgent");
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
return receive<agent_status>(pAgent->status_port(), _IsDone, timeout);
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/// <summary>
|
| 289 |
+
/// Wait for all agents in a given Agent array to complete their tasks. A task is completed
|
| 290 |
+
/// when it enters the agent_canceled or agent_done states.
|
| 291 |
+
/// </summary>
|
| 292 |
+
void agent::wait_for_all(size_t count, _In_reads_(count) agent ** pAgents, _Out_writes_opt_(count) agent_status * pStatus, unsigned int timeout)
|
| 293 |
+
{
|
| 294 |
+
if ( pAgents == NULL )
|
| 295 |
+
{
|
| 296 |
+
throw std::invalid_argument("pAgents");
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
for (size_t i = 0; i < count; i++)
|
| 300 |
+
{
|
| 301 |
+
if ( pAgents[i] == NULL )
|
| 302 |
+
{
|
| 303 |
+
throw std::invalid_argument("pAgents");
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
// Create the following network
|
| 308 |
+
//
|
| 309 |
+
// agent - orderNode -
|
| 310 |
+
// \
|
| 311 |
+
// agent - orderNode - --call ~~~ single_assignment
|
| 312 |
+
// /
|
| 313 |
+
// agent - orderNode -
|
| 314 |
+
|
| 315 |
+
single_assignment<size_t> _Sa;
|
| 316 |
+
volatile size_t _CompletedAgents = 0;
|
| 317 |
+
call<size_t> _Call([&](size_t const&)
|
| 318 |
+
{
|
| 319 |
+
// Safe to access without synchronization since call blocks
|
| 320 |
+
// guarantee that the function is not called for multiple
|
| 321 |
+
// messages at the same time.
|
| 322 |
+
_CONCRT_ASSERT(_CompletedAgents < count);
|
| 323 |
+
size_t value = _CompletedAgents;
|
| 324 |
+
_CompletedAgents = ++value;
|
| 325 |
+
if (_CompletedAgents == count)
|
| 326 |
+
{
|
| 327 |
+
// All the agents have completed. Indicate the same by sending a message
|
| 328 |
+
// (initialize) to the single assignment.
|
| 329 |
+
send<size_t>(_Sa, 1);
|
| 330 |
+
}
|
| 331 |
+
});
|
| 332 |
+
|
| 333 |
+
_OrderBlock<_Greedy_node<agent_status>> _OrderedAgents(count, pAgents, &_Call);
|
| 334 |
+
|
| 335 |
+
receive(&_Sa, timeout);
|
| 336 |
+
|
| 337 |
+
// single_assignment has a message => all agents completed
|
| 338 |
+
// Retrieve their status messages.
|
| 339 |
+
if(pStatus != NULL)
|
| 340 |
+
{
|
| 341 |
+
for (size_t i = 0; i < count; i++)
|
| 342 |
+
{
|
| 343 |
+
pStatus[i] = _OrderedAgents._Status(i);
|
| 344 |
+
}
|
| 345 |
+
}
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
/// <summary>
|
| 349 |
+
/// Wait for any one of the agents in a given AgentTask array to complete its task. A task is completed
|
| 350 |
+
/// when it enters the agent_canceled or agent_done states.
|
| 351 |
+
/// </summary>
|
| 352 |
+
void agent::wait_for_one(size_t count, _In_reads_(count) agent ** pAgents, agent_status &status, size_t& index, unsigned int timeout)
|
| 353 |
+
{
|
| 354 |
+
if ( pAgents == NULL )
|
| 355 |
+
{
|
| 356 |
+
throw std::invalid_argument("pAgents");
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
for (size_t i = 0; i < count; i++)
|
| 360 |
+
{
|
| 361 |
+
if ( pAgents[i] == NULL )
|
| 362 |
+
{
|
| 363 |
+
throw std::invalid_argument("pAgents");
|
| 364 |
+
}
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
// Create the following network
|
| 368 |
+
//
|
| 369 |
+
// agent - orderNode -
|
| 370 |
+
// \
|
| 371 |
+
// agent - orderNode - --single_assignment
|
| 372 |
+
// /
|
| 373 |
+
// agent - orderNode -
|
| 374 |
+
|
| 375 |
+
single_assignment<size_t> _Sa;
|
| 376 |
+
_OrderBlock<_Greedy_node<agent_status>> _OrderedAgents(count, pAgents, &_Sa);
|
| 377 |
+
|
| 378 |
+
index = receive(&_Sa, timeout);
|
| 379 |
+
|
| 380 |
+
// We were able to receive the index. Get the message (agent_status)
|
| 381 |
+
status = _OrderedAgents._Status(index);
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
// A static wrapper function that calls the Run() method. Used for scheduling of the task
|
| 385 |
+
void agent::_Agent_task_wrapper(void* data)
|
| 386 |
+
{
|
| 387 |
+
agent *pAgent = (agent *) data;
|
| 388 |
+
|
| 389 |
+
if(InterlockedCompareExchange(&pAgent->_M_fCancelable, FALSE, TRUE) == TRUE)
|
| 390 |
+
{
|
| 391 |
+
send<agent_status> (pAgent->_M_status, agent_started);
|
| 392 |
+
|
| 393 |
+
// Invoke the run() function of the agent.
|
| 394 |
+
_Trace_agents(AGENTS_EVENT_START, details::_Trace_agents_get_id(pAgent));
|
| 395 |
+
pAgent->run();
|
| 396 |
+
_Trace_agents(AGENTS_EVENT_END, details::_Trace_agents_get_id(pAgent), 0);
|
| 397 |
+
}
|
| 398 |
+
else
|
| 399 |
+
{
|
| 400 |
+
// This else path can be entered only if an agent was canceled before it
|
| 401 |
+
// ran. Send a agent_canceled message to the status.
|
| 402 |
+
send<agent_status> (pAgent->_M_status, agent_canceled);
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
// Implementation of agent APIs that should not be publicly exposed
|
| 407 |
+
|
| 408 |
+
namespace details
|
| 409 |
+
{
|
| 410 |
+
static volatile runtime_object_identity s_RuntimeObjectIdentity = 0;
|
| 411 |
+
|
| 412 |
+
_CONCRTIMP _Runtime_object::_Runtime_object()
|
| 413 |
+
{
|
| 414 |
+
// Increment the id by 2. This is done because certain blocks (like join) need to have
|
| 415 |
+
// a special message id to indicate a NULL id. In this case, we use -1. Incrementing by 2
|
| 416 |
+
// will avoid any wrap-around issues causing us to hit -1.
|
| 417 |
+
runtime_object_identity id = InterlockedExchangeAdd((volatile long *) &s_RuntimeObjectIdentity, 2);
|
| 418 |
+
_CONCRT_ASSERT(id != -1);
|
| 419 |
+
_M_id = id;
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
_CONCRTIMP _Runtime_object::_Runtime_object(runtime_object_identity _Id) : _M_id(_Id)
|
| 423 |
+
{
|
| 424 |
+
}
|
| 425 |
+
} // namespace details
|
| 426 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.cpp
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// CacheLocalScheduleGroup.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation file for CacheLocalScheduleGroup.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Puts a runnable context into the runnables collection in the schedule group.
|
| 22 |
+
/// </summary>
|
| 23 |
+
void CacheLocalScheduleGroupSegment::AddToRunnablesCollection(InternalContextBase* pContext)
|
| 24 |
+
{
|
| 25 |
+
m_runnableContexts.Enqueue(pContext);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/// <summary>
|
| 29 |
+
/// Places a chore in the mailbox associated with this schedule group segment.
|
| 30 |
+
/// </summary>
|
| 31 |
+
/// <param name="pChore">
|
| 32 |
+
/// The chore to mail.
|
| 33 |
+
/// </param>
|
| 34 |
+
/// <returns>
|
| 35 |
+
/// The mailbox slot into which the chore was placed.
|
| 36 |
+
/// </returns>
|
| 37 |
+
/// <remarks>
|
| 38 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 39 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 40 |
+
/// </remarks>
|
| 41 |
+
Mailbox<_UnrealizedChore>::Slot CacheLocalScheduleGroupSegment::MailChore(_UnrealizedChore *pChore)
|
| 42 |
+
{
|
| 43 |
+
//
|
| 44 |
+
// 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
|
| 45 |
+
// 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
|
| 46 |
+
// issues. It will be attributed to the group it was picked up from which will further honor that affinity if the task blocks, etc...
|
| 47 |
+
//
|
| 48 |
+
ASSERT(!m_affinity._Is_system());
|
| 49 |
+
Mailbox<_UnrealizedChore>::Slot affinitySlot = m_mailedTasks.Enqueue(pChore);
|
| 50 |
+
|
| 51 |
+
ASSERT(!affinitySlot.IsEmpty());
|
| 52 |
+
return affinitySlot;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/// <summary>
|
| 56 |
+
/// Notifies virtual processors that work affinitized to them has become available in the schedule group segment.
|
| 57 |
+
/// </summary>
|
| 58 |
+
void CacheLocalScheduleGroupSegment::NotifyAffinitizedWork()
|
| 59 |
+
{
|
| 60 |
+
SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler();
|
| 61 |
+
pScheduler->PostAffinityMessage(m_affinitySet);
|
| 62 |
+
|
| 63 |
+
//
|
| 64 |
+
// If this item qualifies for the quick cache, stash it.
|
| 65 |
+
//
|
| 66 |
+
if (m_affinity._GetType() == location::_ExecutionResource)
|
| 67 |
+
{
|
| 68 |
+
pScheduler->SetQuickCacheSlot(m_maskIdIf, this);
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/// <summary>
|
| 73 |
+
/// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified
|
| 74 |
+
/// location.
|
| 75 |
+
/// </summary>
|
| 76 |
+
/// <param name="pChore">
|
| 77 |
+
/// The chore to mail.
|
| 78 |
+
/// </param>
|
| 79 |
+
/// <param name="pPlacement">
|
| 80 |
+
/// A pointer to a location where the chore will be mailed.
|
| 81 |
+
/// </param>
|
| 82 |
+
/// <returns>
|
| 83 |
+
/// The mailbox slot into which the chore was placed.
|
| 84 |
+
/// </returns>
|
| 85 |
+
/// <remarks>
|
| 86 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 87 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 88 |
+
/// </remarks>
|
| 89 |
+
Mailbox<_UnrealizedChore>::Slot CacheLocalScheduleGroup::MailChore(_UnrealizedChore * pChore,
|
| 90 |
+
location * pPlacement,
|
| 91 |
+
ScheduleGroupSegmentBase ** ppDestinationSegment)
|
| 92 |
+
{
|
| 93 |
+
CacheLocalScheduleGroupSegment * pCacheLocalSegment = static_cast<CacheLocalScheduleGroupSegment *>(LocateSegment(pPlacement, true));
|
| 94 |
+
*ppDestinationSegment = pCacheLocalSegment;
|
| 95 |
+
return pCacheLocalSegment->MailChore(pChore);
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
} // namespace details
|
| 99 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CacheLocalScheduleGroup.h
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// CacheLocalScheduleGroup.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing CacheLocalScheduleGroup related declarations.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
|
| 21 |
+
class CacheLocalScheduleGroup;
|
| 22 |
+
|
| 23 |
+
class CacheLocalScheduleGroupSegment : public ScheduleGroupSegmentBase
|
| 24 |
+
{
|
| 25 |
+
|
| 26 |
+
public:
|
| 27 |
+
|
| 28 |
+
//
|
| 29 |
+
// Public Methods
|
| 30 |
+
//
|
| 31 |
+
|
| 32 |
+
/// <summary>
|
| 33 |
+
/// Constructs a cache local schedule group segment
|
| 34 |
+
/// </summary>
|
| 35 |
+
CacheLocalScheduleGroupSegment(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) :
|
| 36 |
+
ScheduleGroupSegmentBase(pOwningGroup, pOwningRing, pSegmentAffinity)
|
| 37 |
+
{
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/// <summary>
|
| 41 |
+
/// Places a chore in the mailbox associated with this schedule group segment.
|
| 42 |
+
/// </summary>
|
| 43 |
+
/// <param name="pChore">
|
| 44 |
+
/// The chore to mail.
|
| 45 |
+
/// </param>
|
| 46 |
+
/// <returns>
|
| 47 |
+
/// The mailbox slot into which the chore was placed.
|
| 48 |
+
/// </returns>
|
| 49 |
+
/// <remarks>
|
| 50 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 51 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 52 |
+
/// </remarks>
|
| 53 |
+
Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore *pChore);
|
| 54 |
+
|
| 55 |
+
/// <summary>
|
| 56 |
+
/// Notifies virtual processors that work affinitized to them has become available in the schedule group segment.
|
| 57 |
+
/// </summary>
|
| 58 |
+
virtual void NotifyAffinitizedWork();
|
| 59 |
+
|
| 60 |
+
protected:
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
private:
|
| 64 |
+
friend class SchedulerBase;
|
| 65 |
+
friend class CacheLocalScheduleGroup;
|
| 66 |
+
friend class ContextBase;
|
| 67 |
+
friend class ExternalContextBase;
|
| 68 |
+
friend class InternalContextBase;
|
| 69 |
+
friend class ThreadInternalContext;
|
| 70 |
+
friend class SchedulingNode;
|
| 71 |
+
friend class SchedulingRing;
|
| 72 |
+
friend class VirtualProcessor;
|
| 73 |
+
|
| 74 |
+
//
|
| 75 |
+
// Private data
|
| 76 |
+
//
|
| 77 |
+
|
| 78 |
+
// Each schedule group has three stores of work. It has a collection of runnable contexts,
|
| 79 |
+
// a FIFO queue of realized chores and a list of workqueues that hold unrealized chores.
|
| 80 |
+
|
| 81 |
+
// A collection of Runnable contexts.
|
| 82 |
+
SafeSQueue<InternalContextBase, _HyperNonReentrantLock> m_runnableContexts;
|
| 83 |
+
|
| 84 |
+
//
|
| 85 |
+
// Private methods
|
| 86 |
+
//
|
| 87 |
+
|
| 88 |
+
/// <summary>
|
| 89 |
+
/// Puts a runnable context into the runnables collection in the schedule group.
|
| 90 |
+
/// </summary>
|
| 91 |
+
void AddToRunnablesCollection(InternalContextBase *pContext);
|
| 92 |
+
|
| 93 |
+
InternalContextBase *GetRunnableContext()
|
| 94 |
+
{
|
| 95 |
+
if (m_runnableContexts.Empty())
|
| 96 |
+
return NULL;
|
| 97 |
+
|
| 98 |
+
InternalContextBase *pContext = m_runnableContexts.Dequeue();
|
| 99 |
+
#if defined(_DEBUG)
|
| 100 |
+
SetContextDebugBits(pContext, CTX_DEBUGBIT_REMOVEDFROMRUNNABLES);
|
| 101 |
+
#endif // _DEBUG
|
| 102 |
+
return pContext;
|
| 103 |
+
}
|
| 104 |
+
};
|
| 105 |
+
|
| 106 |
+
class CacheLocalScheduleGroup : public ScheduleGroupBase
|
| 107 |
+
{
|
| 108 |
+
public:
|
| 109 |
+
|
| 110 |
+
/// <summary>
|
| 111 |
+
/// Constructs a new cache local schedule group.
|
| 112 |
+
/// </summary>
|
| 113 |
+
CacheLocalScheduleGroup(SchedulerBase *pScheduler, location* pGroupPlacement) :
|
| 114 |
+
ScheduleGroupBase(pScheduler, pGroupPlacement)
|
| 115 |
+
{
|
| 116 |
+
m_kind = CacheLocalScheduling;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/// <summary>
|
| 120 |
+
/// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified
|
| 121 |
+
/// location.
|
| 122 |
+
/// </summary>
|
| 123 |
+
/// <param name="pChore">
|
| 124 |
+
/// The chore to mail.
|
| 125 |
+
/// </param>
|
| 126 |
+
/// <param name="pPlacement">
|
| 127 |
+
/// A pointer to a location where the chore will be mailed.
|
| 128 |
+
/// </param>
|
| 129 |
+
/// <returns>
|
| 130 |
+
/// The mailbox slot into which the chore was placed.
|
| 131 |
+
/// </returns>
|
| 132 |
+
/// <remarks>
|
| 133 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 134 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 135 |
+
/// </remarks>
|
| 136 |
+
virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore,
|
| 137 |
+
location * pPlacement,
|
| 138 |
+
ScheduleGroupSegmentBase ** ppDestinationSegment);
|
| 139 |
+
protected:
|
| 140 |
+
|
| 141 |
+
/// <summary>
|
| 142 |
+
/// Allocates a new cache local schedule group segment within the specified group and ring with the specified affinity.
|
| 143 |
+
/// </summary>
|
| 144 |
+
/// <param name="pSegmentAffinity">
|
| 145 |
+
/// The affinity for the segment.
|
| 146 |
+
/// </param>
|
| 147 |
+
/// <param name="pOwningRing">
|
| 148 |
+
/// The scheduling ring to which the newly allocated segment will belong.
|
| 149 |
+
/// </param>
|
| 150 |
+
/// <returns>
|
| 151 |
+
/// A new cache local schedule group within the specified group and ring with the specified affinity.
|
| 152 |
+
/// </returns>
|
| 153 |
+
virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity)
|
| 154 |
+
{
|
| 155 |
+
return _concrt_new CacheLocalScheduleGroupSegment(this, pOwningRing, pSegmentAffinity);
|
| 156 |
+
}
|
| 157 |
+
};
|
| 158 |
+
} // namespace details
|
| 159 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Chores.cpp
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Chores.cpp
|
| 9 |
+
//
|
| 10 |
+
// Miscellaneous implementations of things related to individuals chores
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Sets the attachment state of the chore at the time of stealing.
|
| 22 |
+
/// </summary>
|
| 23 |
+
void _UnrealizedChore::_SetDetached(bool _FDetached)
|
| 24 |
+
{
|
| 25 |
+
_M_fDetached = _FDetached;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/// <summary>
|
| 29 |
+
/// To free memory allocated with _InternalAlloc.
|
| 30 |
+
/// </summary>
|
| 31 |
+
void _UnrealizedChore::_InternalFree(_UnrealizedChore * _PChore)
|
| 32 |
+
{
|
| 33 |
+
ASSERT(_PChore->_M_fRuntimeOwnsLifetime);
|
| 34 |
+
delete _PChore;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/// <summary>
|
| 38 |
+
/// Place associated task collection in a safe state.
|
| 39 |
+
/// </summary>
|
| 40 |
+
void _UnrealizedChore::_CheckTaskCollection()
|
| 41 |
+
{
|
| 42 |
+
//
|
| 43 |
+
// If _M_pTaskCollection is non-NULL, the chore is still scheduled to a task collection. This is only happening
|
| 44 |
+
// from a handle destructor and we have blown back through a stack based handle while it's still scheduled. We must
|
| 45 |
+
// wait. The semantic we choose is that this means cancellation too.
|
| 46 |
+
//
|
| 47 |
+
Concurrency::details::_TaskCollectionBase *pBase = _M_pTaskCollection;
|
| 48 |
+
if (pBase != NULL)
|
| 49 |
+
{
|
| 50 |
+
bool fThrow = false;
|
| 51 |
+
|
| 52 |
+
if (_M_pChoreFunction == &_UnrealizedChore::_StructuredChoreWrapper)
|
| 53 |
+
{
|
| 54 |
+
_StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *>(pBase);
|
| 55 |
+
fThrow = !pTaskCollection->_TaskCleanup();
|
| 56 |
+
}
|
| 57 |
+
else
|
| 58 |
+
{
|
| 59 |
+
_TaskCollection *pTaskCollection = static_cast<_TaskCollection *>(pBase);
|
| 60 |
+
fThrow = !pTaskCollection->_TaskCleanup(true);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
if (fThrow)
|
| 64 |
+
throw missing_wait();
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
/// <summary>
|
| 69 |
+
/// Prepares for execution as a stolen chore.
|
| 70 |
+
/// </summary>
|
| 71 |
+
void _UnrealizedChore::_PrepareSteal(ContextBase *pContext)
|
| 72 |
+
{
|
| 73 |
+
if (_M_pChoreFunction == &_UnrealizedChore::_StructuredChoreWrapper)
|
| 74 |
+
{
|
| 75 |
+
_PrepareStealStructured(pContext);
|
| 76 |
+
}
|
| 77 |
+
else
|
| 78 |
+
{
|
| 79 |
+
_PrepareStealUnstructured(pContext);
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
/// <summary>
|
| 84 |
+
/// Called when a stolen chore from a given cancellation token is canceled.
|
| 85 |
+
/// </summary>
|
| 86 |
+
void _UnrealizedChore::_CancelViaToken(ContextBase *pContext)
|
| 87 |
+
{
|
| 88 |
+
pContext->CancelEntireContext();
|
| 89 |
+
pContext->CancelStealers(NULL);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Prepares for execution as a stolen chore.
|
| 94 |
+
/// </summary>
|
| 95 |
+
void _UnrealizedChore::_PrepareStealStructured(ContextBase *pBaseContext)
|
| 96 |
+
{
|
| 97 |
+
InternalContextBase *pContext = static_cast<InternalContextBase *> (pBaseContext);
|
| 98 |
+
|
| 99 |
+
if (pContext->GetRootCollection() == NULL)
|
| 100 |
+
{
|
| 101 |
+
_StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *> (_M_pTaskCollection);
|
| 102 |
+
ContextBase *pOriginContext = reinterpret_cast <ContextBase *> (pTaskCollection->_M_pOwningContext);
|
| 103 |
+
|
| 104 |
+
pContext->SetRootCollection(pTaskCollection);
|
| 105 |
+
|
| 106 |
+
pOriginContext->AddStealer(pContext, false);
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/// <summary>
|
| 111 |
+
/// Wrapper around execution of a structured chore that performs appropriate notification
|
| 112 |
+
/// and exception handling semantics.
|
| 113 |
+
/// </summary>
|
| 114 |
+
__declspec(noinline)
|
| 115 |
+
void __cdecl _UnrealizedChore::_StructuredChoreWrapper(_UnrealizedChore * pChore)
|
| 116 |
+
{
|
| 117 |
+
InternalContextBase *pContext = static_cast<InternalContextBase *> (SchedulerBase::FastCurrentContext());
|
| 118 |
+
// The context could be canceled if it was already prepared for steal (this happens during a block unblock race)
|
| 119 |
+
ASSERT(pContext != NULL && (!pContext->HasInlineCancellation() || pContext->GetRootCollection() != NULL));
|
| 120 |
+
|
| 121 |
+
_StructuredTaskCollection *pTaskCollection = static_cast<_StructuredTaskCollection *> (pChore->_M_pTaskCollection);
|
| 122 |
+
ContextBase *pOriginContext = reinterpret_cast <ContextBase *> (pTaskCollection->_M_pOwningContext);
|
| 123 |
+
|
| 124 |
+
pChore->_PrepareStealStructured(pContext);
|
| 125 |
+
|
| 126 |
+
//
|
| 127 |
+
// This allows cancellation of stolen chores based on a cancellation token between the declaration of a stg and its inlining.
|
| 128 |
+
//
|
| 129 |
+
_CancellationTokenState *pTokenState = pTaskCollection->_GetTokenState();
|
| 130 |
+
_CancellationTokenRegistration *pRegistration = NULL;
|
| 131 |
+
|
| 132 |
+
if (_CancellationTokenState::_IsValid(pTokenState))
|
| 133 |
+
{
|
| 134 |
+
pRegistration = pTokenState->_RegisterCallback(reinterpret_cast<TaskProc>(&_UnrealizedChore::_CancelViaToken), (ContextBase *)pContext);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
try
|
| 138 |
+
{
|
| 139 |
+
//
|
| 140 |
+
// We need to consider this a possible interruption point. It's entirely possible that we stole and raced with a
|
| 141 |
+
// cancellation thread. The collection was canceled after we stole(e.g.: removed from the WSQ) but before we added ourselves
|
| 142 |
+
// to the stealing chain list above. In this case, the entire context will wait until completion (bad). Immediately
|
| 143 |
+
// after we go on the list (a memory barrier) we need to check the collection cancellation flag. If the collection is going away,
|
| 144 |
+
// we need to get out *NOW* otherwise the entire subtree executes.
|
| 145 |
+
//
|
| 146 |
+
if (pTaskCollection->_IsAbnormalExit())
|
| 147 |
+
throw _Interruption_exception();
|
| 148 |
+
|
| 149 |
+
pChore->m_pFunction(pChore);
|
| 150 |
+
}
|
| 151 |
+
catch(const _Interruption_exception &)
|
| 152 |
+
{
|
| 153 |
+
//
|
| 154 |
+
// If someone manually threw the _Interruption_exception exception, we will have a cancel count but not a canceled context. This
|
| 155 |
+
// means we need to apply the cancel one level up. Normally, the act of throwing would do that via being caught in the
|
| 156 |
+
// wait, but this is special "marshaling" for _Interruption_exception.
|
| 157 |
+
//
|
| 158 |
+
if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled())
|
| 159 |
+
pTaskCollection->_Cancel();
|
| 160 |
+
}
|
| 161 |
+
catch(...)
|
| 162 |
+
{
|
| 163 |
+
//
|
| 164 |
+
// Track the exception that was thrown here. _RaisedException makes the decision on what
|
| 165 |
+
// exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow.
|
| 166 |
+
//
|
| 167 |
+
pTaskCollection->_RaisedException();
|
| 168 |
+
pTaskCollection->_Cancel();
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
pOriginContext->RemoveStealer(pContext);
|
| 172 |
+
ASSERT(pContext->GetGoverningTokenState() == NULL);
|
| 173 |
+
|
| 174 |
+
//
|
| 175 |
+
// This allows cancellation of stolen chores based on a cancellation token between the declaration of a stg and its inlining.
|
| 176 |
+
//
|
| 177 |
+
if (pRegistration != NULL)
|
| 178 |
+
{
|
| 179 |
+
ASSERT(pTokenState != NULL);
|
| 180 |
+
pTokenState->_DeregisterCallback(pRegistration);
|
| 181 |
+
pRegistration->_Release();
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
pContext->ClearCancel();
|
| 185 |
+
pContext->SetRootCollection(NULL);
|
| 186 |
+
pChore->_M_pTaskCollection = NULL;
|
| 187 |
+
pTaskCollection->_CountUp();
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// Prepares for execution as a stolen chore.
|
| 192 |
+
/// </summary>
|
| 193 |
+
void _UnrealizedChore::_PrepareStealUnstructured(ContextBase *pBaseContext)
|
| 194 |
+
{
|
| 195 |
+
InternalContextBase *pContext = static_cast<InternalContextBase *> (pBaseContext);
|
| 196 |
+
|
| 197 |
+
if (pContext->GetRootCollection() == NULL)
|
| 198 |
+
{
|
| 199 |
+
_TaskCollection* pTaskCollection = static_cast<_TaskCollection *> (_M_pTaskCollection);
|
| 200 |
+
ContextBase *pOriginContext = reinterpret_cast <ContextBase *> (pTaskCollection->_M_pOwningContext);
|
| 201 |
+
|
| 202 |
+
pContext->SetRootCollection(pTaskCollection);
|
| 203 |
+
|
| 204 |
+
//
|
| 205 |
+
// pOriginContext is only safe to touch if the act of stealing from a non-detached context put a hold on that context
|
| 206 |
+
// to block deletion until we are chained for cancellation.
|
| 207 |
+
//
|
| 208 |
+
SafeRWList<ListEntry> *pList = reinterpret_cast<SafeRWList<ListEntry> *> (pTaskCollection->_M_stealTracker);
|
| 209 |
+
ASSERT(sizeof(pTaskCollection->_M_stealTracker) >= sizeof(*pList));
|
| 210 |
+
|
| 211 |
+
if (_M_fDetached)
|
| 212 |
+
{
|
| 213 |
+
//
|
| 214 |
+
// We cannot touch the owning context -- it was detached as of the steal. The chain goes onto the task collection.
|
| 215 |
+
//
|
| 216 |
+
pContext->NotifyTaskCollectionChainedStealer();
|
| 217 |
+
pList->AddTail(&(pContext->m_stealChain));
|
| 218 |
+
}
|
| 219 |
+
else
|
| 220 |
+
{
|
| 221 |
+
pList->AcquireWrite();
|
| 222 |
+
pTaskCollection->_M_activeStealersForCancellation++;
|
| 223 |
+
pList->ReleaseWrite();
|
| 224 |
+
pOriginContext->AddStealer(pContext, true);
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// <summary>
|
| 230 |
+
/// Wrapper around execution of an unstructured chore that performs appropriate notification
|
| 231 |
+
/// and exception handling semantics.
|
| 232 |
+
/// </summary>
|
| 233 |
+
__declspec(noinline)
|
| 234 |
+
void __cdecl _UnrealizedChore::_UnstructuredChoreWrapper(_UnrealizedChore * pChore)
|
| 235 |
+
{
|
| 236 |
+
InternalContextBase *pContext = static_cast<InternalContextBase *> (SchedulerBase::FastCurrentContext());
|
| 237 |
+
// The context could be canceled if it was already prepared for steal (this happens during a block unblock race)
|
| 238 |
+
ASSERT(pContext != NULL && (!pContext->HasInlineCancellation() || pContext->GetRootCollection() != NULL));
|
| 239 |
+
|
| 240 |
+
_TaskCollection* pTaskCollection = static_cast<_TaskCollection *> (pChore->_M_pTaskCollection);
|
| 241 |
+
|
| 242 |
+
//
|
| 243 |
+
// pOriginContext is only safe to touch if the act of stealing from a non-detached context put a hold on that context
|
| 244 |
+
// to block deletion until we are chained for cancellation.
|
| 245 |
+
//
|
| 246 |
+
ContextBase *pOriginContext = reinterpret_cast <ContextBase *> (pTaskCollection->_M_pOwningContext);
|
| 247 |
+
SafeRWList<ListEntry> *pList = reinterpret_cast<SafeRWList<ListEntry> *> (pTaskCollection->_M_stealTracker);
|
| 248 |
+
|
| 249 |
+
pChore->_PrepareStealUnstructured(pContext);
|
| 250 |
+
|
| 251 |
+
_CancellationTokenState *pTokenState = pTaskCollection->_GetTokenState();
|
| 252 |
+
_CancellationTokenRegistration *pRegistration = NULL;
|
| 253 |
+
if (_CancellationTokenState::_IsValid(pTokenState))
|
| 254 |
+
{
|
| 255 |
+
pRegistration = pTokenState->_RegisterCallback(reinterpret_cast<TaskProc>(&_UnrealizedChore::_CancelViaToken), (ContextBase *)pContext);
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
//
|
| 259 |
+
// Waiting on the indirect alias may throw (e.g.: the entire context may have been canceled). If it
|
| 260 |
+
// throws, we need to deal with appropriate marshaling.
|
| 261 |
+
//
|
| 262 |
+
try
|
| 263 |
+
{
|
| 264 |
+
//
|
| 265 |
+
// Set up an indirect alias for this task collection. Any usage of the original task collection
|
| 266 |
+
// within this stolen chore will automatically redirect through the indirect alias. This allows
|
| 267 |
+
// preservation of single-threaded semantics within the task collection while allowing it to be "accessed"
|
| 268 |
+
// from stolen chores (multiple threads).
|
| 269 |
+
//
|
| 270 |
+
// This stack based collection will wait on stolen chores at destruction time. In the event the collection is not
|
| 271 |
+
// used during the steal, this doesn't do much.
|
| 272 |
+
//
|
| 273 |
+
_TaskCollection indirectAlias(pTaskCollection, false);
|
| 274 |
+
|
| 275 |
+
pContext->SetIndirectAlias(&indirectAlias);
|
| 276 |
+
|
| 277 |
+
try
|
| 278 |
+
{
|
| 279 |
+
//
|
| 280 |
+
// We need to consider this a possible interruption point. It's entirely possible that we stole and raced with a
|
| 281 |
+
// cancellation thread. The collection was canceled after we stole(e.g.: removed from the WSQ) but before we added ourselves
|
| 282 |
+
// to the stealing chain list above. In this case, the entire context will wait until completion (bad). Immediately
|
| 283 |
+
// after we go on the list (a memory barrier), we need to check the collection cancellation flag. If the collection is going away,
|
| 284 |
+
// we need to get out *NOW* otherwise the entire subtree executes.
|
| 285 |
+
//
|
| 286 |
+
if (pTaskCollection->_M_pOriginalCollection->_M_exitCode != 0 ||
|
| 287 |
+
(_CancellationTokenState::_IsValid(pTokenState) && pTokenState->_IsCanceled()) ||
|
| 288 |
+
(pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_CLEAR &&
|
| 289 |
+
pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_INLINE &&
|
| 290 |
+
pTaskCollection->_M_executionStatus != TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK))
|
| 291 |
+
throw _Interruption_exception();
|
| 292 |
+
|
| 293 |
+
pChore->m_pFunction(pChore);
|
| 294 |
+
}
|
| 295 |
+
catch(const _Interruption_exception &)
|
| 296 |
+
{
|
| 297 |
+
//
|
| 298 |
+
// If someone manually threw _Interruption_exception, we will have a cancel count but not a canceled context. This
|
| 299 |
+
// means we need to apply the cancel one level up. Normally, the act of throwing would do that via being caught in the
|
| 300 |
+
// wait, but this is special "marshaling" for _Interruption_exception.
|
| 301 |
+
//
|
| 302 |
+
if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled())
|
| 303 |
+
pTaskCollection->_Cancel();
|
| 304 |
+
}
|
| 305 |
+
catch(...)
|
| 306 |
+
{
|
| 307 |
+
//
|
| 308 |
+
// Track the exception that was thrown here and subsequently cancel all work. _RaisedException makes the decision on what
|
| 309 |
+
// exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow.
|
| 310 |
+
//
|
| 311 |
+
pTaskCollection->_RaisedException();
|
| 312 |
+
pTaskCollection->_Cancel();
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
indirectAlias._Wait();
|
| 316 |
+
}
|
| 317 |
+
catch(const _Interruption_exception &)
|
| 318 |
+
{
|
| 319 |
+
//
|
| 320 |
+
// If someone manually threw _Interruption_exception out of a task on the indirect alias, the same thing applies as to
|
| 321 |
+
// a directly stolen chore (above).
|
| 322 |
+
//
|
| 323 |
+
if (pContext->HasInlineCancellation() && !pContext->IsEntireContextCanceled())
|
| 324 |
+
pTaskCollection->_Cancel();
|
| 325 |
+
}
|
| 326 |
+
catch(...)
|
| 327 |
+
{
|
| 328 |
+
//
|
| 329 |
+
// Track the exception that was thrown here and subsequently cancel all work. _RaisedException makes the decision on what
|
| 330 |
+
// exceptions to keep and what to discard. The flags it sets will indicate to the thread calling ::Wait that it must rethrow.
|
| 331 |
+
//
|
| 332 |
+
pTaskCollection->_RaisedException();
|
| 333 |
+
pTaskCollection->_Cancel();
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
pContext->SetIndirectAlias(NULL);
|
| 337 |
+
ASSERT(pContext->GetGoverningTokenState() == NULL);
|
| 338 |
+
|
| 339 |
+
if ( !pChore->_M_fDetached)
|
| 340 |
+
{
|
| 341 |
+
//
|
| 342 |
+
// pOriginContext may die at any point (detachment). When it does, it will transfer the stolen chore trace from the context to the
|
| 343 |
+
// given task collection (us) under lock. We can, therefore, take this lock and check if we are still okay to check the context.
|
| 344 |
+
//
|
| 345 |
+
pList->AcquireWrite();
|
| 346 |
+
|
| 347 |
+
if (pContext->IsContextChainedStealer())
|
| 348 |
+
pOriginContext->RemoveStealer(pContext);
|
| 349 |
+
else
|
| 350 |
+
pList->UnlockedRemove(&(pContext->m_stealChain));
|
| 351 |
+
|
| 352 |
+
pTaskCollection->_M_activeStealersForCancellation--;
|
| 353 |
+
|
| 354 |
+
pList->ReleaseWrite();
|
| 355 |
+
|
| 356 |
+
}
|
| 357 |
+
else
|
| 358 |
+
{
|
| 359 |
+
pList->Remove(&(pContext->m_stealChain));
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
if (pRegistration != NULL)
|
| 363 |
+
{
|
| 364 |
+
pTokenState->_DeregisterCallback(pRegistration);
|
| 365 |
+
pRegistration->_Release();
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
pContext->ClearCancel();
|
| 369 |
+
pContext->ClearAliasTable();
|
| 370 |
+
pContext->SetRootCollection(NULL);
|
| 371 |
+
pChore->_M_pTaskCollection = NULL;
|
| 372 |
+
pTaskCollection->_NotifyCompletedChoreAndFree(pChore);
|
| 373 |
+
}
|
| 374 |
+
} // namespace details
|
| 375 |
+
|
| 376 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Context.cpp
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Context.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation of static context APIs
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
/// <summary>
|
| 19 |
+
/// Returns a per scheduler unique identifier for the current context.
|
| 20 |
+
/// </summary>
|
| 21 |
+
/// <returns>
|
| 22 |
+
/// A per scheduler unique identifier for the current context or -1 if no such context exists.
|
| 23 |
+
/// </returns>
|
| 24 |
+
unsigned int Context::Id()
|
| 25 |
+
{
|
| 26 |
+
const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext();
|
| 27 |
+
return (pContext != NULL ? pContext->GetId() : UINT_MAX);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/// <summary>
|
| 31 |
+
/// Returns an identifier for the virtual processor the current context is executing on.
|
| 32 |
+
/// </summary>
|
| 33 |
+
/// <returns>
|
| 34 |
+
/// An identifier for the virtual processor the current context is executing on or -1 if there is no such context
|
| 35 |
+
/// or it is not executing on a virtual processor at present.
|
| 36 |
+
/// </returns>
|
| 37 |
+
unsigned int Context::VirtualProcessorId()
|
| 38 |
+
{
|
| 39 |
+
const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext();
|
| 40 |
+
return (pContext != NULL ? pContext->GetVirtualProcessorId() : UINT_MAX);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/// <summary>
|
| 44 |
+
/// Returns an identifier for the schedule group the current context is working on.
|
| 45 |
+
/// </summary>
|
| 46 |
+
/// <returns>
|
| 47 |
+
/// An identifier for the schedule group the current context is working on or -1 if there is no such context
|
| 48 |
+
/// or it is not executing a schedule group at present.
|
| 49 |
+
/// </returns>
|
| 50 |
+
unsigned int Context::ScheduleGroupId()
|
| 51 |
+
{
|
| 52 |
+
const ContextBase *pContext = SchedulerBase::SafeFastCurrentContext();
|
| 53 |
+
return (pContext != NULL ? pContext->GetScheduleGroupId() : UINT_MAX);
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/// <summary>
|
| 57 |
+
/// Causes the current context to block, yielding execution to another context. If the current
|
| 58 |
+
/// thread does not have a ConcRT context associated with it, it is inducted into one.
|
| 59 |
+
/// </summary>
|
| 60 |
+
void Context::Block()
|
| 61 |
+
{
|
| 62 |
+
return SchedulerBase::CurrentContext()->Block();
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/// <summary>
|
| 66 |
+
/// Yields execution so that another context may execute. The current context is placed on the
|
| 67 |
+
/// scheduler's list of runnable contexts. If the current thread does not have a context, it is inducted
|
| 68 |
+
/// into a ConcRT context. If no other function is available to yield to, the function simply returns.
|
| 69 |
+
/// </summary>
|
| 70 |
+
void Context::Yield()
|
| 71 |
+
{
|
| 72 |
+
SchedulerBase::CurrentContext()->Yield();
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Yields execution so that another context may execute. The current context is placed on the
|
| 77 |
+
/// scheduler's list of runnable contexts. If the current thread does not have a context, it is inducted
|
| 78 |
+
/// into a ConcRT context. If no other function is available to yield to, the function simply returns.
|
| 79 |
+
///
|
| 80 |
+
/// This is intended for spin loops.
|
| 81 |
+
/// </summary>
|
| 82 |
+
void Context::_SpinYield()
|
| 83 |
+
{
|
| 84 |
+
SchedulerBase::CurrentContext()->SpinYield();
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
/// <summary>
|
| 88 |
+
/// Returns an indication of whether the task collection which is currently executing inline on the current context
|
| 89 |
+
/// is in the midst of an active cancellation (or will be shortly).
|
| 90 |
+
/// </summary>
|
| 91 |
+
bool Context::IsCurrentTaskCollectionCanceling()
|
| 92 |
+
{
|
| 93 |
+
ContextBase *pCurrentContext = SchedulerBase::SafeFastCurrentContext();
|
| 94 |
+
if (pCurrentContext != NULL)
|
| 95 |
+
{
|
| 96 |
+
//
|
| 97 |
+
// If a structured collection has an unstructured collection as a parent,
|
| 98 |
+
// then GetExecutingCollection will always return the parent.
|
| 99 |
+
//
|
| 100 |
+
_TaskCollectionBase *pCollection = pCurrentContext->GetExecutingCollection();
|
| 101 |
+
if (pCollection != NULL)
|
| 102 |
+
{
|
| 103 |
+
if (pCollection->_IsStructured())
|
| 104 |
+
{
|
| 105 |
+
return static_cast<details::_StructuredTaskCollection*>(pCollection)->_IsCanceling();
|
| 106 |
+
}
|
| 107 |
+
else if (static_cast<details::_TaskCollection*>(pCollection)->_IsAlias())
|
| 108 |
+
{
|
| 109 |
+
return static_cast<details::_TaskCollection*>(pCollection)->_OriginalCollection()->_IsCanceling();
|
| 110 |
+
}
|
| 111 |
+
else
|
| 112 |
+
{
|
| 113 |
+
return static_cast<details::_TaskCollection*>(pCollection)->_IsCanceling();
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
return false;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
/// <summary>
|
| 121 |
+
/// Returns the ConcRT context associated with the current thread.
|
| 122 |
+
/// </summary>
|
| 123 |
+
/// <returns>
|
| 124 |
+
/// A pointer to the ConcRT context associated with the current thread if it exists. If one does not exist,
|
| 125 |
+
/// a new context is created.
|
| 126 |
+
/// <returns>
|
| 127 |
+
_Ret_notnull_ Context* Context::CurrentContext()
|
| 128 |
+
{
|
| 129 |
+
return SchedulerBase::CurrentContext();
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// Depending on the argument, causes the scheduler to add an extra virtual processor for the
|
| 134 |
+
/// duration of a block of code or remove a previously added one.
|
| 135 |
+
///
|
| 136 |
+
/// Oversubscribe(true);
|
| 137 |
+
/// /* some slow kernel or I/O code, etc.*/
|
| 138 |
+
/// Oversubscribe(false);
|
| 139 |
+
///
|
| 140 |
+
/// An extra virtual processor is allocated on the current hardware thread between the two calls
|
| 141 |
+
/// to Oversubscribe. If additional idle virtual processors are available, the virtual processor is created
|
| 142 |
+
/// and made available, but if no available virtual processors exist, the virtual processor is kicked into
|
| 143 |
+
/// action with an internal context that searches for work.
|
| 144 |
+
/// Calls to Oversubscribe(TRUE) must be matched with calls to Oversubscribe(FALSE) -> calls can be nested,
|
| 145 |
+
/// but only a maximum of one additional virtual processor is created. The additional vproc, if any, will
|
| 146 |
+
/// be retired after the outermost call to Oversubscribe(FALSE), as soon as the currently executing root
|
| 147 |
+
/// chore on the vproc is completed.
|
| 148 |
+
/// </summary>
|
| 149 |
+
/// <param name="beginOversubscription">
|
| 150 |
+
/// [in] A boolean value specifying whether oversubscription is to be turned on or off.
|
| 151 |
+
/// </param>
|
| 152 |
+
void Context::Oversubscribe(bool beginOversubscription)
|
| 153 |
+
{
|
| 154 |
+
SchedulerBase::CurrentContext()->Oversubscribe(beginOversubscription);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
namespace details
|
| 158 |
+
{
|
| 159 |
+
_Context _Context::_CurrentContext()
|
| 160 |
+
{
|
| 161 |
+
return _Context(SchedulerBase::CurrentContext());
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
void _Context::_Yield()
|
| 165 |
+
{
|
| 166 |
+
SchedulerBase::CurrentContext()->Yield();
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
void _Context::_Oversubscribe(bool _BeginOversubscription)
|
| 170 |
+
{
|
| 171 |
+
SchedulerBase::CurrentContext()->Oversubscribe(_BeginOversubscription);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
bool _Context::_IsSynchronouslyBlocked() const
|
| 175 |
+
{
|
| 176 |
+
return _M_pContext->IsSynchronouslyBlocked();
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.cpp
ADDED
|
@@ -0,0 +1,1341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ContextBase.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the implementation for an execution ContextBase/stack/thread.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#include "concrtinternal.h"
|
| 14 |
+
|
| 15 |
+
#pragma warning (disable : 4702)
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
/// <summary>
|
| 22 |
+
/// Constructor
|
| 23 |
+
/// </summary>
|
| 24 |
+
ContextBase::ContextBase(SchedulerBase *pScheduler, bool fIsExternal) :
|
| 25 |
+
m_criticalRegionCount(0),
|
| 26 |
+
m_hyperCriticalRegionCount(0),
|
| 27 |
+
m_oversubscribeCount(0),
|
| 28 |
+
m_pScheduler(pScheduler),
|
| 29 |
+
m_pWorkQueue(NULL),
|
| 30 |
+
m_pParentContext(NULL),
|
| 31 |
+
m_blockedState(CONTEXT_BLOCKED),
|
| 32 |
+
m_contextSwitchingFence(0),
|
| 33 |
+
m_pRootCollection(NULL),
|
| 34 |
+
m_pExecutingCollection(NULL),
|
| 35 |
+
m_pGoverningTokenState(NULL),
|
| 36 |
+
m_governingTokenDepth(-1),
|
| 37 |
+
m_asyncTaskCollectionInlineDepth(0),
|
| 38 |
+
m_threadId(0),
|
| 39 |
+
m_fIsExternal(fIsExternal),
|
| 40 |
+
#if defined(_DEBUG)
|
| 41 |
+
m_fShutdownValidations(false),
|
| 42 |
+
#endif // _DEBUG
|
| 43 |
+
m_cancellationRefCount(0),
|
| 44 |
+
m_minCancellationDepth(-1),
|
| 45 |
+
m_maxCancellationDepth(-1),
|
| 46 |
+
m_inlineCancellations(0),
|
| 47 |
+
m_canceledContext(0),
|
| 48 |
+
m_pendingCancellations(0),
|
| 49 |
+
m_pIndirectAlias(NULL),
|
| 50 |
+
//
|
| 51 |
+
// The alias table must be sufficiently small that clearing it at the end of a stolen chore isn't a huge penalty, yet
|
| 52 |
+
// large enough to splay a few task collections. Hopefully, the number of collections being utilized in stolen chores isn't very
|
| 53 |
+
// large (1 or 2), so this size should be sufficient.
|
| 54 |
+
//
|
| 55 |
+
m_aliasTable(7)
|
| 56 |
+
{
|
| 57 |
+
m_id = m_pScheduler->GetNewContextId();
|
| 58 |
+
TraceContextEvent(CONCRT_EVENT_START, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id);
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
unsigned int ContextBase::ScheduleGroupRefCount() const
|
| 62 |
+
{
|
| 63 |
+
return m_pSegment != NULL ? (unsigned int)m_pSegment->GetGroup()->m_refCount : UINT_MAX;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/// <summary>
|
| 67 |
+
/// Returns a unique identifier to the context
|
| 68 |
+
/// </summary>
|
| 69 |
+
unsigned int ContextBase::GetId() const
|
| 70 |
+
{
|
| 71 |
+
return m_id;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/// <summary>
|
| 75 |
+
/// Returns an identifier to the schedule group the context is currently working on, if any.
|
| 76 |
+
/// </summary>
|
| 77 |
+
unsigned int ContextBase::GetScheduleGroupId() const
|
| 78 |
+
{
|
| 79 |
+
return (m_pSegment != NULL) ? m_pSegment->GetGroup()->Id() : UINT_MAX;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/// <summary>
|
| 83 |
+
/// Places a reference on the context preventing it from being destroyed until such time as the stealer is added to the chain
|
| 84 |
+
/// via AddStealer. Note that the operation of AddStealer should happen rapidly as it will *BLOCK* cleanup of the context.
|
| 85 |
+
/// </summary>
|
| 86 |
+
void ContextBase::ReferenceForCancellation()
|
| 87 |
+
{
|
| 88 |
+
InterlockedIncrement(&m_cancellationRefCount);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/// <summary>
|
| 92 |
+
/// Removes a reference on the context which was preventing it from being destroyed.
|
| 93 |
+
/// </summary>
|
| 94 |
+
void ContextBase::DereferenceForCancellation()
|
| 95 |
+
{
|
| 96 |
+
InterlockedDecrement(&m_cancellationRefCount);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
/// <summary>
|
| 100 |
+
/// Adds a stealing context.
|
| 101 |
+
/// </summary>
|
| 102 |
+
void ContextBase::AddStealer(ContextBase *pStealer, bool fDereferenceForCancellation)
|
| 103 |
+
{
|
| 104 |
+
m_stealers.AddTail(&(pStealer->m_stealChain));
|
| 105 |
+
pStealer->m_fContextChainedStealer = true;
|
| 106 |
+
if (fDereferenceForCancellation)
|
| 107 |
+
DereferenceForCancellation();
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/// <summary>
|
| 111 |
+
/// Removes a stealing context.
|
| 112 |
+
/// </summary>
|
| 113 |
+
void ContextBase::RemoveStealer(ContextBase *pStealer)
|
| 114 |
+
{
|
| 115 |
+
m_stealers.Remove(&(pStealer->m_stealChain));
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/// <summary>
|
| 119 |
+
/// Cancel everything stolen from pCanceledCollection outward from this context.
|
| 120 |
+
/// </summary>
|
| 121 |
+
void ContextBase::CancelStealers(_TaskCollectionBase *pCanceledCollection)
|
| 122 |
+
{
|
| 123 |
+
ASSERT(pCanceledCollection != NULL || IsEntireContextCanceled());
|
| 124 |
+
|
| 125 |
+
SafeRWList<ListEntry>::_Scoped_lock_read readLock(m_stealers);
|
| 126 |
+
ListEntry *pLE = m_stealers.First();
|
| 127 |
+
while (pLE != NULL)
|
| 128 |
+
{
|
| 129 |
+
ContextBase *pStealingContext = CONTAINING_RECORD(pLE, ContextBase, m_stealChain);
|
| 130 |
+
|
| 131 |
+
//
|
| 132 |
+
// We don't want to be recursively traversing the tree needlessly every time the exception propagates back
|
| 133 |
+
// up a given context. If a context is already canceled, nothing can steal from it and we don't need to traverse
|
| 134 |
+
// there.
|
| 135 |
+
//
|
| 136 |
+
if (!pStealingContext->IsEntireContextCanceled())
|
| 137 |
+
{
|
| 138 |
+
_TaskCollectionBase *pRootCollection = pStealingContext->GetRootCollection();
|
| 139 |
+
ASSERT(pRootCollection != NULL);
|
| 140 |
+
//
|
| 141 |
+
// If pCanceledCollection != NULL, it is an indication that we're at the first level. We can only cancel things that are stolen
|
| 142 |
+
// from greater inlining depth or things from equal if the root collection is pCollection. Further, we cannot cancel things which are not
|
| 143 |
+
// inlined. For example:
|
| 144 |
+
//
|
| 145 |
+
// _TaskCollection p1;
|
| 146 |
+
// p1.Schedule( [] {
|
| 147 |
+
// _TaskCollection *p2 = new _TaskCollection;
|
| 148 |
+
// p2.Schedule(alpha);
|
| 149 |
+
// _TaskCollection p3;
|
| 150 |
+
// p3.Schedule( [] {
|
| 151 |
+
// Blah;
|
| 152 |
+
// });
|
| 153 |
+
// });
|
| 154 |
+
//
|
| 155 |
+
// 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
|
| 156 |
+
// based, but remember we can have task collection pointers which are passed amongst threads and detached.
|
| 157 |
+
//
|
| 158 |
+
// 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
|
| 159 |
+
// 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
|
| 160 |
+
// that stole in this manner either.
|
| 161 |
+
//
|
| 162 |
+
|
| 163 |
+
if (
|
| 164 |
+
// A context whose root chore belongs to the task collection being canceled is fair game. No further checks are required.
|
| 165 |
+
(pRootCollection == pCanceledCollection) ||
|
| 166 |
+
|
| 167 |
+
// 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
|
| 168 |
+
// context and that by definition gives it the correct parentage to be shot down.
|
| 169 |
+
(pCanceledCollection == NULL && pRootCollection->_IsCurrentlyInlined()) ||
|
| 170 |
+
|
| 171 |
+
// The only way cancellation can be satisfied if both aren't inlined is above. Otherwise, the one that stole must have greater
|
| 172 |
+
// inline depth than the one we're canceling.
|
| 173 |
+
(pCanceledCollection != NULL && pCanceledCollection->_IsCurrentlyInlined() && pRootCollection->_InliningDepth() > pCanceledCollection->_InliningDepth())
|
| 174 |
+
)
|
| 175 |
+
{
|
| 176 |
+
ASSERT(pRootCollection == pCanceledCollection || pCanceledCollection == NULL || pRootCollection->_IsCurrentlyInlined());
|
| 177 |
+
//
|
| 178 |
+
// 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
|
| 179 |
+
// stability on the inlining depth because of the lock on the stealers list.
|
| 180 |
+
//
|
| 181 |
+
bool fCancel = true;
|
| 182 |
+
if (pRootCollection != pCanceledCollection && m_governingTokenDepth != -1)
|
| 183 |
+
{
|
| 184 |
+
ASSERT(pRootCollection->_IsCurrentlyInlined() && m_pGoverningTokenState != NULL);
|
| 185 |
+
fCancel = IsCanceledAtDepth(pRootCollection);
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
if (fCancel)
|
| 189 |
+
{
|
| 190 |
+
pStealingContext->CancelEntireContext();
|
| 191 |
+
pStealingContext->CancelStealers(NULL);
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
pLE = m_stealers.Next(pLE);
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/// <summary>
|
| 201 |
+
/// Cleans up the context.
|
| 202 |
+
/// </summary>
|
| 203 |
+
void ContextBase::Cleanup()
|
| 204 |
+
{
|
| 205 |
+
ReleaseWorkQueue();
|
| 206 |
+
|
| 207 |
+
TraceContextEvent(CONCRT_EVENT_END, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id);
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/// <summary>
|
| 211 |
+
/// Called on both internal and external contexts, either when the are put into an idle pool to
|
| 212 |
+
/// be recycled, or when they are ready to be deleted. The API moves the contexts that are in
|
| 213 |
+
/// the list of 'stealers' (used for cancellation) to lists in the task collections from which
|
| 214 |
+
/// those contexts have stolen chores.
|
| 215 |
+
/// </summary>
|
| 216 |
+
void ContextBase::DetachStealers()
|
| 217 |
+
{
|
| 218 |
+
//
|
| 219 |
+
// 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.
|
| 220 |
+
// 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
|
| 221 |
+
// and between the time of the steal and the time the wrapper executed the original thread went away.
|
| 222 |
+
//
|
| 223 |
+
|
| 224 |
+
if (m_cancellationRefCount != 0)
|
| 225 |
+
{
|
| 226 |
+
// Spin wait (no yielding)
|
| 227 |
+
_SpinWaitNoYield spinWait;
|
| 228 |
+
|
| 229 |
+
do
|
| 230 |
+
{
|
| 231 |
+
spinWait._SpinOnce();
|
| 232 |
+
|
| 233 |
+
} while (m_cancellationRefCount != 0);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
if (m_aliasTable.Count() > 0)
|
| 237 |
+
ClearAliasTable();
|
| 238 |
+
|
| 239 |
+
if (m_stealers.Empty())
|
| 240 |
+
{
|
| 241 |
+
//
|
| 242 |
+
// After a DetachStealers, it is entirely possible that the context (the *this*) pointer goes away. Normally, the lock on the stealers
|
| 243 |
+
// list is what guards against manipulation by stolen chores; however -- the early exit above presents an interesting risk. It is now entirely
|
| 244 |
+
// possible that the last stolen chore is removing its context from the stealers list under the governance of the write lock and makes the
|
| 245 |
+
// 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
|
| 246 |
+
// thread releases the write lock.
|
| 247 |
+
//
|
| 248 |
+
// 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
|
| 249 |
+
// prevent touching freed memory, we need to flush out any write owner (take and release the lock if someone holds a write).
|
| 250 |
+
//
|
| 251 |
+
m_stealers.FlushWriteOwners();
|
| 252 |
+
return;
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
//
|
| 256 |
+
// 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
|
| 257 |
+
// on and still has stolen chores. In order to continue to facilitate cancellation of those task collections, any stealers in the list have
|
| 258 |
+
// to be moved to the individual task collection lists.
|
| 259 |
+
//
|
| 260 |
+
bool isDone = false;
|
| 261 |
+
|
| 262 |
+
while(!isDone)
|
| 263 |
+
{
|
| 264 |
+
bool fContinue = true;
|
| 265 |
+
m_stealers.AcquireWrite();
|
| 266 |
+
__try
|
| 267 |
+
{
|
| 268 |
+
fContinue = true;
|
| 269 |
+
ListEntry *pEntry = m_stealers.First();
|
| 270 |
+
while (pEntry != NULL && fContinue)
|
| 271 |
+
{
|
| 272 |
+
ListEntry *pNext = m_stealers.Next(pEntry);
|
| 273 |
+
|
| 274 |
+
ContextBase *pContext = CONTAINING_RECORD(pEntry, ContextBase, m_stealChain);
|
| 275 |
+
|
| 276 |
+
_TaskCollectionBase *pCollectionBase = pContext->GetRootCollection();
|
| 277 |
+
ASSERT(pCollectionBase != NULL && !pCollectionBase->_IsStructured());
|
| 278 |
+
|
| 279 |
+
_TaskCollection *pCollection = static_cast<_TaskCollection *>(pCollectionBase);
|
| 280 |
+
|
| 281 |
+
//
|
| 282 |
+
// In all likelihood, we rarely get here; however -- there is an issue in that the lock ordering here is from the bottom up
|
| 283 |
+
// (task collection then context) in order to preserve patterns in stealing and cancellation.
|
| 284 |
+
//
|
| 285 |
+
// When we move, we must do so in a backwards order. The only time we should see contention on these locks is during minimal
|
| 286 |
+
// periods where we are cancelling or for tiny time frames during steal. We will play a pseudo-atomic lock acquire game. If we cannot
|
| 287 |
+
// get both, we back off and let the other thread through.
|
| 288 |
+
//
|
| 289 |
+
SafeRWList<ListEntry> *pCollectionList = reinterpret_cast<SafeRWList<ListEntry> *> (pCollection->_GetStealTrackingList());
|
| 290 |
+
if (!pCollectionList->TryAcquireWrite())
|
| 291 |
+
{
|
| 292 |
+
//
|
| 293 |
+
// Yield in an attempt to force the other thread through.
|
| 294 |
+
//
|
| 295 |
+
m_stealers.ReleaseWrite();
|
| 296 |
+
fContinue = false;
|
| 297 |
+
platform::__Sleep(1);
|
| 298 |
+
break;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
__try
|
| 302 |
+
{
|
| 303 |
+
m_stealers.UnlockedRemove(&(pContext->m_stealChain));
|
| 304 |
+
pContext->m_fContextChainedStealer = false;
|
| 305 |
+
pCollectionList->UnlockedAddTail(&(pContext->m_stealChain));
|
| 306 |
+
}
|
| 307 |
+
__finally
|
| 308 |
+
{
|
| 309 |
+
pCollectionList->ReleaseWrite();
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
pEntry = pNext;
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
isDone = (pEntry == NULL);
|
| 316 |
+
}
|
| 317 |
+
__finally
|
| 318 |
+
{
|
| 319 |
+
//
|
| 320 |
+
// It may have been released due to a back-off.
|
| 321 |
+
//
|
| 322 |
+
if (fContinue)
|
| 323 |
+
{
|
| 324 |
+
m_stealers.ReleaseWrite();
|
| 325 |
+
}
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
/// <summary>
|
| 331 |
+
/// Pushes an unrealized chore onto the work stealing queue for structured parallelism.
|
| 332 |
+
/// </summary>
|
| 333 |
+
/// <param name="pChore">
|
| 334 |
+
/// The chore to push onto the structured work stealing queue.
|
| 335 |
+
/// </param>
|
| 336 |
+
void ContextBase::PushStructured(_UnrealizedChore *pChore, location *pLocation)
|
| 337 |
+
{
|
| 338 |
+
Mailbox<_UnrealizedChore>::Slot affinitySlot;
|
| 339 |
+
|
| 340 |
+
// If the chore has been scheduled with a location and the scheduler supports location-based scheduling, the destination schedule
|
| 341 |
+
// group segment may be different from the current one.
|
| 342 |
+
ScheduleGroupSegmentBase * pDestinationSegment = m_pSegment;
|
| 343 |
+
|
| 344 |
+
if (pLocation != NULL)
|
| 345 |
+
{
|
| 346 |
+
//
|
| 347 |
+
// If the current segment this context is operating within has the same affinity as the requested task, there is *NO NEED* to mail
|
| 348 |
+
// the task anywhere. It will get a natural affinity to pLocation without any additional work.
|
| 349 |
+
//
|
| 350 |
+
if (!pLocation->_Is_system())
|
| 351 |
+
{
|
| 352 |
+
if (*pLocation != m_pSegment->GetAffinity())
|
| 353 |
+
{
|
| 354 |
+
affinitySlot = m_pSegment->GetGroup()->MailChore(pChore, pLocation, &pDestinationSegment);
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
pDestinationSegment->NotifyAffinitizedWork();
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
GetStructuredWorkQueue()->PushStructured(pChore, affinitySlot);
|
| 362 |
+
|
| 363 |
+
//
|
| 364 |
+
// Update the enqueued task numbers for statistics. Since this is a critical performance
|
| 365 |
+
// path we avoid making a virtual call since that will imply two memory dereferences plus
|
| 366 |
+
// an indirect call. Instead, we make one memory dereference to get a condition and one
|
| 367 |
+
// branch. This is faster ONLY because target function call will be inlined.
|
| 368 |
+
//
|
| 369 |
+
if (IsExternal())
|
| 370 |
+
{
|
| 371 |
+
static_cast<ExternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 372 |
+
}
|
| 373 |
+
else
|
| 374 |
+
{
|
| 375 |
+
static_cast<InternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
if (m_pScheduler->HasVirtualProcessorAvailableForNewWork())
|
| 379 |
+
{
|
| 380 |
+
m_pScheduler->StartupNewVirtualProcessor(pDestinationSegment, pDestinationSegment->GetAffinity());
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
/// <summary>
|
| 385 |
+
/// Pushes an unrealized chore onto the work stealing queue for structured parallelism.
|
| 386 |
+
/// </summary>
|
| 387 |
+
/// <param name="pChore">
|
| 388 |
+
/// The chore to push onto the structured work stealing queue.
|
| 389 |
+
/// </param>
|
| 390 |
+
void ContextBase::PushStructured(_UnrealizedChore *pChore)
|
| 391 |
+
{
|
| 392 |
+
GetStructuredWorkQueue()->PushStructured(pChore);
|
| 393 |
+
|
| 394 |
+
//
|
| 395 |
+
// Update the enqueued task numbers for statistics. Since this is a critical performance
|
| 396 |
+
// path we avoid making a virtual call since that will imply two memory dereferences plus
|
| 397 |
+
// an indirect call. Instead, we make one memory dereference to get a condition and one
|
| 398 |
+
// branch. This is faster ONLY because target function call will be inlined.
|
| 399 |
+
//
|
| 400 |
+
if (IsExternal())
|
| 401 |
+
{
|
| 402 |
+
static_cast<ExternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 403 |
+
}
|
| 404 |
+
else
|
| 405 |
+
{
|
| 406 |
+
static_cast<InternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
if (m_pScheduler->HasVirtualProcessorAvailableForNewWork())
|
| 410 |
+
{
|
| 411 |
+
m_pScheduler->StartupNewVirtualProcessor(m_pSegment);
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/// <summary>
|
| 416 |
+
/// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism.
|
| 417 |
+
/// </summary>
|
| 418 |
+
/// <param name="pChore">
|
| 419 |
+
/// The chore to push onto the unstructured work stealing queue.
|
| 420 |
+
/// </param>
|
| 421 |
+
int ContextBase::PushUnstructured(_UnrealizedChore *pChore, location *pLocation)
|
| 422 |
+
{
|
| 423 |
+
Mailbox<_UnrealizedChore>::Slot affinitySlot;
|
| 424 |
+
|
| 425 |
+
// If the chore has been scheduled with a location and the scheduler supports location-based scheduling, the destination schedule
|
| 426 |
+
// group segment may be different from the current one.
|
| 427 |
+
ScheduleGroupSegmentBase * pDestinationSegment = m_pSegment;
|
| 428 |
+
|
| 429 |
+
if (pLocation != NULL)
|
| 430 |
+
{
|
| 431 |
+
//
|
| 432 |
+
// If the current segment this context is operating within has the same affinity as the requested task, there is *NO NEED* to mail
|
| 433 |
+
// the task anywhere. It will get a natural affinity to pLocation without any additional work.
|
| 434 |
+
//
|
| 435 |
+
if (!pLocation->_Is_system())
|
| 436 |
+
{
|
| 437 |
+
if (*pLocation != m_pSegment->GetAffinity())
|
| 438 |
+
{
|
| 439 |
+
affinitySlot = m_pSegment->GetGroup()->MailChore(pChore, pLocation, &pDestinationSegment);
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
pDestinationSegment->NotifyAffinitizedWork();
|
| 443 |
+
}
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
int cookie = GetWorkQueue()->PushUnstructured(pChore, affinitySlot);
|
| 447 |
+
|
| 448 |
+
//
|
| 449 |
+
// Update the enqueued task numbers for statistics. Since this is a critical performance
|
| 450 |
+
// path we avoid making a virtual call since that will imply two memory dereferences plus
|
| 451 |
+
// an indirect call. Instead, we make one memory dereference to get a condition and one
|
| 452 |
+
// branch. This is faster ONLY because target function call will be inlined.
|
| 453 |
+
//
|
| 454 |
+
if (IsExternal())
|
| 455 |
+
{
|
| 456 |
+
static_cast<ExternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 457 |
+
}
|
| 458 |
+
else
|
| 459 |
+
{
|
| 460 |
+
static_cast<InternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
if (m_pScheduler->HasVirtualProcessorAvailableForNewWork())
|
| 464 |
+
{
|
| 465 |
+
m_pScheduler->StartupNewVirtualProcessor(pDestinationSegment, pDestinationSegment->GetAffinity());
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
return cookie;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
/// <summary>
|
| 472 |
+
/// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism.
|
| 473 |
+
/// </summary>
|
| 474 |
+
/// <param name="pChore">
|
| 475 |
+
/// The chore to push onto the unstructured work stealing queue.
|
| 476 |
+
/// </param>
|
| 477 |
+
int ContextBase::PushUnstructured(_UnrealizedChore *pChore)
|
| 478 |
+
{
|
| 479 |
+
int cookie = GetWorkQueue()->PushUnstructured(pChore);
|
| 480 |
+
|
| 481 |
+
//
|
| 482 |
+
// Update the enqueued task numbers for statistics. Since this is a critical performance
|
| 483 |
+
// path we avoid making a virtual call since that will imply two memory dereferences plus
|
| 484 |
+
// an indirect call. Instead, we make one memory dereference to get a condition and one
|
| 485 |
+
// branch. This is faster ONLY because target function call will be inlined.
|
| 486 |
+
//
|
| 487 |
+
if (IsExternal())
|
| 488 |
+
{
|
| 489 |
+
static_cast<ExternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 490 |
+
}
|
| 491 |
+
else
|
| 492 |
+
{
|
| 493 |
+
static_cast<InternalContextBase *>(this)->IncrementEnqueuedTaskCounter();
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
if (m_pScheduler->HasVirtualProcessorAvailableForNewWork())
|
| 497 |
+
{
|
| 498 |
+
m_pScheduler->StartupNewVirtualProcessor(m_pSegment);
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
return cookie;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
/// <summary>
|
| 505 |
+
/// Pops the topmost chore from the work stealing queue for structured parallelism. Failure
|
| 506 |
+
/// to pop typically indicates stealing.
|
| 507 |
+
/// </summary>
|
| 508 |
+
/// <returns>
|
| 509 |
+
/// An unrealized chore from the structured work stealing queue or NULL if none is present.
|
| 510 |
+
/// </returns>
|
| 511 |
+
_UnrealizedChore *ContextBase::PopStructured()
|
| 512 |
+
{
|
| 513 |
+
ASSERT(m_pWorkQueue != NULL);
|
| 514 |
+
_UnrealizedChore *pChore = m_pWorkQueue->PopStructured();
|
| 515 |
+
|
| 516 |
+
return pChore;
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
/// <summary>
|
| 520 |
+
/// Attempts to pop the chore specified by a cookie value from the unstructured work stealing queue. Failure
|
| 521 |
+
/// to pop typically indicates stealing.
|
| 522 |
+
/// </summary>
|
| 523 |
+
/// <param name="cookie">
|
| 524 |
+
/// A cookie returned from PushUnstructured indicating the chore to attempt to pop from
|
| 525 |
+
/// the unstructured work stealing queue.
|
| 526 |
+
/// </param>
|
| 527 |
+
/// <returns>
|
| 528 |
+
/// The specified unrealized chore (as indicated by cookie) or NULL if it could not be popped from
|
| 529 |
+
/// the work stealing queue
|
| 530 |
+
/// </returns>
|
| 531 |
+
_UnrealizedChore *ContextBase::TryPopUnstructured(int cookie)
|
| 532 |
+
{
|
| 533 |
+
ASSERT(m_pWorkQueue != NULL);
|
| 534 |
+
_UnrealizedChore *pChore = m_pWorkQueue->TryPopUnstructured(cookie);
|
| 535 |
+
|
| 536 |
+
return pChore;
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
/// <summary>
|
| 540 |
+
/// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them
|
| 541 |
+
/// based on the result of a callback.
|
| 542 |
+
/// </summary>
|
| 543 |
+
/// <param name="pPredicate">
|
| 544 |
+
/// The predicate for things to call pSweepFn on.
|
| 545 |
+
/// </param>
|
| 546 |
+
/// <param name="pData">
|
| 547 |
+
/// The data for the predicate callback
|
| 548 |
+
/// </param>
|
| 549 |
+
/// <param name="pSweepFn">
|
| 550 |
+
/// The sweep function
|
| 551 |
+
/// </param>
|
| 552 |
+
void ContextBase::SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate,
|
| 553 |
+
void *pData,
|
| 554 |
+
WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn
|
| 555 |
+
)
|
| 556 |
+
{
|
| 557 |
+
ASSERT(m_pWorkQueue != NULL);
|
| 558 |
+
return m_pWorkQueue->SweepUnstructured(pPredicate, pData, pSweepFn);
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
/// <summary>
|
| 562 |
+
/// Create a workqueue for use in unstructured task collections.
|
| 563 |
+
/// </summary>
|
| 564 |
+
void ContextBase::CreateWorkQueue()
|
| 565 |
+
{
|
| 566 |
+
//
|
| 567 |
+
// First try and reuse a detached workqueue.
|
| 568 |
+
//
|
| 569 |
+
m_pWorkQueue = m_pSegment->GetDetachedWorkQueue();
|
| 570 |
+
//
|
| 571 |
+
// A detached work queue is still on m_pGroup->m_workQueues.
|
| 572 |
+
//
|
| 573 |
+
if (m_pWorkQueue == NULL)
|
| 574 |
+
{
|
| 575 |
+
//
|
| 576 |
+
// If that failed, try and reuse a workqueue from the free pool.
|
| 577 |
+
//
|
| 578 |
+
m_pWorkQueue = m_pSegment->m_workQueues.PullFromFreePool();
|
| 579 |
+
|
| 580 |
+
if (m_pWorkQueue == NULL)
|
| 581 |
+
{
|
| 582 |
+
//
|
| 583 |
+
// Must create a new one.
|
| 584 |
+
//
|
| 585 |
+
m_pWorkQueue = _concrt_new WorkQueue();
|
| 586 |
+
}
|
| 587 |
+
else
|
| 588 |
+
{
|
| 589 |
+
//
|
| 590 |
+
// Reinitialize the work queue from the free pool.
|
| 591 |
+
//
|
| 592 |
+
m_pWorkQueue->Reinitialize();
|
| 593 |
+
}
|
| 594 |
+
|
| 595 |
+
m_pSegment->m_workQueues.Add(m_pWorkQueue);
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
ASSERT(m_pWorkQueue != NULL);
|
| 599 |
+
m_pWorkQueue->SetOwningContext(this);
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
/// <summary>
|
| 603 |
+
/// Create a workqueue for use in structured task collections.
|
| 604 |
+
/// </summary>
|
| 605 |
+
void ContextBase::CreateStructuredWorkQueue()
|
| 606 |
+
{
|
| 607 |
+
//
|
| 608 |
+
// First, try and reuse a workqueue from the free pool.
|
| 609 |
+
// When using structured task collections, quite often there are
|
| 610 |
+
// no previous unstructured task collections that neglected to wait (thus generating detached workqueues).
|
| 611 |
+
//
|
| 612 |
+
m_pWorkQueue = m_pSegment->m_workQueues.PullFromFreePool();
|
| 613 |
+
|
| 614 |
+
if (m_pWorkQueue == NULL)
|
| 615 |
+
{
|
| 616 |
+
//
|
| 617 |
+
// If that failed, see if there is a workqueue on the detachedWorkQueues list to reuse.
|
| 618 |
+
//
|
| 619 |
+
m_pWorkQueue = m_pSegment->GetDetachedWorkQueue();
|
| 620 |
+
|
| 621 |
+
//
|
| 622 |
+
// A detached work queue is still on m_pSegment->m_workQueues.
|
| 623 |
+
//
|
| 624 |
+
if (m_pWorkQueue == NULL)
|
| 625 |
+
{
|
| 626 |
+
m_pWorkQueue = _concrt_new WorkQueue();
|
| 627 |
+
m_pSegment->m_workQueues.Add(m_pWorkQueue);
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
else
|
| 631 |
+
{
|
| 632 |
+
//
|
| 633 |
+
// Reinitialize the work queue from the free pool.
|
| 634 |
+
//
|
| 635 |
+
m_pWorkQueue->Reinitialize();
|
| 636 |
+
m_pSegment->m_workQueues.Add(m_pWorkQueue);
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
ASSERT(m_pWorkQueue != NULL);
|
| 640 |
+
m_pWorkQueue->SetOwningContext(this);
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
/// <summary>
|
| 644 |
+
/// Cleans up the internal workqueue.
|
| 645 |
+
/// </summary>
|
| 646 |
+
void ContextBase::ReleaseWorkQueue()
|
| 647 |
+
{
|
| 648 |
+
if (m_pWorkQueue != NULL)
|
| 649 |
+
{
|
| 650 |
+
//
|
| 651 |
+
// It's entirely possible that this particular work queue had chores left on the unstructured work queue.
|
| 652 |
+
// Someone could create an unstructured task collection within an LWT, queue chores, and subsequently pass
|
| 653 |
+
// the collection out of the LWT to be waited upon later. In this case, we must leave the work queue around
|
| 654 |
+
// in order for stealing to appropriately happen. This work queue will not be dechained from the schedule
|
| 655 |
+
// group, but will remain until empty. It will go on a lookaside and, while in this state, can be handed
|
| 656 |
+
// to some new context working on an item within the same schedule group.
|
| 657 |
+
//
|
| 658 |
+
|
| 659 |
+
// Save off a local copy of the workqueue and work with that. The debugger mines the workqueue information
|
| 660 |
+
// held in this context, and if we remove the work queue while it's still pointed at by this context, the
|
| 661 |
+
// debugger can become confused.
|
| 662 |
+
WorkQueue* workQueue = m_pWorkQueue;
|
| 663 |
+
m_pWorkQueue = NULL;
|
| 664 |
+
|
| 665 |
+
if ( !workQueue->IsUnstructuredEmpty())
|
| 666 |
+
{
|
| 667 |
+
workQueue->LockedSetOwningContext(NULL);
|
| 668 |
+
m_pSegment->DetachActiveWorkQueue(workQueue);
|
| 669 |
+
}
|
| 670 |
+
else
|
| 671 |
+
{
|
| 672 |
+
//
|
| 673 |
+
// Unless someone really side-stepped the intent of _StructuredTaskCollection, it's almost certain that
|
| 674 |
+
// workQueue->IsStructuredEmpty() is true or else a missing_wait was already thrown.
|
| 675 |
+
//
|
| 676 |
+
if (workQueue->IsLockHeld())
|
| 677 |
+
{
|
| 678 |
+
// Somebody is stealing, don't want to NULL out owning ctx until they're done.
|
| 679 |
+
workQueue->LockedSetOwningContext(NULL);
|
| 680 |
+
}
|
| 681 |
+
else
|
| 682 |
+
{
|
| 683 |
+
// We know workQueue has no unstructured, since we're on the owning thread.
|
| 684 |
+
// Moreover, structured must be empty at this point, because we cannot ever get here until the wait is satisfied.
|
| 685 |
+
// If the UnlockedSteal is entered, then we'll early exit w/o ever touching the owning ctx of workQueue.
|
| 686 |
+
workQueue->SetOwningContext(NULL);
|
| 687 |
+
}
|
| 688 |
+
m_pSegment->m_workQueues.Remove(workQueue);
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
//
|
| 693 |
+
// Make sure that any detachment triggers the stealers to move into the task collection list. Otherwise, we can wind up with
|
| 694 |
+
// an A<-B<-A stealing pattern:
|
| 695 |
+
//
|
| 696 |
+
// TC 1 on thread A
|
| 697 |
+
// Thread B steals from TC 1 (A<-B)
|
| 698 |
+
// Thread A detaches (no wait on TC1)
|
| 699 |
+
// Thread A does SFW and steals from TC 2 deeper inline on thread B (B<-A)
|
| 700 |
+
//
|
| 701 |
+
// The overall stealers pattern is A<-B<-A which will wind up with lock traversal in this order. The recursive reacquire of
|
| 702 |
+
// R/W lock (or out of order acquire: A<-B on one thread, B<-A on the other) will result in later deadlock.
|
| 703 |
+
//
|
| 704 |
+
DetachStealers();
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
/// <summary>
|
| 708 |
+
/// Sets the 'this' context into the tls slot as the current context. This is used by internal contexts in
|
| 709 |
+
/// their dispatch loops.
|
| 710 |
+
/// </summary>
|
| 711 |
+
void ContextBase::SetAsCurrentTls()
|
| 712 |
+
{
|
| 713 |
+
platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, this);
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
/// <summary>
|
| 717 |
+
/// When schedulers are nested on the same thread, the nested scheduler creates a new external context that overrides
|
| 718 |
+
/// the previous context. PopContextFromTls will restore the previous context by setting the TLS value appropriately.
|
| 719 |
+
/// </summary>
|
| 720 |
+
ContextBase* ContextBase::PopContextFromTls()
|
| 721 |
+
{
|
| 722 |
+
ContextBase* pPreviousContext = m_pParentContext;
|
| 723 |
+
platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, pPreviousContext);
|
| 724 |
+
m_pParentContext = NULL;
|
| 725 |
+
return pPreviousContext;
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
/// <summary>
|
| 729 |
+
/// When schedulers are nested on the same thread, the nested scheduler creates a new external context that overrides
|
| 730 |
+
/// the previous context. PushContextToTls will store the previous context and set the new context into TLS.
|
| 731 |
+
/// </summary>
|
| 732 |
+
void ContextBase::PushContextToTls(ContextBase* pParentContext)
|
| 733 |
+
{
|
| 734 |
+
m_pParentContext = pParentContext;
|
| 735 |
+
|
| 736 |
+
// For the first context on a thread, we expect the TLS values to be null. If there is a parent context,
|
| 737 |
+
// the TLS value should have been cleared right before nesting.
|
| 738 |
+
ASSERT(platform::__TlsGetValue(SchedulerBase::t_dwContextIndex) == NULL);
|
| 739 |
+
platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, this);
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
/// <summary>
|
| 743 |
+
/// Context TLS is cleared during nesting on internal contexts before the external context TLS is correctly setup. If not,
|
| 744 |
+
/// code that executes between the clear and setting the new TLS could get confused.
|
| 745 |
+
/// </summary>
|
| 746 |
+
void ContextBase::ClearContextTls()
|
| 747 |
+
{
|
| 748 |
+
ASSERT(platform::__TlsGetValue(SchedulerBase::t_dwContextIndex) != NULL);
|
| 749 |
+
platform::__TlsSetValue(SchedulerBase::t_dwContextIndex, NULL);
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
/// <summary>
|
| 753 |
+
/// Returns the scheduler the specified context is associated with.
|
| 754 |
+
/// </summary>
|
| 755 |
+
SchedulerBase* ContextBase::GetScheduler() const
|
| 756 |
+
{
|
| 757 |
+
return m_pScheduler;
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
/// <summary>
|
| 761 |
+
/// Returns the schedule group the specified context is associated with.
|
| 762 |
+
/// </summary>
|
| 763 |
+
ScheduleGroupBase* ContextBase::GetScheduleGroup() const
|
| 764 |
+
{
|
| 765 |
+
return m_pSegment != NULL ? m_pSegment->GetGroup() : NULL;
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
/// <summary>
|
| 769 |
+
/// Returns the schedule group the specified context is associated with.
|
| 770 |
+
/// </summary>
|
| 771 |
+
ScheduleGroupSegmentBase* ContextBase::GetScheduleGroupSegment() const
|
| 772 |
+
{
|
| 773 |
+
return m_pSegment;
|
| 774 |
+
}
|
| 775 |
+
|
| 776 |
+
/// <summary>
|
| 777 |
+
/// Gets the indirect alias.
|
| 778 |
+
/// </summary>
|
| 779 |
+
_TaskCollection *ContextBase::GetIndirectAlias() const
|
| 780 |
+
{
|
| 781 |
+
return m_pIndirectAlias;
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
/// <summary>
|
| 785 |
+
/// Sets the indirect alias.
|
| 786 |
+
/// </summary>
|
| 787 |
+
void ContextBase::SetIndirectAlias(_TaskCollection *pAlias)
|
| 788 |
+
{
|
| 789 |
+
m_pIndirectAlias = pAlias;
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
/// <summary>
|
| 793 |
+
/// Sweeps the alias table removing anything that's marked for delete. This is done every time we create a new direct alias
|
| 794 |
+
/// in order to avoid growing the table arbitrarily for a context which isn't going away. Note -- passing a task collection between
|
| 795 |
+
/// threads is expensive the first time it's used.
|
| 796 |
+
/// </summary>
|
| 797 |
+
void ContextBase::SweepAliasTable()
|
| 798 |
+
{
|
| 799 |
+
int x;
|
| 800 |
+
Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.First(&x);
|
| 801 |
+
while (pNode != NULL)
|
| 802 |
+
{
|
| 803 |
+
Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNextNode = m_aliasTable.Next(&x, pNode);
|
| 804 |
+
|
| 805 |
+
if (pNode->m_value->_IsStaleAlias())
|
| 806 |
+
{
|
| 807 |
+
_TaskCollection *pCollection = pNode->m_value;
|
| 808 |
+
m_aliasTable.Delete(pCollection->_OriginalCollection()); // may delete pNode
|
| 809 |
+
delete pCollection;
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
pNode = pNextNode;
|
| 813 |
+
}
|
| 814 |
+
}
|
| 815 |
+
|
| 816 |
+
/// <summary>
|
| 817 |
+
/// Clears the alias table.
|
| 818 |
+
/// </summary>
|
| 819 |
+
void ContextBase::ClearAliasTable()
|
| 820 |
+
{
|
| 821 |
+
int x;
|
| 822 |
+
Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.First(&x);
|
| 823 |
+
while (pNode != NULL)
|
| 824 |
+
{
|
| 825 |
+
pNode->m_value->_ReleaseAlias();
|
| 826 |
+
pNode = m_aliasTable.Next(&x, pNode);
|
| 827 |
+
}
|
| 828 |
+
m_aliasTable.Wipe();
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
/// <summary>
|
| 832 |
+
/// Sets the cancellation token currently governing this context.
|
| 833 |
+
/// </summary>
|
| 834 |
+
void ContextBase::PushGoverningTokenState(_CancellationTokenState *pTokenState, int inliningDepth)
|
| 835 |
+
{
|
| 836 |
+
ASSERT(SchedulerBase::FastCurrentContext() == this);
|
| 837 |
+
m_pGoverningTokenState = pTokenState;
|
| 838 |
+
m_governingTokenDepth = inliningDepth;
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
/// <summary>
|
| 842 |
+
/// Reverts to the previously set cancellation token.
|
| 843 |
+
/// </summary>
|
| 844 |
+
void ContextBase::PopGoverningTokenState(_CancellationTokenState *pTokenState)
|
| 845 |
+
{
|
| 846 |
+
ASSERT(SchedulerBase::FastCurrentContext() == this);
|
| 847 |
+
ASSERT(m_pGoverningTokenState == pTokenState);
|
| 848 |
+
ASSERT(m_pExecutingCollection->_InliningDepth() == m_governingTokenDepth);
|
| 849 |
+
|
| 850 |
+
// Move back up to find the parent. Even if the parent has the same token, we need to change the
|
| 851 |
+
// governing token depth to *its* inlining depth
|
| 852 |
+
_TaskCollectionBase *pCollection = m_pExecutingCollection->_SafeGetParent();
|
| 853 |
+
|
| 854 |
+
while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_GetTokenState() == NULL)
|
| 855 |
+
{
|
| 856 |
+
pCollection = pCollection->_SafeGetParent();
|
| 857 |
+
}
|
| 858 |
+
//
|
| 859 |
+
// We only keep governing tokens for THIS context.
|
| 860 |
+
//
|
| 861 |
+
if (pCollection != NULL && pCollection != m_pRootCollection)
|
| 862 |
+
{
|
| 863 |
+
ASSERT(pCollection->_GetTokenState() != NULL && pCollection->_InliningDepth() != -1);
|
| 864 |
+
m_pGoverningTokenState = pCollection->_GetTokenState();
|
| 865 |
+
m_governingTokenDepth = pCollection->_M_inliningDepth;
|
| 866 |
+
}
|
| 867 |
+
else
|
| 868 |
+
{
|
| 869 |
+
m_pGoverningTokenState = NULL;
|
| 870 |
+
m_governingTokenDepth = -1;
|
| 871 |
+
}
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
/// <summary>
|
| 875 |
+
/// Called in order to indicate that a collection executing on this context was canceled. This will often cause cancellation
|
| 876 |
+
/// and unwinding of the entire context (up to the point where we get to the canceled collection). This method is paired with
|
| 877 |
+
/// CancelCollectionComplete.
|
| 878 |
+
/// NOTE: Callers of CancelCollection must first guarantee through other means that the collection they're cancelling (the one at the
|
| 879 |
+
/// depth by the argument) will have a stable inlining depth through the duration of the CancelCollection call.
|
| 880 |
+
/// * For structured task collections, since cancel is only allowed to be called by the owning context or within a stolen chore, if an
|
| 881 |
+
/// inlining depth greater than zero is observed, it is stable since the owning thread will have to wait until the chore invoking CancelCollection
|
| 882 |
+
/// completes.
|
| 883 |
+
/// * For general task collections, cancel is allowed from arbitrary threads. If the calling thread is an indirect alias, the inlining
|
| 884 |
+
/// depth will be stable if observed to be greater than 0 (because CancelCollection is executing inside a stolen chore). Alternatively the thread can use
|
| 885 |
+
/// a CAS based state lock (see _TaskCollection::_CancelFromArbitraryThread) to ensure that inlining depth is stable.
|
| 886 |
+
/// </summary>
|
| 887 |
+
void ContextBase::CancelCollection(int inliningDepth)
|
| 888 |
+
{
|
| 889 |
+
InterlockedIncrement(&m_inlineCancellations);
|
| 890 |
+
|
| 891 |
+
long curDepth = m_minCancellationDepth;
|
| 892 |
+
//
|
| 893 |
+
// Keep track of the minimum cancellation depth.
|
| 894 |
+
//
|
| 895 |
+
for(;;)
|
| 896 |
+
{
|
| 897 |
+
if (curDepth != -1 && inliningDepth > curDepth)
|
| 898 |
+
break;
|
| 899 |
+
|
| 900 |
+
long xchgDepth = InterlockedCompareExchange(&m_minCancellationDepth, inliningDepth, curDepth);
|
| 901 |
+
if (xchgDepth == curDepth)
|
| 902 |
+
{
|
| 903 |
+
//
|
| 904 |
+
// Cancellation beacons are a bit different. If the entire context was canceled due to a steal, we flag top level cancellation
|
| 905 |
+
// beacons even though they are not considered to have inlining depth since the caller might not have been inlined.
|
| 906 |
+
//
|
| 907 |
+
FlagCancellationBeacons(IsEntireContextCanceled() ? -1 : inliningDepth);
|
| 908 |
+
break;
|
| 909 |
+
}
|
| 910 |
+
curDepth = xchgDepth;
|
| 911 |
+
}
|
| 912 |
+
|
| 913 |
+
long curMaxDepth = m_maxCancellationDepth;
|
| 914 |
+
//
|
| 915 |
+
// Keep track of the maximum cancellation depth
|
| 916 |
+
//
|
| 917 |
+
for(;;)
|
| 918 |
+
{
|
| 919 |
+
if (curMaxDepth != -1 && inliningDepth < curMaxDepth)
|
| 920 |
+
break;
|
| 921 |
+
|
| 922 |
+
long xchgDepth = InterlockedCompareExchange(&m_maxCancellationDepth, inliningDepth, curMaxDepth);
|
| 923 |
+
if (xchgDepth == curMaxDepth)
|
| 924 |
+
{
|
| 925 |
+
break;
|
| 926 |
+
}
|
| 927 |
+
curMaxDepth = xchgDepth;
|
| 928 |
+
}
|
| 929 |
+
}
|
| 930 |
+
|
| 931 |
+
/// <summary>
|
| 932 |
+
/// Recomputes the maximum depth of cancellation after a canceled task group clears its cancellation flag.
|
| 933 |
+
/// </summary>
|
| 934 |
+
void ContextBase::RecomputeMaximumCancellationDepth()
|
| 935 |
+
{
|
| 936 |
+
//
|
| 937 |
+
// Before doing the recompute, we **MUST** reset to uninitialized to avoid a race between someone setting this in ::CancelCollection and
|
| 938 |
+
// someone doing a recompute across a boundary.
|
| 939 |
+
//
|
| 940 |
+
InterlockedExchange(&m_maxCancellationDepth, -1);
|
| 941 |
+
|
| 942 |
+
long computedMaximumDepth = IsEntireContextCanceled() ? ENTIRE_CONTEXT_CANCELED : -1;
|
| 943 |
+
|
| 944 |
+
_TaskCollectionBase *pCollection = m_pExecutingCollection;
|
| 945 |
+
while (pCollection != NULL && pCollection != m_pRootCollection)
|
| 946 |
+
{
|
| 947 |
+
if ((pCollection->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pCollection))->_IsMarkedForCancellation()) ||
|
| 948 |
+
(!pCollection->_IsStructured() && (static_cast<_TaskCollection *>(pCollection))->_IsMarkedForAbnormalExit()))
|
| 949 |
+
{
|
| 950 |
+
computedMaximumDepth = pCollection->_M_inliningDepth;
|
| 951 |
+
break;
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
pCollection = pCollection->_SafeGetParent();
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
long curMaxDepth = -1;
|
| 958 |
+
|
| 959 |
+
//
|
| 960 |
+
// Keep track of the maximum cancellation depth
|
| 961 |
+
//
|
| 962 |
+
for(;;)
|
| 963 |
+
{
|
| 964 |
+
if (curMaxDepth != -1 && computedMaximumDepth < curMaxDepth)
|
| 965 |
+
break;
|
| 966 |
+
|
| 967 |
+
long xchgDepth = InterlockedCompareExchange(&m_maxCancellationDepth, computedMaximumDepth, curMaxDepth);
|
| 968 |
+
if (xchgDepth == curMaxDepth)
|
| 969 |
+
{
|
| 970 |
+
break;
|
| 971 |
+
}
|
| 972 |
+
|
| 973 |
+
curMaxDepth = xchgDepth;
|
| 974 |
+
}
|
| 975 |
+
}
|
| 976 |
+
|
| 977 |
+
/// <summary>
|
| 978 |
+
/// When a cancellation bubbles up to the collection being canceled, this function is called in order to stop propagation of
|
| 979 |
+
/// the cancellation further up the work tree. This method is paired with CancelCollection.
|
| 980 |
+
/// </summary>
|
| 981 |
+
bool ContextBase::CancelCollectionComplete(int inliningDepth)
|
| 982 |
+
{
|
| 983 |
+
ASSERT(m_inlineCancellations > 0);
|
| 984 |
+
|
| 985 |
+
//
|
| 986 |
+
// Keep track of minimum/maximum cancellation depth.
|
| 987 |
+
//
|
| 988 |
+
InterlockedCompareExchange(&m_minCancellationDepth, -1, inliningDepth);
|
| 989 |
+
RecomputeMaximumCancellationDepth();
|
| 990 |
+
|
| 991 |
+
return (InterlockedDecrement(&m_inlineCancellations) == 0);
|
| 992 |
+
}
|
| 993 |
+
|
| 994 |
+
/// <summary>
|
| 995 |
+
/// Send a context ETW event.
|
| 996 |
+
/// </summary>
|
| 997 |
+
void ContextBase::ThrowContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId)
|
| 998 |
+
{
|
| 999 |
+
if (g_pEtw != NULL)
|
| 1000 |
+
{
|
| 1001 |
+
CONCRT_TRACE_EVENT_HEADER_COMMON concrtHeader = {0};
|
| 1002 |
+
|
| 1003 |
+
concrtHeader.header.Size = sizeof concrtHeader;
|
| 1004 |
+
concrtHeader.header.Flags = WNODE_FLAG_TRACED_GUID;
|
| 1005 |
+
concrtHeader.header.Class.Type = (UCHAR)eventType;
|
| 1006 |
+
concrtHeader.header.Class.Level = level;
|
| 1007 |
+
concrtHeader.header.Guid = ContextEventGuid;
|
| 1008 |
+
|
| 1009 |
+
concrtHeader.SchedulerID = schedulerId;
|
| 1010 |
+
concrtHeader.ContextID = contextId;
|
| 1011 |
+
|
| 1012 |
+
g_pEtw->Trace(g_ConcRTSessionHandle, &concrtHeader.header);
|
| 1013 |
+
}
|
| 1014 |
+
}
|
| 1015 |
+
|
| 1016 |
+
/// <summary>
|
| 1017 |
+
/// Enters a critical region of the scheduler. Calling this guarantees that the virtual processor on which this context lives
|
| 1018 |
+
/// is guaranteed to be stable throughout the critical region. For some context types, this is virtually a NOP.
|
| 1019 |
+
/// Note that critical regions suppress asynchronous blocking but not synchronous blocking.
|
| 1020 |
+
/// </summary>
|
| 1021 |
+
int ContextBase::EnterCriticalRegion()
|
| 1022 |
+
{
|
| 1023 |
+
return 0;
|
| 1024 |
+
}
|
| 1025 |
+
|
| 1026 |
+
/// <summary>
|
| 1027 |
+
/// Exits a critical region of the scheduler.
|
| 1028 |
+
/// </summary>
|
| 1029 |
+
int ContextBase::ExitCriticalRegion()
|
| 1030 |
+
{
|
| 1031 |
+
return 0;
|
| 1032 |
+
}
|
| 1033 |
+
|
| 1034 |
+
/// <summary>
|
| 1035 |
+
/// Enters a hyper-critical region of the scheduler. Calling this guarantees not only the conditions of a critical region but it
|
| 1036 |
+
/// guarantees that synchronous blocking is suppressed as well. This allows for lock sharing between the primary and hyper-critical
|
| 1037 |
+
/// regions running on UTs. No lock sharing can occur between the inside of this region type and the outside of this region type
|
| 1038 |
+
/// on a UT.
|
| 1039 |
+
/// </summary>
|
| 1040 |
+
int ContextBase::EnterHyperCriticalRegion()
|
| 1041 |
+
{
|
| 1042 |
+
return 0;
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
/// <summary>
|
| 1046 |
+
/// Exits a hyper-critical region of the scheduler.
|
| 1047 |
+
/// </summary>
|
| 1048 |
+
int ContextBase::ExitHyperCriticalRegion()
|
| 1049 |
+
{
|
| 1050 |
+
return 0;
|
| 1051 |
+
}
|
| 1052 |
+
|
| 1053 |
+
/// <summary>
|
| 1054 |
+
/// Static version of EnterCriticalRegion.
|
| 1055 |
+
/// </summary>
|
| 1056 |
+
void ContextBase::StaticEnterCriticalRegion()
|
| 1057 |
+
{
|
| 1058 |
+
ContextBase *pContext = SchedulerBase::FastCurrentContext();
|
| 1059 |
+
if (pContext != NULL)
|
| 1060 |
+
pContext->EnterCriticalRegion();
|
| 1061 |
+
}
|
| 1062 |
+
|
| 1063 |
+
/// <summary>
|
| 1064 |
+
/// Static version of EnterHyperCriticalRegion.
|
| 1065 |
+
/// </summary>
|
| 1066 |
+
void ContextBase::StaticEnterHyperCriticalRegion()
|
| 1067 |
+
{
|
| 1068 |
+
ContextBase *pContext = SchedulerBase::FastCurrentContext();
|
| 1069 |
+
if (pContext != NULL)
|
| 1070 |
+
pContext->EnterHyperCriticalRegion();
|
| 1071 |
+
}
|
| 1072 |
+
|
| 1073 |
+
/// <summary>
|
| 1074 |
+
/// Static version of ExitCriticalRegion.
|
| 1075 |
+
/// </summary>
|
| 1076 |
+
void ContextBase::StaticExitCriticalRegion()
|
| 1077 |
+
{
|
| 1078 |
+
ContextBase *pContext = SchedulerBase::FastCurrentContext();
|
| 1079 |
+
if (pContext != NULL)
|
| 1080 |
+
pContext->ExitCriticalRegion();
|
| 1081 |
+
}
|
| 1082 |
+
|
| 1083 |
+
/// <summary>
|
| 1084 |
+
/// Static version of ExitHyperCriticalRegion.
|
| 1085 |
+
/// </summary>
|
| 1086 |
+
void ContextBase::StaticExitHyperCriticalRegion()
|
| 1087 |
+
{
|
| 1088 |
+
ContextBase *pContext = SchedulerBase::FastCurrentContext();
|
| 1089 |
+
if (pContext != NULL)
|
| 1090 |
+
pContext->ExitHyperCriticalRegion();
|
| 1091 |
+
}
|
| 1092 |
+
|
| 1093 |
+
/// <summary>
|
| 1094 |
+
/// Static version of GetCriticalRegionType.
|
| 1095 |
+
/// </summary>
|
| 1096 |
+
CriticalRegionType ContextBase::StaticGetCriticalRegionType()
|
| 1097 |
+
{
|
| 1098 |
+
ContextBase *pContext = SchedulerBase::FastCurrentContext();
|
| 1099 |
+
if (pContext != NULL)
|
| 1100 |
+
return pContext->GetCriticalRegionType();
|
| 1101 |
+
return OutsideCriticalRegion;
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
/// <summary>
|
| 1105 |
+
/// Since critical region counts are turned off for thread schedulers, this method is used
|
| 1106 |
+
/// where the return value is expected to be true. For a thread scheduler, it always returns true.
|
| 1107 |
+
/// </summary>
|
| 1108 |
+
bool ContextBase::IsInsideCriticalRegion() const
|
| 1109 |
+
{
|
| 1110 |
+
return true;
|
| 1111 |
+
}
|
| 1112 |
+
|
| 1113 |
+
/// <summary>
|
| 1114 |
+
/// Returns a bool which can be polled from the current location in lieu of calling is_current_task_group_canceling.
|
| 1115 |
+
/// </summary>
|
| 1116 |
+
_Beacon_reference *ContextBase::PushCancellationBeacon()
|
| 1117 |
+
{
|
| 1118 |
+
int inliningDepth = m_pExecutingCollection ? m_pExecutingCollection->_InliningDepth() : -1;
|
| 1119 |
+
|
| 1120 |
+
CancellationBeacon *pBeacon = m_cancellationBeacons.AcquirePushBeacon(inliningDepth);
|
| 1121 |
+
|
| 1122 |
+
//
|
| 1123 |
+
// AcquirePushBeacon has a full fence to guard R/W ordering here.
|
| 1124 |
+
//
|
| 1125 |
+
if (IsEntireContextCanceled() || (m_minCancellationDepth != -1 && m_minCancellationDepth <= pBeacon->m_beaconDepth))
|
| 1126 |
+
pBeacon->InternalSignal();
|
| 1127 |
+
|
| 1128 |
+
return &(pBeacon->m_beacon);
|
| 1129 |
+
}
|
| 1130 |
+
|
| 1131 |
+
/// <summary>
|
| 1132 |
+
/// Releases the topmost bool acquired in RAII fashion from PushCancellationBeacon.
|
| 1133 |
+
/// </summary>
|
| 1134 |
+
void ContextBase::PopCancellationBeacon()
|
| 1135 |
+
{
|
| 1136 |
+
m_cancellationBeacons.ReleaseBeacon();
|
| 1137 |
+
}
|
| 1138 |
+
|
| 1139 |
+
/// <summary>
|
| 1140 |
+
/// Flags any cancellation beacons that are inlined at or below the specified point.
|
| 1141 |
+
/// </summary>
|
| 1142 |
+
void ContextBase::FlagCancellationBeacons(int inliningDepth)
|
| 1143 |
+
{
|
| 1144 |
+
LONG snapSize = m_cancellationBeacons.BeaconCount();
|
| 1145 |
+
for (LONG i = 0; i < snapSize; i++)
|
| 1146 |
+
{
|
| 1147 |
+
//
|
| 1148 |
+
// The beacon list is guaranteed to exist. Further, because we do this during cancellation for inlined collections, we can
|
| 1149 |
+
// never unpop and reuse a beacon for a lower depth until the cancellation is complete because of strict nesting on the
|
| 1150 |
+
// beacon stack (RAII).
|
| 1151 |
+
//
|
| 1152 |
+
CancellationBeacon *pBeacon = m_cancellationBeacons[i];
|
| 1153 |
+
if (pBeacon->m_beaconDepth >= inliningDepth)
|
| 1154 |
+
{
|
| 1155 |
+
//
|
| 1156 |
+
// We have one interesting conundrum here. Everything from depth 0 -> inliningDepth is guaranteed to be stable. Anything from
|
| 1157 |
+
// inliningDepth + 1 -> N can change. That change might include what cancellation tokens are active. This might, in fact, change
|
| 1158 |
+
// whether a cancellation has truly happened or not.
|
| 1159 |
+
//
|
| 1160 |
+
// In order to solve this, two things will happen:
|
| 1161 |
+
//
|
| 1162 |
+
// - Whoever observes a beacon signaled must do a further check to CONFIRM the cancellation.
|
| 1163 |
+
//
|
| 1164 |
+
// - If there is a guarantee that the cancellation will not hit us in THIS call, we will not flag the beacon as a performance
|
| 1165 |
+
// optimization.
|
| 1166 |
+
//
|
| 1167 |
+
// 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
|
| 1168 |
+
// can be double checked. A false negative will never be flagged again and will lead to uncancellable trees!
|
| 1169 |
+
//
|
| 1170 |
+
int governingDepth = m_governingTokenDepth; // *MUST* be captured to be observationally consistent in the check below
|
| 1171 |
+
if (governingDepth == -1 || governingDepth <= inliningDepth)
|
| 1172 |
+
{
|
| 1173 |
+
pBeacon->InternalSignal();
|
| 1174 |
+
}
|
| 1175 |
+
}
|
| 1176 |
+
}
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
/// <summary>
|
| 1180 |
+
/// Called to determine if a confirmed cancellation on this context is hidden at the depth of the caller.
|
| 1181 |
+
/// A governing token that is not canceled could be protecting the task collection from cancellation from above.
|
| 1182 |
+
/// The token of the supplied task collection is used to veto an interruption. See comments in IsCancellationVisible
|
| 1183 |
+
/// <summary>
|
| 1184 |
+
bool ContextBase::TokenHidesCancellation(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken) const
|
| 1185 |
+
{
|
| 1186 |
+
//
|
| 1187 |
+
// An override token is used to determine visibility of cancellation at the end of _RunAndWait for structured
|
| 1188 |
+
// and unstructured task collections. The governing token and cancellation depths apply to higher level task
|
| 1189 |
+
// collections at this point, however, _RunAndWait should not interrupt if the token of pCurrentTaskCollection
|
| 1190 |
+
// is not canceled, so that the token provides total isolation from parent cancellation.
|
| 1191 |
+
//
|
| 1192 |
+
if (hasOverrideToken)
|
| 1193 |
+
{
|
| 1194 |
+
_CancellationTokenState * pOverrideTokenState = pCurrentTaskCollection->_GetTokenState();
|
| 1195 |
+
if (pOverrideTokenState == _CancellationTokenState::_None() || !pOverrideTokenState->_IsCanceled())
|
| 1196 |
+
{
|
| 1197 |
+
return true;
|
| 1198 |
+
}
|
| 1199 |
+
}
|
| 1200 |
+
//
|
| 1201 |
+
// Any token hides the propagation of implicit cancellation from above unless the token itself is EXPLICITLY canceled.
|
| 1202 |
+
// Note, that m_maxCancellationDepth can be ENTIRE_CONTEXT_CANCELED, which is < -1, therefore we must check that the
|
| 1203 |
+
// governing token depth is not -1.
|
| 1204 |
+
//
|
| 1205 |
+
if (m_maxCancellationDepth < m_governingTokenDepth && m_governingTokenDepth != -1)
|
| 1206 |
+
{
|
| 1207 |
+
ASSERT(m_pGoverningTokenState != NULL);
|
| 1208 |
+
if (m_pGoverningTokenState == _CancellationTokenState::_None())
|
| 1209 |
+
{
|
| 1210 |
+
return true;
|
| 1211 |
+
}
|
| 1212 |
+
return (!m_pGoverningTokenState->_IsCanceled());
|
| 1213 |
+
}
|
| 1214 |
+
return false;
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
/// <summary>
|
| 1218 |
+
/// Called to determine whether a committed or pending cancellation on this context is visible at the level of the caller.
|
| 1219 |
+
/// NOTE: This method should only be called on the current context from _RunAndWait for the task collection supplied at an argument.
|
| 1220 |
+
/// The asserts below will check for that.
|
| 1221 |
+
/// The interruption points at the end of _RunAndWait must use the token of the task collection to override cancellation from
|
| 1222 |
+
/// above - i.e, even if the cancellation depth and governing token depth determine that an interruption point would've thrown
|
| 1223 |
+
/// an interruption exception, if there was an uncanceled token on this task collection, no interruption should take place.
|
| 1224 |
+
/// This allows total isolation from parent cancellation using cancellation tokens.
|
| 1225 |
+
/// </summary>
|
| 1226 |
+
bool ContextBase::IsCancellationVisible(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken /* = false */) const
|
| 1227 |
+
{
|
| 1228 |
+
ASSERT(SchedulerBase::FastCurrentContext() == this && pCurrentTaskCollection->_M_pOwningContext == this);
|
| 1229 |
+
ASSERT(m_pExecutingCollection == pCurrentTaskCollection || m_pExecutingCollection == pCurrentTaskCollection->_M_pParent);
|
| 1230 |
+
ASSERT(HasAnyCancellation());
|
| 1231 |
+
|
| 1232 |
+
return ((HasInlineCancellation() && !TokenHidesCancellation(pCurrentTaskCollection, hasOverrideToken)) ||
|
| 1233 |
+
(HasPendingCancellation() && pCurrentTaskCollection->_WillInterruptForPendingCancel()));
|
| 1234 |
+
}
|
| 1235 |
+
|
| 1236 |
+
/// <summary>
|
| 1237 |
+
/// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is normally only valid when
|
| 1238 |
+
/// called from the thread representing this context. There are times under the context chaining lock (stealers list) or from an indirect
|
| 1239 |
+
/// alias of a collection on this context, where this can be called safely **FOR CERTAIN DEPTHS** from another thread.
|
| 1240 |
+
/// </summary>
|
| 1241 |
+
/// <param name="depth">
|
| 1242 |
+
/// The depth at which to check for cancellation. If the method is called from a thread other than the one representing this context,
|
| 1243 |
+
/// the caller must guarantee that this context will not unwind past a task group or structured task group of inlining depth = 'depth'.
|
| 1244 |
+
/// If the caller has observed a collection inlined at 'depth' != -1 while holding the stealers lock on this context, or the caller
|
| 1245 |
+
/// is executing a chores on an indirect alias while the original task group is inlined, this guarantee is automatically provided.
|
| 1246 |
+
/// </param>
|
| 1247 |
+
bool ContextBase::IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection, int depth)
|
| 1248 |
+
{
|
| 1249 |
+
ASSERT(pStartingCollection->_M_inliningDepth >= depth);
|
| 1250 |
+
if (HasInlineCancellation() && m_minCancellationDepth <= depth)
|
| 1251 |
+
{
|
| 1252 |
+
//
|
| 1253 |
+
// Normally, this would be an indication of a cancellation in progress. There may, however, be a cancellation token which stops
|
| 1254 |
+
// us from observing it. Detecting this at arbitrary depth is more complex than detecting it at a current interruption point because
|
| 1255 |
+
// we only track min/max on cancellation depth. Arbitrary depth requires us to walk back up the inlining tree until we find the token
|
| 1256 |
+
// governing depth.
|
| 1257 |
+
//
|
| 1258 |
+
// If there is no token or all tokens are above the cancellation depth, clearly we do not need to do this.
|
| 1259 |
+
//
|
| 1260 |
+
if (m_governingTokenDepth == -1 || m_minCancellationDepth >= m_governingTokenDepth)
|
| 1261 |
+
return true;
|
| 1262 |
+
|
| 1263 |
+
//
|
| 1264 |
+
// If we are checking a cancellation beacon in strictly nested order, this is a simple bottom check.
|
| 1265 |
+
//
|
| 1266 |
+
if (pStartingCollection == m_pExecutingCollection && depth == m_pExecutingCollection->_M_inliningDepth)
|
| 1267 |
+
{
|
| 1268 |
+
if (m_pGoverningTokenState == _CancellationTokenState::_None())
|
| 1269 |
+
return false;
|
| 1270 |
+
|
| 1271 |
+
return m_pGoverningTokenState->_IsCanceled();
|
| 1272 |
+
}
|
| 1273 |
+
|
| 1274 |
+
//
|
| 1275 |
+
// 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,
|
| 1276 |
+
// this should not need to be done often.
|
| 1277 |
+
//
|
| 1278 |
+
_TaskCollectionBase *pCollection = pStartingCollection;
|
| 1279 |
+
while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_M_inliningDepth != depth)
|
| 1280 |
+
{
|
| 1281 |
+
pCollection = pCollection->_SafeGetParent();
|
| 1282 |
+
}
|
| 1283 |
+
|
| 1284 |
+
while (pCollection != NULL && pCollection != m_pRootCollection && pCollection->_GetTokenState() == NULL)
|
| 1285 |
+
{
|
| 1286 |
+
if ((pCollection->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pCollection))->_IsMarkedForCancellation()) ||
|
| 1287 |
+
(!pCollection->_IsStructured() && (static_cast<_TaskCollection *>(pCollection))->_IsMarkedForAbnormalExit()))
|
| 1288 |
+
{
|
| 1289 |
+
return true;
|
| 1290 |
+
}
|
| 1291 |
+
pCollection = pCollection->_SafeGetParent();
|
| 1292 |
+
}
|
| 1293 |
+
|
| 1294 |
+
if (pCollection != NULL && pCollection != m_pRootCollection)
|
| 1295 |
+
{
|
| 1296 |
+
_CancellationTokenState *pGoverningTokenState = pCollection->_GetTokenState();
|
| 1297 |
+
ASSERT(pGoverningTokenState != NULL);
|
| 1298 |
+
if (pGoverningTokenState != _CancellationTokenState::_None())
|
| 1299 |
+
{
|
| 1300 |
+
return pGoverningTokenState->_IsCanceled();
|
| 1301 |
+
}
|
| 1302 |
+
}
|
| 1303 |
+
}
|
| 1304 |
+
return false;
|
| 1305 |
+
}
|
| 1306 |
+
|
| 1307 |
+
_Cancellation_beacon::_Cancellation_beacon()
|
| 1308 |
+
{
|
| 1309 |
+
ContextBase *pContext = SchedulerBase::CurrentContext();
|
| 1310 |
+
_M_pRef = pContext->PushCancellationBeacon();
|
| 1311 |
+
}
|
| 1312 |
+
|
| 1313 |
+
_Cancellation_beacon::~_Cancellation_beacon()
|
| 1314 |
+
{
|
| 1315 |
+
ContextBase *pContext = SchedulerBase::CurrentContext();
|
| 1316 |
+
pContext->PopCancellationBeacon();
|
| 1317 |
+
}
|
| 1318 |
+
|
| 1319 |
+
bool _Cancellation_beacon::_Confirm_cancel()
|
| 1320 |
+
{
|
| 1321 |
+
ContextBase *pContext = SchedulerBase::CurrentContext();
|
| 1322 |
+
bool fCanceled = pContext->ConfirmCancel(_M_pRef);
|
| 1323 |
+
if (!fCanceled)
|
| 1324 |
+
{
|
| 1325 |
+
_Lower();
|
| 1326 |
+
}
|
| 1327 |
+
return fCanceled;
|
| 1328 |
+
}
|
| 1329 |
+
|
| 1330 |
+
/// <summary>
|
| 1331 |
+
/// Return a reference to the ppltask inline schedule depth slot on current context
|
| 1332 |
+
/// The inline depth will be set to 0 when the context is first initialized,
|
| 1333 |
+
/// and the caller is responsible to maintain that depth.
|
| 1334 |
+
/// </summary>
|
| 1335 |
+
_CONCRTIMP size_t & __cdecl _StackGuard::_GetCurrentInlineDepth()
|
| 1336 |
+
{
|
| 1337 |
+
return SchedulerBase::CurrentContext()->m_asyncTaskCollectionInlineDepth;
|
| 1338 |
+
}
|
| 1339 |
+
} // namespace details
|
| 1340 |
+
|
| 1341 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ContextBase.h
ADDED
|
@@ -0,0 +1,1147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ContextBase.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the metaphor for an execution context/stack/thread.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
// Defines used for context blocking (m_blockedState):
|
| 16 |
+
// * Possible blocked states
|
| 17 |
+
#define CONTEXT_NOT_BLOCKED 0x0
|
| 18 |
+
#define CONTEXT_BLOCKED 0x1
|
| 19 |
+
#define CONTEXT_UMS_SYNC_BLOCKED 0x2
|
| 20 |
+
#define CONTEXT_UMS_ASYNC_BLOCKED 0x4
|
| 21 |
+
|
| 22 |
+
// * Useful bit-masks
|
| 23 |
+
#define CONTEXT_SYNC_BLOCKED (CONTEXT_BLOCKED | CONTEXT_UMS_SYNC_BLOCKED)
|
| 24 |
+
#define CONTEXT_UMS_BLOCKED (CONTEXT_UMS_SYNC_BLOCKED | CONTEXT_UMS_ASYNC_BLOCKED)
|
| 25 |
+
|
| 26 |
+
#define ENTIRE_CONTEXT_CANCELED -999
|
| 27 |
+
|
| 28 |
+
namespace Concurrency
|
| 29 |
+
{
|
| 30 |
+
namespace details
|
| 31 |
+
{
|
| 32 |
+
/// <summary>
|
| 33 |
+
/// Implements the base class for a ConcRT execution context.
|
| 34 |
+
/// </summary>
|
| 35 |
+
#pragma warning(push)
|
| 36 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 37 |
+
class ContextBase : public Context
|
| 38 |
+
{
|
| 39 |
+
public:
|
| 40 |
+
//
|
| 41 |
+
// Public Methods
|
| 42 |
+
//
|
| 43 |
+
|
| 44 |
+
/// <summary>
|
| 45 |
+
/// Constructor
|
| 46 |
+
/// </summary>
|
| 47 |
+
ContextBase(SchedulerBase *pScheduler, bool fIsExternal);
|
| 48 |
+
|
| 49 |
+
/// <summary>
|
| 50 |
+
/// Returns a unique identifier to the context.
|
| 51 |
+
/// </summary>
|
| 52 |
+
virtual unsigned int GetId() const;
|
| 53 |
+
|
| 54 |
+
/// <summary>
|
| 55 |
+
/// Returns an identifier to the virtual processor the context is currently executing on, if any.
|
| 56 |
+
/// </summary>
|
| 57 |
+
virtual unsigned int GetVirtualProcessorId() const =0;
|
| 58 |
+
|
| 59 |
+
/// <summary>
|
| 60 |
+
/// Returns an identifier to the schedule group the context is currently working on, if any.
|
| 61 |
+
/// </summary>
|
| 62 |
+
virtual unsigned int GetScheduleGroupId() const;
|
| 63 |
+
|
| 64 |
+
/// <summary>
|
| 65 |
+
/// Returns the reference count of the underlying schedule group, which is equivalent
|
| 66 |
+
/// to the number of contexts performing work on the schedule group.
|
| 67 |
+
/// <summary>
|
| 68 |
+
unsigned int ScheduleGroupRefCount() const;
|
| 69 |
+
|
| 70 |
+
/// <summary>
|
| 71 |
+
/// Causes the context to block, yielding the virtual processor to another context.
|
| 72 |
+
/// </summary>
|
| 73 |
+
virtual void Block() =0;
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Unblocks the context and makes it runnable.
|
| 77 |
+
/// </summary>
|
| 78 |
+
virtual void Unblock() =0;
|
| 79 |
+
|
| 80 |
+
/// <summary>
|
| 81 |
+
/// Determines whether or not the context is synchronously blocked at this given time.
|
| 82 |
+
/// </summary>
|
| 83 |
+
/// <returns>
|
| 84 |
+
/// Whether context is in synchronous block state.
|
| 85 |
+
/// </returns>
|
| 86 |
+
virtual bool IsSynchronouslyBlocked() const =0;
|
| 87 |
+
|
| 88 |
+
/// <summary>
|
| 89 |
+
/// Returns whether the context is blocked or not. Note that this definition of blocked is "blocked and requires
|
| 90 |
+
/// eventual reexecution -- e.g.: finalization will call this during the sweep phase).
|
| 91 |
+
/// </summary>
|
| 92 |
+
bool IsBlocked() const
|
| 93 |
+
{
|
| 94 |
+
return (m_blockedState != CONTEXT_NOT_BLOCKED);
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
/// <summary>
|
| 98 |
+
/// Yields execution to a different runnable context, and puts this context on a runnables collection.
|
| 99 |
+
/// If no context is found to yield to, the context continues to run.
|
| 100 |
+
/// </summary>
|
| 101 |
+
virtual void Yield() =0;
|
| 102 |
+
|
| 103 |
+
/// <summary>
|
| 104 |
+
/// Yields execution to a different runnable context, and puts this context on a runnables collection.
|
| 105 |
+
/// If no context is found to yield to, the context continues to run.
|
| 106 |
+
///
|
| 107 |
+
/// This is intended for spin loops.
|
| 108 |
+
/// </summary>
|
| 109 |
+
virtual void SpinYield() =0;
|
| 110 |
+
|
| 111 |
+
/// <summary>
|
| 112 |
+
/// See comments for Concurrency::Context::Oversubscribe.
|
| 113 |
+
/// </summary>
|
| 114 |
+
virtual void Oversubscribe(bool beginOversubscription) =0;
|
| 115 |
+
|
| 116 |
+
/// <summary>
|
| 117 |
+
/// Cleans up the Context.
|
| 118 |
+
/// </summary>
|
| 119 |
+
void Cleanup();
|
| 120 |
+
|
| 121 |
+
/// <summary>
|
| 122 |
+
/// Allocates a block of memory of the size specified.
|
| 123 |
+
/// </summary>
|
| 124 |
+
/// <param name="numBytes">
|
| 125 |
+
/// Number of bytes to allocate.
|
| 126 |
+
/// </param>
|
| 127 |
+
/// <returns>
|
| 128 |
+
/// A pointer to newly allocated memory.
|
| 129 |
+
/// </returns>
|
| 130 |
+
virtual void* Alloc(size_t numBytes) =0;
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 134 |
+
/// </summary>
|
| 135 |
+
/// <param name="pAllocation">
|
| 136 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 137 |
+
/// </param>
|
| 138 |
+
virtual void Free(void* pAllocation) =0;
|
| 139 |
+
|
| 140 |
+
/// <summary>
|
| 141 |
+
/// Enters a critical region of the scheduler. Calling this guarantees that the virtual processor on which this context lives
|
| 142 |
+
/// is guaranteed to be stable throughout the critical region. For some context types, this is virtually a NOP. For others
|
| 143 |
+
/// (UMS), this makes it appear that blocking on the context actually blocks the UMS thread instead of triggering return to
|
| 144 |
+
/// primary. Note that critical regions suppress asynchronous blocking but not synchronous blocking.
|
| 145 |
+
/// </summary>
|
| 146 |
+
virtual int EnterCriticalRegionHelper()
|
| 147 |
+
{
|
| 148 |
+
CONCRT_COREASSERT(Context::CurrentContext() == this);
|
| 149 |
+
return ++m_criticalRegionCount;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
int EnterCriticalRegion();
|
| 153 |
+
|
| 154 |
+
/// <summary>
|
| 155 |
+
/// Static version of EnterCriticalRegion.
|
| 156 |
+
/// </summary>
|
| 157 |
+
static void StaticEnterCriticalRegion();
|
| 158 |
+
|
| 159 |
+
/// <summary>
|
| 160 |
+
/// Enters a hyper-critical region of the scheduler. Calling this guarantees not only the conditions of a critical region but it
|
| 161 |
+
/// guarantees that synchronous blocking is suppressed as well. This allows for lock sharing between the primary and hyper-critical
|
| 162 |
+
/// regions running on UTs. No lock sharing can occur between the inside of this region type and the outside of this region type
|
| 163 |
+
/// on a UT.
|
| 164 |
+
/// </summary>
|
| 165 |
+
virtual int EnterHyperCriticalRegionHelper()
|
| 166 |
+
{
|
| 167 |
+
m_criticalRegionCount++;
|
| 168 |
+
return ++m_hyperCriticalRegionCount;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
int EnterHyperCriticalRegion();
|
| 172 |
+
|
| 173 |
+
/// <summary>
|
| 174 |
+
/// Static version of EnterHyperCriticalRegion.
|
| 175 |
+
/// </summary>
|
| 176 |
+
static void StaticEnterHyperCriticalRegion();
|
| 177 |
+
|
| 178 |
+
/// <summary>
|
| 179 |
+
/// Exits a critical region of the scheduler.
|
| 180 |
+
/// </summary>
|
| 181 |
+
virtual int ExitCriticalRegionHelper()
|
| 182 |
+
{
|
| 183 |
+
CONCRT_COREASSERT(m_criticalRegionCount > 0);
|
| 184 |
+
CONCRT_COREASSERT(Context::CurrentContext() == this);
|
| 185 |
+
return --m_criticalRegionCount;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
int ExitCriticalRegion();
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// Static version of ExitCriticalRegion.
|
| 192 |
+
/// </summary>
|
| 193 |
+
static void StaticExitCriticalRegion();
|
| 194 |
+
|
| 195 |
+
/// <summary>
|
| 196 |
+
/// Exits a hyper-critical region of the scheduler.
|
| 197 |
+
/// </summary>
|
| 198 |
+
virtual int ExitHyperCriticalRegionHelper()
|
| 199 |
+
{
|
| 200 |
+
CONCRT_COREASSERT(m_hyperCriticalRegionCount > 0);
|
| 201 |
+
CONCRT_COREASSERT(m_criticalRegionCount > 0);
|
| 202 |
+
m_criticalRegionCount--;
|
| 203 |
+
return --m_hyperCriticalRegionCount;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
int ExitHyperCriticalRegion();
|
| 207 |
+
|
| 208 |
+
/// <summary>
|
| 209 |
+
/// Static version of ExitHyperCriticalRegion.
|
| 210 |
+
/// </summary>
|
| 211 |
+
static void StaticExitHyperCriticalRegion();
|
| 212 |
+
|
| 213 |
+
/// <summary>
|
| 214 |
+
/// Checks if a context is in a critical region. This is only safe from either the current context or from a UMS primary which
|
| 215 |
+
/// has woken due to a given context blocking.
|
| 216 |
+
/// </summary>
|
| 217 |
+
virtual CriticalRegionType GetCriticalRegionType() const
|
| 218 |
+
{
|
| 219 |
+
if (m_hyperCriticalRegionCount > 0)
|
| 220 |
+
return InsideHyperCriticalRegion;
|
| 221 |
+
if (m_criticalRegionCount > 0)
|
| 222 |
+
return InsideCriticalRegion;
|
| 223 |
+
return OutsideCriticalRegion;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
/// <summary>
|
| 227 |
+
/// Since critical region counts are turned off for thread schedulers, this method is used
|
| 228 |
+
/// where the return value is expected to be true. For a thread scheduler, it always returns true.
|
| 229 |
+
/// For a ums scheduler it returns (GetCriticalRegionType() != OutsideCriticalRegion).
|
| 230 |
+
/// IsInsideContextLevelCriticalRegion only checks (ContextBase::GetCriticalRegionType() != OutsideCriticalRegion).
|
| 231 |
+
/// </summary>
|
| 232 |
+
bool IsInsideCriticalRegion() const;
|
| 233 |
+
|
| 234 |
+
/// <summary>
|
| 235 |
+
/// Static version of GetCriticalRegionType.
|
| 236 |
+
/// </summary>
|
| 237 |
+
static CriticalRegionType StaticGetCriticalRegionType();
|
| 238 |
+
|
| 239 |
+
/// <summary>
|
| 240 |
+
/// Set critical region counts to zero
|
| 241 |
+
/// </summary>
|
| 242 |
+
void ClearCriticalRegion()
|
| 243 |
+
{
|
| 244 |
+
m_hyperCriticalRegionCount = m_criticalRegionCount = 0;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
#if defined(_DEBUG)
|
| 248 |
+
/// <summary>
|
| 249 |
+
/// Tells the context it's shutting down a virtual processor and normal lock validations don't apply.
|
| 250 |
+
/// </summary>
|
| 251 |
+
void SetShutdownValidations()
|
| 252 |
+
{
|
| 253 |
+
m_fShutdownValidations = true;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
/// <summary>
|
| 257 |
+
/// Re-enable normal lock validations
|
| 258 |
+
/// </summary>
|
| 259 |
+
void ClearShutdownValidations()
|
| 260 |
+
{
|
| 261 |
+
m_fShutdownValidations = false;
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
/// <summary>
|
| 265 |
+
/// Returns whether or not the context is in a "shutting down a virtual processor" mode where normal lock validations don't apply.
|
| 266 |
+
/// </summary>
|
| 267 |
+
bool IsShutdownValidations() const
|
| 268 |
+
{
|
| 269 |
+
return m_fShutdownValidations;
|
| 270 |
+
}
|
| 271 |
+
#endif // _DEBUG
|
| 272 |
+
|
| 273 |
+
/// <summary>
|
| 274 |
+
/// Wrapper for m_pWorkQueue for use in unstructured task collections
|
| 275 |
+
/// that performs delay construction as well as insertion into schedule group.
|
| 276 |
+
/// </summary>
|
| 277 |
+
WorkQueue *GetWorkQueue()
|
| 278 |
+
{
|
| 279 |
+
// want inlining
|
| 280 |
+
if (m_pWorkQueue == NULL)
|
| 281 |
+
CreateWorkQueue();
|
| 282 |
+
return m_pWorkQueue;
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
/// <summary>
|
| 286 |
+
/// Wrapper for m_pWorkQueue for use in structured task collections
|
| 287 |
+
/// that performs delay construction as well as insertion into schedule group.
|
| 288 |
+
/// </summary>
|
| 289 |
+
WorkQueue *GetStructuredWorkQueue()
|
| 290 |
+
{
|
| 291 |
+
// want inlining
|
| 292 |
+
if (m_pWorkQueue == NULL)
|
| 293 |
+
CreateStructuredWorkQueue();
|
| 294 |
+
return m_pWorkQueue;
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
/// <summary>
|
| 298 |
+
/// Create a workqueue for use in unstructured task collections.
|
| 299 |
+
/// </summary>
|
| 300 |
+
void CreateWorkQueue();
|
| 301 |
+
|
| 302 |
+
/// <summary>
|
| 303 |
+
/// Create a workqueue for use in structured task collections.
|
| 304 |
+
/// </summary>
|
| 305 |
+
void CreateStructuredWorkQueue();
|
| 306 |
+
|
| 307 |
+
/// <summary>
|
| 308 |
+
/// Returns a unique identifier for the work queue associated with this context. Note that this should only be used
|
| 309 |
+
/// for binding (e.g.: task collection binding)
|
| 310 |
+
/// </summary>
|
| 311 |
+
unsigned int GetWorkQueueIdentity()
|
| 312 |
+
{
|
| 313 |
+
return GetWorkQueue()->Id();
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
/// <summary>
|
| 317 |
+
/// Pushes an unrealized chore onto the work stealing queue for structured parallelism.
|
| 318 |
+
/// </summary>
|
| 319 |
+
/// <param name="pChore">
|
| 320 |
+
/// The chore to push onto the structured work stealing queue.
|
| 321 |
+
/// </param>
|
| 322 |
+
/// <param name="_PLocation">
|
| 323 |
+
/// The location where the unrealized chore should execute.
|
| 324 |
+
/// </param>
|
| 325 |
+
void PushStructured(_UnrealizedChore *pChore, location *pLocation);
|
| 326 |
+
|
| 327 |
+
/// <summary>
|
| 328 |
+
/// Pushes an unrealized chore onto the work stealing queue for structured parallelism.
|
| 329 |
+
/// </summary>
|
| 330 |
+
/// <param name="pChore">
|
| 331 |
+
/// The chore to push onto the structured work stealing queue.
|
| 332 |
+
/// </param>
|
| 333 |
+
void PushStructured(_UnrealizedChore *pChore);
|
| 334 |
+
|
| 335 |
+
/// <summary>
|
| 336 |
+
/// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism.
|
| 337 |
+
/// </summary>
|
| 338 |
+
/// <param name="pChore">
|
| 339 |
+
/// The chore to push onto the unstructured work stealing queue.
|
| 340 |
+
/// </param>
|
| 341 |
+
/// <param name="_PLocation">
|
| 342 |
+
/// The location where the unrealized chore should execute.
|
| 343 |
+
/// </param>
|
| 344 |
+
int PushUnstructured(_UnrealizedChore *pChore, location *pLocation);
|
| 345 |
+
|
| 346 |
+
/// <summary>
|
| 347 |
+
/// Pushes an unrealized chore onto the work stealing queue for unstructured parallelism.
|
| 348 |
+
/// </summary>
|
| 349 |
+
/// <param name="pChore">
|
| 350 |
+
/// The chore to push onto the unstructured work stealing queue.
|
| 351 |
+
/// </param>
|
| 352 |
+
int PushUnstructured(_UnrealizedChore *pChore);
|
| 353 |
+
|
| 354 |
+
/// <summary>
|
| 355 |
+
/// Sweeps the unstructured work stealing queue for items matching a predicate and potentially removes them
|
| 356 |
+
/// based on the result of a callback.
|
| 357 |
+
/// </summary>
|
| 358 |
+
/// <param name="pPredicate">
|
| 359 |
+
/// The predicate for things to call pSweepFn on.
|
| 360 |
+
/// </param>
|
| 361 |
+
/// <param name="pData">
|
| 362 |
+
/// The data for the predicate callback
|
| 363 |
+
/// </param>
|
| 364 |
+
/// <param name="pSweepFn">
|
| 365 |
+
/// The sweep function
|
| 366 |
+
/// </param>
|
| 367 |
+
void SweepUnstructured(WorkStealingQueue<_UnrealizedChore>::SweepPredicate pPredicate,
|
| 368 |
+
void *pData,
|
| 369 |
+
WorkStealingQueue<_UnrealizedChore>::SweepFunction pSweepFn
|
| 370 |
+
);
|
| 371 |
+
|
| 372 |
+
/// <summary>
|
| 373 |
+
/// Pops the topmost chore from the work stealing queue for structured parallelism. Failure
|
| 374 |
+
/// to pop typically indicates stealing.
|
| 375 |
+
/// </summary>
|
| 376 |
+
/// <returns>
|
| 377 |
+
/// An unrealized chore from the structured work stealing queue or NULL if none is present.
|
| 378 |
+
/// </returns>
|
| 379 |
+
_UnrealizedChore *PopStructured();
|
| 380 |
+
|
| 381 |
+
/// <summary>
|
| 382 |
+
/// Attempts to pop the chore specified by a cookie value from the unstructured work stealing queue. Failure
|
| 383 |
+
/// to pop typically indicates stealing.
|
| 384 |
+
/// </summary>
|
| 385 |
+
/// <param name="cookie">
|
| 386 |
+
/// A cookie returned from PushUnstructured indicating the chore to attempt to pop from
|
| 387 |
+
/// the unstructured work stealing queue.
|
| 388 |
+
/// </param>
|
| 389 |
+
/// <returns>
|
| 390 |
+
/// The specified unrealized chore (as indicated by cookie) or NULL if it could not be popped from
|
| 391 |
+
/// the work stealing queue.
|
| 392 |
+
/// </returns>
|
| 393 |
+
_UnrealizedChore *TryPopUnstructured(int cookie);
|
| 394 |
+
|
| 395 |
+
/// <summary>
|
| 396 |
+
/// Returns the scheduler the specified context is associated with.
|
| 397 |
+
/// </summary>
|
| 398 |
+
SchedulerBase *GetScheduler() const;
|
| 399 |
+
|
| 400 |
+
/// <summary>
|
| 401 |
+
/// Returns the schedule group the specified context is associated with.
|
| 402 |
+
/// </summary>
|
| 403 |
+
ScheduleGroupBase *GetScheduleGroup() const;
|
| 404 |
+
|
| 405 |
+
/// <summary>
|
| 406 |
+
/// Returns the schedule group segment the specified context is associated with.
|
| 407 |
+
/// </summary>
|
| 408 |
+
ScheduleGroupSegmentBase *GetScheduleGroupSegment() const;
|
| 409 |
+
|
| 410 |
+
/// <summary>
|
| 411 |
+
/// Tells whether the context is an external context
|
| 412 |
+
/// </summary>
|
| 413 |
+
bool IsExternal() const { return m_fIsExternal; }
|
| 414 |
+
|
| 415 |
+
/// <summary>
|
| 416 |
+
/// Gets the indirect alias.
|
| 417 |
+
/// </summary>
|
| 418 |
+
_TaskCollection *GetIndirectAlias() const;
|
| 419 |
+
|
| 420 |
+
/// <summary>
|
| 421 |
+
/// Sets the indirect alias.
|
| 422 |
+
/// </summary>
|
| 423 |
+
void SetIndirectAlias(_TaskCollection *pAlias);
|
| 424 |
+
|
| 425 |
+
/// <summary>
|
| 426 |
+
/// Returns whether a task collection or structured task collection executing on this context was canceled while it was inlined.
|
| 427 |
+
/// </summary>
|
| 428 |
+
bool HasInlineCancellation() const
|
| 429 |
+
{
|
| 430 |
+
return (m_inlineCancellations > 0);
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
/// <summary>
|
| 434 |
+
/// Returns whether the entire context was canceled due to a steal.
|
| 435 |
+
/// </summary>
|
| 436 |
+
bool IsEntireContextCanceled() const
|
| 437 |
+
{
|
| 438 |
+
return (m_canceledContext != 0);
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
/// <summary>
|
| 442 |
+
/// Called in order to indicate that a cancellation is happening for a structured task collection associated with this thread
|
| 443 |
+
/// that has not been inlined yet.
|
| 444 |
+
/// </summary>
|
| 445 |
+
void PendingCancel()
|
| 446 |
+
{
|
| 447 |
+
InterlockedIncrement(&m_pendingCancellations);
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
/// <summary>
|
| 451 |
+
/// Called when a pending cancel completes.
|
| 452 |
+
/// </summary>
|
| 453 |
+
void PendingCancelComplete()
|
| 454 |
+
{
|
| 455 |
+
ASSERT(m_pendingCancellations > 0);
|
| 456 |
+
InterlockedDecrement(&m_pendingCancellations);
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
/// <summary>
|
| 460 |
+
/// Returns whether a structured task collection executing on this context was canceled before it was inlined.
|
| 461 |
+
/// </summary>
|
| 462 |
+
bool HasPendingCancellation() const
|
| 463 |
+
{
|
| 464 |
+
return (m_pendingCancellations > 0);
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
/// <summary>
|
| 468 |
+
/// Returns whether there is any cancellation on the context (pending or inline)
|
| 469 |
+
/// </summary>
|
| 470 |
+
bool HasAnyCancellation() const
|
| 471 |
+
{
|
| 472 |
+
return (m_pendingCancellations + m_inlineCancellations > 0);
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
/// <summary>
|
| 476 |
+
/// Called to determine if a confirmed cancellation on this context is hidden at the depth of the caller.
|
| 477 |
+
/// A governing token that is not canceled could be protecting the task collection from cancellation from above.
|
| 478 |
+
/// <summary>
|
| 479 |
+
bool TokenHidesCancellation(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken) const;
|
| 480 |
+
|
| 481 |
+
/// <summary>
|
| 482 |
+
/// Called to determine whether a inline or pending cancellation on this context is visible to the caller.
|
| 483 |
+
/// </summary>
|
| 484 |
+
bool IsCancellationVisible(_TaskCollectionBase* pCurrentTaskCollection, bool hasOverrideToken = false) const;
|
| 485 |
+
|
| 486 |
+
/// <summary>
|
| 487 |
+
/// Called in order to indicate that a collection executing on this context was canceled. This will often cause cancellation
|
| 488 |
+
/// and unwinding of the entire context (up to the point where we get to the canceled collection).
|
| 489 |
+
/// </summary>
|
| 490 |
+
void CancelCollection(int inliningDepth);
|
| 491 |
+
|
| 492 |
+
/// <summary>
|
| 493 |
+
/// Called in order to indicate that we're blowing away the entire context. It's stolen from a collection which was canceled.
|
| 494 |
+
/// </summary>
|
| 495 |
+
void CancelEntireContext()
|
| 496 |
+
{
|
| 497 |
+
InterlockedExchange(&m_canceledContext, TRUE);
|
| 498 |
+
CancelCollection(ENTIRE_CONTEXT_CANCELED);
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
/// <summary>
|
| 502 |
+
/// When a cancellation bubbles up to the collection being canceled, this function is called in order to stop propagation of
|
| 503 |
+
/// the cancellation further up the work tree.
|
| 504 |
+
/// </summary>
|
| 505 |
+
bool CancelCollectionComplete(int inliningDepth);
|
| 506 |
+
|
| 507 |
+
/// <summary>
|
| 508 |
+
/// Completely clears the cancel count. This should be called when a root stolen chore completes on a context.
|
| 509 |
+
/// </summary>
|
| 510 |
+
void ClearCancel()
|
| 511 |
+
{
|
| 512 |
+
m_minCancellationDepth = -1;
|
| 513 |
+
m_maxCancellationDepth = -1;
|
| 514 |
+
m_inlineCancellations = 0;
|
| 515 |
+
m_canceledContext = 0;
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
/// <summary>
|
| 519 |
+
/// Returns the task collection executing atop a stolen context.
|
| 520 |
+
/// </summary>
|
| 521 |
+
_TaskCollectionBase *GetRootCollection()
|
| 522 |
+
{
|
| 523 |
+
return m_pRootCollection;
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
/// <summary>
|
| 527 |
+
/// Sets the task collection executing atop a stolen context. Note that this also sets the executing collection since the root
|
| 528 |
+
/// collection is executing at the time it is set.
|
| 529 |
+
/// </summary>
|
| 530 |
+
void SetRootCollection(_TaskCollectionBase *pRootCollection)
|
| 531 |
+
{
|
| 532 |
+
m_pRootCollection = pRootCollection;
|
| 533 |
+
m_pExecutingCollection = pRootCollection;
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
/// <summary>
|
| 537 |
+
/// Gets the task collection currently executing atop the context.
|
| 538 |
+
/// </summary>
|
| 539 |
+
_TaskCollectionBase *GetExecutingCollection()
|
| 540 |
+
{
|
| 541 |
+
return m_pExecutingCollection;
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
/// <summary>
|
| 545 |
+
/// Sets the task collection currently executing atop the context.
|
| 546 |
+
/// </summary>
|
| 547 |
+
void SetExecutingCollection(_TaskCollectionBase *pExecutingCollection)
|
| 548 |
+
{
|
| 549 |
+
m_pExecutingCollection = pExecutingCollection;
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
/// <summary>
|
| 553 |
+
/// Gets the cancellation token currently governing this context.
|
| 554 |
+
/// </summary>
|
| 555 |
+
_CancellationTokenState *GetGoverningTokenState()
|
| 556 |
+
{
|
| 557 |
+
return m_pGoverningTokenState;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
/// <summary>
|
| 561 |
+
/// Sets the cancellation token currently governing this context.
|
| 562 |
+
/// </summary>
|
| 563 |
+
void PushGoverningTokenState(_CancellationTokenState *pTokenState, int inliningDepth);
|
| 564 |
+
|
| 565 |
+
/// <summary>
|
| 566 |
+
/// Reverts to the previously set cancellation token.
|
| 567 |
+
/// </summary>
|
| 568 |
+
void PopGoverningTokenState(_CancellationTokenState *pTokenState);
|
| 569 |
+
|
| 570 |
+
/// <summary>
|
| 571 |
+
/// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is only valid when
|
| 572 |
+
/// called from the thread representing this context.
|
| 573 |
+
/// </summary>
|
| 574 |
+
bool IsCanceledAtDepth(int depth)
|
| 575 |
+
{
|
| 576 |
+
return IsCanceledAtDepth(m_pExecutingCollection, depth);
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
/// <summary>
|
| 580 |
+
/// Returns an indication as to whether a cancellation is occurring at the depth specified by the inlining depth of the given collection. This
|
| 581 |
+
/// may ONLY be called while the context chaining (stealers) lock is held and only where it is known that there is a steal from
|
| 582 |
+
/// pStartingCollection.
|
| 583 |
+
/// </summary>
|
| 584 |
+
bool IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection)
|
| 585 |
+
{
|
| 586 |
+
return IsCanceledAtDepth(pStartingCollection, pStartingCollection->_M_inliningDepth);
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
/// <summary>
|
| 590 |
+
/// Verifies that a cancellation beacon signal is really a cancellation for that beacon.
|
| 591 |
+
/// </summary>
|
| 592 |
+
bool ConfirmCancel(_Beacon_reference *pBeaconRef)
|
| 593 |
+
{
|
| 594 |
+
CancellationBeacon *pBeacon = CONTAINING_RECORD(pBeaconRef, CancellationBeacon, m_beacon);
|
| 595 |
+
return IsCanceledAtDepth(pBeacon->m_beaconDepth);
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
/// <summary>
|
| 599 |
+
/// Places a reference on the context preventing it from being destroyed until such time as the stealer is added to the chain
|
| 600 |
+
/// via AddStealer. Note that the operation of AddStealer should happen rapidly as it will *BLOCK* cleanup of the context.
|
| 601 |
+
/// </summary>
|
| 602 |
+
void ReferenceForCancellation();
|
| 603 |
+
|
| 604 |
+
/// <summary>
|
| 605 |
+
/// Removes a reference on the context which was preventing it from being destroyed.
|
| 606 |
+
/// </summary>
|
| 607 |
+
void DereferenceForCancellation();
|
| 608 |
+
|
| 609 |
+
/// <summary>
|
| 610 |
+
/// Adds a stealing context. Removes a reference.
|
| 611 |
+
/// </summary>
|
| 612 |
+
void AddStealer(ContextBase *pStealer, bool fDereferenceForCancellation);
|
| 613 |
+
|
| 614 |
+
/// <summary>
|
| 615 |
+
/// Removes a stealing context.
|
| 616 |
+
/// </summary>
|
| 617 |
+
void RemoveStealer(ContextBase *pStealer);
|
| 618 |
+
|
| 619 |
+
/// <summary>
|
| 620 |
+
/// Called by a stolen chore to flag the context as running a chore for which the steal is chained to a task collection instead
|
| 621 |
+
/// of the context.
|
| 622 |
+
/// </summary>
|
| 623 |
+
void NotifyTaskCollectionChainedStealer()
|
| 624 |
+
{
|
| 625 |
+
m_fContextChainedStealer = false;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
/// <summary>
|
| 629 |
+
/// Returns whether the given context's steal is chained to the context (true) or some task collection (false)
|
| 630 |
+
/// </summary>
|
| 631 |
+
bool IsContextChainedStealer() const
|
| 632 |
+
{
|
| 633 |
+
return m_fContextChainedStealer;
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
/// <summary>
|
| 637 |
+
/// Called on both internal and external contexts, either when the are put into an idle pool to
|
| 638 |
+
/// be recycled, or when they are ready to be deleted. The API moves the contexts that are in
|
| 639 |
+
/// the list of 'stealers' (used for cancellation) to lists in the task collections from which
|
| 640 |
+
/// those contexts have stolen chores.
|
| 641 |
+
/// </summary>
|
| 642 |
+
void DetachStealers();
|
| 643 |
+
|
| 644 |
+
/// <summary>
|
| 645 |
+
/// Gets an arbitrary alias out of the context's alias table.
|
| 646 |
+
/// </summary>
|
| 647 |
+
_TaskCollection *GetArbitraryAlias(_TaskCollection *pCollection)
|
| 648 |
+
{
|
| 649 |
+
Hash<_TaskCollection*, _TaskCollection*>::ListNode *pNode = m_aliasTable.Find(pCollection, NULL);
|
| 650 |
+
_TaskCollection *pAlias = (pNode != NULL ? pNode->m_value : NULL);
|
| 651 |
+
if (pAlias != NULL && pAlias->_IsStaleAlias())
|
| 652 |
+
{
|
| 653 |
+
m_aliasTable.Delete(pAlias->_OriginalCollection());
|
| 654 |
+
delete pAlias;
|
| 655 |
+
pAlias = NULL;
|
| 656 |
+
}
|
| 657 |
+
return pAlias;
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
/// <summary>
|
| 661 |
+
/// Adds an arbitrary alias (direct or indirect) to the alias table.
|
| 662 |
+
/// </summary>
|
| 663 |
+
void AddArbitraryAlias(_TaskCollection *pOriginCollection, _TaskCollection *pAliasCollection)
|
| 664 |
+
{
|
| 665 |
+
SweepAliasTable();
|
| 666 |
+
m_aliasTable.Insert(pOriginCollection, pAliasCollection);
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
/// <summary>
|
| 670 |
+
/// Sweeps the alias table for stale entries. Anything considered stale is deleted.
|
| 671 |
+
/// </summary>
|
| 672 |
+
void SweepAliasTable();
|
| 673 |
+
|
| 674 |
+
/// <summary>
|
| 675 |
+
/// Clears the alias table.
|
| 676 |
+
/// </summary>
|
| 677 |
+
void ClearAliasTable();
|
| 678 |
+
|
| 679 |
+
/// <summary>
|
| 680 |
+
/// Cancel everything stolen from pCollection outward from this context.
|
| 681 |
+
/// </summary>
|
| 682 |
+
void CancelStealers(_TaskCollectionBase *pCollection);
|
| 683 |
+
|
| 684 |
+
/// <summary>
|
| 685 |
+
/// Returns the highest inlining depth (tree wise) of a canceled task collection. Note that it will return -1
|
| 686 |
+
/// if there is no in-progress cancellation on the context.
|
| 687 |
+
/// </summary>
|
| 688 |
+
int MinimumCancellationDepth() const
|
| 689 |
+
{
|
| 690 |
+
//
|
| 691 |
+
// If the entire context is canceled, the minimum depth is reported to be zero so as to be less than all inlining depths
|
| 692 |
+
// for the purposes of checking cancellation. Note that even if the top collection has inlining depth of zero, it does not matter
|
| 693 |
+
// since it **IS** the top collection.
|
| 694 |
+
//
|
| 695 |
+
return IsEntireContextCanceled() ? 0 : m_minCancellationDepth;
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
// An enumerated type that tells the type of the underlying execution context.
|
| 699 |
+
enum ContextKind
|
| 700 |
+
{
|
| 701 |
+
ExternalContext,
|
| 702 |
+
ThreadContext,
|
| 703 |
+
};
|
| 704 |
+
|
| 705 |
+
/// <summary>
|
| 706 |
+
/// Returns the type of context
|
| 707 |
+
/// </summary>
|
| 708 |
+
virtual ContextKind GetContextKind() const = 0;
|
| 709 |
+
|
| 710 |
+
#if _DEBUG
|
| 711 |
+
// _DEBUG helper
|
| 712 |
+
virtual DWORD GetThreadId() const = 0;
|
| 713 |
+
#endif
|
| 714 |
+
|
| 715 |
+
/// <summary>
|
| 716 |
+
/// Returns a bool which can be polled from the current location in lieu of calling is_current_task_group_canceling.
|
| 717 |
+
/// </summary>
|
| 718 |
+
_Beacon_reference *PushCancellationBeacon();
|
| 719 |
+
|
| 720 |
+
/// <summary>
|
| 721 |
+
/// Releases the topmost bool acquired in RAII fashion from PushCancellationBeacon.
|
| 722 |
+
/// </summary>
|
| 723 |
+
void PopCancellationBeacon();
|
| 724 |
+
|
| 725 |
+
/// <summary>
|
| 726 |
+
/// Flags any cancellation beacons that are inlined at or below the specified point.
|
| 727 |
+
/// </summary>
|
| 728 |
+
void FlagCancellationBeacons(int inliningDepth);
|
| 729 |
+
|
| 730 |
+
protected:
|
| 731 |
+
class ScopedCriticalRegion
|
| 732 |
+
{
|
| 733 |
+
public:
|
| 734 |
+
ScopedCriticalRegion(ContextBase* pCB) : m_pCB(pCB)
|
| 735 |
+
{
|
| 736 |
+
m_pCB->EnterCriticalRegion();
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
~ScopedCriticalRegion()
|
| 740 |
+
{
|
| 741 |
+
m_pCB->ExitCriticalRegion();
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
private:
|
| 745 |
+
const ScopedCriticalRegion& operator=(const ScopedCriticalRegion&); //no assignment operator
|
| 746 |
+
ContextBase* m_pCB;
|
| 747 |
+
};
|
| 748 |
+
|
| 749 |
+
//
|
| 750 |
+
// Protected data members
|
| 751 |
+
//
|
| 752 |
+
|
| 753 |
+
// Entry for freelist
|
| 754 |
+
SLIST_ENTRY m_slNext;
|
| 755 |
+
|
| 756 |
+
// Unique identifier
|
| 757 |
+
unsigned int m_id;
|
| 758 |
+
|
| 759 |
+
// Critical region counter.
|
| 760 |
+
DWORD m_criticalRegionCount;
|
| 761 |
+
|
| 762 |
+
// Hyper-critical region counter.
|
| 763 |
+
DWORD m_hyperCriticalRegionCount;
|
| 764 |
+
|
| 765 |
+
// Oversubscription count - the number of outstanding Oversubscribe(true) calls on this context.
|
| 766 |
+
DWORD m_oversubscribeCount;
|
| 767 |
+
|
| 768 |
+
// The schedule group segment that the context picked up work from
|
| 769 |
+
ScheduleGroupSegmentBase *m_pSegment;
|
| 770 |
+
|
| 771 |
+
// The scheduler instance the context belongs to.
|
| 772 |
+
SchedulerBase *m_pScheduler;
|
| 773 |
+
|
| 774 |
+
// Workqueue for unrealized chores.
|
| 775 |
+
WorkQueue *m_pWorkQueue;
|
| 776 |
+
|
| 777 |
+
// Link to implement the stack of parent contexts for nested schedulers.
|
| 778 |
+
ContextBase *m_pParentContext;
|
| 779 |
+
|
| 780 |
+
// Flag indicating whether the context is blocked.
|
| 781 |
+
volatile LONG m_blockedState;
|
| 782 |
+
|
| 783 |
+
// Memory fence to assist Block/Unblock.
|
| 784 |
+
volatile LONG m_contextSwitchingFence;
|
| 785 |
+
|
| 786 |
+
// Tracks the task collection from which this context stole (if it's a context executing a stolen chore).
|
| 787 |
+
_TaskCollectionBase *m_pRootCollection;
|
| 788 |
+
|
| 789 |
+
// Tracks the task collection currently executing (used to maintain parent/child relationships).
|
| 790 |
+
_TaskCollectionBase *m_pExecutingCollection;
|
| 791 |
+
|
| 792 |
+
// Tracks the current cancellation token (for optimization)
|
| 793 |
+
_CancellationTokenState *m_pGoverningTokenState;
|
| 794 |
+
|
| 795 |
+
// The inlining depth of the first construct on this stack to utilize the governing token
|
| 796 |
+
int m_governingTokenDepth;
|
| 797 |
+
|
| 798 |
+
// The depth of ppltask being inlining scheduled on this context.
|
| 799 |
+
size_t m_asyncTaskCollectionInlineDepth;
|
| 800 |
+
|
| 801 |
+
// The thread id for the thread backing the context.
|
| 802 |
+
DWORD m_threadId;
|
| 803 |
+
|
| 804 |
+
//
|
| 805 |
+
// Protected methods
|
| 806 |
+
//
|
| 807 |
+
|
| 808 |
+
/// <summary>
|
| 809 |
+
/// Clean up the work queue for this Context.
|
| 810 |
+
/// </summary>
|
| 811 |
+
void ReleaseWorkQueue();
|
| 812 |
+
|
| 813 |
+
/// <summary>
|
| 814 |
+
/// Sets the 'this' context into the tls slot as the current context. This is used by internal contexts in
|
| 815 |
+
/// their dispatch loops.
|
| 816 |
+
/// </summary>
|
| 817 |
+
void SetAsCurrentTls();
|
| 818 |
+
|
| 819 |
+
///<summary>Send a context ETW event</summary>
|
| 820 |
+
void TraceContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId)
|
| 821 |
+
{
|
| 822 |
+
if (g_TraceInfo._IsEnabled(level, ContextEventFlag))
|
| 823 |
+
ThrowContextEvent(eventType, level, schedulerId, contextId);
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
static void ThrowContextEvent(ConcRT_EventType eventType, UCHAR level, DWORD schedulerId, DWORD contextId);
|
| 827 |
+
|
| 828 |
+
private:
|
| 829 |
+
|
| 830 |
+
//
|
| 831 |
+
// Friend declarations
|
| 832 |
+
//
|
| 833 |
+
friend class SchedulerBase;
|
| 834 |
+
friend class ThreadScheduler;
|
| 835 |
+
friend class InternalContextBase;
|
| 836 |
+
friend class SchedulingRing;
|
| 837 |
+
friend class VirtualProcessor;
|
| 838 |
+
friend class ScheduleGroupBase;
|
| 839 |
+
friend class ScheduleGroupSegmentBase;
|
| 840 |
+
friend class ScheduleGroup;
|
| 841 |
+
friend class FairScheduleGroup;
|
| 842 |
+
friend class CacheLocalScheduleGroup;
|
| 843 |
+
friend class _UnrealizedChore;
|
| 844 |
+
friend class _TaskCollection;
|
| 845 |
+
friend class _StructuredTaskCollection;
|
| 846 |
+
friend class _StackGuard;
|
| 847 |
+
template <class T> friend class LockFreeStack;
|
| 848 |
+
|
| 849 |
+
//
|
| 850 |
+
// Private data
|
| 851 |
+
//
|
| 852 |
+
|
| 853 |
+
// Used in finalization to distinguish between blocked and free-list contexts
|
| 854 |
+
LONG m_sweeperMarker;
|
| 855 |
+
|
| 856 |
+
// Flag indicating context kind.
|
| 857 |
+
bool m_fIsExternal;
|
| 858 |
+
|
| 859 |
+
// Keeps track as to whether this context is chained to a context (true) or a schedule group (false) for the purposes of stealing/cancellation.
|
| 860 |
+
bool m_fContextChainedStealer;
|
| 861 |
+
|
| 862 |
+
// Indicates that normal lock validations should not be performed -- the context is shutting down a virtual processor.
|
| 863 |
+
bool m_fShutdownValidations;
|
| 864 |
+
|
| 865 |
+
// Tracks all contexts which stole from any collection on *this* context.
|
| 866 |
+
SafeRWList<ListEntry> m_stealers;
|
| 867 |
+
// Link for contexts added to m_stealers
|
| 868 |
+
ListEntry m_stealChain;
|
| 869 |
+
|
| 870 |
+
// Reference count of things waiting to be added to the steal chain of this context.
|
| 871 |
+
volatile LONG m_cancellationRefCount;
|
| 872 |
+
|
| 873 |
+
// Depth is inversely proportion to height in the description of min and max depths. If inlined tg A at depth 0 inlines tg B,
|
| 874 |
+
// tg A is considered to be higher than tg B on that context.
|
| 875 |
+
// The inlining depth of the highest canceled task collection.
|
| 876 |
+
volatile LONG m_minCancellationDepth;
|
| 877 |
+
// The inlining depth of the lowest canceled task collection.
|
| 878 |
+
volatile LONG m_maxCancellationDepth;
|
| 879 |
+
|
| 880 |
+
// The number of task collections and structured task collections running on this context that were canceled when they were inlined
|
| 881 |
+
volatile LONG m_inlineCancellations;
|
| 882 |
+
// An indication that the context was shot down as it stole from a canceled collection.
|
| 883 |
+
volatile LONG m_canceledContext;
|
| 884 |
+
// An indication that there is a pending cancellation of a structured collection on this thread (the collection was canceled before it
|
| 885 |
+
// was inlined).
|
| 886 |
+
volatile LONG m_pendingCancellations;
|
| 887 |
+
// The indirect alias for this context. This allows an unstructured task collection to carry into a stolen chore and be
|
| 888 |
+
// utilized there without any cross threaded semantics within the task collection.
|
| 889 |
+
_TaskCollection *m_pIndirectAlias;
|
| 890 |
+
// The table of aliases for this context. This allows transitive indirect aliases as well as direct aliases (which
|
| 891 |
+
// are not presently implemented).
|
| 892 |
+
Hash<_TaskCollection*, _TaskCollection*> m_aliasTable;
|
| 893 |
+
|
| 894 |
+
//
|
| 895 |
+
// A cancellation beacon is a flag that the runtime signals when cancellation occurs. It allows hot code paths to poll
|
| 896 |
+
// for cancellation in an inlinable way. Parallel for, for instance, gets huge performance wins utilizing this mechanism over
|
| 897 |
+
// a non-inlinable call to is_current_task_group_canceling.
|
| 898 |
+
//
|
| 899 |
+
// Beacons also allow manual raising from the outside for various things in conjunction with cancellation.
|
| 900 |
+
//
|
| 901 |
+
struct CancellationBeacon
|
| 902 |
+
{
|
| 903 |
+
_Beacon_reference m_beacon;
|
| 904 |
+
int m_beaconDepth;
|
| 905 |
+
|
| 906 |
+
void Raise()
|
| 907 |
+
{
|
| 908 |
+
InterlockedIncrement(&m_beacon._M_signals);
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
void Lower()
|
| 912 |
+
{
|
| 913 |
+
InterlockedDecrement(&m_beacon._M_signals);
|
| 914 |
+
}
|
| 915 |
+
|
| 916 |
+
void InternalSignal()
|
| 917 |
+
{
|
| 918 |
+
Raise();
|
| 919 |
+
}
|
| 920 |
+
};
|
| 921 |
+
|
| 922 |
+
//
|
| 923 |
+
// In order for the cancellation beacon mechanism to work, we must manage all storage for beacons. A cancellation beacon may disappear
|
| 924 |
+
// asynchronously with respect to cancellation walking the stack of the thread holding the beacon. Once we hand out a beacon flag, we must
|
| 925 |
+
// NOT allow that memory location to become invalid until the runtime owns the base of the stack again.
|
| 926 |
+
//
|
| 927 |
+
// 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.
|
| 928 |
+
//
|
| 929 |
+
// The CancellationBeaconStack manages a growing stack of beacons without reallocations.
|
| 930 |
+
//
|
| 931 |
+
class CancellationBeaconStack
|
| 932 |
+
{
|
| 933 |
+
private:
|
| 934 |
+
|
| 935 |
+
// Defines the number of segments in the index
|
| 936 |
+
static const LONG NODE_INDEX_SIZE = 4;
|
| 937 |
+
|
| 938 |
+
// Defines how large (and the bitmasks) each segment is.
|
| 939 |
+
static const LONG BEACON_NODE_SIZE = 16;
|
| 940 |
+
static const LONG BEACON_NODE_MASK = 0xFFFFFFF0;
|
| 941 |
+
static const LONG BEACON_NODE_ITEM_MASK = 0xF;
|
| 942 |
+
static const LONG BEACON_NODE_SHIFT = 4;
|
| 943 |
+
|
| 944 |
+
//
|
| 945 |
+
// A segment of the stack. Once allocated, data can never move (even after being released).
|
| 946 |
+
//
|
| 947 |
+
struct CancellationBeaconNode
|
| 948 |
+
{
|
| 949 |
+
CancellationBeaconNode() : m_pNext(NULL)
|
| 950 |
+
{
|
| 951 |
+
m_pBeacons = _concrt_new CancellationBeacon[BEACON_NODE_SIZE];
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
~CancellationBeaconNode()
|
| 955 |
+
{
|
| 956 |
+
delete[] m_pBeacons;
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
CancellationBeacon *m_pBeacons;
|
| 960 |
+
CancellationBeaconNode *m_pNext;
|
| 961 |
+
};
|
| 962 |
+
|
| 963 |
+
// The stack pointer
|
| 964 |
+
LONG m_beaconDepth;
|
| 965 |
+
|
| 966 |
+
// The size of the stack
|
| 967 |
+
LONG m_size;
|
| 968 |
+
|
| 969 |
+
// The index to stack segments
|
| 970 |
+
CancellationBeaconNode **m_pNodeIndex;
|
| 971 |
+
|
| 972 |
+
/// <summary>
|
| 973 |
+
/// Increases the size of the beacon stack without moving any memory associated with beacons that have been handed
|
| 974 |
+
/// out.
|
| 975 |
+
/// </summary>
|
| 976 |
+
void Grow()
|
| 977 |
+
{
|
| 978 |
+
CancellationBeaconNode *pNewNode;
|
| 979 |
+
CancellationBeaconNode *pPrevNode = NULL;
|
| 980 |
+
|
| 981 |
+
LONG idx = (m_size & BEACON_NODE_MASK) >> BEACON_NODE_SHIFT;
|
| 982 |
+
if (idx < NODE_INDEX_SIZE)
|
| 983 |
+
{
|
| 984 |
+
if (idx > 0)
|
| 985 |
+
pPrevNode = m_pNodeIndex[idx - 1];
|
| 986 |
+
|
| 987 |
+
pNewNode = m_pNodeIndex[idx] = _concrt_new CancellationBeaconNode;
|
| 988 |
+
}
|
| 989 |
+
else
|
| 990 |
+
{
|
| 991 |
+
pNewNode = pPrevNode = m_pNodeIndex[NODE_INDEX_SIZE - 1];
|
| 992 |
+
|
| 993 |
+
idx -= (NODE_INDEX_SIZE - 1);
|
| 994 |
+
while (idx--)
|
| 995 |
+
{
|
| 996 |
+
pPrevNode = pNewNode;
|
| 997 |
+
pNewNode = pNewNode->m_pNext;
|
| 998 |
+
}
|
| 999 |
+
|
| 1000 |
+
ASSERT(pNewNode == NULL);
|
| 1001 |
+
pNewNode = _concrt_new CancellationBeaconNode;
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
if (pPrevNode)
|
| 1005 |
+
pPrevNode->m_pNext = pNewNode;
|
| 1006 |
+
|
| 1007 |
+
m_size += BEACON_NODE_SIZE;
|
| 1008 |
+
|
| 1009 |
+
}
|
| 1010 |
+
|
| 1011 |
+
public:
|
| 1012 |
+
|
| 1013 |
+
/// <summary>
|
| 1014 |
+
/// Creates a new cancellation beacon stack.
|
| 1015 |
+
/// </summary>
|
| 1016 |
+
CancellationBeaconStack() :
|
| 1017 |
+
m_beaconDepth(0),
|
| 1018 |
+
m_size(0)
|
| 1019 |
+
{
|
| 1020 |
+
m_pNodeIndex = _concrt_new CancellationBeaconNode* [NODE_INDEX_SIZE];
|
| 1021 |
+
}
|
| 1022 |
+
|
| 1023 |
+
/// <summary>
|
| 1024 |
+
/// Destroys a cancellation beacon stack.
|
| 1025 |
+
/// </summary>
|
| 1026 |
+
~CancellationBeaconStack()
|
| 1027 |
+
{
|
| 1028 |
+
if (m_size > 0)
|
| 1029 |
+
{
|
| 1030 |
+
CancellationBeaconNode *pNode = m_pNodeIndex[0];
|
| 1031 |
+
while (pNode != NULL)
|
| 1032 |
+
{
|
| 1033 |
+
CancellationBeaconNode *pNext = pNode->m_pNext;
|
| 1034 |
+
delete pNode;
|
| 1035 |
+
pNode = pNext;
|
| 1036 |
+
}
|
| 1037 |
+
}
|
| 1038 |
+
|
| 1039 |
+
delete [] m_pNodeIndex;
|
| 1040 |
+
}
|
| 1041 |
+
|
| 1042 |
+
/// <summary>
|
| 1043 |
+
/// Acquires memory for a new cancellation beacon and initializes it for the specified inlining depth.
|
| 1044 |
+
/// </summary>
|
| 1045 |
+
CancellationBeacon *AcquirePushBeacon(int inliningDepth)
|
| 1046 |
+
{
|
| 1047 |
+
if (m_beaconDepth >= m_size)
|
| 1048 |
+
Grow();
|
| 1049 |
+
|
| 1050 |
+
CancellationBeacon *pBeacon = operator[](m_beaconDepth);
|
| 1051 |
+
pBeacon->m_beacon._M_signals = 0;
|
| 1052 |
+
pBeacon->m_beaconDepth = inliningDepth;
|
| 1053 |
+
m_beaconDepth++;
|
| 1054 |
+
|
| 1055 |
+
//
|
| 1056 |
+
// Force a full fence here for any R/W dependencies between the cancellation thread reading the beacon stack and us reading
|
| 1057 |
+
// the cancellation state later once the beacon is acquired.
|
| 1058 |
+
//
|
| 1059 |
+
MemoryBarrier();
|
| 1060 |
+
|
| 1061 |
+
return pBeacon;
|
| 1062 |
+
}
|
| 1063 |
+
|
| 1064 |
+
/// <summary>
|
| 1065 |
+
/// Releases the topmost cancellation beacon. The beacon can be handed out
|
| 1066 |
+
/// </summary>
|
| 1067 |
+
void ReleaseBeacon()
|
| 1068 |
+
{
|
| 1069 |
+
ASSERT(m_beaconDepth > 0);
|
| 1070 |
+
m_beaconDepth--;
|
| 1071 |
+
}
|
| 1072 |
+
|
| 1073 |
+
/// <summary>
|
| 1074 |
+
/// Returns a view of the number of beacons.
|
| 1075 |
+
/// </summary>
|
| 1076 |
+
LONG BeaconCount() const
|
| 1077 |
+
{
|
| 1078 |
+
return m_beaconDepth;
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
/// <summary>
|
| 1082 |
+
/// Returns the cancellation beacon specified as specified by the supplied index. Note that the index must be within
|
| 1083 |
+
/// the bounds of BeaconCount when used externally and m_size when used internally.
|
| 1084 |
+
/// </summary>
|
| 1085 |
+
CancellationBeacon *operator[](LONG idx)
|
| 1086 |
+
{
|
| 1087 |
+
CancellationBeaconNode *pNode = NULL;
|
| 1088 |
+
|
| 1089 |
+
LONG nIdx = (idx & BEACON_NODE_MASK) >> BEACON_NODE_SHIFT;
|
| 1090 |
+
if (nIdx < NODE_INDEX_SIZE)
|
| 1091 |
+
{
|
| 1092 |
+
pNode = m_pNodeIndex[nIdx];
|
| 1093 |
+
}
|
| 1094 |
+
else
|
| 1095 |
+
{
|
| 1096 |
+
pNode = m_pNodeIndex[NODE_INDEX_SIZE - 1];
|
| 1097 |
+
nIdx -= (NODE_INDEX_SIZE - 1);
|
| 1098 |
+
while(nIdx--)
|
| 1099 |
+
{
|
| 1100 |
+
pNode = pNode->m_pNext;
|
| 1101 |
+
}
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
return &(pNode->m_pBeacons[idx & BEACON_NODE_ITEM_MASK]);
|
| 1105 |
+
}
|
| 1106 |
+
};
|
| 1107 |
+
|
| 1108 |
+
CancellationBeaconStack m_cancellationBeacons;
|
| 1109 |
+
|
| 1110 |
+
//
|
| 1111 |
+
// Private member functions
|
| 1112 |
+
//
|
| 1113 |
+
|
| 1114 |
+
/// <summary>
|
| 1115 |
+
/// When schedulers are nested on the same stack context, the nested scheduler creates a new external context that overrides
|
| 1116 |
+
/// the previous context. PopContextFromTls will restore the previous context by setting the TLS value appropriately.
|
| 1117 |
+
/// </summary>
|
| 1118 |
+
ContextBase* PopContextFromTls();
|
| 1119 |
+
|
| 1120 |
+
/// <summary>
|
| 1121 |
+
/// When schedulers are nested on the same stack context, the nested scheduler creates a new external context that overrides
|
| 1122 |
+
/// the previous context. PushContextToTls will remember the parent context and set the new context into TLS.
|
| 1123 |
+
/// </summary>
|
| 1124 |
+
void PushContextToTls(ContextBase* pParentContext);
|
| 1125 |
+
|
| 1126 |
+
/// <summary>
|
| 1127 |
+
/// Context TLS is cleared during nesting on internal contexts before the external context TLS is correctly setup. If not,
|
| 1128 |
+
/// code that executes between the clear and setting the new TLS could get confused.
|
| 1129 |
+
/// </summary>
|
| 1130 |
+
void ClearContextTls();
|
| 1131 |
+
|
| 1132 |
+
/// <summary>
|
| 1133 |
+
/// Recomputes the maximum depth of cancellation after a canceled task group clears its cancellation flag.
|
| 1134 |
+
/// </summary>
|
| 1135 |
+
void RecomputeMaximumCancellationDepth();
|
| 1136 |
+
|
| 1137 |
+
/// <summary>
|
| 1138 |
+
/// Returns an indication as to whether a cancellation is occurring at the specified depth. The result here is normally only valid when
|
| 1139 |
+
/// called from the thread representing this context. There are times under the context chaining lock (stealers list) where this can be
|
| 1140 |
+
/// called safely **FOR CERTAIN DEPTHS** from another thread. This variant should never be called directly. Always utilize one of the
|
| 1141 |
+
/// other overloads.
|
| 1142 |
+
/// </summary>
|
| 1143 |
+
bool IsCanceledAtDepth(_TaskCollectionBase *pStartingCollection, int depth);
|
| 1144 |
+
};
|
| 1145 |
+
#pragma warning(pop)
|
| 1146 |
+
} // namespace details
|
| 1147 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/CurrentScheduler.cpp
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// CurrentScheduler.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation of static scheduler APIs for CurrentScheduler::
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
/// <returns>
|
| 19 |
+
/// Returns a unique identifier for the current scheduler. Returns -1 if no current scheduler exists.
|
| 20 |
+
/// </returns>
|
| 21 |
+
unsigned int CurrentScheduler::Id()
|
| 22 |
+
{
|
| 23 |
+
const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler();
|
| 24 |
+
return pScheduler != NULL ? pScheduler->Id() : UINT_MAX;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
/// <returns>
|
| 28 |
+
/// Returns a current number of virtual processors for the current scheduler. Returns -1 if no current scheduler exists.
|
| 29 |
+
/// No error state.
|
| 30 |
+
/// </returns>
|
| 31 |
+
unsigned int CurrentScheduler::GetNumberOfVirtualProcessors()
|
| 32 |
+
{
|
| 33 |
+
const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler();
|
| 34 |
+
return pScheduler != NULL ? pScheduler->GetNumberOfVirtualProcessors() : UINT_MAX;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/// <returns>
|
| 38 |
+
/// Returns a copy of the policy the current scheduler is using. Returns NULL if no current
|
| 39 |
+
/// scheduler exists.
|
| 40 |
+
/// </returns>
|
| 41 |
+
SchedulerPolicy CurrentScheduler::GetPolicy()
|
| 42 |
+
{
|
| 43 |
+
const SchedulerBase *pScheduler = SchedulerBase::CurrentScheduler();
|
| 44 |
+
return pScheduler->GetPolicy();
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Returns a reference to the scheduler instance in TLS storage (viz., the current scheduler).
|
| 49 |
+
/// If one does not exist, the default scheduler for the process is attached to the calling thread and returned --
|
| 50 |
+
/// if the default scheduler does not exist it is created
|
| 51 |
+
/// </summary>
|
| 52 |
+
/// <returns>
|
| 53 |
+
/// The TLS storage for the current scheduler is returned.
|
| 54 |
+
/// </returns>
|
| 55 |
+
Scheduler* CurrentScheduler::Get()
|
| 56 |
+
{
|
| 57 |
+
return SchedulerBase::CurrentScheduler();
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/// <summary>
|
| 61 |
+
/// The normal scheduler factory. (Implicitly calls Scheduler::Attach on the internally represented scheduler instance.)
|
| 62 |
+
/// The created scheduler will become the current scheduler for the current context (if it is an OS context it will be
|
| 63 |
+
/// inducted to a ConcRT context). To shutdown such a scheduler, Detach needs to be called. Any extra Reference calls
|
| 64 |
+
/// must be matched with Release for shutdown to commence.
|
| 65 |
+
/// </summary>
|
| 66 |
+
/// <param name="pPolicy">
|
| 67 |
+
/// [in] A const pointer to the scheduler policy (See Scheduler Policy API)
|
| 68 |
+
/// </param>
|
| 69 |
+
void CurrentScheduler::Create(const SchedulerPolicy& policy)
|
| 70 |
+
{
|
| 71 |
+
SchedulerBase *pScheduler = SchedulerBase::Create(policy);
|
| 72 |
+
pScheduler->Attach();
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Detaches the current scheduler from the calling thread and restores the previously attached scheduler as the current
|
| 77 |
+
/// scheduler. Implicitly calls Release. After this function is called, the calling thread is then managed by the scheduler
|
| 78 |
+
/// that was previously activated via Create() or Attach().
|
| 79 |
+
/// </summary>
|
| 80 |
+
void CurrentScheduler::Detach()
|
| 81 |
+
{
|
| 82 |
+
SchedulerBase* pScheduler = SchedulerBase::SafeFastCurrentScheduler();
|
| 83 |
+
|
| 84 |
+
if (pScheduler != NULL)
|
| 85 |
+
{
|
| 86 |
+
return pScheduler->Detach();
|
| 87 |
+
}
|
| 88 |
+
else
|
| 89 |
+
{
|
| 90 |
+
throw scheduler_not_attached();
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
/// <summary>
|
| 95 |
+
/// Causes the OS event object 'shutdownEvent' to be set when the scheduler shuts down and destroys itself.
|
| 96 |
+
/// </summary>
|
| 97 |
+
/// <param name="shutdownEvent">
|
| 98 |
+
/// [in] A valid event object
|
| 99 |
+
/// </param>
|
| 100 |
+
void CurrentScheduler::RegisterShutdownEvent(HANDLE shutdownEvent)
|
| 101 |
+
{
|
| 102 |
+
SchedulerBase* pScheduler = SchedulerBase::SafeFastCurrentScheduler();
|
| 103 |
+
|
| 104 |
+
if (pScheduler != NULL)
|
| 105 |
+
{
|
| 106 |
+
return pScheduler->RegisterShutdownEvent(shutdownEvent);
|
| 107 |
+
}
|
| 108 |
+
else
|
| 109 |
+
{
|
| 110 |
+
throw scheduler_not_attached();
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
/// <summary>
|
| 115 |
+
/// Create a schedule group within the current scheduler.
|
| 116 |
+
/// </summary>
|
| 117 |
+
ScheduleGroup* CurrentScheduler::CreateScheduleGroup()
|
| 118 |
+
{
|
| 119 |
+
return SchedulerBase::CurrentScheduler()->CreateScheduleGroup();
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
/// <summary>
|
| 123 |
+
/// Creates a new schedule group within the scheduler associated with the calling context. Tasks scheduled within the newly created
|
| 124 |
+
/// schedule group will be biased towards executing at the specified location.
|
| 125 |
+
/// </summary>
|
| 126 |
+
/// <param name="_Placement">
|
| 127 |
+
/// A reference to a location where the tasks within the schedule group will biased towards executing at.
|
| 128 |
+
/// </param>
|
| 129 |
+
/// <returns>
|
| 130 |
+
/// A pointer to the newly created schedule group. This <c>ScheduleGroup</c> object has an initial reference count placed on it.
|
| 131 |
+
/// </returns>
|
| 132 |
+
/// <remarks>
|
| 133 |
+
/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no
|
| 134 |
+
/// scheduler currently associated with the calling context.
|
| 135 |
+
/// <para>You must invoke the <see cref="ScheduleGroup::Release Method">Release</see> method on a schedule group when you are
|
| 136 |
+
/// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed.</para>
|
| 137 |
+
/// <para>Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before
|
| 138 |
+
/// you release your reference on the scheduler, via detaching the current context from it.</para>
|
| 139 |
+
/// </remarks>
|
| 140 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 141 |
+
/// <seealso cref="ScheduleGroup::Release Method"/>
|
| 142 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 143 |
+
/// <seealso cref="location Class"/>
|
| 144 |
+
ScheduleGroup* CurrentScheduler::CreateScheduleGroup(location& placement)
|
| 145 |
+
{
|
| 146 |
+
return SchedulerBase::CurrentScheduler()->CreateScheduleGroup(placement);
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/// <summary>
|
| 150 |
+
/// Create a light-weight schedule within the current scheduler in an implementation dependent schedule group.
|
| 151 |
+
/// </summary>
|
| 152 |
+
/// <param name="proc">
|
| 153 |
+
/// [in] A pointer to the main function of a task.
|
| 154 |
+
/// </param>
|
| 155 |
+
/// <param name="data">
|
| 156 |
+
/// [in] A void pointer to the data that will be passed in to the task.
|
| 157 |
+
/// <param>
|
| 158 |
+
_Use_decl_annotations_
|
| 159 |
+
void CurrentScheduler::ScheduleTask(TaskProc proc, void *data)
|
| 160 |
+
{
|
| 161 |
+
SchedulerBase::CurrentScheduler()->ScheduleTask(proc, data);
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/// <summary>
|
| 165 |
+
/// Schedules a light-weight task within the scheduler associated with the calling context. The light-weight task will be placed
|
| 166 |
+
/// within a schedule group of the runtime's choosing. It will also be biased towards executing at the specified location.
|
| 167 |
+
/// </summary>
|
| 168 |
+
/// <param name="proc">
|
| 169 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 170 |
+
/// </param>
|
| 171 |
+
/// <param name="data">
|
| 172 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 173 |
+
/// </param>
|
| 174 |
+
/// <param name="placement">
|
| 175 |
+
/// A reference to a location where the light-weight task will be biased towards executing at.
|
| 176 |
+
/// </param>
|
| 177 |
+
/// <remarks>
|
| 178 |
+
/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no
|
| 179 |
+
/// scheduler currently associated with the calling context.
|
| 180 |
+
/// </remarks>
|
| 181 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 182 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 183 |
+
/// <seealso cref="location Class"/>
|
| 184 |
+
_Use_decl_annotations_
|
| 185 |
+
void CurrentScheduler::ScheduleTask(TaskProc proc, void * data, location& placement)
|
| 186 |
+
{
|
| 187 |
+
SchedulerBase::CurrentScheduler()->ScheduleTask(proc, data, placement);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// Determines whether a given location is available on the current scheduler.
|
| 192 |
+
/// </summary>
|
| 193 |
+
/// <param name="_Placement">
|
| 194 |
+
/// A reference to the location to query the current scheduler about.
|
| 195 |
+
/// </param>
|
| 196 |
+
/// <returns>
|
| 197 |
+
/// An indication of whether or not the location specified by the <paramref name="_Placement"/> argument is available on the current
|
| 198 |
+
/// scheduler.
|
| 199 |
+
/// </returns>
|
| 200 |
+
/// <remarks>
|
| 201 |
+
/// This method will not result in scheduler attachment if the calling context is not already associated with a scheduler.
|
| 202 |
+
/// <para>Note that the return value is an instantaneous sampling of whether the given location is available. In the presence of multiple
|
| 203 |
+
/// schedulers, dynamic resource management may add or take away resources from schedulers at any point. Should this happen, the given
|
| 204 |
+
/// location may change availability.</para>
|
| 205 |
+
/// </remarks>
|
| 206 |
+
/**/
|
| 207 |
+
bool CurrentScheduler::IsAvailableLocation(const location& _Placement)
|
| 208 |
+
{
|
| 209 |
+
const SchedulerBase *pScheduler = SchedulerBase::SafeFastCurrentScheduler();
|
| 210 |
+
return pScheduler != NULL ? pScheduler->IsAvailableLocation(_Placement) : false;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
namespace details
|
| 214 |
+
{
|
| 215 |
+
void _CurrentScheduler::_ScheduleTask(TaskProc _Proc, void * _Data)
|
| 216 |
+
{
|
| 217 |
+
SchedulerBase::CurrentScheduler()->ScheduleTask(_Proc, _Data);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
unsigned int _CurrentScheduler::_Id()
|
| 221 |
+
{
|
| 222 |
+
return CurrentScheduler::Id();
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
unsigned int _CurrentScheduler::_GetNumberOfVirtualProcessors()
|
| 226 |
+
{
|
| 227 |
+
return SchedulerBase::CurrentScheduler()->GetNumberOfVirtualProcessors();
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
_Scheduler _CurrentScheduler::_Get()
|
| 231 |
+
{
|
| 232 |
+
return _Scheduler(SchedulerBase::CurrentScheduler());
|
| 233 |
+
}
|
| 234 |
+
} // namespace details
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Exceptions.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation for concurrency runtime exceptions.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
//
|
| 19 |
+
// scheduler_resource_allocation_error
|
| 20 |
+
//
|
| 21 |
+
|
| 22 |
+
/// <summary>
|
| 23 |
+
/// Construct a scheduler_resource_allocation_error exception with a message and an error code
|
| 24 |
+
/// </summary>
|
| 25 |
+
/// <param name="message">
|
| 26 |
+
/// Descriptive message of error
|
| 27 |
+
/// </param>
|
| 28 |
+
/// <param name="hresult">
|
| 29 |
+
/// HRESULT of error that caused this exception
|
| 30 |
+
/// </param>
|
| 31 |
+
_Use_decl_annotations_
|
| 32 |
+
_CONCRTIMP scheduler_resource_allocation_error::scheduler_resource_allocation_error(const char* message, HRESULT hresult) noexcept
|
| 33 |
+
: exception(message), _Hresult(hresult)
|
| 34 |
+
{ }
|
| 35 |
+
|
| 36 |
+
/// <summary>
|
| 37 |
+
/// Construct a scheduler_resource_allocation_error exception with an error code
|
| 38 |
+
/// </summary>
|
| 39 |
+
/// <param name="hresult">
|
| 40 |
+
/// HRESULT of error that caused this exception
|
| 41 |
+
/// </param>
|
| 42 |
+
_CONCRTIMP scheduler_resource_allocation_error::scheduler_resource_allocation_error(HRESULT hresult) noexcept
|
| 43 |
+
: exception(), _Hresult(hresult)
|
| 44 |
+
{
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Get the error code that caused this exception
|
| 49 |
+
/// </summary>
|
| 50 |
+
///<returns>HRESULT of error that caused the exception</returns>
|
| 51 |
+
_CONCRTIMP HRESULT scheduler_resource_allocation_error::get_error_code() const noexcept
|
| 52 |
+
{
|
| 53 |
+
return _Hresult;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
//
|
| 57 |
+
// scheduler_worker_creation_error
|
| 58 |
+
//
|
| 59 |
+
|
| 60 |
+
/// <summary>
|
| 61 |
+
/// Constructs a <c>scheduler_worker_creation_error</c> object.
|
| 62 |
+
/// </summary>
|
| 63 |
+
/// <param name="_Message">
|
| 64 |
+
/// A descriptive message of the error.
|
| 65 |
+
/// </param>
|
| 66 |
+
/// <param name="_Hresult">
|
| 67 |
+
/// The <c>HRESULT</c> value of the error that caused the exception.
|
| 68 |
+
/// </param>
|
| 69 |
+
/**/
|
| 70 |
+
_Use_decl_annotations_
|
| 71 |
+
_CONCRTIMP scheduler_worker_creation_error::scheduler_worker_creation_error(const char * message, HRESULT hresult) noexcept
|
| 72 |
+
: scheduler_resource_allocation_error(message, hresult)
|
| 73 |
+
{ }
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Constructs a <c>scheduler_worker_creation_error</c> object.
|
| 77 |
+
/// </summary>
|
| 78 |
+
/// <param name="_Hresult">
|
| 79 |
+
/// The <c>HRESULT</c> value of the error that caused the exception.
|
| 80 |
+
/// </param>
|
| 81 |
+
/**/
|
| 82 |
+
_CONCRTIMP scheduler_worker_creation_error::scheduler_worker_creation_error(HRESULT hresult) noexcept
|
| 83 |
+
: scheduler_resource_allocation_error(hresult)
|
| 84 |
+
{ }
|
| 85 |
+
|
| 86 |
+
//
|
| 87 |
+
// unsupported_os -- exception thrown whenever an unsupported OS is used
|
| 88 |
+
//
|
| 89 |
+
|
| 90 |
+
/// <summary>
|
| 91 |
+
/// Construct a unsupported_os exception with a message
|
| 92 |
+
/// </summary>
|
| 93 |
+
/// <param name="message">
|
| 94 |
+
/// Descriptive message of error
|
| 95 |
+
/// </param>
|
| 96 |
+
_Use_decl_annotations_
|
| 97 |
+
_CONCRTIMP unsupported_os::unsupported_os(const char* message) noexcept
|
| 98 |
+
: exception(message)
|
| 99 |
+
{ }
|
| 100 |
+
|
| 101 |
+
/// <summary>
|
| 102 |
+
/// Construct a unsupported_os exception
|
| 103 |
+
/// </summary>
|
| 104 |
+
_CONCRTIMP unsupported_os::unsupported_os() noexcept
|
| 105 |
+
: exception()
|
| 106 |
+
{
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
//
|
| 110 |
+
// scheduler_not_attached
|
| 111 |
+
//
|
| 112 |
+
|
| 113 |
+
/// <summary>
|
| 114 |
+
/// Construct a scheduler_not_attached exception with a message
|
| 115 |
+
/// </summary>
|
| 116 |
+
/// <param name="message">
|
| 117 |
+
/// Descriptive message of error
|
| 118 |
+
/// </param>
|
| 119 |
+
_Use_decl_annotations_
|
| 120 |
+
_CONCRTIMP scheduler_not_attached::scheduler_not_attached(const char* message) noexcept
|
| 121 |
+
: exception(message)
|
| 122 |
+
{ }
|
| 123 |
+
|
| 124 |
+
/// <summary>
|
| 125 |
+
/// Construct a scheduler_not_attached exception
|
| 126 |
+
/// </summary>
|
| 127 |
+
_CONCRTIMP scheduler_not_attached::scheduler_not_attached() noexcept
|
| 128 |
+
: exception()
|
| 129 |
+
{
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
//
|
| 133 |
+
// improper_scheduler_attach
|
| 134 |
+
//
|
| 135 |
+
|
| 136 |
+
/// <summary>
|
| 137 |
+
/// Construct a improper_scheduler_attach exception with a message
|
| 138 |
+
/// </summary>
|
| 139 |
+
/// <param name="message">
|
| 140 |
+
/// Descriptive message of error
|
| 141 |
+
/// </param>
|
| 142 |
+
_Use_decl_annotations_
|
| 143 |
+
_CONCRTIMP improper_scheduler_attach::improper_scheduler_attach(const char* message) noexcept
|
| 144 |
+
: exception(message)
|
| 145 |
+
{ }
|
| 146 |
+
|
| 147 |
+
/// <summary>
|
| 148 |
+
/// Construct a improper_scheduler_attach exception
|
| 149 |
+
/// </summary>
|
| 150 |
+
_CONCRTIMP improper_scheduler_attach::improper_scheduler_attach() noexcept
|
| 151 |
+
: exception()
|
| 152 |
+
{
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
//
|
| 156 |
+
// improper_scheduler_detach
|
| 157 |
+
//
|
| 158 |
+
|
| 159 |
+
/// <summary>
|
| 160 |
+
/// Construct a improper_scheduler_detach exception with a message
|
| 161 |
+
/// </summary>
|
| 162 |
+
/// <param name="message">
|
| 163 |
+
/// Descriptive message of error
|
| 164 |
+
/// </param>
|
| 165 |
+
_Use_decl_annotations_
|
| 166 |
+
_CONCRTIMP improper_scheduler_detach::improper_scheduler_detach(const char* message) noexcept
|
| 167 |
+
: exception(message)
|
| 168 |
+
{ }
|
| 169 |
+
|
| 170 |
+
/// <summary>
|
| 171 |
+
/// Construct a improper_scheduler_detach exception
|
| 172 |
+
/// </summary>
|
| 173 |
+
_CONCRTIMP improper_scheduler_detach::improper_scheduler_detach() noexcept
|
| 174 |
+
: exception()
|
| 175 |
+
{
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
//
|
| 179 |
+
// improper_scheduler_reference
|
| 180 |
+
//
|
| 181 |
+
|
| 182 |
+
/// <summary>
|
| 183 |
+
/// Construct a improper_scheduler_reference exception with a message
|
| 184 |
+
/// </summary>
|
| 185 |
+
/// <param name="message">
|
| 186 |
+
/// Descriptive message of error
|
| 187 |
+
/// </param>
|
| 188 |
+
_Use_decl_annotations_
|
| 189 |
+
_CONCRTIMP improper_scheduler_reference::improper_scheduler_reference(const char* message) noexcept
|
| 190 |
+
: exception(message)
|
| 191 |
+
{ }
|
| 192 |
+
|
| 193 |
+
/// <summary>
|
| 194 |
+
/// Construct a improper_scheduler_reference exception
|
| 195 |
+
/// </summary>
|
| 196 |
+
_CONCRTIMP improper_scheduler_reference::improper_scheduler_reference() noexcept
|
| 197 |
+
: exception()
|
| 198 |
+
{
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
//
|
| 202 |
+
// default_scheduler_exists
|
| 203 |
+
//
|
| 204 |
+
|
| 205 |
+
/// <summary>
|
| 206 |
+
/// Construct a default_scheduler_exists exception with a message
|
| 207 |
+
/// </summary>
|
| 208 |
+
/// <param name="message">
|
| 209 |
+
/// Descriptive message of error
|
| 210 |
+
/// </param>
|
| 211 |
+
_Use_decl_annotations_
|
| 212 |
+
_CONCRTIMP default_scheduler_exists::default_scheduler_exists(const char* message) noexcept
|
| 213 |
+
: exception(message)
|
| 214 |
+
{ }
|
| 215 |
+
|
| 216 |
+
/// <summary>
|
| 217 |
+
/// Construct a default_scheduler_exists exception
|
| 218 |
+
/// </summary>
|
| 219 |
+
_CONCRTIMP default_scheduler_exists::default_scheduler_exists() noexcept
|
| 220 |
+
: exception()
|
| 221 |
+
{
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
//
|
| 225 |
+
// context_unblock_unbalanced
|
| 226 |
+
//
|
| 227 |
+
|
| 228 |
+
/// <summary>
|
| 229 |
+
/// Construct a context_unblock_unbalanced exception with a message
|
| 230 |
+
/// </summary>
|
| 231 |
+
/// <param name="message">
|
| 232 |
+
/// Descriptive message of error
|
| 233 |
+
/// </param>
|
| 234 |
+
_Use_decl_annotations_
|
| 235 |
+
_CONCRTIMP context_unblock_unbalanced::context_unblock_unbalanced(const char* message) noexcept
|
| 236 |
+
: exception(message)
|
| 237 |
+
{ }
|
| 238 |
+
|
| 239 |
+
/// <summary>
|
| 240 |
+
/// Construct a context_unblock_unbalanced exception
|
| 241 |
+
/// </summary>
|
| 242 |
+
_CONCRTIMP context_unblock_unbalanced::context_unblock_unbalanced() noexcept
|
| 243 |
+
: exception()
|
| 244 |
+
{
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
//
|
| 248 |
+
// context_self_unblock
|
| 249 |
+
//
|
| 250 |
+
|
| 251 |
+
/// <summary>
|
| 252 |
+
/// Construct a context_self_unblock exception with a message
|
| 253 |
+
/// </summary>
|
| 254 |
+
/// <param name="message">
|
| 255 |
+
/// Descriptive message of error
|
| 256 |
+
/// </param>
|
| 257 |
+
_Use_decl_annotations_
|
| 258 |
+
_CONCRTIMP context_self_unblock::context_self_unblock(const char* message) noexcept
|
| 259 |
+
: exception(message)
|
| 260 |
+
{ }
|
| 261 |
+
|
| 262 |
+
/// <summary>
|
| 263 |
+
/// Construct a context_unblock_unbalanced exception
|
| 264 |
+
/// </summary>
|
| 265 |
+
_CONCRTIMP context_self_unblock::context_self_unblock() noexcept
|
| 266 |
+
: exception()
|
| 267 |
+
{
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
//
|
| 271 |
+
// missing_wait -- Exception thrown whenever a task collection is destructed without being waited upon and still contains work
|
| 272 |
+
//
|
| 273 |
+
|
| 274 |
+
/// <summary>
|
| 275 |
+
/// Construct a missing_wait exception with a message
|
| 276 |
+
/// </summary>
|
| 277 |
+
/// <param name="message">
|
| 278 |
+
/// Descriptive message of error
|
| 279 |
+
/// </param>
|
| 280 |
+
_Use_decl_annotations_
|
| 281 |
+
_CONCRTIMP missing_wait::missing_wait(const char* message) noexcept
|
| 282 |
+
: exception(message)
|
| 283 |
+
{ }
|
| 284 |
+
|
| 285 |
+
/// <summary>
|
| 286 |
+
/// Construct a missing_wait exception
|
| 287 |
+
/// </summary>
|
| 288 |
+
_CONCRTIMP missing_wait::missing_wait() noexcept
|
| 289 |
+
: exception()
|
| 290 |
+
{
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
//
|
| 294 |
+
// bad_target -- Exception thrown whenever a messaging block is given a bad target pointer
|
| 295 |
+
//
|
| 296 |
+
|
| 297 |
+
/// <summary>
|
| 298 |
+
/// Construct a bad_target exception with a message
|
| 299 |
+
/// </summary>
|
| 300 |
+
/// <param name="message">
|
| 301 |
+
/// Descriptive message of error
|
| 302 |
+
/// </param>
|
| 303 |
+
_Use_decl_annotations_
|
| 304 |
+
_CONCRTIMP bad_target::bad_target(const char* message) noexcept
|
| 305 |
+
: exception(message)
|
| 306 |
+
{ }
|
| 307 |
+
|
| 308 |
+
/// <summary>
|
| 309 |
+
/// Construct a bad_target exception
|
| 310 |
+
/// </summary>
|
| 311 |
+
_CONCRTIMP bad_target::bad_target() noexcept
|
| 312 |
+
: exception()
|
| 313 |
+
{
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
//
|
| 317 |
+
// message_not_found -- Exception thrown whenever a messaging block is unable to find a requested message
|
| 318 |
+
//
|
| 319 |
+
|
| 320 |
+
/// <summary>
|
| 321 |
+
/// Construct a message_not_found exception with a message
|
| 322 |
+
/// </summary>
|
| 323 |
+
/// <param name="message">
|
| 324 |
+
/// Descriptive message of error
|
| 325 |
+
/// </param>
|
| 326 |
+
_Use_decl_annotations_
|
| 327 |
+
_CONCRTIMP message_not_found::message_not_found(const char* message) noexcept
|
| 328 |
+
: exception(message)
|
| 329 |
+
{ }
|
| 330 |
+
|
| 331 |
+
/// <summary>
|
| 332 |
+
/// Construct a message_not_found exception
|
| 333 |
+
/// </summary>
|
| 334 |
+
_CONCRTIMP message_not_found::message_not_found() noexcept
|
| 335 |
+
: exception()
|
| 336 |
+
{
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
//
|
| 340 |
+
// invalid_link_target -- Exception thrown whenever a messaging block tries to link a target twice
|
| 341 |
+
// when it should only occur once
|
| 342 |
+
//
|
| 343 |
+
|
| 344 |
+
/// <summary>
|
| 345 |
+
/// Construct a invalid_link_target exception with a message
|
| 346 |
+
/// </summary>
|
| 347 |
+
/// <param name="message">
|
| 348 |
+
/// Descriptive message of error
|
| 349 |
+
/// </param>
|
| 350 |
+
_Use_decl_annotations_
|
| 351 |
+
_CONCRTIMP invalid_link_target::invalid_link_target(const char* message) noexcept
|
| 352 |
+
: exception(message)
|
| 353 |
+
{ }
|
| 354 |
+
|
| 355 |
+
/// <summary>
|
| 356 |
+
/// Construct a message_not_found exception
|
| 357 |
+
/// </summary>
|
| 358 |
+
_CONCRTIMP invalid_link_target::invalid_link_target() noexcept
|
| 359 |
+
: exception()
|
| 360 |
+
{
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
//
|
| 364 |
+
// invalid_scheduler_policy_key -- Exception thrown whenever a policy key is invalid
|
| 365 |
+
//
|
| 366 |
+
|
| 367 |
+
/// <summary>
|
| 368 |
+
/// Construct a invalid_scheduler_policy_key exception with a message
|
| 369 |
+
/// </summary>
|
| 370 |
+
/// <param name="message">
|
| 371 |
+
/// Descriptive message of error
|
| 372 |
+
/// </param>
|
| 373 |
+
_Use_decl_annotations_
|
| 374 |
+
_CONCRTIMP invalid_scheduler_policy_key::invalid_scheduler_policy_key(const char* message) noexcept
|
| 375 |
+
: exception(message)
|
| 376 |
+
{
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
/// <summary>
|
| 380 |
+
/// Construct a invalid_scheduler_policy_key exception
|
| 381 |
+
/// </summary>
|
| 382 |
+
_CONCRTIMP invalid_scheduler_policy_key::invalid_scheduler_policy_key() noexcept
|
| 383 |
+
: exception()
|
| 384 |
+
{
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
//
|
| 388 |
+
// invalid_scheduler_policy_value -- Exception thrown whenever a policy value is invalid
|
| 389 |
+
//
|
| 390 |
+
|
| 391 |
+
/// <summary>
|
| 392 |
+
/// Construct a invalid_scheduler_policy_value exception with a message
|
| 393 |
+
/// </summary>
|
| 394 |
+
/// <param name="message">
|
| 395 |
+
/// Descriptive message of error
|
| 396 |
+
/// </param>
|
| 397 |
+
_Use_decl_annotations_
|
| 398 |
+
_CONCRTIMP invalid_scheduler_policy_value::invalid_scheduler_policy_value(const char* message) noexcept
|
| 399 |
+
: exception(message)
|
| 400 |
+
{
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
/// <summary>
|
| 404 |
+
/// Construct a invalid_scheduler_policy_value exception
|
| 405 |
+
/// </summary>
|
| 406 |
+
_CONCRTIMP invalid_scheduler_policy_value::invalid_scheduler_policy_value() noexcept
|
| 407 |
+
: exception()
|
| 408 |
+
{
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
//
|
| 412 |
+
// invalid_scheduler_policy_thread_specification -- Exception thrown whenever a combination of thread specifications are invalid
|
| 413 |
+
//
|
| 414 |
+
|
| 415 |
+
/// <summary>
|
| 416 |
+
/// Construct a invalid_scheduler_policy_thread_specification exception with a message
|
| 417 |
+
/// </summary>
|
| 418 |
+
/// <param name="message">
|
| 419 |
+
/// Descriptive message of error
|
| 420 |
+
/// </param>
|
| 421 |
+
_Use_decl_annotations_
|
| 422 |
+
_CONCRTIMP invalid_scheduler_policy_thread_specification::invalid_scheduler_policy_thread_specification(const char* message) noexcept
|
| 423 |
+
: exception(message)
|
| 424 |
+
{
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
/// <summary>
|
| 428 |
+
/// Construct a invalid_scheduler_policy_thread_specification exception
|
| 429 |
+
/// </summary>
|
| 430 |
+
_CONCRTIMP invalid_scheduler_policy_thread_specification::invalid_scheduler_policy_thread_specification() noexcept
|
| 431 |
+
: exception()
|
| 432 |
+
{
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
//
|
| 436 |
+
// nested_scheduler_missing_detach -- Exception thrown when the runtime can detect that
|
| 437 |
+
// a Detach() was missing for a nested scheduler.
|
| 438 |
+
//
|
| 439 |
+
|
| 440 |
+
/// <summary>
|
| 441 |
+
/// Construct an nested_scheduler_missing_detach exception with a message
|
| 442 |
+
/// </summary>
|
| 443 |
+
/// <param name="message">
|
| 444 |
+
/// Descriptive message of error
|
| 445 |
+
/// </param>
|
| 446 |
+
_Use_decl_annotations_
|
| 447 |
+
_CONCRTIMP nested_scheduler_missing_detach::nested_scheduler_missing_detach(const char* message) noexcept
|
| 448 |
+
: exception(message)
|
| 449 |
+
{ }
|
| 450 |
+
|
| 451 |
+
/// <summary>
|
| 452 |
+
/// Construct an nested_scheduler_missing_detach exception
|
| 453 |
+
/// </summary>
|
| 454 |
+
_CONCRTIMP nested_scheduler_missing_detach::nested_scheduler_missing_detach() noexcept
|
| 455 |
+
: exception()
|
| 456 |
+
{
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
//
|
| 460 |
+
// operation_timed_out -- An operation has timed out.
|
| 461 |
+
//
|
| 462 |
+
|
| 463 |
+
/// <summary>
|
| 464 |
+
/// Construct an operation_timed_out exception with a message
|
| 465 |
+
/// </summary>
|
| 466 |
+
/// <param name="message">
|
| 467 |
+
/// Descriptive message of error
|
| 468 |
+
/// </param>
|
| 469 |
+
_Use_decl_annotations_
|
| 470 |
+
_CONCRTIMP operation_timed_out::operation_timed_out(const char* message) noexcept
|
| 471 |
+
: exception(message)
|
| 472 |
+
{ }
|
| 473 |
+
|
| 474 |
+
/// <summary>
|
| 475 |
+
/// Construct an operation_timed_out exception
|
| 476 |
+
/// </summary>
|
| 477 |
+
_CONCRTIMP operation_timed_out::operation_timed_out() noexcept
|
| 478 |
+
: exception()
|
| 479 |
+
{
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
//
|
| 483 |
+
// invalid_multiple_scheduling -- An exception thrown when a chore/task_handle is scheduled multiple
|
| 484 |
+
// times on one or more *TaskCollection/*task_group constructs before completing.
|
| 485 |
+
//
|
| 486 |
+
|
| 487 |
+
/// <summary>
|
| 488 |
+
/// Construct an invalid_multiple_scheduling exception with a message
|
| 489 |
+
/// </summary>
|
| 490 |
+
/// <param name="_Message">
|
| 491 |
+
/// Descriptive message of error
|
| 492 |
+
/// </param>
|
| 493 |
+
_Use_decl_annotations_
|
| 494 |
+
_CONCRTIMP invalid_multiple_scheduling::invalid_multiple_scheduling(const char* message) noexcept
|
| 495 |
+
: exception(message)
|
| 496 |
+
{ }
|
| 497 |
+
|
| 498 |
+
/// <summary>
|
| 499 |
+
/// Construct an invalid_multiple_scheduling exception
|
| 500 |
+
/// </summary>
|
| 501 |
+
_CONCRTIMP invalid_multiple_scheduling::invalid_multiple_scheduling() noexcept
|
| 502 |
+
: exception()
|
| 503 |
+
{
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
//
|
| 507 |
+
//
|
| 508 |
+
// invalid_oversubscribe_operation -- An exception thrown when Context::Oversubscribe(false)
|
| 509 |
+
// is called without calling Context::Oversubscribe(true) first.
|
| 510 |
+
//
|
| 511 |
+
|
| 512 |
+
/// <summary>
|
| 513 |
+
/// Construct an invalid_oversubscribe_operation exception with a message
|
| 514 |
+
/// </summary>
|
| 515 |
+
/// <param name="_Message">
|
| 516 |
+
/// Descriptive message of error
|
| 517 |
+
/// </param>
|
| 518 |
+
_Use_decl_annotations_
|
| 519 |
+
_CONCRTIMP invalid_oversubscribe_operation::invalid_oversubscribe_operation(const char* message) noexcept
|
| 520 |
+
: exception(message)
|
| 521 |
+
{ }
|
| 522 |
+
|
| 523 |
+
/// <summary>
|
| 524 |
+
/// Construct an invalid_oversubscribe_operation exception
|
| 525 |
+
/// </summary>
|
| 526 |
+
_CONCRTIMP invalid_oversubscribe_operation::invalid_oversubscribe_operation() noexcept
|
| 527 |
+
: exception()
|
| 528 |
+
{
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
//
|
| 532 |
+
// improper_lock
|
| 533 |
+
//
|
| 534 |
+
|
| 535 |
+
/// <summary>
|
| 536 |
+
/// Construct a improper_lock exception with a message
|
| 537 |
+
/// </summary>
|
| 538 |
+
/// <param name="message">
|
| 539 |
+
/// Descriptive message of error
|
| 540 |
+
/// </param>
|
| 541 |
+
_Use_decl_annotations_
|
| 542 |
+
_CONCRTIMP improper_lock::improper_lock(const char* message) noexcept
|
| 543 |
+
: exception(message)
|
| 544 |
+
{ }
|
| 545 |
+
|
| 546 |
+
/// <summary>
|
| 547 |
+
/// Construct a improper_lock exception
|
| 548 |
+
/// </summary>
|
| 549 |
+
_CONCRTIMP improper_lock::improper_lock() noexcept
|
| 550 |
+
: exception()
|
| 551 |
+
{
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.cpp
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ExecutionResource.cpp
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this file contains the internal implementation for the execution
|
| 11 |
+
// resource.
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
#include "concrtinternal.h"
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
/// <summary>
|
| 22 |
+
/// Constructs a new execution resource.
|
| 23 |
+
/// </summary>
|
| 24 |
+
/// <param name="pSchedulerProxy">
|
| 25 |
+
/// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of
|
| 26 |
+
/// a scheduler.
|
| 27 |
+
/// <param name="pNode">
|
| 28 |
+
/// The processor node that this resource belongs to. The processor node is one among the nodes allocated to the
|
| 29 |
+
/// scheduler proxy.
|
| 30 |
+
/// </param>
|
| 31 |
+
/// <param name="coreIndex">
|
| 32 |
+
/// The index into the array of cores for the processor node specified.
|
| 33 |
+
/// </param>
|
| 34 |
+
ExecutionResource::ExecutionResource(SchedulerProxy * pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex)
|
| 35 |
+
: m_pSchedulerProxy(pSchedulerProxy)
|
| 36 |
+
, m_pParentExecutionResource(NULL)
|
| 37 |
+
, m_pVirtualProcessorRoot(NULL)
|
| 38 |
+
, m_tlsResetValue(0)
|
| 39 |
+
, m_nodeId(pNode->m_id)
|
| 40 |
+
, m_coreIndex(coreIndex)
|
| 41 |
+
, m_numThreadSubscriptions(0)
|
| 42 |
+
{
|
| 43 |
+
// Derive the execution resource id from the node and the core.
|
| 44 |
+
m_executionResourceId = ((int)(pNode->m_processorGroup) << 8) + pNode->m_pCores[coreIndex].m_processorNumber;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Constructs a new execution resource.
|
| 49 |
+
/// </summary>
|
| 50 |
+
/// <param name="pSchedulerProxy">
|
| 51 |
+
/// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of
|
| 52 |
+
/// a scheduler.
|
| 53 |
+
/// <param name="pParentExecutionResource">
|
| 54 |
+
/// The parent execution resource representing this thread. If there was already an execution resource on the
|
| 55 |
+
/// calling thread that was created in a different scheduler, it becomes the parent of this execution resource.
|
| 56 |
+
/// </param>
|
| 57 |
+
ExecutionResource::ExecutionResource(SchedulerProxy * pSchedulerProxy, ExecutionResource * pParentExecutionResource)
|
| 58 |
+
: m_pSchedulerProxy(pSchedulerProxy)
|
| 59 |
+
, m_pParentExecutionResource(pParentExecutionResource)
|
| 60 |
+
, m_pVirtualProcessorRoot(NULL)
|
| 61 |
+
, m_tlsResetValue(0)
|
| 62 |
+
, m_nodeId(pParentExecutionResource->GetNodeId())
|
| 63 |
+
, m_coreIndex(pParentExecutionResource->GetCoreIndex())
|
| 64 |
+
, m_numThreadSubscriptions(0)
|
| 65 |
+
{
|
| 66 |
+
m_executionResourceId = pParentExecutionResource->GetExecutionResourceId();
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
/// <summary>
|
| 71 |
+
/// Called to indicate that a scheduler is done with an execution resource and wishes to return it to the resource manager.
|
| 72 |
+
/// </summary>
|
| 73 |
+
/// <param name="pScheduler">
|
| 74 |
+
/// The scheduler making the request to remove this execution resource.
|
| 75 |
+
/// </param>
|
| 76 |
+
void ExecutionResource::Remove(IScheduler *pScheduler)
|
| 77 |
+
{
|
| 78 |
+
if (pScheduler == NULL)
|
| 79 |
+
{
|
| 80 |
+
throw std::invalid_argument("pScheduler");
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Remove must be called on the same thread that called SubscribeCurrentThread.
|
| 84 |
+
ExecutionResource * pExecutionResource = m_pSchedulerProxy->GetCurrentThreadExecutionResource();
|
| 85 |
+
if (pExecutionResource != this)
|
| 86 |
+
{
|
| 87 |
+
throw invalid_operation();
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// The scheduler proxy should match the scheduler calling remove.
|
| 91 |
+
if (m_pSchedulerProxy->Scheduler() != pScheduler)
|
| 92 |
+
{
|
| 93 |
+
throw invalid_operation();
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
m_pSchedulerProxy->GetResourceManager()->RemoveExecutionResource(this);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
/// <summary>
|
| 100 |
+
/// Set this execution resource as current on this thread
|
| 101 |
+
/// </summary>
|
| 102 |
+
void ExecutionResource::SetAsCurrent()
|
| 103 |
+
{
|
| 104 |
+
// Save the information about this execution resource in the TLS for nested SubscribeCurrentThread calls.
|
| 105 |
+
DWORD tlsSlot = m_pSchedulerProxy->GetResourceManager()->GetExecutionResourceTls();
|
| 106 |
+
m_tlsResetValue = (size_t) platform::__TlsGetValue(tlsSlot);
|
| 107 |
+
ASSERT((void *) m_tlsResetValue != (void *)this);
|
| 108 |
+
platform::__TlsSetValue(tlsSlot, this);
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
/// <summary>
|
| 112 |
+
/// Clear the current execution resource on this thread.
|
| 113 |
+
/// </summary>
|
| 114 |
+
void ExecutionResource::ResetCurrent()
|
| 115 |
+
{
|
| 116 |
+
DWORD tlsSlot = m_pSchedulerProxy->GetResourceManager()->GetExecutionResourceTls();
|
| 117 |
+
platform::__TlsSetValue(tlsSlot, (void *) m_tlsResetValue);
|
| 118 |
+
m_tlsResetValue = 0;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/// <summary>
|
| 122 |
+
/// Increments the number of external threads that run on this execution resource as well as
|
| 123 |
+
/// the number of fixed threads that are running on the underlying core.
|
| 124 |
+
/// </summary>
|
| 125 |
+
/// <remarks>
|
| 126 |
+
/// This information is used to validate matching SubscribeCurrentThread/Release calls, as well as
|
| 127 |
+
/// to mark a core on which this resource runs as fixed (not-movable).
|
| 128 |
+
/// </remarks>
|
| 129 |
+
void ExecutionResource::IncrementUseCounts()
|
| 130 |
+
{
|
| 131 |
+
// The RM LOCK needs to be held before calling this routine
|
| 132 |
+
|
| 133 |
+
if (m_numThreadSubscriptions++ == 0)
|
| 134 |
+
{
|
| 135 |
+
// For an execution resources associated with a vproc, the threadsubscription count is expected to
|
| 136 |
+
// go from 0 to 1 when a context running on that vproc subscribes a thread to the scheduler it is running
|
| 137 |
+
// on or a different scheduler.
|
| 138 |
+
|
| 139 |
+
// For an execution resource *not* associated with a vproc, the threadsubscription count is expected to
|
| 140 |
+
// go from 0 to 1 when it is created.
|
| 141 |
+
bool isVPRoot = (m_pVirtualProcessorRoot != NULL);
|
| 142 |
+
|
| 143 |
+
if (m_pParentExecutionResource == NULL)
|
| 144 |
+
{
|
| 145 |
+
// Mark on the core that this execution resource has added a new reference
|
| 146 |
+
m_pSchedulerProxy->IncrementFixedCoreCount(m_nodeId, m_coreIndex, !isVPRoot);
|
| 147 |
+
|
| 148 |
+
if (!isVPRoot)
|
| 149 |
+
{
|
| 150 |
+
// Save old affinity
|
| 151 |
+
HANDLE hThread = GetCurrentThread();
|
| 152 |
+
m_oldAffinity = HardwareAffinity(hThread);
|
| 153 |
+
|
| 154 |
+
// Affinitize this thread to a given node
|
| 155 |
+
HardwareAffinity newAffinity = m_pSchedulerProxy->GetNodeAffinity(m_nodeId);
|
| 156 |
+
newAffinity.ApplyTo(hThread);
|
| 157 |
+
|
| 158 |
+
m_pSchedulerProxy->IncrementCoreSubscription(this);
|
| 159 |
+
m_pSchedulerProxy->AddExecutionResource(this);
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
else
|
| 163 |
+
{
|
| 164 |
+
ASSERT(!isVPRoot);
|
| 165 |
+
m_pSchedulerProxy->AddThreadSubscription(this);
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
SetAsCurrent();
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/// <summary>
|
| 173 |
+
/// Called to update the proxy counts, which must be done under the RM lock.
|
| 174 |
+
/// </summary>
|
| 175 |
+
void ExecutionResource::DecrementUseCounts()
|
| 176 |
+
{
|
| 177 |
+
// The RM LOCK needs to be held before calling this routine
|
| 178 |
+
ASSERT(m_numThreadSubscriptions > 0);
|
| 179 |
+
|
| 180 |
+
// This particular call does not have to worry about the RM receiving a SchedulerShutdown for the scheduler proxy in question.
|
| 181 |
+
if (--m_numThreadSubscriptions == 0)
|
| 182 |
+
{
|
| 183 |
+
bool isVPRoot = (m_pVirtualProcessorRoot != NULL);
|
| 184 |
+
// Reset the TLS to the previous state.
|
| 185 |
+
// The previous state could be either NULL (if this was not an external threads first subscription),
|
| 186 |
+
// a pointer to a thread proxy (it if was originally a vproc), or a parent execution resource (if this
|
| 187 |
+
// was a nested execution resource).
|
| 188 |
+
ResetCurrent();
|
| 189 |
+
|
| 190 |
+
if (m_pParentExecutionResource == NULL)
|
| 191 |
+
{
|
| 192 |
+
// Mark on the core that this execution resource has removed one of its references
|
| 193 |
+
m_pSchedulerProxy->DecrementFixedCoreCount(m_nodeId, m_coreIndex, !isVPRoot);
|
| 194 |
+
|
| 195 |
+
if (!isVPRoot)
|
| 196 |
+
{
|
| 197 |
+
m_oldAffinity.ApplyTo(GetCurrentThread());
|
| 198 |
+
m_pSchedulerProxy->DecrementCoreSubscription(this);
|
| 199 |
+
m_pSchedulerProxy->DestroyExecutionResource(this);
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
else
|
| 203 |
+
{
|
| 204 |
+
ASSERT(!isVPRoot);
|
| 205 |
+
m_pParentExecutionResource->DecrementUseCounts();
|
| 206 |
+
m_pSchedulerProxy->RemoveThreadSubscription(this);
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/// <summary>
|
| 212 |
+
/// Returns the subscription level on the core that this execution resource represents
|
| 213 |
+
/// </summary>
|
| 214 |
+
/// <returns>
|
| 215 |
+
/// A current subscription level of the underlying execution resource.
|
| 216 |
+
/// </returns>
|
| 217 |
+
unsigned int ExecutionResource::CurrentSubscriptionLevel() const
|
| 218 |
+
{
|
| 219 |
+
return m_pSchedulerProxy->GetResourceManager()->CurrentSubscriptionLevel(m_nodeId, m_coreIndex);
|
| 220 |
+
}
|
| 221 |
+
} // namespace details
|
| 222 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExecutionResource.h
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ExecutionResource.h
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the
|
| 11 |
+
// execution resource.
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
#pragma once
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
#pragma warning(push)
|
| 22 |
+
#pragma warning(disable: 4265) // non-virtual destructor in base class
|
| 23 |
+
/// <summary>
|
| 24 |
+
/// An abstraction for an execution resource -- an entity on top of which a single thread of execution (of whatever
|
| 25 |
+
/// type) runs.
|
| 26 |
+
/// </summary>
|
| 27 |
+
class ExecutionResource final : public IExecutionResource
|
| 28 |
+
{
|
| 29 |
+
public:
|
| 30 |
+
|
| 31 |
+
/// <summary>
|
| 32 |
+
/// Constructs a new execution resource.
|
| 33 |
+
/// </summary>
|
| 34 |
+
/// <param name="pSchedulerProxy">
|
| 35 |
+
/// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of
|
| 36 |
+
/// a scheduler.
|
| 37 |
+
/// </param>
|
| 38 |
+
/// <param name="pNode">
|
| 39 |
+
/// The processor node that this resource belongs to. The processor node is one among the nodes allocated to the
|
| 40 |
+
/// scheduler proxy.
|
| 41 |
+
/// </param>
|
| 42 |
+
/// <param name="coreIndex">
|
| 43 |
+
/// The index into the array of cores for the processor node specified.
|
| 44 |
+
/// </param>
|
| 45 |
+
ExecutionResource(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex);
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Constructs a new execution resource.
|
| 49 |
+
/// </summary>
|
| 50 |
+
/// <param name="pSchedulerProxy">
|
| 51 |
+
/// The scheduler proxy this resource is created for. A scheduler proxy holds RM data associated with an instance of
|
| 52 |
+
/// a scheduler.
|
| 53 |
+
/// <param name="pParentExecutionResource">
|
| 54 |
+
/// The parent execution resource representing this thread
|
| 55 |
+
/// scheduler proxy.
|
| 56 |
+
/// </param>
|
| 57 |
+
ExecutionResource(SchedulerProxy * pSchedulerProxy, ExecutionResource * pParentExecutionResource);
|
| 58 |
+
|
| 59 |
+
/// <summary>
|
| 60 |
+
/// Destroys an execution resource.
|
| 61 |
+
/// </summary>
|
| 62 |
+
~ExecutionResource()
|
| 63 |
+
{
|
| 64 |
+
ASSERT(m_numThreadSubscriptions == 0);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
/// <summary>
|
| 68 |
+
/// Returns a unique identifier for the node that the given execution resource belongs to. The identifier returned
|
| 69 |
+
/// will fall in the range [0, nodeCount] where nodeCount is the value returned from Concurrency::GetProcessorNodeCount.
|
| 70 |
+
/// </summary>
|
| 71 |
+
virtual unsigned int GetNodeId() const
|
| 72 |
+
{
|
| 73 |
+
return m_nodeId;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/// <summary>
|
| 77 |
+
/// Returns a unique identifier for the execution resource that this execution resource runs atop.
|
| 78 |
+
/// </summary>
|
| 79 |
+
virtual unsigned int GetExecutionResourceId() const
|
| 80 |
+
{
|
| 81 |
+
return m_executionResourceId;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/// <summary>
|
| 85 |
+
/// Called to indicate that a scheduler is done with an execution resource and wishes to return it to the resource manager.
|
| 86 |
+
/// </summary>
|
| 87 |
+
/// <param name="pScheduler">
|
| 88 |
+
/// The scheduler making the request to remove this execution resource.
|
| 89 |
+
/// </param>
|
| 90 |
+
virtual void Remove(IScheduler *pScheduler);
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Returns the subscription level on the core that this execution resource represents
|
| 94 |
+
/// </summary>
|
| 95 |
+
/// <returns>
|
| 96 |
+
/// A current subscription level of the underlying execution resource.
|
| 97 |
+
/// </returns>
|
| 98 |
+
virtual unsigned int CurrentSubscriptionLevel() const;
|
| 99 |
+
|
| 100 |
+
// **************************************************
|
| 101 |
+
// Internal
|
| 102 |
+
// **************************************************
|
| 103 |
+
|
| 104 |
+
/// <summary>
|
| 105 |
+
/// Returns a pointer to the scheduler proxy this execution resource was created by.
|
| 106 |
+
/// </summary>
|
| 107 |
+
SchedulerProxy * GetSchedulerProxy()
|
| 108 |
+
{
|
| 109 |
+
return m_pSchedulerProxy;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/// <summary>
|
| 113 |
+
/// Returns the core index into the array of cores, for the node that this execution resource is part of.
|
| 114 |
+
/// </summary>
|
| 115 |
+
unsigned int GetCoreIndex()
|
| 116 |
+
{
|
| 117 |
+
return m_coreIndex;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
/// <summary>
|
| 121 |
+
/// Retrieves a virtual processor root that contains this execution resource, if any.
|
| 122 |
+
/// </summary>
|
| 123 |
+
VirtualProcessorRoot * GetVirtualProcessorRoot()
|
| 124 |
+
{
|
| 125 |
+
return m_pVirtualProcessorRoot;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
/// <summary>
|
| 129 |
+
/// Set this execution resource as current on this thread
|
| 130 |
+
/// </summary>
|
| 131 |
+
void SetAsCurrent();
|
| 132 |
+
|
| 133 |
+
/// <summary>
|
| 134 |
+
/// Clear the current execution resource on this thread.
|
| 135 |
+
/// </summary>
|
| 136 |
+
void ResetCurrent();
|
| 137 |
+
|
| 138 |
+
/// <summary>
|
| 139 |
+
/// Initializes the execution resource as either standalone or belonging to virtual processor root.
|
| 140 |
+
/// </summary>
|
| 141 |
+
void MarkAsVirtualProcessorRoot(VirtualProcessorRoot * pVPRoot)
|
| 142 |
+
{
|
| 143 |
+
ASSERT(m_pVirtualProcessorRoot == NULL);
|
| 144 |
+
m_pVirtualProcessorRoot = pVPRoot;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
/// <summary>
|
| 148 |
+
/// Increments the number of external threads that run on this execution resource as well as
|
| 149 |
+
/// the number of fixed threads that are running on the underlying core.
|
| 150 |
+
/// </summary>
|
| 151 |
+
/// <remarks>
|
| 152 |
+
/// This information is used to validate matching SubscribeCurrentThread/Release calls, as well as
|
| 153 |
+
/// to mark a core on which this resource runs as fixed (not-movable).
|
| 154 |
+
/// </remarks>
|
| 155 |
+
void IncrementUseCounts();
|
| 156 |
+
|
| 157 |
+
/// <summary>
|
| 158 |
+
/// Called to update the crucial counts, which must be done under the RM lock.
|
| 159 |
+
/// </summary>
|
| 160 |
+
void DecrementUseCounts();
|
| 161 |
+
|
| 162 |
+
protected:
|
| 163 |
+
|
| 164 |
+
// Guards critical regions of the Execution Resource
|
| 165 |
+
_NonReentrantLock m_lock;
|
| 166 |
+
|
| 167 |
+
// The previous affinity of the external thread
|
| 168 |
+
HardwareAffinity m_oldAffinity;
|
| 169 |
+
|
| 170 |
+
// The scheduler proxy associated with the scheduler for which
|
| 171 |
+
// this resource was created.
|
| 172 |
+
SchedulerProxy * m_pSchedulerProxy;
|
| 173 |
+
|
| 174 |
+
// Parent execution resource in the case of a nested subscribe
|
| 175 |
+
ExecutionResource * m_pParentExecutionResource;
|
| 176 |
+
|
| 177 |
+
// Virtual processor root that this execution resource is a part of, if any
|
| 178 |
+
VirtualProcessorRoot * m_pVirtualProcessorRoot;
|
| 179 |
+
|
| 180 |
+
// The value to use when external resource subscription of a virtual processor is removed
|
| 181 |
+
size_t m_tlsResetValue;
|
| 182 |
+
|
| 183 |
+
// The node to which this execution resource belongs.
|
| 184 |
+
unsigned int m_nodeId;
|
| 185 |
+
|
| 186 |
+
// The core index within this node.
|
| 187 |
+
unsigned int m_coreIndex;
|
| 188 |
+
|
| 189 |
+
// The hardware thread upon which this execution resource executes.
|
| 190 |
+
unsigned int m_executionResourceId;
|
| 191 |
+
|
| 192 |
+
// Number of subscription requests that have been received for this execution resource.
|
| 193 |
+
unsigned int m_numThreadSubscriptions;
|
| 194 |
+
|
| 195 |
+
private:
|
| 196 |
+
template <class T, class Counter> friend class List;
|
| 197 |
+
|
| 198 |
+
// Intrusive links
|
| 199 |
+
ExecutionResource * m_pPrev{}, * m_pNext{};
|
| 200 |
+
};
|
| 201 |
+
|
| 202 |
+
#pragma warning(pop)
|
| 203 |
+
} // namespace details
|
| 204 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.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right (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ExternalContextBase.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the metaphor for an external execution ContextBase/stack/thread.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#include "concrtinternal.h"
|
| 14 |
+
|
| 15 |
+
#pragma warning (disable : 4702)
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
/// <summary>
|
| 22 |
+
/// Constructs an external context.
|
| 23 |
+
/// </summary>
|
| 24 |
+
/// <param name="pScheduler">
|
| 25 |
+
/// The scheduler the context will belong to.
|
| 26 |
+
/// </param>
|
| 27 |
+
/// <param name="explicitAttach">
|
| 28 |
+
/// Whether or not this is an explicit attach. An explicit attach occurs as a result of calling a scheduler
|
| 29 |
+
/// creation API, or the scheduler attach API. The scheduler will not detach implicitly for explicitly
|
| 30 |
+
/// attached threads, on thread exit.
|
| 31 |
+
/// </param>
|
| 32 |
+
ExternalContextBase::ExternalContextBase(SchedulerBase *pScheduler, bool explicitAttach) :
|
| 33 |
+
ContextBase(pScheduler, true),
|
| 34 |
+
m_pSubAllocator(NULL),
|
| 35 |
+
m_hPhysicalContext(NULL)
|
| 36 |
+
{
|
| 37 |
+
// Create an auto-reset event that is initially not signaled.
|
| 38 |
+
m_hBlock = platform::__CreateAutoResetEvent(); // VSO#459907
|
| 39 |
+
|
| 40 |
+
// External contexts are all grouped together in the 'anonymous' schedule group.
|
| 41 |
+
m_pSegment = m_pScheduler->GetAnonymousScheduleGroupSegment();
|
| 42 |
+
|
| 43 |
+
// Create external context statistics as a place where this external context we are about to create
|
| 44 |
+
// will store all the statistical data.
|
| 45 |
+
m_pStats = _concrt_new ExternalStatistics(); // VSO#459907
|
| 46 |
+
m_pScheduler->AddExternalStatistics(m_pStats);
|
| 47 |
+
|
| 48 |
+
// Initialize data that is reset each time the external context is reused.
|
| 49 |
+
PrepareForUse(explicitAttach);
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
#if !defined(_ONECORE)
|
| 53 |
+
/// <summary>
|
| 54 |
+
/// Callback to indicate the exit of one of the external threads. This function
|
| 55 |
+
/// is invoked on the wait thread. It is assumed that this function is short and quick.
|
| 56 |
+
/// </summary>
|
| 57 |
+
void CALLBACK ExternalContextBase::ImplicitDetachHandler(PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WAIT waiter, TP_WAIT_RESULT waitResult)
|
| 58 |
+
{
|
| 59 |
+
ExternalContextBase * pContext = reinterpret_cast<ExternalContextBase *>(parameter);
|
| 60 |
+
|
| 61 |
+
ASSERT(waitResult == WAIT_OBJECT_0);
|
| 62 |
+
|
| 63 |
+
pContext->m_pScheduler->DetachExternalContext(pContext, false);
|
| 64 |
+
|
| 65 |
+
// This is non-blocking
|
| 66 |
+
UnRegisterAsyncWaitAndUnloadLibrary(instance, waiter);
|
| 67 |
+
}
|
| 68 |
+
#endif // !defined(_ONECORE)
|
| 69 |
+
|
| 70 |
+
/// <summary>
|
| 71 |
+
/// Same callback function as ImplicitDetachHandler but used on XP.
|
| 72 |
+
/// </summary>
|
| 73 |
+
void CALLBACK ExternalContextBase::ImplicitDetachHandlerXP(PVOID parameter, BOOLEAN is_timeout)
|
| 74 |
+
{
|
| 75 |
+
ExternalContextBase * pContext = reinterpret_cast<ExternalContextBase *>(parameter);
|
| 76 |
+
|
| 77 |
+
// This is non-blocking
|
| 78 |
+
platform::__UnregisterWait(pContext->m_hWaitHandle);
|
| 79 |
+
|
| 80 |
+
ASSERT(!is_timeout);
|
| 81 |
+
|
| 82 |
+
pContext->m_pScheduler->DetachExternalContext(pContext, false);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
/// <summary>
|
| 86 |
+
/// Initializes fields that need re-initialization when an external context is recycled. This is called
|
| 87 |
+
/// in the constructor and when an external context is taken off the idle pool for reuse.
|
| 88 |
+
/// </summary>
|
| 89 |
+
/// <param name="explicitAttach">
|
| 90 |
+
/// Whether or not this is an explicit attach. An explicit attach occurs as a result of calling a scheduler
|
| 91 |
+
/// creation API, or the scheduler attach API. The scheduler will not detach implicitly for explicitly
|
| 92 |
+
/// attached threads, on thread exit.
|
| 93 |
+
/// </param>
|
| 94 |
+
void ExternalContextBase::PrepareForUse(bool explicitAttach)
|
| 95 |
+
{
|
| 96 |
+
// Even in the case of a nested external context being initialized, we expect the TLS slot to be clear.
|
| 97 |
+
ASSERT(SchedulerBase::FastCurrentContext() == NULL);
|
| 98 |
+
|
| 99 |
+
m_fExplicitlyAttached = explicitAttach;
|
| 100 |
+
m_threadId = GetCurrentThreadId();
|
| 101 |
+
|
| 102 |
+
if (!explicitAttach)
|
| 103 |
+
{
|
| 104 |
+
// We only need to capture the current thread's handle for an implicit attach, so that we can register the
|
| 105 |
+
// handle for exit tracking, in order that references may be released on thread exit.
|
| 106 |
+
if (!DuplicateHandle(GetCurrentProcess(),
|
| 107 |
+
GetCurrentThread(),
|
| 108 |
+
GetCurrentProcess(),
|
| 109 |
+
&m_hPhysicalContext,
|
| 110 |
+
0,
|
| 111 |
+
FALSE,
|
| 112 |
+
DUPLICATE_SAME_ACCESS))
|
| 113 |
+
{
|
| 114 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
#if !defined(_ONECORE)
|
| 118 |
+
// Request a thread pool thread to wait for this thread exit.
|
| 119 |
+
if ((m_hWaitHandle = RegisterAsyncWaitAndLoadLibrary(m_hPhysicalContext, ExternalContextBase::ImplicitDetachHandler, this)) == nullptr)
|
| 120 |
+
{
|
| 121 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 122 |
+
}
|
| 123 |
+
#else // ^^^ !defined(_ONECORE) / defined(_ONECORE) vvv
|
| 124 |
+
m_hWaitHandle = platform::__RegisterWaitForSingleObject(m_hPhysicalContext, ExternalContextBase::ImplicitDetachHandlerXP, this);
|
| 125 |
+
#endif // ^^^ defined(_ONECORE) ^^^
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
/// <summary>
|
| 130 |
+
/// Causes the external context to block. Since external contexts do not execute on virtual processors,
|
| 131 |
+
/// the context does not switch to another one. Instead, it stops executing until it is unblocked.
|
| 132 |
+
/// </summary>
|
| 133 |
+
void ExternalContextBase::Block()
|
| 134 |
+
{
|
| 135 |
+
ASSERT(this == SchedulerBase::FastCurrentContext());
|
| 136 |
+
|
| 137 |
+
TraceContextEvent(CONCRT_EVENT_BLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id);
|
| 138 |
+
|
| 139 |
+
if (InterlockedIncrement(&m_contextSwitchingFence) == 1)
|
| 140 |
+
{
|
| 141 |
+
WaitForSingleObjectEx(m_hBlock, INFINITE, FALSE);
|
| 142 |
+
}
|
| 143 |
+
else
|
| 144 |
+
{
|
| 145 |
+
// Skip the block, since an unblock has already been encountered.
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/// <summary>
|
| 150 |
+
/// Unblocks the external context causing it to start running.
|
| 151 |
+
/// </summary>
|
| 152 |
+
void ExternalContextBase::Unblock()
|
| 153 |
+
{
|
| 154 |
+
if (this != SchedulerBase::FastCurrentContext())
|
| 155 |
+
{
|
| 156 |
+
TraceContextEvent(CONCRT_EVENT_UNBLOCK, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id);
|
| 157 |
+
|
| 158 |
+
LONG newValue = InterlockedDecrement(&m_contextSwitchingFence);
|
| 159 |
+
|
| 160 |
+
if (newValue == 0)
|
| 161 |
+
{
|
| 162 |
+
SetEvent(m_hBlock);
|
| 163 |
+
}
|
| 164 |
+
else
|
| 165 |
+
{
|
| 166 |
+
if ((newValue < -1) || (newValue > 0))
|
| 167 |
+
{
|
| 168 |
+
// Should not be able to get m_contextSwitchingFence above 0.
|
| 169 |
+
ASSERT(newValue < -1);
|
| 170 |
+
|
| 171 |
+
throw context_unblock_unbalanced();
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
else
|
| 176 |
+
{
|
| 177 |
+
throw context_self_unblock();
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/// <summary>
|
| 182 |
+
/// Just a thread yield on the current processor.
|
| 183 |
+
/// </summary>
|
| 184 |
+
void ExternalContextBase::Yield()
|
| 185 |
+
{
|
| 186 |
+
TraceContextEvent(CONCRT_EVENT_YIELD, TRACE_LEVEL_INFORMATION, m_pScheduler->Id(), m_id);
|
| 187 |
+
|
| 188 |
+
platform::__SwitchToThread();
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
/// <summary>
|
| 192 |
+
/// See comments for Concurrency::Context::Oversubscribe.
|
| 193 |
+
/// External contexts do not support oversubscription. However, we keep track of calls and throw exceptions
|
| 194 |
+
/// when appropriate.
|
| 195 |
+
/// </summary>
|
| 196 |
+
void ExternalContextBase::Oversubscribe(bool beginOversubscription)
|
| 197 |
+
{
|
| 198 |
+
if (beginOversubscription)
|
| 199 |
+
{
|
| 200 |
+
++m_oversubscribeCount;
|
| 201 |
+
}
|
| 202 |
+
else
|
| 203 |
+
{
|
| 204 |
+
if (m_oversubscribeCount == 0)
|
| 205 |
+
{
|
| 206 |
+
throw invalid_oversubscribe_operation();
|
| 207 |
+
}
|
| 208 |
+
--m_oversubscribeCount;
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
/// <summary>
|
| 213 |
+
/// Allocates a block of memory of the size specified.
|
| 214 |
+
/// </summary>
|
| 215 |
+
/// <param name="numBytes">
|
| 216 |
+
/// Number of bytes to allocate.
|
| 217 |
+
/// </param>
|
| 218 |
+
/// <returns>
|
| 219 |
+
/// A pointer to newly allocated memory.
|
| 220 |
+
/// </returns>
|
| 221 |
+
void* ExternalContextBase::Alloc(size_t numBytes)
|
| 222 |
+
{
|
| 223 |
+
void* pAllocation = NULL;
|
| 224 |
+
ASSERT(SchedulerBase::FastCurrentContext() == this);
|
| 225 |
+
|
| 226 |
+
// Find the suballocator for this external context if there is one. Note that if we are unable to get an allocator now,
|
| 227 |
+
// we may be able to get one for a later Alloc or Free call (if a different external context released its allocator to
|
| 228 |
+
// the free pool).
|
| 229 |
+
SubAllocator* pAllocator = GetCurrentSubAllocator();
|
| 230 |
+
|
| 231 |
+
if (pAllocator != NULL)
|
| 232 |
+
{
|
| 233 |
+
pAllocation = pAllocator->Alloc(numBytes);
|
| 234 |
+
}
|
| 235 |
+
else
|
| 236 |
+
{
|
| 237 |
+
// Allocate from the CRT heap. At the point this allocation is freed, if the context has a suballocator, it will be
|
| 238 |
+
// freed to the suballocator of the context.
|
| 239 |
+
pAllocation = SubAllocator::StaticAlloc(numBytes);
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
return pAllocation;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/// <summary>
|
| 246 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 247 |
+
/// </summary>
|
| 248 |
+
/// <param name="pAllocation">
|
| 249 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 250 |
+
/// </param>
|
| 251 |
+
void ExternalContextBase::Free(void* pAllocation)
|
| 252 |
+
{
|
| 253 |
+
ASSERT(SchedulerBase::FastCurrentContext() == this);
|
| 254 |
+
ASSERT(pAllocation != NULL);
|
| 255 |
+
|
| 256 |
+
// Find the suballocator for this external context if there is one. Note that if we are unable to get an allocator now,
|
| 257 |
+
// we may be able to get one for a later Alloc or Free call (if a different external context released its allocator to
|
| 258 |
+
// the free pool).
|
| 259 |
+
SubAllocator* pAllocator = GetCurrentSubAllocator();
|
| 260 |
+
|
| 261 |
+
if (pAllocator != NULL)
|
| 262 |
+
{
|
| 263 |
+
pAllocator->Free(pAllocation);
|
| 264 |
+
}
|
| 265 |
+
else
|
| 266 |
+
{
|
| 267 |
+
// Free to the CRT heap.
|
| 268 |
+
SubAllocator::StaticFree(pAllocation);
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
/// <summary>
|
| 273 |
+
/// Prepares an external context for the idle pool by releasing some resources.
|
| 274 |
+
/// </summary>
|
| 275 |
+
void ExternalContextBase::RemoveFromUse()
|
| 276 |
+
{
|
| 277 |
+
ReleaseWorkQueue();
|
| 278 |
+
|
| 279 |
+
CONCRT_COREASSERT(GetCriticalRegionType() == OutsideCriticalRegion);
|
| 280 |
+
|
| 281 |
+
if (m_hPhysicalContext != NULL)
|
| 282 |
+
{
|
| 283 |
+
CloseHandle(m_hPhysicalContext);
|
| 284 |
+
m_hPhysicalContext = NULL;
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/// <summary>
|
| 289 |
+
/// Destroys an external thread based context.
|
| 290 |
+
/// </summary>
|
| 291 |
+
ExternalContextBase::~ExternalContextBase()
|
| 292 |
+
{
|
| 293 |
+
// This takes care of calling the cleanup routine for ContextBase.
|
| 294 |
+
Cleanup();
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
/// <summary>
|
| 298 |
+
/// Performs cleanup of the external context
|
| 299 |
+
/// </summary>
|
| 300 |
+
void ExternalContextBase::Cleanup()
|
| 301 |
+
{
|
| 302 |
+
ContextBase::Cleanup();
|
| 303 |
+
//
|
| 304 |
+
// m_pGroup is an anonymous schedule group that is destroyed at scheduler shutdown, so don't release here.
|
| 305 |
+
//
|
| 306 |
+
if (m_hPhysicalContext != NULL)
|
| 307 |
+
{
|
| 308 |
+
CloseHandle(m_hPhysicalContext);
|
| 309 |
+
m_hPhysicalContext = NULL;
|
| 310 |
+
}
|
| 311 |
+
if (m_hBlock)
|
| 312 |
+
{
|
| 313 |
+
CloseHandle(m_hBlock);
|
| 314 |
+
}
|
| 315 |
+
if (m_pSubAllocator != NULL)
|
| 316 |
+
{
|
| 317 |
+
SchedulerBase::ReturnSubAllocator(m_pSubAllocator);
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
// Mark the scheduler's list of non-internal contexts (external or non-bound to context) for removal. We
|
| 321 |
+
// can't remove this item yet because statistics might not have had a chance to aggregate this information yet.
|
| 322 |
+
DetachStatistics();
|
| 323 |
+
}
|
| 324 |
+
} // namespace details
|
| 325 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ExternalContextBase.h
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ExternalContextBase.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the metaphor for an external execution context.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
namespace Concurrency
|
| 16 |
+
{
|
| 17 |
+
namespace details
|
| 18 |
+
{
|
| 19 |
+
/// <summary>
|
| 20 |
+
/// Provides a storage area for external contexts bound to this scheduler or alien threads (threads not
|
| 21 |
+
/// associated with any scheduler or those associated with scheduler other than this one) where they can put
|
| 22 |
+
/// the statistical data necessary to track the rate of work.
|
| 23 |
+
/// </summary>
|
| 24 |
+
|
| 25 |
+
#pragma warning(push)
|
| 26 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 27 |
+
class ExternalStatistics
|
| 28 |
+
{
|
| 29 |
+
public:
|
| 30 |
+
//
|
| 31 |
+
// Public methods
|
| 32 |
+
//
|
| 33 |
+
|
| 34 |
+
/// <summary>
|
| 35 |
+
/// Constructs the statistics object for an external context or alien thread.
|
| 36 |
+
/// </summary>
|
| 37 |
+
ExternalStatistics() : m_enqueuedTaskCounter(0), m_dequeuedTaskCounter(0), m_enqueuedTaskCheckpoint(0), m_dequeuedTaskCheckpoint(0), m_fIsActive(true)
|
| 38 |
+
{
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/// <summary>
|
| 42 |
+
/// Increments the count of work coming in.
|
| 43 |
+
/// </summary>
|
| 44 |
+
void IncrementEnqueuedTaskCounter()
|
| 45 |
+
{
|
| 46 |
+
m_enqueuedTaskCounter++;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
/// <summary>
|
| 50 |
+
/// Increments the count of work being done.
|
| 51 |
+
/// </summary>
|
| 52 |
+
void IncrementDequeuedTaskCounter()
|
| 53 |
+
{
|
| 54 |
+
m_dequeuedTaskCounter++;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/// <summary>
|
| 58 |
+
/// Increments the count of work being done.
|
| 59 |
+
/// </summary>
|
| 60 |
+
void IncrementDequeuedTaskCounter(unsigned int count)
|
| 61 |
+
{
|
| 62 |
+
m_dequeuedTaskCounter += count;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/// <summary>
|
| 66 |
+
/// Resets the count of work coming in.
|
| 67 |
+
/// </summary>
|
| 68 |
+
/// <remarks>
|
| 69 |
+
/// This function will reset the state so that the next time it is called, it reports only the
|
| 70 |
+
/// units of work that came in since the last time. One obvious solution is to reset the
|
| 71 |
+
/// counter, but that introduces a race with a thread that tries to increment. Instead,
|
| 72 |
+
/// we update the trailing counter to match the current count. This way the difference
|
| 73 |
+
/// between the two is always the number of work coming in. By keeping these numbers unsigned
|
| 74 |
+
/// we make use of "modulo 2" behavior of unsigned ints and avoid overflow problems.
|
| 75 |
+
///
|
| 76 |
+
/// NOTE: There is a highly rare condition present in this code. If, for some reason,
|
| 77 |
+
// statistics calls were infrequent enough that UINT_MAX units of work were enqueued
|
| 78 |
+
/// between two calls we will wrap around and consequently think that no work came in at all.
|
| 79 |
+
/// </remarks>
|
| 80 |
+
/// <returns>
|
| 81 |
+
/// Previous value of the counter.
|
| 82 |
+
/// </returns>
|
| 83 |
+
unsigned int GetEnqueuedTaskCount()
|
| 84 |
+
{
|
| 85 |
+
unsigned int currentValue = m_enqueuedTaskCounter;
|
| 86 |
+
unsigned int retVal = currentValue - m_enqueuedTaskCheckpoint;
|
| 87 |
+
|
| 88 |
+
// Update the checkpoint value with the current value
|
| 89 |
+
m_enqueuedTaskCheckpoint = currentValue;
|
| 90 |
+
|
| 91 |
+
ASSERT(retVal < INT_MAX);
|
| 92 |
+
return retVal;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/// <summary>
|
| 96 |
+
/// Resets the count of work being done.
|
| 97 |
+
/// </summary>
|
| 98 |
+
/// <remarks>
|
| 99 |
+
/// Look at remarks for GetEnqueuedTaskCount.
|
| 100 |
+
/// </remarks>
|
| 101 |
+
/// <returns>
|
| 102 |
+
/// Previous value of the counter.
|
| 103 |
+
/// </returns>
|
| 104 |
+
unsigned int GetDequeuedTaskCount()
|
| 105 |
+
{
|
| 106 |
+
unsigned int currentValue = m_dequeuedTaskCounter;
|
| 107 |
+
unsigned int retVal = currentValue - m_dequeuedTaskCheckpoint;
|
| 108 |
+
|
| 109 |
+
// Update the checkpoint value with the current value
|
| 110 |
+
m_dequeuedTaskCheckpoint = currentValue;
|
| 111 |
+
|
| 112 |
+
ASSERT(retVal < INT_MAX);
|
| 113 |
+
return retVal;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
/// <summary>
|
| 117 |
+
/// Marks this statistics as not active anymore. This means that external context
|
| 118 |
+
/// has gone away and it will no longer update the statistical information. However,
|
| 119 |
+
/// we can't remove statistics right away because they might not have been collected yet.
|
| 120 |
+
/// So, we mark it as inactive and we wait for the next collection to take place before
|
| 121 |
+
/// permanently retiring this statistics.
|
| 122 |
+
/// </summary>
|
| 123 |
+
void MarkInactive()
|
| 124 |
+
{
|
| 125 |
+
m_fIsActive = FALSE;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
/// <summary>
|
| 129 |
+
/// Checks whether this statistics class expects any new updates.
|
| 130 |
+
/// </summary>
|
| 131 |
+
/// <returns>
|
| 132 |
+
/// True if statistics is still active.
|
| 133 |
+
/// </returns>
|
| 134 |
+
bool IsActive()
|
| 135 |
+
{
|
| 136 |
+
// By the memory ordering rules the only way that m_fIsActive would be marked as false
|
| 137 |
+
// is if external context is being destroyed, which means there is no work coming in or
|
| 138 |
+
// out of this external context. The task counts are final and there is no race between
|
| 139 |
+
// task counts and active bit.
|
| 140 |
+
return (m_fIsActive || (m_enqueuedTaskCounter != m_enqueuedTaskCheckpoint) || (m_dequeuedTaskCounter != m_dequeuedTaskCheckpoint));
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// A field that is necessary to store the statistics data structure in a ListArray<ExternalStatistics>
|
| 144 |
+
int m_listArrayIndex{};
|
| 145 |
+
|
| 146 |
+
private:
|
| 147 |
+
//
|
| 148 |
+
// Private data
|
| 149 |
+
//
|
| 150 |
+
|
| 151 |
+
template <class T> friend class ListArray;
|
| 152 |
+
|
| 153 |
+
// Intrusive links for list array.
|
| 154 |
+
SLIST_ENTRY m_listArrayFreeLink{};
|
| 155 |
+
|
| 156 |
+
// Statistics data counters
|
| 157 |
+
unsigned int m_enqueuedTaskCounter;
|
| 158 |
+
unsigned int m_dequeuedTaskCounter;
|
| 159 |
+
|
| 160 |
+
// Statistics data checkpoints
|
| 161 |
+
unsigned int m_enqueuedTaskCheckpoint;
|
| 162 |
+
unsigned int m_dequeuedTaskCheckpoint;
|
| 163 |
+
|
| 164 |
+
// Whether this statistics is actively worked on
|
| 165 |
+
volatile BOOL m_fIsActive;
|
| 166 |
+
};
|
| 167 |
+
#pragma warning(pop)
|
| 168 |
+
|
| 169 |
+
/// <summary>
|
| 170 |
+
/// Implements the base class for ConcRT external contexts.
|
| 171 |
+
/// </summary>
|
| 172 |
+
class ExternalContextBase : public ContextBase
|
| 173 |
+
{
|
| 174 |
+
public:
|
| 175 |
+
|
| 176 |
+
//
|
| 177 |
+
// Public methods
|
| 178 |
+
//
|
| 179 |
+
|
| 180 |
+
/// <summary>
|
| 181 |
+
/// Constructs an external context.
|
| 182 |
+
/// </summary>
|
| 183 |
+
ExternalContextBase(SchedulerBase *pScheduler, bool explicitAttach);
|
| 184 |
+
|
| 185 |
+
/// <summary>
|
| 186 |
+
/// Destroys an external context.
|
| 187 |
+
/// </summary>
|
| 188 |
+
virtual ~ExternalContextBase();
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// Causes the external context to block. Since external contexts do not execute on virtual processors,
|
| 192 |
+
/// the context does not switch to another one. Instead, it stops executing until it is unblocked.
|
| 193 |
+
/// </summary>
|
| 194 |
+
virtual void Block();
|
| 195 |
+
|
| 196 |
+
/// <summary>
|
| 197 |
+
/// Unblocks the external context causing it to start running.
|
| 198 |
+
/// </summary>
|
| 199 |
+
virtual void Unblock();
|
| 200 |
+
|
| 201 |
+
/// <summary>
|
| 202 |
+
/// Since there is no underlying virtual processor, the yield operation is a no-op for external contexts.
|
| 203 |
+
/// </summary>
|
| 204 |
+
virtual void Yield();
|
| 205 |
+
|
| 206 |
+
/// <summary>
|
| 207 |
+
/// Since there is no underlying virtual processor, the yield operation is a no-op for external contexts.
|
| 208 |
+
/// </summary>
|
| 209 |
+
virtual void SpinYield()
|
| 210 |
+
{
|
| 211 |
+
Yield();
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
/// <summary>
|
| 215 |
+
/// See comments for Concurrency::Context::Oversubscribe.
|
| 216 |
+
/// </summary>
|
| 217 |
+
virtual void Oversubscribe(bool beginOversubscription);
|
| 218 |
+
|
| 219 |
+
/// <summary>
|
| 220 |
+
/// Allocates a block of memory of the size specified.
|
| 221 |
+
/// </summary>
|
| 222 |
+
/// <param name="numBytes">
|
| 223 |
+
/// Number of bytes to allocate.
|
| 224 |
+
/// </param>
|
| 225 |
+
/// <returns>
|
| 226 |
+
/// A pointer to newly allocated memory.
|
| 227 |
+
/// </returns>
|
| 228 |
+
virtual void* Alloc(size_t numBytes);
|
| 229 |
+
|
| 230 |
+
/// <summary>
|
| 231 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 232 |
+
/// </summary>
|
| 233 |
+
/// <param name="pAllocation">
|
| 234 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 235 |
+
/// </param>
|
| 236 |
+
virtual void Free(void* pAllocation);
|
| 237 |
+
|
| 238 |
+
/// <summary>
|
| 239 |
+
/// Tells whether the context was explicitly attached to the scheduler at the time it was created
|
| 240 |
+
/// </summary>
|
| 241 |
+
bool WasExplicitlyAttached() const { return m_fExplicitlyAttached; }
|
| 242 |
+
|
| 243 |
+
/// <summary>
|
| 244 |
+
/// Returns an identifier to the virtual processor the context is currently executing on, if any.
|
| 245 |
+
/// </summary>
|
| 246 |
+
virtual unsigned int GetVirtualProcessorId() const { return UINT_MAX; }
|
| 247 |
+
|
| 248 |
+
/// <summary>
|
| 249 |
+
/// Initializes fields that need re-initialization when an external context is reused. This is called
|
| 250 |
+
/// in the constructor and when an external context is taken off the idle pool for reuse.
|
| 251 |
+
/// </summary>
|
| 252 |
+
void PrepareForUse(bool explicitAttach);
|
| 253 |
+
|
| 254 |
+
/// <summary>
|
| 255 |
+
/// Prepares an external context for the idle pool by releasing some resources.
|
| 256 |
+
/// </summary>
|
| 257 |
+
void RemoveFromUse();
|
| 258 |
+
|
| 259 |
+
/// <summary>
|
| 260 |
+
/// Returns a handle to the underlying thread.
|
| 261 |
+
/// </summary>
|
| 262 |
+
HANDLE GetPhysicalContext() { return m_hPhysicalContext; }
|
| 263 |
+
|
| 264 |
+
/// <summary>
|
| 265 |
+
/// Returns a pointer to the suballocator for this external context. Note that the RM call to get an
|
| 266 |
+
/// allocator can return NULL, since the RM only hands out a fixed number of allocators for external
|
| 267 |
+
/// contexts.
|
| 268 |
+
/// </summary>
|
| 269 |
+
SubAllocator* GetCurrentSubAllocator()
|
| 270 |
+
{
|
| 271 |
+
if (m_pSubAllocator == NULL)
|
| 272 |
+
{
|
| 273 |
+
m_pSubAllocator = SchedulerBase::GetSubAllocator(true);
|
| 274 |
+
}
|
| 275 |
+
return m_pSubAllocator;
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
/// <summary>
|
| 279 |
+
/// Increments the count of work coming in.
|
| 280 |
+
/// </summary>
|
| 281 |
+
void IncrementEnqueuedTaskCounter()
|
| 282 |
+
{
|
| 283 |
+
m_pStats->IncrementEnqueuedTaskCounter();
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/// <summary>
|
| 287 |
+
/// Increments the count of work being done.
|
| 288 |
+
/// </summary>
|
| 289 |
+
void IncrementDequeuedTaskCounter()
|
| 290 |
+
{
|
| 291 |
+
m_pStats->IncrementDequeuedTaskCounter();
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
/// <summary>
|
| 295 |
+
/// Increments the count of work being done.
|
| 296 |
+
/// </summary>
|
| 297 |
+
void IncrementDequeuedTaskCounter(unsigned int count)
|
| 298 |
+
{
|
| 299 |
+
m_pStats->IncrementDequeuedTaskCounter(count);
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/// <summary>
|
| 303 |
+
/// Orphan the statistics and let it know there will be no more updates.
|
| 304 |
+
/// </summary>
|
| 305 |
+
/// <returns>
|
| 306 |
+
/// The statistics that were attached to this external context.
|
| 307 |
+
/// </returns>
|
| 308 |
+
ExternalStatistics * DetachStatistics()
|
| 309 |
+
{
|
| 310 |
+
ExternalStatistics * externalStatistics = m_pStats;
|
| 311 |
+
m_pStats = NULL;
|
| 312 |
+
externalStatistics->MarkInactive();
|
| 313 |
+
|
| 314 |
+
return externalStatistics;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
/// <summary>
|
| 318 |
+
/// Determines whether or not the context is synchronously blocked at this given time.
|
| 319 |
+
/// </summary>
|
| 320 |
+
/// <returns>
|
| 321 |
+
/// Whether context is in synchronous block state.
|
| 322 |
+
/// </returns>
|
| 323 |
+
virtual bool IsSynchronouslyBlocked() const
|
| 324 |
+
{
|
| 325 |
+
return (m_contextSwitchingFence == 1);
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
#if _DEBUG
|
| 329 |
+
// _DEBUG helper
|
| 330 |
+
DWORD GetThreadId() const { return m_threadId; }
|
| 331 |
+
#endif
|
| 332 |
+
|
| 333 |
+
private:
|
| 334 |
+
friend class SchedulerBase;
|
| 335 |
+
template<class T> friend void _InternalDeleteHelper(T*);
|
| 336 |
+
|
| 337 |
+
//
|
| 338 |
+
// Private data
|
| 339 |
+
//
|
| 340 |
+
|
| 341 |
+
// Specifies whether the context was created as a result of an explicit or implicit attach.
|
| 342 |
+
bool m_fExplicitlyAttached;
|
| 343 |
+
|
| 344 |
+
// Statistical information for this external context.
|
| 345 |
+
ExternalStatistics * m_pStats;
|
| 346 |
+
|
| 347 |
+
// A pointer to the suballocator for this context.
|
| 348 |
+
SubAllocator * m_pSubAllocator;
|
| 349 |
+
|
| 350 |
+
// Handle to the underlying thread.
|
| 351 |
+
HANDLE m_hPhysicalContext;
|
| 352 |
+
|
| 353 |
+
// Handle to the event used for blocking.
|
| 354 |
+
HANDLE m_hBlock;
|
| 355 |
+
|
| 356 |
+
// Wait handle for thread exit event (used on XP)
|
| 357 |
+
HANDLE m_hWaitHandle;
|
| 358 |
+
|
| 359 |
+
//
|
| 360 |
+
// Private methods
|
| 361 |
+
//
|
| 362 |
+
|
| 363 |
+
/// <summary>
|
| 364 |
+
/// Performs cleanup of the external context
|
| 365 |
+
/// </summary>
|
| 366 |
+
void Cleanup();
|
| 367 |
+
|
| 368 |
+
/// <summary>
|
| 369 |
+
/// Callback to indicate the exit of one of the external threads.
|
| 370 |
+
/// </summary>
|
| 371 |
+
static void CALLBACK ImplicitDetachHandler(PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WAIT waiter, TP_WAIT_RESULT waitResult);
|
| 372 |
+
|
| 373 |
+
/// <summary>
|
| 374 |
+
/// Same callback function as ImplicitDetachHandler but used on XP.
|
| 375 |
+
/// </summary>
|
| 376 |
+
static void CALLBACK ImplicitDetachHandlerXP(PVOID parameter, BOOLEAN is_timeout);
|
| 377 |
+
|
| 378 |
+
/// <summary>
|
| 379 |
+
/// Returns the type of context
|
| 380 |
+
/// </summary>
|
| 381 |
+
virtual ContextKind GetContextKind() const { return ExternalContext; }
|
| 382 |
+
};
|
| 383 |
+
} // namespace details
|
| 384 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FairScheduleGroup.cpp
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FairScheduleGroup.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation file for FairScheduleGroup.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Puts a runnable context into the runnables collection in the schedule group.
|
| 22 |
+
/// </summary>
|
| 23 |
+
void FairScheduleGroupSegment::AddToRunnablesCollection(InternalContextBase* pContext)
|
| 24 |
+
{
|
| 25 |
+
m_runnableContexts.Enqueue(pContext);
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/// <summary>
|
| 29 |
+
/// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement
|
| 30 |
+
/// and the origin of the thread making the call.
|
| 31 |
+
/// </summary>
|
| 32 |
+
/// <param name="pSegmentAffinity">
|
| 33 |
+
/// A segment with affinity to this particular location will be located.
|
| 34 |
+
/// </param>
|
| 35 |
+
/// <param name="fCreateNew">
|
| 36 |
+
/// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is
|
| 37 |
+
/// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found.
|
| 38 |
+
/// </param>
|
| 39 |
+
/// <returns>
|
| 40 |
+
/// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned
|
| 41 |
+
/// if fCreateNew is specified as false and no appropriate segment yet exists for the group.
|
| 42 |
+
/// </returns>
|
| 43 |
+
ScheduleGroupSegmentBase *FairScheduleGroup::LocateSegment(location*, bool fCreateNew)
|
| 44 |
+
{
|
| 45 |
+
// Ignore the passed in affinity for fair schedule groups.
|
| 46 |
+
location unbiased;
|
| 47 |
+
if (m_kind & AnonymousScheduleGroup)
|
| 48 |
+
{
|
| 49 |
+
//
|
| 50 |
+
// In order to provide a "like" functionality to Dev10 for anonymous fair groups, we still let the group be split by rings. Non-anonymous
|
| 51 |
+
// groups are also treated identically to Dev10 -- they live in one ring which is more for separation than any biasing.
|
| 52 |
+
//
|
| 53 |
+
return ScheduleGroupBase::LocateSegment(&unbiased, fCreateNew);
|
| 54 |
+
}
|
| 55 |
+
else
|
| 56 |
+
{
|
| 57 |
+
ScheduleGroupSegmentBase *pSegment = m_pDefaultSegment;
|
| 58 |
+
if (fCreateNew && !pSegment)
|
| 59 |
+
{
|
| 60 |
+
m_segmentLock._Acquire();
|
| 61 |
+
if (m_pDefaultSegment)
|
| 62 |
+
{
|
| 63 |
+
pSegment = m_pDefaultSegment;
|
| 64 |
+
}
|
| 65 |
+
else
|
| 66 |
+
{
|
| 67 |
+
pSegment = CreateSegment(&unbiased, m_pScheduler->GetNextSchedulingRing());
|
| 68 |
+
// CreateSegment adds the segment to the list array as its last step, which generates a fence ensuring that the segment
|
| 69 |
+
// is fully initialized before it is published on weaker memory models.
|
| 70 |
+
m_pDefaultSegment = static_cast<FairScheduleGroupSegment *>(pSegment);
|
| 71 |
+
}
|
| 72 |
+
m_segmentLock._Release();
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
return pSegment;
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/// <summary>
|
| 80 |
+
/// Internal routine which finds an appropriate segment for a task placement.
|
| 81 |
+
/// </summary>
|
| 82 |
+
/// <param name="pSegmentAffinity">
|
| 83 |
+
/// A segment with this affinity will be located.
|
| 84 |
+
/// </param>
|
| 85 |
+
/// <param name="pRing">
|
| 86 |
+
/// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order
|
| 87 |
+
/// to keep work local.
|
| 88 |
+
/// </param>
|
| 89 |
+
/// <returns>
|
| 90 |
+
/// A segment with the specified affinity close to the specified location.
|
| 91 |
+
/// </returns>
|
| 92 |
+
ScheduleGroupSegmentBase *FairScheduleGroup::FindSegment(location*, SchedulingRing *pRing)
|
| 93 |
+
{
|
| 94 |
+
// Ignore the passed in affinity for fair schedule groups
|
| 95 |
+
location unbiased;
|
| 96 |
+
if (m_kind & AnonymousScheduleGroup)
|
| 97 |
+
{
|
| 98 |
+
return ScheduleGroupBase::FindSegment(&unbiased, pRing);
|
| 99 |
+
}
|
| 100 |
+
else
|
| 101 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FairScheduleGroup.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing FairScheduleGroup related declarations.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
class FairScheduleGroup;
|
| 21 |
+
|
| 22 |
+
class FairScheduleGroupSegment : public ScheduleGroupSegmentBase
|
| 23 |
+
{
|
| 24 |
+
|
| 25 |
+
public:
|
| 26 |
+
|
| 27 |
+
//
|
| 28 |
+
// Public Methods
|
| 29 |
+
//
|
| 30 |
+
|
| 31 |
+
/// <summary>
|
| 32 |
+
/// Constructs a fair schedule group segment
|
| 33 |
+
/// </summary>
|
| 34 |
+
FairScheduleGroupSegment(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) :
|
| 35 |
+
ScheduleGroupSegmentBase(pOwningGroup, pOwningRing, pSegmentAffinity)
|
| 36 |
+
{
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/// <summary>
|
| 40 |
+
/// Notifies virtual processors that work affinitized to them has become available in the schedule group segment.
|
| 41 |
+
/// </summary>
|
| 42 |
+
virtual void NotifyAffinitizedWork() { }
|
| 43 |
+
|
| 44 |
+
private:
|
| 45 |
+
friend class SchedulerBase;
|
| 46 |
+
friend class FairScheduleGroup;
|
| 47 |
+
friend class ContextBase;
|
| 48 |
+
friend class ExternalContextBase;
|
| 49 |
+
friend class InternalContextBase;
|
| 50 |
+
friend class ThreadInternalContext;
|
| 51 |
+
friend class SchedulingNode;
|
| 52 |
+
friend class SchedulingRing;
|
| 53 |
+
friend class VirtualProcessor;
|
| 54 |
+
|
| 55 |
+
//
|
| 56 |
+
// Private data
|
| 57 |
+
//
|
| 58 |
+
|
| 59 |
+
// Each schedule group has three stores of work. It has a collection of runnable contexts,
|
| 60 |
+
// a FIFO queue of realized chores and a list of workqueues that hold unrealized chores.
|
| 61 |
+
|
| 62 |
+
// A collection of Runnable contexts.
|
| 63 |
+
SafeSQueue<InternalContextBase, _HyperNonReentrantLock> m_runnableContexts;
|
| 64 |
+
|
| 65 |
+
//
|
| 66 |
+
// Private methods
|
| 67 |
+
//
|
| 68 |
+
|
| 69 |
+
/// <summary>
|
| 70 |
+
/// Puts a runnable context into the runnables collection in the schedule group.
|
| 71 |
+
/// </summary>
|
| 72 |
+
void AddToRunnablesCollection(InternalContextBase *pContext);
|
| 73 |
+
|
| 74 |
+
InternalContextBase *GetRunnableContext()
|
| 75 |
+
{
|
| 76 |
+
if (m_runnableContexts.Empty())
|
| 77 |
+
return NULL;
|
| 78 |
+
|
| 79 |
+
InternalContextBase *pContext = m_runnableContexts.Dequeue();
|
| 80 |
+
#if defined(_DEBUG)
|
| 81 |
+
SetContextDebugBits(pContext, CTX_DEBUGBIT_REMOVEDFROMRUNNABLES);
|
| 82 |
+
#endif // _DEBUG
|
| 83 |
+
return pContext;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
};
|
| 87 |
+
|
| 88 |
+
class FairScheduleGroup : public ScheduleGroupBase
|
| 89 |
+
{
|
| 90 |
+
public:
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Constructs a new fair schedule group.
|
| 94 |
+
/// </summary>
|
| 95 |
+
FairScheduleGroup(SchedulerBase *pScheduler, location* pGroupPlacement) :
|
| 96 |
+
ScheduleGroupBase(pScheduler, pGroupPlacement),
|
| 97 |
+
m_pDefaultSegment(NULL)
|
| 98 |
+
{
|
| 99 |
+
ASSERT(pGroupPlacement->_Is_system());
|
| 100 |
+
m_kind = FairScheduling;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
/// <summary>
|
| 104 |
+
/// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement
|
| 105 |
+
/// and the origin of the thread making the call.
|
| 106 |
+
/// </summary>
|
| 107 |
+
/// <param name="pSegmentAffinity">
|
| 108 |
+
/// A segment with affinity to this particular location will be located.
|
| 109 |
+
/// </param>
|
| 110 |
+
/// <param name="fCreateNew">
|
| 111 |
+
/// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is
|
| 112 |
+
/// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found.
|
| 113 |
+
/// </param>
|
| 114 |
+
/// <returns>
|
| 115 |
+
/// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned
|
| 116 |
+
/// if fCreateNew is specified as false and no appropriate segment yet exists for the group.
|
| 117 |
+
/// </returns>
|
| 118 |
+
virtual ScheduleGroupSegmentBase *LocateSegment(location* pSegmentAffinity, bool fCreateNew);
|
| 119 |
+
|
| 120 |
+
/// <summary>
|
| 121 |
+
/// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified
|
| 122 |
+
/// location. For a fair schedule group, the function returns an empty slot
|
| 123 |
+
/// </summary>
|
| 124 |
+
/// <param name="pChore">
|
| 125 |
+
/// The chore to mail.
|
| 126 |
+
/// </param>
|
| 127 |
+
/// <param name="pPlacement">
|
| 128 |
+
/// A pointer to a location where the chore will be mailed.
|
| 129 |
+
/// </param>
|
| 130 |
+
/// <returns>
|
| 131 |
+
/// The mailbox slot into which the chore was placed.
|
| 132 |
+
/// </returns>
|
| 133 |
+
/// <remarks>
|
| 134 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 135 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 136 |
+
/// </remarks>
|
| 137 |
+
virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore,
|
| 138 |
+
location * pPlacement,
|
| 139 |
+
ScheduleGroupSegmentBase **)
|
| 140 |
+
{
|
| 141 |
+
(pChore); (pPlacement);
|
| 142 |
+
return Mailbox<_UnrealizedChore>::Slot();
|
| 143 |
+
}
|
| 144 |
+
protected:
|
| 145 |
+
|
| 146 |
+
/// <summary>
|
| 147 |
+
/// Allocates a new fair schedule group segment within the specified group and ring with the specified affinity.
|
| 148 |
+
/// </summary>
|
| 149 |
+
/// <param name="pSegmentAffinity">
|
| 150 |
+
/// The affinity for the segment.
|
| 151 |
+
/// </param>
|
| 152 |
+
/// <param name="pOwningRing">
|
| 153 |
+
/// The scheduling ring to which the newly allocated segment will belong.
|
| 154 |
+
/// </param>
|
| 155 |
+
/// <returns>
|
| 156 |
+
/// A new fair schedule group within the specified group and ring with the specified affinity.
|
| 157 |
+
/// </returns>
|
| 158 |
+
virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity)
|
| 159 |
+
{
|
| 160 |
+
//
|
| 161 |
+
// For fair schedule groups, we completely ignore any location hint since we are directed to round robin the groups anyway!
|
| 162 |
+
//
|
| 163 |
+
(pSegmentAffinity);
|
| 164 |
+
location unbiased;
|
| 165 |
+
return _concrt_new FairScheduleGroupSegment(this, pOwningRing, &unbiased);
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
/// <summary>
|
| 169 |
+
/// Internal routine which finds an appropriate segment for a task placement.
|
| 170 |
+
/// </summary>
|
| 171 |
+
/// <param name="pSegmentAffinity">
|
| 172 |
+
/// A segment with this affinity will be located.
|
| 173 |
+
/// </param>
|
| 174 |
+
/// <param name="pRing">
|
| 175 |
+
/// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order
|
| 176 |
+
/// to keep work local.
|
| 177 |
+
/// </param>
|
| 178 |
+
/// <returns>
|
| 179 |
+
/// A segment with the specified affinity close to the specified location.
|
| 180 |
+
/// </returns>
|
| 181 |
+
virtual ScheduleGroupSegmentBase *FindSegment(location* pSegmentAffinity, SchedulingRing *pRing);
|
| 182 |
+
|
| 183 |
+
/// <summary>
|
| 184 |
+
/// Removes all schedule group segments from the group.
|
| 185 |
+
/// </summary>
|
| 186 |
+
virtual void RemoveSegments()
|
| 187 |
+
{
|
| 188 |
+
ScheduleGroupBase::RemoveSegments();
|
| 189 |
+
m_pDefaultSegment = NULL;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
private:
|
| 193 |
+
|
| 194 |
+
FairScheduleGroupSegment *m_pDefaultSegment;
|
| 195 |
+
|
| 196 |
+
};
|
| 197 |
+
|
| 198 |
+
} // namespace details
|
| 199 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.cpp
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FreeThreadProxy.cpp
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this source file contains the internal definition for the free thread
|
| 11 |
+
// proxy.
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
#include "concrtinternal.h"
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
/// <summary>
|
| 22 |
+
/// Called in order to perform a cooperative context switch between one context and another. After this call, pContext will
|
| 23 |
+
/// be running atop the virtual processor root and the context which was running will not. What happens to the context that
|
| 24 |
+
/// was running depends on the value of the reason argument.
|
| 25 |
+
/// </summary>
|
| 26 |
+
/// <param name="pContext">
|
| 27 |
+
/// The context to cooperatively switch to.
|
| 28 |
+
/// </param>
|
| 29 |
+
/// <param name="switchState">
|
| 30 |
+
/// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread
|
| 31 |
+
/// proxy and context.
|
| 32 |
+
/// </param>
|
| 33 |
+
void FreeThreadProxy::SwitchTo(Concurrency::IExecutionContext *pContext, SwitchingProxyState switchState)
|
| 34 |
+
{
|
| 35 |
+
if (pContext == NULL)
|
| 36 |
+
throw std::invalid_argument("pContext");
|
| 37 |
+
|
| 38 |
+
// Find out if this context already has a thread proxy, if not, we have to request one from the factory.
|
| 39 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *> (pContext->GetProxy());
|
| 40 |
+
|
| 41 |
+
if (pProxy == NULL)
|
| 42 |
+
{
|
| 43 |
+
// Find a thread proxy from the pool that corresponds to the stack size and priority we need. Since this
|
| 44 |
+
// is a context in the same scheduler as the current context's scheduler, we can use existing values of
|
| 45 |
+
// stack size and priority.
|
| 46 |
+
pProxy = static_cast<FreeThreadProxy *> (m_pRoot->GetSchedulerProxy()->GetNewThreadProxy(pContext));
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
FreeVirtualProcessorRoot *pRoot = static_cast<FreeVirtualProcessorRoot *>(m_pRoot);
|
| 50 |
+
m_pRoot = NULL;
|
| 51 |
+
|
| 52 |
+
if (switchState == Blocking)
|
| 53 |
+
{
|
| 54 |
+
ASSERT(m_fBlocked == FALSE);
|
| 55 |
+
InterlockedExchange(&m_fBlocked, TRUE);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// The 'next' thread proxy must be affinitized to a copy of the 'this' proxy's vproc root VPRoot1, snapped BEFORE the blocked flag
|
| 59 |
+
// is set. Not doing this could result in vproc root orphanage. See VirtualProcessorRoot::Affinitize for details.
|
| 60 |
+
pRoot->Affinitize(pProxy);
|
| 61 |
+
|
| 62 |
+
switch (switchState)
|
| 63 |
+
{
|
| 64 |
+
case Blocking:
|
| 65 |
+
//
|
| 66 |
+
// Signal the other thread proxy and block until switched to, or until a virtual processor is activated with
|
| 67 |
+
// the context running on this thread proxy.
|
| 68 |
+
//
|
| 69 |
+
platform::__SignalObjectAndWait(pProxy->m_hBlock, m_hBlock, INFINITE, TRUE);
|
| 70 |
+
ASSERT(m_fBlocked == TRUE);
|
| 71 |
+
InterlockedExchange(&m_fBlocked, FALSE);
|
| 72 |
+
|
| 73 |
+
break;
|
| 74 |
+
case Nesting:
|
| 75 |
+
//
|
| 76 |
+
// Signal the other thread proxy that now owns this virtual processor, but do not block. The current thread proxy
|
| 77 |
+
// is about to move to a nested scheduler.
|
| 78 |
+
//
|
| 79 |
+
ASSERT(pProxy->m_pRoot != NULL);
|
| 80 |
+
ASSERT(pProxy->m_pContext != NULL);
|
| 81 |
+
pProxy->ResumeExecution();
|
| 82 |
+
|
| 83 |
+
break;
|
| 84 |
+
case Idle:
|
| 85 |
+
//
|
| 86 |
+
// Return without blocking, indicating to the caller that the scheduler should yield this thread proxy
|
| 87 |
+
// back to the RM, by exiting the contexts dispatch loop.
|
| 88 |
+
//
|
| 89 |
+
ASSERT(pProxy->m_pRoot != NULL);
|
| 90 |
+
ASSERT(pProxy->m_pContext != NULL);
|
| 91 |
+
pProxy->ResumeExecution();
|
| 92 |
+
|
| 93 |
+
break;
|
| 94 |
+
default:
|
| 95 |
+
|
| 96 |
+
ASSERT(false);
|
| 97 |
+
break;
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
/// <summary>
|
| 102 |
+
/// Called in order to disassociate the currently executing context from its virtual processor root, and reinitialize the root
|
| 103 |
+
/// for future use.
|
| 104 |
+
/// </summary>
|
| 105 |
+
/// <param name="switchState">
|
| 106 |
+
/// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread
|
| 107 |
+
/// proxy and context.
|
| 108 |
+
/// </param>
|
| 109 |
+
void FreeThreadProxy::SwitchOut(SwitchingProxyState switchState)
|
| 110 |
+
{
|
| 111 |
+
if ((switchState == Idle) || (m_pRoot == NULL && switchState != Blocking))
|
| 112 |
+
throw std::invalid_argument("switchState");
|
| 113 |
+
|
| 114 |
+
ASSERT(m_fBlocked == 0);
|
| 115 |
+
|
| 116 |
+
//
|
| 117 |
+
// 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
|
| 118 |
+
// 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
|
| 119 |
+
// correspondingly act as both a switch out and a deactivate.
|
| 120 |
+
//
|
| 121 |
+
if (m_pRoot != NULL)
|
| 122 |
+
{
|
| 123 |
+
FreeVirtualProcessorRoot * pRoot = static_cast<FreeVirtualProcessorRoot *>(m_pRoot);
|
| 124 |
+
if (switchState == Nesting)
|
| 125 |
+
{
|
| 126 |
+
// IThreadProxy::SwitchOut can be called with Nesting, if the context tried to InternalContextBase::SwitchTo(NULL, Nesting). Ensure the
|
| 127 |
+
// root is set to NULL here so the right thing happens with this context/proxy rejoins the scheduler by calling IThreadProxy::SwitchOut(Blocking).
|
| 128 |
+
m_pRoot = NULL;
|
| 129 |
+
}
|
| 130 |
+
(static_cast<FreeVirtualProcessorRoot *>(pRoot))->ResetOnIdle(switchState);
|
| 131 |
+
|
| 132 |
+
// If we're nesting, we should return without blocking with the root unchanged. If not, we should have been affinitized to a different root.
|
| 133 |
+
ASSERT(m_pRoot != NULL || switchState == Nesting);
|
| 134 |
+
}
|
| 135 |
+
else
|
| 136 |
+
{
|
| 137 |
+
// There are currently only two cases where the m_pRoot field is expected to be NULL.
|
| 138 |
+
// - A virtual processor is being retired and the caller invokes SwitchOut to block the thread proxy.
|
| 139 |
+
// (root was set to NULL in FreeVirtualProcessorRoot::DeleteThis)
|
| 140 |
+
// - A thread proxy that previously switched to a different, nested scheduler, is now joining its original scheduler again.
|
| 141 |
+
// (root was set to NULL in FreeThreadProxy::SwitchOut or FreeThreadProxy::SwitchTo)
|
| 142 |
+
SuspendExecution();
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
/// <summary>
|
| 147 |
+
/// Called right after obtaining a thread proxy from the factory. Associates the thread proxy with the execution
|
| 148 |
+
/// context it is about to run.
|
| 149 |
+
/// </summary>
|
| 150 |
+
void FreeThreadProxy::AssociateExecutionContext(Concurrency::IExecutionContext * pContext)
|
| 151 |
+
{
|
| 152 |
+
m_pContext = pContext;
|
| 153 |
+
pContext->SetProxy(this);
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
/// <summary>
|
| 157 |
+
/// Returns a thread proxy to the factory when it is no longer in use.
|
| 158 |
+
/// </summary>
|
| 159 |
+
void FreeThreadProxy::ReturnIdleProxy()
|
| 160 |
+
{
|
| 161 |
+
_CONCRT_ASSERT(m_pFactory != NULL);
|
| 162 |
+
m_pContext = NULL;
|
| 163 |
+
m_pFactory->ReclaimProxy(this);
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
/// <summary>
|
| 167 |
+
/// The main dispatch loop for the free thread proxy.
|
| 168 |
+
/// </summary>
|
| 169 |
+
void FreeThreadProxy::Dispatch()
|
| 170 |
+
{
|
| 171 |
+
// Send the default dispatch state into Dispatch.
|
| 172 |
+
DispatchState dispatchState;
|
| 173 |
+
|
| 174 |
+
if (!m_fCanceled)
|
| 175 |
+
{
|
| 176 |
+
platform::__TlsSetValue(m_pFactory->GetExecutionResourceTls(), (LPVOID) (((size_t) this) | TlsResourceInProxy));
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
while (!m_fCanceled)
|
| 180 |
+
{
|
| 181 |
+
_CONCRT_ASSERT(m_pContext != NULL);
|
| 182 |
+
_CONCRT_ASSERT(m_pRoot != NULL);
|
| 183 |
+
|
| 184 |
+
// Call the dispatch loop of the registered context.
|
| 185 |
+
m_pContext->SetProxy(this);
|
| 186 |
+
m_pContext->Dispatch(&dispatchState);
|
| 187 |
+
|
| 188 |
+
//
|
| 189 |
+
// The dispatch loop returns when the scheduler that the proxy was given to, has decided to return it back to the RM.
|
| 190 |
+
// It should be returned to the free proxy factory, so that it can be handed out to a different virtual processor root
|
| 191 |
+
// (bound to a different context).
|
| 192 |
+
//
|
| 193 |
+
// Before doing so, however, we restore the virtual processor to its original state so that it can be activated again. Note
|
| 194 |
+
// that if the virtual processor deleted on the way out, m_pRoot is already NULL. This is only thread which does this and
|
| 195 |
+
// we are on the same thread. There is no race.
|
| 196 |
+
//
|
| 197 |
+
FreeVirtualProcessorRoot *pRoot = static_cast<FreeVirtualProcessorRoot *>(m_pRoot);
|
| 198 |
+
|
| 199 |
+
m_pContext = NULL;
|
| 200 |
+
m_pRoot = NULL;
|
| 201 |
+
|
| 202 |
+
// Return to the idle pool in the RM. If the pool is full, the proxy will be canceled.
|
| 203 |
+
ReturnIdleProxy();
|
| 204 |
+
|
| 205 |
+
if (pRoot != NULL)
|
| 206 |
+
{
|
| 207 |
+
pRoot->ResetOnIdle(Blocking);
|
| 208 |
+
}
|
| 209 |
+
else
|
| 210 |
+
{
|
| 211 |
+
SuspendExecution();
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
}
|
| 215 |
+
} // namespace details
|
| 216 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeThreadProxy.h
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FreeThreadProxy.h
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the free thread
|
| 11 |
+
// proxy.
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
namespace Concurrency
|
| 16 |
+
{
|
| 17 |
+
namespace details
|
| 18 |
+
{
|
| 19 |
+
#pragma warning(push)
|
| 20 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 21 |
+
class FreeThreadProxy : public ThreadProxy
|
| 22 |
+
{
|
| 23 |
+
public:
|
| 24 |
+
|
| 25 |
+
/// <summary>
|
| 26 |
+
/// Construct a free thread proxy.
|
| 27 |
+
/// </summary>
|
| 28 |
+
FreeThreadProxy(IThreadProxyFactory * pFactory, unsigned int stackSize)
|
| 29 |
+
: ThreadProxy(pFactory, stackSize)
|
| 30 |
+
{ }
|
| 31 |
+
|
| 32 |
+
/// <summary>
|
| 33 |
+
/// Destroy a free thread proxy.
|
| 34 |
+
/// </summary>
|
| 35 |
+
virtual ~FreeThreadProxy()
|
| 36 |
+
{ }
|
| 37 |
+
|
| 38 |
+
/// <summary>
|
| 39 |
+
/// Called in order to perform a cooperative context switch between one context and another. After this call, pContext will
|
| 40 |
+
/// be running atop the virtual processor root and the context which was running will not. What happens to the context that
|
| 41 |
+
/// was running depends on the value of the reason argument.
|
| 42 |
+
/// </summary>
|
| 43 |
+
/// <param name="pContext">
|
| 44 |
+
/// The context to cooperatively switch to.
|
| 45 |
+
/// </param>
|
| 46 |
+
/// <param name="switchState">
|
| 47 |
+
/// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread
|
| 48 |
+
/// proxy and context.
|
| 49 |
+
/// </param>
|
| 50 |
+
virtual void SwitchTo(::Concurrency::IExecutionContext * pContext, SwitchingProxyState switchState);
|
| 51 |
+
|
| 52 |
+
/// <summary>
|
| 53 |
+
/// Called in order to disassociate the currently executing context from its virtual processor root, and reinitialize the root
|
| 54 |
+
/// for future use.
|
| 55 |
+
/// </summary>
|
| 56 |
+
/// <param name="switchState">
|
| 57 |
+
/// Indicates the state of the thread proxy that is executing the switch. This can determine ownership of the underlying thread
|
| 58 |
+
/// proxy and context.
|
| 59 |
+
/// </param>
|
| 60 |
+
virtual void SwitchOut(SwitchingProxyState switchState = Blocking);
|
| 61 |
+
|
| 62 |
+
/// <summary>
|
| 63 |
+
/// Called in order to yield to the underlying operating system. This allows the operating system to schedule
|
| 64 |
+
/// other work in that time quantum.
|
| 65 |
+
/// </summary>
|
| 66 |
+
virtual void YieldToSystem()
|
| 67 |
+
{
|
| 68 |
+
platform::__SwitchToThread();
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/// <summary>
|
| 72 |
+
/// Returns the execution context currently attached to the thread proxy.
|
| 73 |
+
/// </summary>
|
| 74 |
+
::Concurrency::IExecutionContext * GetExecutionContext() { return m_pContext; }
|
| 75 |
+
|
| 76 |
+
/// <summary>
|
| 77 |
+
/// Called right after obtaining a thread proxy from the factory. Associates the thread proxy with the execution
|
| 78 |
+
/// context it is about to run.
|
| 79 |
+
/// </summary>
|
| 80 |
+
/// <param name="pContext">
|
| 81 |
+
/// The context to associate with the thread proxy.
|
| 82 |
+
/// </param>
|
| 83 |
+
void AssociateExecutionContext(::Concurrency::IExecutionContext * pContext);
|
| 84 |
+
|
| 85 |
+
/// <summary>
|
| 86 |
+
/// Returns a thread proxy to the factory when it is no longer in use.
|
| 87 |
+
/// </summary>
|
| 88 |
+
void ReturnIdleProxy();
|
| 89 |
+
|
| 90 |
+
/// <summary>
|
| 91 |
+
/// Set the thread affinity to the given affinity
|
| 92 |
+
/// </summary>
|
| 93 |
+
/// <param name="newAffinity">
|
| 94 |
+
/// The new affinity for the thread
|
| 95 |
+
/// </param>
|
| 96 |
+
void SetAffinity(HardwareAffinity newAffinity)
|
| 97 |
+
{
|
| 98 |
+
// Set the new affinity only if it is different
|
| 99 |
+
if (m_previousAffinity != newAffinity)
|
| 100 |
+
{
|
| 101 |
+
newAffinity.ApplyTo(GetThreadHandle());
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
m_previousAffinity = newAffinity;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
private:
|
| 108 |
+
//
|
| 109 |
+
// Friend declarations
|
| 110 |
+
//
|
| 111 |
+
template <class T> friend class LockFreeStack;
|
| 112 |
+
|
| 113 |
+
//
|
| 114 |
+
// Private member variables
|
| 115 |
+
//
|
| 116 |
+
|
| 117 |
+
// Node affinity
|
| 118 |
+
HardwareAffinity m_previousAffinity;
|
| 119 |
+
|
| 120 |
+
// Entry for freelist
|
| 121 |
+
SLIST_ENTRY m_slNext{};
|
| 122 |
+
|
| 123 |
+
// 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
|
| 124 |
+
// is taken from the idle pool and associated with a virtual processor root that was handed to a scheduler. A free thread proxy
|
| 125 |
+
// is only associated with one context at a time.
|
| 126 |
+
::Concurrency::IExecutionContext * m_pContext{};
|
| 127 |
+
|
| 128 |
+
//
|
| 129 |
+
// Private member functions
|
| 130 |
+
//
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// The main dispatch routine for a free thread proxy
|
| 134 |
+
/// </summary>
|
| 135 |
+
virtual void Dispatch();
|
| 136 |
+
};
|
| 137 |
+
#pragma warning(pop)
|
| 138 |
+
} // namespace details
|
| 139 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.cpp
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FreeVirtualProcessorRoot.cpp
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this header file contains the internal implementation for the free virtual
|
| 11 |
+
// processor root (represents a virtual processor as handed to a scheduler).
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
#include "concrtinternal.h"
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
|
| 22 |
+
/// <summary>
|
| 23 |
+
/// Constructs a new free virtual processor root.
|
| 24 |
+
/// </summary>
|
| 25 |
+
/// <param name="pSchedulerProxy">
|
| 26 |
+
/// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of
|
| 27 |
+
/// a scheduler.
|
| 28 |
+
/// </param>
|
| 29 |
+
/// <param name="pNode">
|
| 30 |
+
/// The processor node that this root belongs to. The processor node is one among the nodes allocated to the
|
| 31 |
+
/// scheduler proxy.
|
| 32 |
+
/// </param>
|
| 33 |
+
/// <param name="coreIndex">
|
| 34 |
+
/// The index into the array of cores for the processor node specified.
|
| 35 |
+
/// </param>
|
| 36 |
+
FreeVirtualProcessorRoot::FreeVirtualProcessorRoot(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex)
|
| 37 |
+
: VirtualProcessorRoot(pSchedulerProxy, pNode, coreIndex),
|
| 38 |
+
m_pExecutingProxy(NULL),
|
| 39 |
+
m_pDeactivatedProxy(NULL)
|
| 40 |
+
{
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/// <summary>
|
| 44 |
+
/// Deletes the virtual processor.
|
| 45 |
+
/// </summary>
|
| 46 |
+
void FreeVirtualProcessorRoot::DeleteThis()
|
| 47 |
+
{
|
| 48 |
+
//
|
| 49 |
+
// This comes in via a Remove() call on one of two threads:
|
| 50 |
+
//
|
| 51 |
+
// - The thread that is running the virtual processor root.
|
| 52 |
+
// - There can be no race. We just need to make sure that the thread on exit doesn't touch us after deletion.
|
| 53 |
+
//
|
| 54 |
+
// - An arbitrary thread.
|
| 55 |
+
// - We need to be careful that we aren't racing between that thread's getting out (SwitchOut followed by returning from
|
| 56 |
+
// the context's dispatch loop), and it trying to reset the vproc root in ResetOnIdle. We must spin until that has happened.
|
| 57 |
+
//
|
| 58 |
+
FreeThreadProxy *pCurrentProxy = NULL;
|
| 59 |
+
|
| 60 |
+
DWORD tlsSlot = GetSchedulerProxy()->GetResourceManager()->GetExecutionResourceTls();
|
| 61 |
+
void * tlsPointer = platform::__TlsGetValue(tlsSlot);
|
| 62 |
+
size_t tlsValue = (size_t) tlsPointer;
|
| 63 |
+
|
| 64 |
+
if (tlsPointer != NULL && ((tlsValue & TlsResourceBitMask) == TlsResourceInProxy))
|
| 65 |
+
pCurrentProxy = (FreeThreadProxy *) (tlsValue & ~TlsResourceInProxy);
|
| 66 |
+
|
| 67 |
+
if (pCurrentProxy != NULL && pCurrentProxy == m_pExecutingProxy)
|
| 68 |
+
{
|
| 69 |
+
pCurrentProxy->SetVirtualProcessorRoot(NULL);
|
| 70 |
+
}
|
| 71 |
+
else
|
| 72 |
+
{
|
| 73 |
+
//
|
| 74 |
+
// Spin wait until there isn't anything running atop this virtual processor root. Yes -- this means that someone had better be
|
| 75 |
+
// on the way out. If you call Remove on a virtual processor that's still running something, the resulting behavior is pretty much
|
| 76 |
+
// undefined anyway.
|
| 77 |
+
//
|
| 78 |
+
SpinUntilIdle();
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
delete this;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/// <summary>
|
| 85 |
+
/// Called in order to reset this virtual processor root to a completely quiescent state (not running anything).
|
| 86 |
+
/// </summary>
|
| 87 |
+
/// <param name="switchState">
|
| 88 |
+
/// Indicates the state of the thread proxy that is making the call. The parameter is of type <typeparamref name="SwitchingProxyState"/>.
|
| 89 |
+
/// </param>
|
| 90 |
+
void FreeVirtualProcessorRoot::ResetOnIdle(SwitchingProxyState switchState)
|
| 91 |
+
{
|
| 92 |
+
FreeThreadProxy *pOriginalProxy = static_cast<FreeThreadProxy *>(m_pExecutingProxy);
|
| 93 |
+
|
| 94 |
+
LONG newVal = InterlockedDecrement(&m_activationFence);
|
| 95 |
+
if (newVal <= 0)
|
| 96 |
+
{
|
| 97 |
+
//
|
| 98 |
+
// The value could be -1 if we raced with the virtual processor root being removed on a different thread.
|
| 99 |
+
//
|
| 100 |
+
ASSERT(newVal >= -1);
|
| 101 |
+
//
|
| 102 |
+
// The fence going down to zero arbitrates between a possible reset/remove race.
|
| 103 |
+
//
|
| 104 |
+
if (newVal == 0)
|
| 105 |
+
Unsubscribe();
|
| 106 |
+
|
| 107 |
+
m_pExecutingProxy = NULL;
|
| 108 |
+
|
| 109 |
+
//
|
| 110 |
+
// *** READ THIS ***:
|
| 111 |
+
//
|
| 112 |
+
// It is imperative on this path that once m_pExecutingProxy has been set to NULL, nothing touches the this pointer. We are the race
|
| 113 |
+
// resolution between a client getting off a vproc and removing it. There can be a race between removal (DeleteThis) from outside and
|
| 114 |
+
// a SwitchOut (here) on the vproc.
|
| 115 |
+
//
|
| 116 |
+
if (switchState == Blocking)
|
| 117 |
+
{
|
| 118 |
+
pOriginalProxy->SuspendExecution();
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
else
|
| 122 |
+
{
|
| 123 |
+
Concurrency::IExecutionContext *pActivatedContext = AcquireActivatedContext();
|
| 124 |
+
ASSERT(newVal == 1 && pActivatedContext != NULL);
|
| 125 |
+
|
| 126 |
+
//
|
| 127 |
+
// This means we had a race between an Activate and an Idling (via either SwitchOut or return from dispatch loop). In either
|
| 128 |
+
// of these cases, we stashed away the context which was activated in m_pActivatedContext. This context now needs to run atop us.
|
| 129 |
+
//
|
| 130 |
+
FreeThreadProxy *pProxy = static_cast<FreeThreadProxy *> (pActivatedContext->GetProxy());
|
| 131 |
+
ASSERT(pProxy != NULL);
|
| 132 |
+
|
| 133 |
+
//
|
| 134 |
+
// 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
|
| 135 |
+
// for the same proxy on the same vproc, it's a NOP.
|
| 136 |
+
//
|
| 137 |
+
if (pOriginalProxy != pProxy)
|
| 138 |
+
{
|
| 139 |
+
pOriginalProxy->SwitchTo(pActivatedContext, switchState);
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
/// <summary>
|
| 145 |
+
/// Causes the scheduler to start running a thread proxy on the specified virtual processor root which will execute
|
| 146 |
+
/// the Dispatch method of the context supplied by pContext. Alternatively, it can be used to resume a
|
| 147 |
+
/// virtual processor root that was de-activated by a previous call to Deactivate.
|
| 148 |
+
/// </summary>
|
| 149 |
+
/// <param name="pContext">
|
| 150 |
+
/// The context which will be dispatched on a (potentially) new thread running atop this virtual processor root.
|
| 151 |
+
/// </param>
|
| 152 |
+
void FreeVirtualProcessorRoot::Activate(Concurrency::IExecutionContext *pContext)
|
| 153 |
+
{
|
| 154 |
+
if (pContext == NULL)
|
| 155 |
+
throw std::invalid_argument("pContext");
|
| 156 |
+
|
| 157 |
+
//
|
| 158 |
+
// If the context is being reused, it had better return a NULL thread proxy when we ask! This is part of the spec contract.
|
| 159 |
+
//
|
| 160 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *> (pContext->GetProxy());
|
| 161 |
+
if (pProxy == NULL)
|
| 162 |
+
{
|
| 163 |
+
pProxy = static_cast<FreeThreadProxy *> (GetSchedulerProxy()->GetNewThreadProxy(pContext));
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
//
|
| 167 |
+
// 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
|
| 168 |
+
// to reduce kernel transitions in case of this race.
|
| 169 |
+
//
|
| 170 |
+
// 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
|
| 171 |
+
// be prepared to deal with this and the implications around trying to bind pContext.
|
| 172 |
+
//
|
| 173 |
+
LONG newVal = InterlockedIncrement(&m_activationFence);
|
| 174 |
+
if (newVal == 2)
|
| 175 |
+
{
|
| 176 |
+
ASSERT(m_pDeactivatedProxy == NULL);
|
| 177 |
+
//
|
| 178 |
+
// We received two activations in a row. According to the contract with the client, this is allowed, but we should expect a deactivation, a
|
| 179 |
+
// SwitchOut, or a return from dispatch loop soon after.
|
| 180 |
+
//
|
| 181 |
+
// Simply return instead of signalling the event. The deactivation will reduce the count back to 1. In addition, we're not responsible
|
| 182 |
+
// for changing the idle state on the core.
|
| 183 |
+
//
|
| 184 |
+
SetActivatedContext(pContext);
|
| 185 |
+
}
|
| 186 |
+
else
|
| 187 |
+
{
|
| 188 |
+
ASSERT(newVal == 1);
|
| 189 |
+
|
| 190 |
+
SpinUntilIdle();
|
| 191 |
+
ASSERT(m_pExecutingProxy == m_pDeactivatedProxy);
|
| 192 |
+
|
| 193 |
+
if (m_pExecutingProxy != NULL)
|
| 194 |
+
{
|
| 195 |
+
//
|
| 196 |
+
// The root already has an associated thread proxy. Check that the context provided is associated with
|
| 197 |
+
// the same proxy.
|
| 198 |
+
//
|
| 199 |
+
if (pProxy != m_pExecutingProxy)
|
| 200 |
+
{
|
| 201 |
+
//
|
| 202 |
+
// This is a fatal exception. We can potentially correct the state of the fence, but the scheduler is beyond confused about
|
| 203 |
+
// the spec. @TODO: Is it worth making some attempt to correct *our* state given that it's already messed up above us?
|
| 204 |
+
//
|
| 205 |
+
throw invalid_operation();
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
m_pDeactivatedProxy = NULL;
|
| 210 |
+
|
| 211 |
+
//
|
| 212 |
+
// An activated root increases the subscription level on the underlying core.
|
| 213 |
+
//
|
| 214 |
+
Subscribe();
|
| 215 |
+
|
| 216 |
+
//
|
| 217 |
+
// Affinitization sets this as the executing proxy for the virtual processor root.
|
| 218 |
+
//
|
| 219 |
+
Affinitize(pProxy);
|
| 220 |
+
|
| 221 |
+
ASSERT(m_pExecutingProxy == pProxy);
|
| 222 |
+
ASSERT(pProxy->GetVirtualProcessorRoot() != NULL);
|
| 223 |
+
ASSERT(pProxy->GetExecutionContext() != NULL);
|
| 224 |
+
|
| 225 |
+
pProxy->ResumeExecution();
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// <summary>
|
| 230 |
+
/// Causes the thread proxy running atop this virtual processor root to temporarily stop dispatching pContext.
|
| 231 |
+
/// </summary>
|
| 232 |
+
/// <param name="pContext">
|
| 233 |
+
/// The context which should temporarily stop being dispatched by the thread proxy running atop this virtual processor root.
|
| 234 |
+
/// </param>
|
| 235 |
+
bool FreeVirtualProcessorRoot::Deactivate(Concurrency::IExecutionContext *pContext)
|
| 236 |
+
{
|
| 237 |
+
if (pContext == NULL)
|
| 238 |
+
throw std::invalid_argument("pContext");
|
| 239 |
+
|
| 240 |
+
if (m_pExecutingProxy == NULL)
|
| 241 |
+
throw invalid_operation();
|
| 242 |
+
|
| 243 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *> (pContext->GetProxy());
|
| 244 |
+
|
| 245 |
+
if (m_pExecutingProxy != pProxy)
|
| 246 |
+
{
|
| 247 |
+
throw invalid_operation();
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
LONG newVal = InterlockedDecrement(&m_activationFence);
|
| 251 |
+
|
| 252 |
+
if (newVal == 0)
|
| 253 |
+
{
|
| 254 |
+
//
|
| 255 |
+
// Reduce the subscription level on the core while the root is suspended. The count is used by dynamic resource management
|
| 256 |
+
// to tell which cores allocated to a scheduler are unused, so that they can be temporarily repurposed.
|
| 257 |
+
//
|
| 258 |
+
InterlockedExchangePointer(reinterpret_cast<void * volatile *>(&m_pDeactivatedProxy), m_pExecutingProxy);
|
| 259 |
+
Unsubscribe();
|
| 260 |
+
pProxy->SuspendExecution();
|
| 261 |
+
}
|
| 262 |
+
else
|
| 263 |
+
{
|
| 264 |
+
//
|
| 265 |
+
// There should be no Deactivate/Remove races.
|
| 266 |
+
//
|
| 267 |
+
ASSERT(newVal == 1);
|
| 268 |
+
|
| 269 |
+
Concurrency::IExecutionContext *pActivatedContext = AcquireActivatedContext();
|
| 270 |
+
|
| 271 |
+
//
|
| 272 |
+
// If we got here, it means while activated we saw an activation of pCtxX and a subsequent deactivation of pCtxY. These contexts
|
| 273 |
+
// must be equal to be spec legal.
|
| 274 |
+
//
|
| 275 |
+
ASSERT(pActivatedContext == pContext);
|
| 276 |
+
|
| 277 |
+
//
|
| 278 |
+
// The activation for this deactivation came in early, so we return early here without making a kernel transition.
|
| 279 |
+
//
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
return true;
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
/// <summary>
|
| 286 |
+
/// Forces all data in the memory heirarchy of one processor to be visible to all other processors.
|
| 287 |
+
/// </summary>
|
| 288 |
+
/// <param name="pContext">
|
| 289 |
+
/// The context which is currently being dispatched by this root.
|
| 290 |
+
/// </param>
|
| 291 |
+
void FreeVirtualProcessorRoot::EnsureAllTasksVisible(Concurrency::IExecutionContext *pContext)
|
| 292 |
+
{
|
| 293 |
+
if (pContext == NULL)
|
| 294 |
+
throw std::invalid_argument("pContext");
|
| 295 |
+
|
| 296 |
+
if (m_pExecutingProxy == NULL)
|
| 297 |
+
throw invalid_operation();
|
| 298 |
+
|
| 299 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *> (pContext->GetProxy());
|
| 300 |
+
|
| 301 |
+
if (m_pExecutingProxy != pProxy)
|
| 302 |
+
{
|
| 303 |
+
throw invalid_operation();
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
GetSchedulerProxy()->GetResourceManager()->FlushStoreBuffers();
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
/// <summary>
|
| 310 |
+
/// Called to affinitize the given thread proxy to this virtual processor.
|
| 311 |
+
/// </summary>
|
| 312 |
+
/// <param name="pThreadProxy">
|
| 313 |
+
/// The new thread proxy to run atop this virtual processor root.
|
| 314 |
+
/// </param>
|
| 315 |
+
void FreeVirtualProcessorRoot::Affinitize(FreeThreadProxy *pThreadProxy)
|
| 316 |
+
{
|
| 317 |
+
//
|
| 318 |
+
// Wait until the thread proxy is firmly blocked. This is essential to prevent vproc root orphanage
|
| 319 |
+
// if the thread proxy we're switching to is IN THE PROCESS of switching out to a different one. An example of how this
|
| 320 |
+
// could happen:
|
| 321 |
+
|
| 322 |
+
// 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
|
| 323 |
+
// tpA must affinitize ctxB's thread proxy tpB to its own vproc root, vproot1.
|
| 324 |
+
|
| 325 |
+
// 2] At the exact same time, ctxA is unblocked by ctxY and put onto a runnables collection in its scheduler. Meanwhile, ctxZ
|
| 326 |
+
// executing on vp2, has also decided to block. It picks ctxA off the runnables collection, and proceeds to switch to it.
|
| 327 |
+
// This means that ctxZ's thread proxy tpZ must affinitize ctxA's thread proxy tpA to ITS vproc root vproot2.
|
| 328 |
+
|
| 329 |
+
// 3] Now, if tpZ affinitizes tpA to vproot2 BEFORE tpA has had a chance to affinitize tpB to vproot1, tpB gets mistakenly
|
| 330 |
+
// affinitized to vproot2, and vproot1 is orphaned.
|
| 331 |
+
|
| 332 |
+
// In order to prevent this, tpZ MUST wait until AFTER tpA has finished its affinitization. This is indicated via the
|
| 333 |
+
// blocked flag. tpA will set its blocked flag to 1, after it has finished affintizing tpB to vproot1, at which point it is
|
| 334 |
+
// safe for tpZ to modify tpA's vproc root and change it from vproot1 to vproot2.
|
| 335 |
+
//
|
| 336 |
+
|
| 337 |
+
pThreadProxy->SpinUntilBlocked();
|
| 338 |
+
|
| 339 |
+
m_pExecutingProxy = pThreadProxy;
|
| 340 |
+
pThreadProxy->SetVirtualProcessorRoot(this);
|
| 341 |
+
|
| 342 |
+
HardwareAffinity newAffinity = GetSchedulerProxy()->GetNodeAffinity(GetNodeId());
|
| 343 |
+
pThreadProxy->SetAffinity(newAffinity);
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
} // namespace details
|
| 347 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/FreeVirtualProcessorRoot.h
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// FreeVirtualProcessorRoot.h
|
| 9 |
+
//
|
| 10 |
+
// Part of the ConcRT Resource Manager -- this header file contains the internal definition for the free virtual
|
| 11 |
+
// processor root (represents a virtual processor as handed to a scheduler).
|
| 12 |
+
//
|
| 13 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 14 |
+
|
| 15 |
+
namespace Concurrency
|
| 16 |
+
{
|
| 17 |
+
namespace details
|
| 18 |
+
{
|
| 19 |
+
|
| 20 |
+
class FreeVirtualProcessorRoot : public VirtualProcessorRoot
|
| 21 |
+
{
|
| 22 |
+
public:
|
| 23 |
+
|
| 24 |
+
/// <summary>
|
| 25 |
+
/// Constructs a new free virtual processor root.
|
| 26 |
+
/// </summary>
|
| 27 |
+
/// <param name="pSchedulerProxy">
|
| 28 |
+
/// The scheduler proxy this root is created for. A scheduler proxy holds RM data associated with an instance of
|
| 29 |
+
/// a scheduler.
|
| 30 |
+
/// </param>
|
| 31 |
+
/// <param name="pNode">
|
| 32 |
+
/// The processor node that this root belongs to. The processor node is one among the nodes allocated to the
|
| 33 |
+
/// scheduler proxy.
|
| 34 |
+
/// </param>
|
| 35 |
+
/// <param name="coreIndex">
|
| 36 |
+
/// The index into the array of cores for the processor node specified.
|
| 37 |
+
/// </param>
|
| 38 |
+
FreeVirtualProcessorRoot(SchedulerProxy *pSchedulerProxy, SchedulerNode* pNode, unsigned int coreIndex);
|
| 39 |
+
|
| 40 |
+
/// <summary>
|
| 41 |
+
/// Causes the scheduler to start running a thread proxy on the specified virtual processor root which will execute
|
| 42 |
+
/// the Dispatch method of the context supplied by pContext.
|
| 43 |
+
/// </summary>
|
| 44 |
+
/// <param name="pContext">
|
| 45 |
+
/// The context which will be dispatched on a (potentially) new thread running atop this virtual processor root.
|
| 46 |
+
/// </param>
|
| 47 |
+
virtual void Activate(::Concurrency::IExecutionContext *pContext);
|
| 48 |
+
|
| 49 |
+
/// <summary>
|
| 50 |
+
/// Causes the thread proxy running atop this virtual processor root to temporarily stop dispatching pContext.
|
| 51 |
+
/// </summary>
|
| 52 |
+
/// <param name="pContext">
|
| 53 |
+
/// The context which should temporarily stop being dispatched by the thread proxy running atop this virtual processor root.
|
| 54 |
+
/// </param>
|
| 55 |
+
virtual bool Deactivate(::Concurrency::IExecutionContext *pContext);
|
| 56 |
+
|
| 57 |
+
/// <summary>
|
| 58 |
+
/// Forces all data in the memory heirarchy of one processor to be visible to all other processors.
|
| 59 |
+
/// </summary>
|
| 60 |
+
/// <param name="pContext">
|
| 61 |
+
/// The context which is currently being dispatched by this root.
|
| 62 |
+
/// </param>
|
| 63 |
+
virtual void EnsureAllTasksVisible(::Concurrency::IExecutionContext *pContext);
|
| 64 |
+
|
| 65 |
+
// **************************************************
|
| 66 |
+
// Internal
|
| 67 |
+
// **************************************************
|
| 68 |
+
|
| 69 |
+
/// <summary>
|
| 70 |
+
/// Deletes the virtual processor.
|
| 71 |
+
/// </summary>
|
| 72 |
+
virtual void DeleteThis();
|
| 73 |
+
|
| 74 |
+
/// <summary>
|
| 75 |
+
/// Called to affinitize the given thread proxy to this virtual processor.
|
| 76 |
+
/// </summary>
|
| 77 |
+
/// <param name="pThreadProxy">
|
| 78 |
+
/// The new thread proxy to run atop this virtual processor root.
|
| 79 |
+
/// </param>
|
| 80 |
+
void Affinitize(FreeThreadProxy *pThreadProxy);
|
| 81 |
+
|
| 82 |
+
/// <summary>
|
| 83 |
+
/// Called in order to reset this virtual processor root to a completely quiescent state (not running anything).
|
| 84 |
+
/// </summary>
|
| 85 |
+
/// <param name="switchState">
|
| 86 |
+
/// Indicates the state of the thread proxy that is making the call. The parameter is of type <typeparamref name="SwitchingProxyState"/>.
|
| 87 |
+
/// </param>
|
| 88 |
+
void ResetOnIdle(SwitchingProxyState switchState);
|
| 89 |
+
|
| 90 |
+
protected:
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Spins until there is no thread proxy executing atop the virtual processor root.
|
| 94 |
+
/// </summary>
|
| 95 |
+
void SpinUntilIdle()
|
| 96 |
+
{
|
| 97 |
+
_SpinWaitBackoffNone spinWait(_Sleep0);
|
| 98 |
+
while(m_pExecutingProxy != NULL && m_pDeactivatedProxy == NULL)
|
| 99 |
+
{
|
| 100 |
+
spinWait._SpinOnce();
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// The thread proxy which is currently executing atop this virtual processor root.
|
| 105 |
+
ThreadProxy * volatile m_pExecutingProxy;
|
| 106 |
+
|
| 107 |
+
// The deactivated proxy.
|
| 108 |
+
ThreadProxy * volatile m_pDeactivatedProxy;
|
| 109 |
+
|
| 110 |
+
};
|
| 111 |
+
} // namespace details
|
| 112 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.cpp
ADDED
|
@@ -0,0 +1,892 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// HillClimbing.cpp
|
| 9 |
+
//
|
| 10 |
+
// Defines classes for the HillClimbing concurrency-optimization algorithm.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
#include <math.h>
|
| 16 |
+
|
| 17 |
+
#pragma warning(disable:4389)
|
| 18 |
+
|
| 19 |
+
namespace Concurrency
|
| 20 |
+
{
|
| 21 |
+
namespace details
|
| 22 |
+
{
|
| 23 |
+
//
|
| 24 |
+
// Initial hill climbing configuration settings. These are the starting points for any hill climbing instance.
|
| 25 |
+
//
|
| 26 |
+
static const unsigned int AlwaysIncrease = 0; // Test setting for always allocating more resources
|
| 27 |
+
static const unsigned int ControlGain = 1; // Used to determine the magnitude of moves, in units of (coefficient of variation)/(thread count)
|
| 28 |
+
static const unsigned int MaxControlSettingChange = 0; // Maximum number of resources that can be changed in one transition (i.e. a capper)
|
| 29 |
+
static const unsigned int MinHistorySize = 3; // Minimum history size to consider relevant for climbing (used for significance test)
|
| 30 |
+
static const unsigned int MaxHistorySize = 5; // Maximum history size, after which a climbing move must be recommended
|
| 31 |
+
static const unsigned int WarmupSampleCount = 1; // How many samples are needed to warm up hill climbing
|
| 32 |
+
static const unsigned int MinCompletionsPerSample = 1; // Minimum number of completions needed to try hill climbing
|
| 33 |
+
static const unsigned int MaxInvalidCount = 3; // Maximum number of consecutive invalid samples; minimum recommended after this point
|
| 34 |
+
static const unsigned int MaxHistoryAge = 50; // Maximum amount of ticks to keep a history from a previous setting
|
| 35 |
+
|
| 36 |
+
/// <summary>
|
| 37 |
+
/// Creates a new instance of hill climbing.
|
| 38 |
+
/// </summary>
|
| 39 |
+
/// <param name="id">
|
| 40 |
+
/// Scheduler id.
|
| 41 |
+
/// </param>
|
| 42 |
+
/// <param name="numberOfCores">
|
| 43 |
+
/// Number that represents the maximum resources available on the machine.
|
| 44 |
+
/// </param>
|
| 45 |
+
/// <param name="pSchedulerProxy">
|
| 46 |
+
/// The scheduler proxy that controls this hill climbing instance.
|
| 47 |
+
/// </param>
|
| 48 |
+
HillClimbing::HillClimbing(unsigned int id, unsigned int numberOfCores, SchedulerProxy * pSchedulerProxy)
|
| 49 |
+
: m_pSchedulerProxy(pSchedulerProxy)
|
| 50 |
+
, m_currentControlSetting(0)
|
| 51 |
+
, m_lastControlSetting(0)
|
| 52 |
+
, m_id(id)
|
| 53 |
+
, m_sampleCount(0)
|
| 54 |
+
, m_totalSampleCount(0)
|
| 55 |
+
, m_invalidCount(0)
|
| 56 |
+
, m_saveCompleted(0)
|
| 57 |
+
, m_saveIncoming(0)
|
| 58 |
+
, m_nextRandomMoveIsUp(true)
|
| 59 |
+
{
|
| 60 |
+
//
|
| 61 |
+
// Assign default configuration
|
| 62 |
+
//
|
| 63 |
+
m_controlGain = ControlGain * numberOfCores;
|
| 64 |
+
m_maxControlSettingChange = (MaxControlSettingChange != 0) ? MaxControlSettingChange : numberOfCores;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
/// <summary>
|
| 68 |
+
/// External call passing statistical information to hill climbing. Based on these
|
| 69 |
+
/// statistics, hill climbing will give a recommendation on the number of resources to be used.
|
| 70 |
+
/// </summary>
|
| 71 |
+
/// <param name="currentControlSetting">
|
| 72 |
+
/// The control setting used in this period of time.
|
| 73 |
+
/// </param>
|
| 74 |
+
/// <param name="completionRate">
|
| 75 |
+
/// The number of completed units or work in that period of time.
|
| 76 |
+
/// </param>
|
| 77 |
+
/// <param name="arrivalRate">
|
| 78 |
+
/// The number of incoming units or work in that period of time.
|
| 79 |
+
/// </param>
|
| 80 |
+
/// <param name="queueLength">
|
| 81 |
+
/// The total length of the work queue.
|
| 82 |
+
/// </param>
|
| 83 |
+
/// <returns>
|
| 84 |
+
/// The recommended number of resources to be used.
|
| 85 |
+
/// </returns>
|
| 86 |
+
unsigned int HillClimbing::Update(unsigned int currentControlSetting, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength)
|
| 87 |
+
{
|
| 88 |
+
HillClimbingStateTransition transition = Undefined;
|
| 89 |
+
int recommendedSetting = 0;
|
| 90 |
+
|
| 91 |
+
// If there are no resources devoted to this scheduler proxy then there is
|
| 92 |
+
// no statistical analysis needed.
|
| 93 |
+
if (currentControlSetting == 0)
|
| 94 |
+
{
|
| 95 |
+
return 0;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
//
|
| 99 |
+
// Hill climbing made a recommendation for a number of resources to be used the next time around. However, that
|
| 100 |
+
// does not mean that this recommendation was accepted by the consumer of that information. Thus, first establish
|
| 101 |
+
// the control setting passed in by the consumer so that we can accurately track history information. Also, it is
|
| 102 |
+
// necessary to flush old, stale history information before trying to hill climb.
|
| 103 |
+
//
|
| 104 |
+
m_totalSampleCount++;
|
| 105 |
+
EstablishControlSetting(currentControlSetting);
|
| 106 |
+
|
| 107 |
+
//
|
| 108 |
+
// If we had some invalid samples, then carefully modify the actual parameters to this function
|
| 109 |
+
//
|
| 110 |
+
if (m_invalidCount > 0)
|
| 111 |
+
{
|
| 112 |
+
completionRate += m_saveCompleted;
|
| 113 |
+
arrivalRate += m_saveIncoming;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
//
|
| 117 |
+
// If we have long running tasks that are not yet completed, report completions and arrivals for those
|
| 118 |
+
// tasks, effectively chunking them up into sample sized tasks. A long running task scenario is defined as:
|
| 119 |
+
//
|
| 120 |
+
// a) Number or completed tasks is smaller than number of resources used in the time interval, AND
|
| 121 |
+
// b) Number of completed tasks is smaller than a length of the queue (resources cannot be invalid)
|
| 122 |
+
//
|
| 123 |
+
if (completionRate < currentControlSetting && completionRate < queueLength)
|
| 124 |
+
{
|
| 125 |
+
arrivalRate += (currentControlSetting - completionRate);
|
| 126 |
+
completionRate = currentControlSetting;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
//
|
| 130 |
+
// Check if reported statistics are within the bounds of a valid sample. A sample is invalid iff:
|
| 131 |
+
// it is not a warmup run AND it is EITHER too short of a measurement OR there were not enough completions.
|
| 132 |
+
//
|
| 133 |
+
if (m_sampleCount >= WarmupSampleCount && MinCompletionsPerSample > completionRate && MinCompletionsPerSample > arrivalRate && queueLength == 0)
|
| 134 |
+
{
|
| 135 |
+
//
|
| 136 |
+
// If this is an invalid sample, save the data
|
| 137 |
+
//
|
| 138 |
+
m_invalidCount++;
|
| 139 |
+
m_saveCompleted = completionRate;
|
| 140 |
+
m_saveIncoming = arrivalRate;
|
| 141 |
+
|
| 142 |
+
unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads();
|
| 143 |
+
unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads();
|
| 144 |
+
(maximumSetting);
|
| 145 |
+
|
| 146 |
+
recommendedSetting = (m_invalidCount < MaxInvalidCount) ? m_currentControlSetting : minimumSetting;
|
| 147 |
+
|
| 148 |
+
TRACE(CONCRT_TRACE_HILLCLIMBING,
|
| 149 |
+
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",
|
| 150 |
+
GetCurrentProcessId(),
|
| 151 |
+
m_id,
|
| 152 |
+
m_invalidCount,
|
| 153 |
+
completionRate,
|
| 154 |
+
arrivalRate,
|
| 155 |
+
queueLength,
|
| 156 |
+
minimumSetting,
|
| 157 |
+
maximumSetting,
|
| 158 |
+
m_currentControlSetting,
|
| 159 |
+
m_lastControlSetting,
|
| 160 |
+
recommendedSetting);
|
| 161 |
+
|
| 162 |
+
return recommendedSetting;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
unsigned int numberOfSamples = m_invalidCount + 1;
|
| 166 |
+
|
| 167 |
+
//
|
| 168 |
+
// Reset the statistics kept for invalid samples and initiate a valid sample
|
| 169 |
+
//
|
| 170 |
+
m_sampleCount++;
|
| 171 |
+
m_saveCompleted = 0;
|
| 172 |
+
m_saveIncoming = 0;
|
| 173 |
+
m_invalidCount = 0;
|
| 174 |
+
|
| 175 |
+
// Unless there is a good reason to climb, the current setting (set by EstablishControlSetting) will remain the same.
|
| 176 |
+
recommendedSetting = m_currentControlSetting;
|
| 177 |
+
|
| 178 |
+
// Calculate the throughput for this given instance
|
| 179 |
+
double throughput = CalculateThroughput(numberOfSamples, completionRate, arrivalRate, queueLength);
|
| 180 |
+
|
| 181 |
+
if (m_sampleCount <= WarmupSampleCount)
|
| 182 |
+
{
|
| 183 |
+
//
|
| 184 |
+
// We're in the "warmup" phase, where we simply bide our time (and initialize our current control setting).
|
| 185 |
+
//
|
| 186 |
+
_CONCRT_ASSERT(m_currentControlSetting != 0);
|
| 187 |
+
m_lastControlSetting = m_currentControlSetting;
|
| 188 |
+
transition = Warmup;
|
| 189 |
+
}
|
| 190 |
+
else
|
| 191 |
+
{
|
| 192 |
+
MeasuredHistory * currentHistory = GetHistory(m_currentControlSetting);
|
| 193 |
+
MeasuredHistory * lastHistory = GetHistory(m_lastControlSetting);
|
| 194 |
+
|
| 195 |
+
currentHistory->Add(throughput, m_totalSampleCount);
|
| 196 |
+
|
| 197 |
+
if (AlwaysIncrease > 0)
|
| 198 |
+
{
|
| 199 |
+
//
|
| 200 |
+
// We're in the "always increase" diagnostic mode. Just increase the control setting
|
| 201 |
+
// along the desired gradient.
|
| 202 |
+
//
|
| 203 |
+
unsigned int newSetting = (unsigned int) ((AlwaysIncrease / 1000.0) * m_sampleCount);
|
| 204 |
+
|
| 205 |
+
if (newSetting > m_currentControlSetting)
|
| 206 |
+
{
|
| 207 |
+
recommendedSetting = RecommendControlSetting(newSetting);
|
| 208 |
+
transition = DoClimbing;
|
| 209 |
+
}
|
| 210 |
+
else
|
| 211 |
+
{
|
| 212 |
+
transition = ContinueLookingForClimb;
|
| 213 |
+
}
|
| 214 |
+
}
|
| 215 |
+
else if (lastHistory->Count() == 0 || currentHistory == lastHistory)
|
| 216 |
+
{
|
| 217 |
+
//
|
| 218 |
+
// If we have no previous history, then we need to initialize. We wait until
|
| 219 |
+
// the current history is stable, then make our first move.
|
| 220 |
+
//
|
| 221 |
+
if (IsStableHistory(currentHistory))
|
| 222 |
+
{
|
| 223 |
+
//
|
| 224 |
+
// This is our first move; we have no history to use to predict the correct move.
|
| 225 |
+
// We'll just make a random move, and see what happens.
|
| 226 |
+
//
|
| 227 |
+
recommendedSetting = RecommendControlSetting(m_currentControlSetting + GetRandomMove());
|
| 228 |
+
transition = CompletedInitialization;
|
| 229 |
+
}
|
| 230 |
+
else
|
| 231 |
+
{
|
| 232 |
+
transition = ContinueInitializing;
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
else if (!IsStableHistory(currentHistory))
|
| 236 |
+
{
|
| 237 |
+
transition = ContinueLookingForClimb;
|
| 238 |
+
}
|
| 239 |
+
else
|
| 240 |
+
{
|
| 241 |
+
//
|
| 242 |
+
// We have two separate stable histories. We can compare them, and make a real climbing move.
|
| 243 |
+
//
|
| 244 |
+
double gradient = CalculateThroughputGradient(m_lastControlSetting, m_currentControlSetting);
|
| 245 |
+
double controlSettingAdjustment = gradient * m_controlGain;
|
| 246 |
+
unsigned int newControlSetting = (unsigned int) (m_currentControlSetting + controlSettingAdjustment);
|
| 247 |
+
|
| 248 |
+
if (newControlSetting == m_currentControlSetting)
|
| 249 |
+
{
|
| 250 |
+
newControlSetting = (unsigned int) (m_currentControlSetting + sign(controlSettingAdjustment));
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
recommendedSetting = RecommendControlSetting(newControlSetting);
|
| 254 |
+
transition = DoClimbing;
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
_CONCRT_ASSERT(transition != Undefined); // Unhandled case for HillClimbing controller
|
| 259 |
+
|
| 260 |
+
#if defined(CONCRT_TRACING)
|
| 261 |
+
LogData(recommendedSetting, transition, numberOfSamples, completionRate, arrivalRate, queueLength, throughput);
|
| 262 |
+
#endif
|
| 263 |
+
|
| 264 |
+
return recommendedSetting;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
/// <summary>
|
| 268 |
+
/// Calculates the throughput based on the input parameters.
|
| 269 |
+
/// </summary>
|
| 270 |
+
/// <param name="numberOfSamples">
|
| 271 |
+
/// The number of sample points in this measurement, including invalid ones.
|
| 272 |
+
/// </param>
|
| 273 |
+
/// <param name="completionRate">
|
| 274 |
+
/// The number of completed units or work in that period of time.
|
| 275 |
+
/// </param>
|
| 276 |
+
/// <param name="arrivalRate">
|
| 277 |
+
/// The number of incoming units or work in that period of time.
|
| 278 |
+
/// </param>
|
| 279 |
+
/// <param name="queueLength">
|
| 280 |
+
/// The total length of the work queue.
|
| 281 |
+
/// </param>
|
| 282 |
+
/// <returns>
|
| 283 |
+
/// The calculated throughput.
|
| 284 |
+
/// </returns>
|
| 285 |
+
double HillClimbing::CalculateThroughput(unsigned int numberOfSamples, unsigned int completionRate, unsigned int, unsigned int)
|
| 286 |
+
{
|
| 287 |
+
const double samplesPerSecond = 10.0; // A double constant representing number of valid samples per second
|
| 288 |
+
|
| 289 |
+
// Compute the rate at which the queue is growing or shrinking. If it is growing, report a higher
|
| 290 |
+
// number which will cause more resources to be allocated for this instance; it the length of the queue
|
| 291 |
+
// is shrinking, try to take away resources while still shrinking the queue.
|
| 292 |
+
//
|
| 293 |
+
// /_\ length incoming - completed
|
| 294 |
+
// growth = ------------ = ----------------------
|
| 295 |
+
// /_\ time t2 - t1
|
| 296 |
+
//
|
| 297 |
+
// For now, instead of looking at the change in the queue length, completion rate will be used. This is due
|
| 298 |
+
// to the fact that typical loads in ConcRT are self-balancing, i.e. completion rate ~ incoming rate.
|
| 299 |
+
//
|
| 300 |
+
return (completionRate * samplesPerSecond) / (double) (numberOfSamples);
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
/// <summary>
|
| 304 |
+
/// Recommends NewControlSetting to be used.
|
| 305 |
+
/// </summary>
|
| 306 |
+
/// <param name="newControlSetting">
|
| 307 |
+
/// The control setting to be established.
|
| 308 |
+
/// </param>
|
| 309 |
+
/// <returns>
|
| 310 |
+
/// New control setting to be used.
|
| 311 |
+
/// </returns>
|
| 312 |
+
unsigned int HillClimbing::RecommendControlSetting(unsigned int newControlSetting)
|
| 313 |
+
{
|
| 314 |
+
//
|
| 315 |
+
// Make sure that the new setting is within the biggest individual move bounds.
|
| 316 |
+
//
|
| 317 |
+
unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads();
|
| 318 |
+
unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads();
|
| 319 |
+
|
| 320 |
+
newControlSetting = min(m_currentControlSetting + m_maxControlSettingChange, newControlSetting);
|
| 321 |
+
|
| 322 |
+
if (m_currentControlSetting > m_maxControlSettingChange)
|
| 323 |
+
{
|
| 324 |
+
newControlSetting = max(m_currentControlSetting - m_maxControlSettingChange, newControlSetting);
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
if (newControlSetting == m_currentControlSetting) // Can't draw a line with a single point
|
| 328 |
+
{
|
| 329 |
+
if (newControlSetting > minimumSetting)
|
| 330 |
+
{
|
| 331 |
+
newControlSetting--;
|
| 332 |
+
}
|
| 333 |
+
else
|
| 334 |
+
{
|
| 335 |
+
newControlSetting++;
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
//
|
| 340 |
+
// Make sure that the new setting is within the min and max bounds of the scheduler proxy.
|
| 341 |
+
//
|
| 342 |
+
newControlSetting = max(minimumSetting, newControlSetting);
|
| 343 |
+
newControlSetting = min(maximumSetting, newControlSetting);
|
| 344 |
+
|
| 345 |
+
if (AlwaysIncrease == 0 && newControlSetting != m_currentControlSetting)
|
| 346 |
+
{
|
| 347 |
+
// If this move would cause us to move through a setting that we know was recently worse than this
|
| 348 |
+
// one, then back off to one before that setting.
|
| 349 |
+
int direction = sign(newControlSetting - m_currentControlSetting);
|
| 350 |
+
|
| 351 |
+
if (direction == -1)
|
| 352 |
+
{
|
| 353 |
+
for (int setting = m_currentControlSetting + direction;
|
| 354 |
+
setting == newControlSetting || sign(newControlSetting - setting) == direction;
|
| 355 |
+
setting += direction)
|
| 356 |
+
{
|
| 357 |
+
if (GetHistory(setting)->Count() > 0)
|
| 358 |
+
{
|
| 359 |
+
double gradient = CalculateThroughputGradient(m_currentControlSetting, setting) * direction;
|
| 360 |
+
|
| 361 |
+
if (gradient <= 0)
|
| 362 |
+
{
|
| 363 |
+
newControlSetting = setting - direction;
|
| 364 |
+
break;
|
| 365 |
+
}
|
| 366 |
+
}
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
return newControlSetting;
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
/// <summary>
|
| 375 |
+
/// Establishes control setting as current. This is the only method that updates the control settings.
|
| 376 |
+
/// </summary>
|
| 377 |
+
/// <param name="newControlSetting">
|
| 378 |
+
/// The control setting to be established.
|
| 379 |
+
/// </param>
|
| 380 |
+
void HillClimbing::EstablishControlSetting(unsigned int newControlSetting)
|
| 381 |
+
{
|
| 382 |
+
if (newControlSetting != m_currentControlSetting)
|
| 383 |
+
{
|
| 384 |
+
m_lastControlSetting = m_currentControlSetting;
|
| 385 |
+
m_currentControlSetting = newControlSetting;
|
| 386 |
+
GetHistory(m_currentControlSetting)->Clear(0);
|
| 387 |
+
FlushHistories();
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
/// <summary>
|
| 392 |
+
/// Calculates the throughput gradient given two history measurements.
|
| 393 |
+
/// </summary>
|
| 394 |
+
/// <param name="fromSetting">
|
| 395 |
+
/// The control setting to move from.
|
| 396 |
+
/// </param>
|
| 397 |
+
/// <param name="toSetting">
|
| 398 |
+
/// The control setting to move to.
|
| 399 |
+
/// </param>
|
| 400 |
+
/// <returns>
|
| 401 |
+
/// A value representing a gradient between two measurements.
|
| 402 |
+
/// </returns>
|
| 403 |
+
double HillClimbing::CalculateThroughputGradient(int fromSetting, int toSetting)
|
| 404 |
+
{
|
| 405 |
+
//
|
| 406 |
+
// Configurable constants to control reactiveness of hill climbing
|
| 407 |
+
//
|
| 408 |
+
const double minJustifiesChange = 0.15; // A minimum fractional change in measurement that justifies a change (cost for making a change)
|
| 409 |
+
const double changeAdjustmentMultiplier = 1.0; // Controls change factor by reducing uncertainty (bigger number pessimizes change frequency)
|
| 410 |
+
|
| 411 |
+
double fractionalChangeInControlSetting = (double) (toSetting - fromSetting) / (double) fromSetting;
|
| 412 |
+
|
| 413 |
+
MeasuredHistory * lastHistory = GetHistory(fromSetting);
|
| 414 |
+
MeasuredHistory * currentHistory = GetHistory(toSetting);
|
| 415 |
+
|
| 416 |
+
double lastHistoryMean = lastHistory->Mean();
|
| 417 |
+
double currentHistoryMean = currentHistory->Mean();
|
| 418 |
+
double meanChangeInMeasuredValue = currentHistoryMean - lastHistoryMean;
|
| 419 |
+
double fractionalChangeInMeasuredValue = meanChangeInMeasuredValue / lastHistoryMean;
|
| 420 |
+
|
| 421 |
+
double gradient = (fractionalChangeInMeasuredValue/fractionalChangeInControlSetting) - minJustifiesChange;
|
| 422 |
+
|
| 423 |
+
double varianceOfcurrentHistory = currentHistory->VarianceMean();
|
| 424 |
+
double varianceOflastHistory = lastHistory->VarianceMean();
|
| 425 |
+
double standardDeviationOfDifferenceInMeans = sqrt(varianceOfcurrentHistory + varianceOflastHistory);
|
| 426 |
+
double coefficientOfVariationOfChangeInMeasuredValue =
|
| 427 |
+
(abs(meanChangeInMeasuredValue) > 0) ? abs(standardDeviationOfDifferenceInMeans / meanChangeInMeasuredValue) : 0;
|
| 428 |
+
|
| 429 |
+
double adjustedGradient = gradient * exp(-changeAdjustmentMultiplier * coefficientOfVariationOfChangeInMeasuredValue);
|
| 430 |
+
|
| 431 |
+
return adjustedGradient;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
/// <summary>
|
| 435 |
+
/// Determines whether a given history measurement is stable enough to make a hill climbing move.
|
| 436 |
+
/// </summary>
|
| 437 |
+
/// <returns>
|
| 438 |
+
/// True if history measurement is stable.
|
| 439 |
+
/// </returns>
|
| 440 |
+
bool HillClimbing::IsStableHistory(MeasuredHistory * pMeasuredHistory)
|
| 441 |
+
{
|
| 442 |
+
const double maxCoefficientOfVariation = 0.004; // Controls history relevance between min and max by bounding the error
|
| 443 |
+
|
| 444 |
+
if (pMeasuredHistory->Count() > MaxHistorySize)
|
| 445 |
+
{
|
| 446 |
+
return true;
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
if (pMeasuredHistory->Count() < MinHistorySize)
|
| 450 |
+
{
|
| 451 |
+
return false;
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
if (abs(pMeasuredHistory->CoefficientOfVariationMean()) > maxCoefficientOfVariation)
|
| 455 |
+
{
|
| 456 |
+
return false;
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
return true;
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
/// <summary>
|
| 463 |
+
/// Flushes all measurement histories that are no longer relevant.
|
| 464 |
+
/// </summary>
|
| 465 |
+
void HillClimbing::FlushHistories()
|
| 466 |
+
{
|
| 467 |
+
for (int i = 0; i < MaxHistoryCount; i++)
|
| 468 |
+
{
|
| 469 |
+
if (m_histories[i].ControlSetting() != m_currentControlSetting &&
|
| 470 |
+
m_histories[i].ControlSetting() != m_lastControlSetting &&
|
| 471 |
+
m_totalSampleCount - m_histories[i].LastDataPointCount() > MaxHistoryAge)
|
| 472 |
+
{
|
| 473 |
+
m_histories[i].Clear(0);
|
| 474 |
+
}
|
| 475 |
+
}
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
/// <summary>
|
| 479 |
+
/// Clears all measurement histories.
|
| 480 |
+
/// </summary>
|
| 481 |
+
void HillClimbing::ClearHistories()
|
| 482 |
+
{
|
| 483 |
+
for (int i = 0; i < MaxHistoryCount; i++)
|
| 484 |
+
{
|
| 485 |
+
m_histories[i].Clear(0);
|
| 486 |
+
}
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
/// <summary>
|
| 490 |
+
/// Makes a pseudo-random hill climbing move by alternating between up and down.
|
| 491 |
+
/// </summary>
|
| 492 |
+
/// <returns>
|
| 493 |
+
/// The random move.
|
| 494 |
+
/// </returns>
|
| 495 |
+
int HillClimbing::GetRandomMove()
|
| 496 |
+
{
|
| 497 |
+
int result = m_nextRandomMoveIsUp ? 1 : 0;
|
| 498 |
+
m_nextRandomMoveIsUp = !m_nextRandomMoveIsUp;
|
| 499 |
+
return result;
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
/// <summary>
|
| 503 |
+
/// Gets the history measurement for a given control setting.
|
| 504 |
+
/// </summary>
|
| 505 |
+
/// <returns>
|
| 506 |
+
/// The history measurement.
|
| 507 |
+
/// </returns>
|
| 508 |
+
HillClimbing::MeasuredHistory * HillClimbing::GetHistory(unsigned int controlSetting)
|
| 509 |
+
{
|
| 510 |
+
int i = controlSetting % MaxHistoryCount;
|
| 511 |
+
|
| 512 |
+
if (m_histories[i].ControlSetting() != controlSetting)
|
| 513 |
+
{
|
| 514 |
+
m_histories[i].Clear(controlSetting);
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
return &m_histories[i];
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
/// <summary>
|
| 521 |
+
/// Creates a new measurement history.
|
| 522 |
+
/// </summary>
|
| 523 |
+
HillClimbing::MeasuredHistory::MeasuredHistory()
|
| 524 |
+
{
|
| 525 |
+
Clear(0);
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
/// <summary>
|
| 529 |
+
/// Clears the history values for this control setting.
|
| 530 |
+
/// </summary>
|
| 531 |
+
/// <param name="controlSetting">
|
| 532 |
+
/// The control setting to reset.
|
| 533 |
+
/// </param>
|
| 534 |
+
void HillClimbing::MeasuredHistory::Clear(unsigned int controlSetting)
|
| 535 |
+
{
|
| 536 |
+
m_count = 0;
|
| 537 |
+
m_sum = 0;
|
| 538 |
+
m_sumOfSquares = 0;
|
| 539 |
+
m_controlSetting = controlSetting;
|
| 540 |
+
m_lastDataPointCount = 0;
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
/// <summary>
|
| 544 |
+
/// Adds a new history data point.
|
| 545 |
+
/// </summary>
|
| 546 |
+
/// <param name="dataValue">
|
| 547 |
+
/// The value representing throughput in this invocation.
|
| 548 |
+
/// </param>
|
| 549 |
+
/// <param name="totalSampleCount">
|
| 550 |
+
/// The value representing the total number of samples for this history, including invalid samples and samples for previous settings.
|
| 551 |
+
/// </param>
|
| 552 |
+
void HillClimbing::MeasuredHistory::Add(const double dataValue, unsigned int totalSampleCount)
|
| 553 |
+
{
|
| 554 |
+
m_sum += dataValue;
|
| 555 |
+
m_sumOfSquares += dataValue * dataValue;
|
| 556 |
+
m_count++;
|
| 557 |
+
m_lastDataPointCount = totalSampleCount;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
/// <summary>
|
| 561 |
+
/// Gets the count for this history measurement.
|
| 562 |
+
/// </summary>
|
| 563 |
+
/// <returns>
|
| 564 |
+
/// The count.
|
| 565 |
+
/// </returns>
|
| 566 |
+
int HillClimbing::MeasuredHistory::Count()
|
| 567 |
+
{
|
| 568 |
+
return m_count;
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
/// <summary>
|
| 572 |
+
/// Gets the count at the last data point for this history measurement.
|
| 573 |
+
/// </summary>
|
| 574 |
+
/// <returns>
|
| 575 |
+
/// The last data point count.
|
| 576 |
+
/// </returns>
|
| 577 |
+
unsigned int HillClimbing::MeasuredHistory::LastDataPointCount()
|
| 578 |
+
{
|
| 579 |
+
return m_lastDataPointCount;
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
/// <summary>
|
| 583 |
+
/// Gets the control setting for this history measurement.
|
| 584 |
+
/// </summary>
|
| 585 |
+
/// <returns>
|
| 586 |
+
/// The control setting.
|
| 587 |
+
/// </returns>
|
| 588 |
+
int HillClimbing::MeasuredHistory::ControlSetting() {
|
| 589 |
+
return m_controlSetting;
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
/// <summary>
|
| 593 |
+
/// Computes the mean for a given history.
|
| 594 |
+
/// </summary>
|
| 595 |
+
/// <returns>
|
| 596 |
+
/// The mean.
|
| 597 |
+
/// </returns>
|
| 598 |
+
double HillClimbing::MeasuredHistory::Mean()
|
| 599 |
+
{
|
| 600 |
+
return (m_count == 0) ? 0.0 : (m_sum / m_count);
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
/// <summary>
|
| 604 |
+
/// Computes the coefficient of variation for a given history.
|
| 605 |
+
/// </summary>
|
| 606 |
+
/// <returns>
|
| 607 |
+
/// The coefficient of variation.
|
| 608 |
+
/// </returns>
|
| 609 |
+
double HillClimbing::MeasuredHistory::CoefficientOfVariation()
|
| 610 |
+
{
|
| 611 |
+
double mean = Mean();
|
| 612 |
+
return (mean <= 0.0) ? 0.0 : (StandardDeviation() / mean);
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
/// <summary>
|
| 616 |
+
/// Computes the mean of coefficients of variation for a given history.
|
| 617 |
+
/// </summary>
|
| 618 |
+
/// <returns>
|
| 619 |
+
/// The mean of coefficients of variation.
|
| 620 |
+
/// </returns>
|
| 621 |
+
double HillClimbing::MeasuredHistory::CoefficientOfVariationMean()
|
| 622 |
+
{
|
| 623 |
+
return (StandardDeviation() / sqrt(1.0 * m_count)) / Mean();
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
/// <summary>
|
| 627 |
+
/// Computes the variance for a given history.
|
| 628 |
+
/// </summary>
|
| 629 |
+
/// <returns>
|
| 630 |
+
/// The variance.
|
| 631 |
+
/// </returns>
|
| 632 |
+
double HillClimbing::MeasuredHistory::Variance()
|
| 633 |
+
{
|
| 634 |
+
const double smallValue = 0.0001;
|
| 635 |
+
double variance = 0.0;
|
| 636 |
+
|
| 637 |
+
if (m_count >= 2)
|
| 638 |
+
{
|
| 639 |
+
variance = (m_sumOfSquares - (m_sum * m_sum)/ m_count)/ (m_count - 1);
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
return abs(variance) > smallValue ? variance : 0;
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
/// <summary>
|
| 646 |
+
/// Computes the mean of variances for a given history.
|
| 647 |
+
/// </summary>
|
| 648 |
+
/// <returns>
|
| 649 |
+
/// The mean of variances.
|
| 650 |
+
/// </returns>
|
| 651 |
+
double HillClimbing::MeasuredHistory::VarianceMean()
|
| 652 |
+
{
|
| 653 |
+
return Variance() / Count();
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
/// <summary>
|
| 657 |
+
/// Computes the standard deviation for a given history.
|
| 658 |
+
/// </summary>
|
| 659 |
+
/// <returns>
|
| 660 |
+
/// The standard deviation.
|
| 661 |
+
/// </returns>
|
| 662 |
+
double HillClimbing::MeasuredHistory::StandardDeviation()
|
| 663 |
+
{
|
| 664 |
+
return sqrt(Variance());
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
/// <summary>
|
| 668 |
+
/// Computes the mean of standard deviations for a given history.
|
| 669 |
+
/// </summary>
|
| 670 |
+
/// <returns>
|
| 671 |
+
/// The mean of standard deviations.
|
| 672 |
+
/// </returns>
|
| 673 |
+
double HillClimbing::MeasuredHistory::StandardDeviationMean()
|
| 674 |
+
{
|
| 675 |
+
return (m_count == 0) ? 0.0 : (StandardDeviation() / sqrt(m_count * 1.0));
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
/// <summary>
|
| 679 |
+
/// Tests if the difference between two measurement histories is statistically significant to
|
| 680 |
+
/// make a hill climbing decision.
|
| 681 |
+
/// </summary>
|
| 682 |
+
/// <remarks>
|
| 683 |
+
/// A two sided test is used.
|
| 684 |
+
/// </remarks>
|
| 685 |
+
/// <param name="value">
|
| 686 |
+
/// The value representing the second history.
|
| 687 |
+
/// </param>
|
| 688 |
+
/// <param name="significanceLevel">
|
| 689 |
+
/// The significance level in percent. Accepts 1 through 10.
|
| 690 |
+
/// </param>
|
| 691 |
+
/// <param name="totalSampleCount">
|
| 692 |
+
/// The value representing the total number of samples for this history, including invalid samples and samples for previous settings.
|
| 693 |
+
/// </param>
|
| 694 |
+
/// <returns>
|
| 695 |
+
/// -1 - second history is larger than this history
|
| 696 |
+
/// 0 - statistically identical
|
| 697 |
+
/// 1 - this history is larger than second history
|
| 698 |
+
/// </returns>
|
| 699 |
+
int HillClimbing::MeasuredHistory::SignificanceTest(double value, const int significanceLevel, unsigned int totalSampleCount)
|
| 700 |
+
{
|
| 701 |
+
MeasuredHistory singleValue;
|
| 702 |
+
singleValue.Add(value, totalSampleCount);
|
| 703 |
+
|
| 704 |
+
return MeasuredHistory::SignificanceTest(&singleValue, significanceLevel);
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
/// <summary>
|
| 708 |
+
/// Tests if the difference between two measurement histories is statistically significant to
|
| 709 |
+
/// make a hill climbing decision.
|
| 710 |
+
/// </summary>
|
| 711 |
+
/// <remarks>
|
| 712 |
+
/// A two sided test is used.
|
| 713 |
+
/// </remarks>
|
| 714 |
+
/// <param name="pMeasuredHistory">
|
| 715 |
+
/// The pointer to second measurement history.
|
| 716 |
+
/// </param>
|
| 717 |
+
/// <param name="significanceLevel">
|
| 718 |
+
/// The significance level in percent. Accepts 1 through 10.
|
| 719 |
+
/// </param>
|
| 720 |
+
/// <returns>
|
| 721 |
+
/// -1 - second history is larger than this history
|
| 722 |
+
/// 0 - statistically identical
|
| 723 |
+
/// 1 - this history is larger than second history
|
| 724 |
+
/// </returns>
|
| 725 |
+
int HillClimbing::MeasuredHistory::SignificanceTest(MeasuredHistory * pMeasuredHistory, const int significanceLevel)
|
| 726 |
+
{
|
| 727 |
+
const int critSize = 10;
|
| 728 |
+
double critArray[critSize] = { 2.576, 2.3263, 2.17, 2.05, 1.96, 1.88, 1.81, 1.75, 1.70, 1.64 };
|
| 729 |
+
|
| 730 |
+
double thisVariance = this->VarianceMean();
|
| 731 |
+
double thisMean = Mean();
|
| 732 |
+
double secondVariance = pMeasuredHistory->VarianceMean();
|
| 733 |
+
double secondMean = pMeasuredHistory->Mean();
|
| 734 |
+
|
| 735 |
+
_CONCRT_ASSERT(significanceLevel > 0 && significanceLevel <= 10); // Invalid significance level
|
| 736 |
+
|
| 737 |
+
int result = (int) sign(thisMean - secondMean);
|
| 738 |
+
|
| 739 |
+
if (thisVariance > 0 && secondVariance > 0)
|
| 740 |
+
{
|
| 741 |
+
double pooledVar = thisVariance / Count() + secondVariance / pMeasuredHistory->Count();
|
| 742 |
+
|
| 743 |
+
double testStatistic = (thisMean - secondMean) / sqrt(pooledVar);
|
| 744 |
+
double critVal = critArray[significanceLevel-1];
|
| 745 |
+
double absVal = abs(testStatistic);
|
| 746 |
+
|
| 747 |
+
if (absVal < critVal)
|
| 748 |
+
{
|
| 749 |
+
result = 0;
|
| 750 |
+
}
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
return result;
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
#if defined(CONCRT_TRACING)
|
| 757 |
+
|
| 758 |
+
// Logging mechanism
|
| 759 |
+
|
| 760 |
+
struct HillClimbingLogEntry
|
| 761 |
+
{
|
| 762 |
+
long sampleCount;
|
| 763 |
+
unsigned int currentTotalSampleCount;
|
| 764 |
+
double throughput;
|
| 765 |
+
double currentHistoryMean;
|
| 766 |
+
double currentHistoryStd;
|
| 767 |
+
double lastHistoryMean;
|
| 768 |
+
double lastHistoryStd;
|
| 769 |
+
unsigned int currentControlSetting;
|
| 770 |
+
unsigned int lastControlSetting;
|
| 771 |
+
unsigned int currentHistoryCount;
|
| 772 |
+
unsigned int lastHistoryCount;
|
| 773 |
+
HillClimbingStateTransition transition;
|
| 774 |
+
};
|
| 775 |
+
|
| 776 |
+
static const int HillClimbingLogCapacity = 100;
|
| 777 |
+
static HillClimbingLogEntry HillClimbingLog[HillClimbingLogCapacity];
|
| 778 |
+
static int HillClimbingLogFirstIndex = 0;
|
| 779 |
+
static int HillClimbingLogSize = 0;
|
| 780 |
+
|
| 781 |
+
static const wchar_t * const HillClimbingTransitionNames[] =
|
| 782 |
+
{
|
| 783 |
+
L"Warmup",
|
| 784 |
+
L"ContinueInitializing",
|
| 785 |
+
L"CompletedInitialization",
|
| 786 |
+
L"DoClimbing",
|
| 787 |
+
L"ChangePoint",
|
| 788 |
+
L"ContinueLookingForClimb",
|
| 789 |
+
L"Undefined"
|
| 790 |
+
};
|
| 791 |
+
|
| 792 |
+
/// <summary>
|
| 793 |
+
/// Logs the hill climbing decision.
|
| 794 |
+
/// </summary>
|
| 795 |
+
/// <param name="recommendedSetting">
|
| 796 |
+
/// The control setting to be established.
|
| 797 |
+
/// </param>
|
| 798 |
+
/// <param name="transition">
|
| 799 |
+
/// The transition that is recommended by hill climbing.
|
| 800 |
+
/// </param>
|
| 801 |
+
/// <param name="numberOfSamples">
|
| 802 |
+
/// The number of sample points in this measurement, including invalid ones.
|
| 803 |
+
/// </param>
|
| 804 |
+
/// <param name="completionRate">
|
| 805 |
+
/// The number of completed units or work in that period of time.
|
| 806 |
+
/// </param>
|
| 807 |
+
/// <param name="arrivalRate">
|
| 808 |
+
/// The number of incoming units or work in that period of time.
|
| 809 |
+
/// </param>
|
| 810 |
+
/// <param name="queueLength">
|
| 811 |
+
/// The total length of the work queue.
|
| 812 |
+
/// </param>
|
| 813 |
+
/// <param name="throughput">
|
| 814 |
+
/// The throughput of the given instance.
|
| 815 |
+
/// </param>
|
| 816 |
+
void HillClimbing::LogData(unsigned int recommendedSetting, HillClimbingStateTransition transition, unsigned int numberOfSamples,
|
| 817 |
+
unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength, double throughput)
|
| 818 |
+
{
|
| 819 |
+
//
|
| 820 |
+
// First, log to memory so we can see it in the debugger
|
| 821 |
+
//
|
| 822 |
+
int index = (HillClimbingLogFirstIndex + HillClimbingLogSize) % HillClimbingLogCapacity;
|
| 823 |
+
if (HillClimbingLogSize == HillClimbingLogCapacity)
|
| 824 |
+
{
|
| 825 |
+
HillClimbingLogFirstIndex = (HillClimbingLogFirstIndex + 1) % HillClimbingLogCapacity;
|
| 826 |
+
HillClimbingLogSize--; //hide this slot while we update it
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
HillClimbingLogEntry * entry = &HillClimbingLog[index];
|
| 830 |
+
unsigned int minimumSetting = m_pSchedulerProxy->MinHWThreads();
|
| 831 |
+
unsigned int maximumSetting = m_pSchedulerProxy->DesiredHWThreads();
|
| 832 |
+
|
| 833 |
+
entry->sampleCount = m_sampleCount;
|
| 834 |
+
entry->currentTotalSampleCount = numberOfSamples;
|
| 835 |
+
entry->throughput = throughput;
|
| 836 |
+
entry->transition = transition;
|
| 837 |
+
entry->currentControlSetting = m_currentControlSetting;
|
| 838 |
+
entry->lastControlSetting = m_lastControlSetting;
|
| 839 |
+
|
| 840 |
+
MeasuredHistory * currentHistory = GetHistory(m_currentControlSetting);
|
| 841 |
+
entry->currentHistoryCount = currentHistory->Count();
|
| 842 |
+
entry->currentHistoryMean = currentHistory->Mean();
|
| 843 |
+
entry->currentHistoryStd = currentHistory->StandardDeviation();
|
| 844 |
+
|
| 845 |
+
MeasuredHistory * lastHistory = GetHistory(m_lastControlSetting);
|
| 846 |
+
entry->lastHistoryCount = lastHistory->Count();
|
| 847 |
+
entry->lastHistoryMean = lastHistory->Mean();
|
| 848 |
+
entry->lastHistoryStd = lastHistory->StandardDeviation();
|
| 849 |
+
|
| 850 |
+
HillClimbingLogSize++;
|
| 851 |
+
|
| 852 |
+
const int bufferSize = 180;
|
| 853 |
+
const wchar_t * delim = L"*******************************************************";
|
| 854 |
+
|
| 855 |
+
wchar_t dateBuffer[bufferSize];
|
| 856 |
+
SYSTEMTIME time;
|
| 857 |
+
GetLocalTime(&time);
|
| 858 |
+
int dateLen = GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_SHORTDATE, &time, NULL, dateBuffer, bufferSize);
|
| 859 |
+
dateBuffer[dateLen-1] = L' ';
|
| 860 |
+
GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, TIME_FORCE24HOURFORMAT | TIME_NOTIMEMARKER, &time, NULL, dateBuffer + dateLen, bufferSize - dateLen);
|
| 861 |
+
|
| 862 |
+
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",
|
| 863 |
+
delim,
|
| 864 |
+
GetCurrentProcessId(),
|
| 865 |
+
m_id,
|
| 866 |
+
dateBuffer,
|
| 867 |
+
m_sampleCount,
|
| 868 |
+
numberOfSamples,
|
| 869 |
+
completionRate,
|
| 870 |
+
arrivalRate,
|
| 871 |
+
queueLength,
|
| 872 |
+
throughput,
|
| 873 |
+
HillClimbingTransitionNames[transition],
|
| 874 |
+
m_nextRandomMoveIsUp ? L"Up" : L"Down",
|
| 875 |
+
minimumSetting,
|
| 876 |
+
maximumSetting,
|
| 877 |
+
m_currentControlSetting,
|
| 878 |
+
currentHistory->Count(),
|
| 879 |
+
currentHistory->Mean(),
|
| 880 |
+
currentHistory->StandardDeviation(),
|
| 881 |
+
currentHistory->CoefficientOfVariationMean(),
|
| 882 |
+
m_lastControlSetting,
|
| 883 |
+
lastHistory->Count(),
|
| 884 |
+
lastHistory->Mean(),
|
| 885 |
+
lastHistory->StandardDeviation(),
|
| 886 |
+
lastHistory->CoefficientOfVariationMean(),
|
| 887 |
+
recommendedSetting,
|
| 888 |
+
delim);
|
| 889 |
+
}
|
| 890 |
+
#endif
|
| 891 |
+
} // namespace details
|
| 892 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/HillClimbing.h
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// HillClimbing.h
|
| 9 |
+
//
|
| 10 |
+
// Defines classes for the HillClimbing concurrency-optimization algorithm.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
|
| 21 |
+
/// <summary>
|
| 22 |
+
/// An enum representing all possible hill climbing transition moves.
|
| 23 |
+
/// </summary>
|
| 24 |
+
enum HillClimbingStateTransition
|
| 25 |
+
{
|
| 26 |
+
Warmup,
|
| 27 |
+
ContinueInitializing,
|
| 28 |
+
CompletedInitialization,
|
| 29 |
+
DoClimbing,
|
| 30 |
+
ChangePoint,
|
| 31 |
+
ContinueLookingForClimb,
|
| 32 |
+
Undefined,
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
/// <summary>
|
| 36 |
+
/// A class responsible for hill climbing.
|
| 37 |
+
/// </summary>
|
| 38 |
+
class HillClimbing
|
| 39 |
+
{
|
| 40 |
+
public:
|
| 41 |
+
|
| 42 |
+
/// <summary>
|
| 43 |
+
/// Creates a new instance of hill climbing.
|
| 44 |
+
/// </summary>
|
| 45 |
+
/// <param name="id">
|
| 46 |
+
/// Scheduler id.
|
| 47 |
+
/// </param>
|
| 48 |
+
/// <param name="numberOfCores">
|
| 49 |
+
/// Number that represents the maximum resources available on the machine.
|
| 50 |
+
/// </param>
|
| 51 |
+
/// <param name="pSchedulerProxy">
|
| 52 |
+
/// The scheduler proxy that controls this hill climbing instance.
|
| 53 |
+
/// </param>
|
| 54 |
+
HillClimbing(unsigned int id, unsigned int numberOfCores, SchedulerProxy * pSchedulerProxy);
|
| 55 |
+
|
| 56 |
+
/// <summary>
|
| 57 |
+
/// External call passing statistical information to hill climbing. Based on these
|
| 58 |
+
/// statistics, hill climbing will give a recommendation on the number of resources to be used.
|
| 59 |
+
/// </summary>
|
| 60 |
+
/// <param name="currentControlSetting">
|
| 61 |
+
/// The control setting used in this period of time.
|
| 62 |
+
/// </param>
|
| 63 |
+
/// <param name="completionRate">
|
| 64 |
+
/// The number of completed units or work in that period of time.
|
| 65 |
+
/// </param>
|
| 66 |
+
/// <param name="arrivalRate">
|
| 67 |
+
/// The number of incoming units or work in that period of time.
|
| 68 |
+
/// </param>
|
| 69 |
+
/// <param name="queueLength">
|
| 70 |
+
/// The total length of the work queue.
|
| 71 |
+
/// </param>
|
| 72 |
+
/// <returns>
|
| 73 |
+
/// The recommended number of resources to be used.
|
| 74 |
+
/// </returns>
|
| 75 |
+
unsigned int Update(unsigned int currentControlSetting, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength);
|
| 76 |
+
|
| 77 |
+
private:
|
| 78 |
+
|
| 79 |
+
/// <summary>
|
| 80 |
+
/// A class responsible for keeping hill climbing history measurements.
|
| 81 |
+
/// </summary>
|
| 82 |
+
class MeasuredHistory
|
| 83 |
+
{
|
| 84 |
+
public:
|
| 85 |
+
|
| 86 |
+
/// <summary>
|
| 87 |
+
/// Creates a new measurement history.
|
| 88 |
+
/// </summary>
|
| 89 |
+
MeasuredHistory();
|
| 90 |
+
|
| 91 |
+
/// <summary>
|
| 92 |
+
/// Adds a new history data point.
|
| 93 |
+
/// </summary>
|
| 94 |
+
/// <param name="dataValue">
|
| 95 |
+
/// The value representing throughput in this invocation.
|
| 96 |
+
/// </param>
|
| 97 |
+
/// <param name="totalSampleCount">
|
| 98 |
+
/// The value representing the total number of samples for this history, including invalid samples and samples for previous settings.
|
| 99 |
+
/// </param>
|
| 100 |
+
void Add(const double data, unsigned int totalSampleCount);
|
| 101 |
+
|
| 102 |
+
/// <summary>
|
| 103 |
+
/// Clears the history values for this control setting.
|
| 104 |
+
/// </summary>
|
| 105 |
+
/// <param name="controlSetting">
|
| 106 |
+
/// The control setting to reset.
|
| 107 |
+
/// </param>
|
| 108 |
+
void Clear(unsigned int controlSetting);
|
| 109 |
+
|
| 110 |
+
/// <summary>
|
| 111 |
+
/// Gets the count for this history measurement.
|
| 112 |
+
/// </summary>
|
| 113 |
+
/// <returns>
|
| 114 |
+
/// The count.
|
| 115 |
+
/// </returns>
|
| 116 |
+
int Count();
|
| 117 |
+
|
| 118 |
+
/// <summary>
|
| 119 |
+
/// Gets the count at the last data point for this history measurement.
|
| 120 |
+
/// </summary>
|
| 121 |
+
/// <returns>
|
| 122 |
+
/// The last data point count.
|
| 123 |
+
/// </returns>
|
| 124 |
+
unsigned int LastDataPointCount();
|
| 125 |
+
|
| 126 |
+
/// <summary>
|
| 127 |
+
/// Gets the control setting for this history measurement.
|
| 128 |
+
/// </summary>
|
| 129 |
+
/// <returns>
|
| 130 |
+
/// The control setting.
|
| 131 |
+
/// </returns>
|
| 132 |
+
int ControlSetting();
|
| 133 |
+
|
| 134 |
+
/// <summary>
|
| 135 |
+
/// Computes the mean for a given history.
|
| 136 |
+
/// </summary>
|
| 137 |
+
/// <returns>
|
| 138 |
+
/// The mean.
|
| 139 |
+
/// </returns>
|
| 140 |
+
double Mean();
|
| 141 |
+
|
| 142 |
+
/// <summary>
|
| 143 |
+
/// Computes the coefficient of variation for a given history.
|
| 144 |
+
/// </summary>
|
| 145 |
+
/// <returns>
|
| 146 |
+
/// The coefficient of variation.
|
| 147 |
+
/// </returns>
|
| 148 |
+
double CoefficientOfVariation();
|
| 149 |
+
|
| 150 |
+
/// <summary>
|
| 151 |
+
/// Computes the mean of coefficients of variation for a given history.
|
| 152 |
+
/// </summary>
|
| 153 |
+
/// <returns>
|
| 154 |
+
/// The mean of coefficients of variation.
|
| 155 |
+
/// </returns>
|
| 156 |
+
double CoefficientOfVariationMean();
|
| 157 |
+
|
| 158 |
+
/// <summary>
|
| 159 |
+
/// Computes the variance for a given history.
|
| 160 |
+
/// </summary>
|
| 161 |
+
/// <returns>
|
| 162 |
+
/// The variance.
|
| 163 |
+
/// </returns>
|
| 164 |
+
double Variance();
|
| 165 |
+
|
| 166 |
+
/// <summary>
|
| 167 |
+
/// Computes the mean of variances for a given history.
|
| 168 |
+
/// </summary>
|
| 169 |
+
/// <returns>
|
| 170 |
+
/// The mean of variances.
|
| 171 |
+
/// </returns>
|
| 172 |
+
double VarianceMean();
|
| 173 |
+
|
| 174 |
+
/// <summary>
|
| 175 |
+
/// Computes the standard deviation for a given history.
|
| 176 |
+
/// </summary>
|
| 177 |
+
/// <returns>
|
| 178 |
+
/// The standard deviation.
|
| 179 |
+
/// </returns>
|
| 180 |
+
double StandardDeviation();
|
| 181 |
+
|
| 182 |
+
/// <summary>
|
| 183 |
+
/// Computes the mean of standard deviations for a given history.
|
| 184 |
+
/// </summary>
|
| 185 |
+
/// <returns>
|
| 186 |
+
/// The mean of standard deviations.
|
| 187 |
+
/// </returns>
|
| 188 |
+
double StandardDeviationMean();
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// Tests if the difference between two measurement histories is statistically significant to
|
| 192 |
+
/// make a hill climbing decision.
|
| 193 |
+
/// </summary>
|
| 194 |
+
/// <remarks>
|
| 195 |
+
/// A two sided test is used.
|
| 196 |
+
/// </remarks>
|
| 197 |
+
/// <param name="value">
|
| 198 |
+
/// The value representing the second history.
|
| 199 |
+
/// </param>
|
| 200 |
+
/// <param name="significanceLevel">
|
| 201 |
+
/// The significance level in percent. Accepts 1 through 10.
|
| 202 |
+
/// </param>
|
| 203 |
+
/// <param name="totalSampleCount">
|
| 204 |
+
/// The value representing the total number of samples for this history, including invalid samples and samples for previous settings.
|
| 205 |
+
/// </param>
|
| 206 |
+
/// <returns>
|
| 207 |
+
/// -1 - second history is larger than this history
|
| 208 |
+
/// 0 - statistically identical
|
| 209 |
+
/// 1 - this history is larger than second history
|
| 210 |
+
/// </returns>
|
| 211 |
+
int SignificanceTest(double value, const int significanceLevel, unsigned int totalSampleCount);
|
| 212 |
+
|
| 213 |
+
/// <summary>
|
| 214 |
+
/// Tests if the difference between two measurement histories is statistically significant to
|
| 215 |
+
/// make a hill climbing decision.
|
| 216 |
+
/// </summary>
|
| 217 |
+
/// <remarks>
|
| 218 |
+
/// A two sided test is used.
|
| 219 |
+
/// </remarks>
|
| 220 |
+
/// <param name="pMeasuredHistory">
|
| 221 |
+
/// The pointer to second measurement history.
|
| 222 |
+
/// </param>
|
| 223 |
+
/// <param name="significanceLevel">
|
| 224 |
+
/// The significance level in percent. Accepts 1 through 10.
|
| 225 |
+
/// </param>
|
| 226 |
+
/// <returns>
|
| 227 |
+
/// -1 - second history is larger than this history
|
| 228 |
+
/// 0 - statistically identical
|
| 229 |
+
/// 1 - this history is larger than second history
|
| 230 |
+
/// </returns>
|
| 231 |
+
int SignificanceTest(MeasuredHistory * pMeasuredHistory, const int significanceLevel);
|
| 232 |
+
|
| 233 |
+
private:
|
| 234 |
+
|
| 235 |
+
// Running sum of throughputs
|
| 236 |
+
double m_sum;
|
| 237 |
+
|
| 238 |
+
// Sum of throughput squares
|
| 239 |
+
double m_sumOfSquares;
|
| 240 |
+
|
| 241 |
+
// Count of measurements in this history
|
| 242 |
+
int m_count;
|
| 243 |
+
|
| 244 |
+
// An integer representing the control setting for this history measurement
|
| 245 |
+
int m_controlSetting;
|
| 246 |
+
|
| 247 |
+
// Last count value when a measurement was taken (used for relevance test)
|
| 248 |
+
unsigned int m_lastDataPointCount;
|
| 249 |
+
};
|
| 250 |
+
|
| 251 |
+
/// <summary>
|
| 252 |
+
/// Makes a pseudo-random hill climbing move by alternating between up and down.
|
| 253 |
+
/// </summary>
|
| 254 |
+
/// <returns>
|
| 255 |
+
/// The random move.
|
| 256 |
+
/// </returns>
|
| 257 |
+
int GetRandomMove();
|
| 258 |
+
|
| 259 |
+
/// <summary>
|
| 260 |
+
/// Recommends NewControlSetting to be used.
|
| 261 |
+
/// </summary>
|
| 262 |
+
/// <param name="newControlSetting">
|
| 263 |
+
/// The control setting to be established.
|
| 264 |
+
/// </param>
|
| 265 |
+
/// <returns>
|
| 266 |
+
/// New control setting to be used.
|
| 267 |
+
/// </returns>
|
| 268 |
+
unsigned RecommendControlSetting(unsigned int newControlSetting);
|
| 269 |
+
|
| 270 |
+
/// <summary>
|
| 271 |
+
/// Establishes control setting as current. This is the only method that updates the control settings.
|
| 272 |
+
/// </summary>
|
| 273 |
+
/// <param name="newControlSetting">
|
| 274 |
+
/// The control setting to be established.
|
| 275 |
+
/// </param>
|
| 276 |
+
void EstablishControlSetting(unsigned int newControlSetting);
|
| 277 |
+
|
| 278 |
+
/// <summary>
|
| 279 |
+
/// Determines whether a given history measurement is stable enough to make a hill climbing move.
|
| 280 |
+
/// </summary>
|
| 281 |
+
/// <returns>
|
| 282 |
+
/// True if history measurement is stable.
|
| 283 |
+
/// </returns>
|
| 284 |
+
bool IsStableHistory(MeasuredHistory * pMeasuredHistory);
|
| 285 |
+
|
| 286 |
+
/// <summary>
|
| 287 |
+
/// Calculates the throughput based on the input parameters.
|
| 288 |
+
/// </summary>
|
| 289 |
+
/// <param name="numberOfSamples">
|
| 290 |
+
/// The number of sample points in this measurement, including invalid ones.
|
| 291 |
+
/// </param>
|
| 292 |
+
/// <param name="completionRate">
|
| 293 |
+
/// The number of completed units or work in that period of time.
|
| 294 |
+
/// </param>
|
| 295 |
+
/// <param name="arrivalRate">
|
| 296 |
+
/// The number of incoming units or work in that period of time.
|
| 297 |
+
/// </param>
|
| 298 |
+
/// <param name="queueLength">
|
| 299 |
+
/// The total length of the work queue.
|
| 300 |
+
/// </param>
|
| 301 |
+
/// <returns>
|
| 302 |
+
/// The calculated throughput.
|
| 303 |
+
/// </returns>
|
| 304 |
+
double CalculateThroughput(unsigned int numberOfSamples, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength);
|
| 305 |
+
|
| 306 |
+
/// <summary>
|
| 307 |
+
/// Calculates the throughput gradient given two history measurements.
|
| 308 |
+
/// </summary>
|
| 309 |
+
/// <param name="fromSetting">
|
| 310 |
+
/// The control setting to move from.
|
| 311 |
+
/// </param>
|
| 312 |
+
/// <param name="toSetting">
|
| 313 |
+
/// The control setting to move to.
|
| 314 |
+
/// </param>
|
| 315 |
+
/// <returns>
|
| 316 |
+
/// A value representing a gradient between two measurements.
|
| 317 |
+
/// </returns>
|
| 318 |
+
double CalculateThroughputGradient(int fromSetting, int toSetting);
|
| 319 |
+
|
| 320 |
+
/// <summary>
|
| 321 |
+
/// Flushes all measurement histories that are no longer relevant.
|
| 322 |
+
/// </summary>
|
| 323 |
+
void FlushHistories();
|
| 324 |
+
|
| 325 |
+
/// <summary>
|
| 326 |
+
/// Clears all measurement histories.
|
| 327 |
+
/// </summary>
|
| 328 |
+
void ClearHistories();
|
| 329 |
+
|
| 330 |
+
/// <summary>
|
| 331 |
+
/// Gets the history measurement for a given control setting.
|
| 332 |
+
/// </summary>
|
| 333 |
+
/// <returns>
|
| 334 |
+
/// The history measurement.
|
| 335 |
+
/// </returns>
|
| 336 |
+
MeasuredHistory * GetHistory(unsigned int controlSetting);
|
| 337 |
+
|
| 338 |
+
// The maximum number of histories to keep
|
| 339 |
+
static const unsigned int MaxHistoryCount = 64;
|
| 340 |
+
|
| 341 |
+
// The array where history data is kept
|
| 342 |
+
MeasuredHistory m_histories[MaxHistoryCount];
|
| 343 |
+
|
| 344 |
+
// Scheduler proxy to which this hill climbing instance belongs
|
| 345 |
+
SchedulerProxy * m_pSchedulerProxy;
|
| 346 |
+
|
| 347 |
+
// Used to determine the magnitude of moves, in units of (coefficient of variation)/(thread count)
|
| 348 |
+
double m_controlGain;
|
| 349 |
+
|
| 350 |
+
// Maximum number of resources that can be changed in one transition
|
| 351 |
+
unsigned int m_maxControlSettingChange;
|
| 352 |
+
|
| 353 |
+
// The current amount of resources allocated in this hill climbing instance
|
| 354 |
+
unsigned int m_currentControlSetting;
|
| 355 |
+
|
| 356 |
+
// The amount of resources allocated in this hill climbing instance before the last move
|
| 357 |
+
unsigned int m_lastControlSetting;
|
| 358 |
+
|
| 359 |
+
// Scheduler id
|
| 360 |
+
unsigned int m_id;
|
| 361 |
+
|
| 362 |
+
// Number of samples collected
|
| 363 |
+
unsigned long m_sampleCount;
|
| 364 |
+
|
| 365 |
+
// Number of samples collected including invalid samples, across settings
|
| 366 |
+
unsigned long m_totalSampleCount;
|
| 367 |
+
|
| 368 |
+
// Number of consecutive invalid samples
|
| 369 |
+
unsigned long m_invalidCount;
|
| 370 |
+
|
| 371 |
+
// Save sum of completions for consecutive invalid samples
|
| 372 |
+
unsigned int m_saveCompleted;
|
| 373 |
+
|
| 374 |
+
// Save sum of arrivals for consecutive invalid samples
|
| 375 |
+
unsigned int m_saveIncoming;
|
| 376 |
+
|
| 377 |
+
// Determines where the next random move is going
|
| 378 |
+
bool m_nextRandomMoveIsUp;
|
| 379 |
+
|
| 380 |
+
#if defined(CONCRT_TRACING)
|
| 381 |
+
/// <summary>
|
| 382 |
+
/// Logs the hill climbing decision by constructing a CSV dump of data.
|
| 383 |
+
/// </summary>
|
| 384 |
+
/// <param name="recommendedSetting">
|
| 385 |
+
/// The control setting to be established.
|
| 386 |
+
/// </param>
|
| 387 |
+
/// <param name="transition">
|
| 388 |
+
/// The transition that is recommended by hill climbing.
|
| 389 |
+
/// </param>
|
| 390 |
+
/// <param name="numberOfSamples">
|
| 391 |
+
/// The number of sample points in this measurement, including invalid ones.
|
| 392 |
+
/// </param>
|
| 393 |
+
/// <param name="completionRate">
|
| 394 |
+
/// The number of completed units or work in that period of time.
|
| 395 |
+
/// </param>
|
| 396 |
+
/// <param name="arrivalRate">
|
| 397 |
+
/// The number of incoming units or work in that period of time.
|
| 398 |
+
/// </param>
|
| 399 |
+
/// <param name="queueLength">
|
| 400 |
+
/// The total length of the work queue.
|
| 401 |
+
/// </param>
|
| 402 |
+
/// <param name="throughput">
|
| 403 |
+
/// The throughput of the given instance.
|
| 404 |
+
/// </param>
|
| 405 |
+
void LogData(unsigned int recommendedSetting, HillClimbingStateTransition transition, unsigned int numberOfSamples,
|
| 406 |
+
unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength, double throughput);
|
| 407 |
+
#endif
|
| 408 |
+
};
|
| 409 |
+
} // namespace details
|
| 410 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.cpp
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/InternalContextBase.h
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// InternalContextBase.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the base class definition for an internal execution context.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
namespace Concurrency
|
| 16 |
+
{
|
| 17 |
+
namespace details
|
| 18 |
+
{
|
| 19 |
+
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Implements the base class for ConcRT internal contexts.
|
| 22 |
+
/// </summary>
|
| 23 |
+
|
| 24 |
+
#pragma warning(push)
|
| 25 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 26 |
+
class InternalContextBase : public IExecutionContext, public ContextBase
|
| 27 |
+
{
|
| 28 |
+
public:
|
| 29 |
+
|
| 30 |
+
using ContextBase::GetId;
|
| 31 |
+
|
| 32 |
+
//
|
| 33 |
+
// Public methods
|
| 34 |
+
//
|
| 35 |
+
|
| 36 |
+
/// <summary>
|
| 37 |
+
/// Constructs the base class object for an internal context.
|
| 38 |
+
/// </summary>
|
| 39 |
+
InternalContextBase(SchedulerBase *pScheduler);
|
| 40 |
+
|
| 41 |
+
/// <summary>
|
| 42 |
+
/// Causes the internal context to block yielding the virtual processor to a different internal context.
|
| 43 |
+
/// </summary>
|
| 44 |
+
virtual void Block();
|
| 45 |
+
|
| 46 |
+
/// <summary>
|
| 47 |
+
/// Unblocks the internal context putting it on a runnables collection in its schedule group.
|
| 48 |
+
/// </summary>
|
| 49 |
+
virtual void Unblock();
|
| 50 |
+
|
| 51 |
+
/// <summary>
|
| 52 |
+
/// Determines whether or not the context is synchronously blocked at this given time.
|
| 53 |
+
/// </summary>
|
| 54 |
+
/// <returns>
|
| 55 |
+
/// Whether context is in synchronous block state.
|
| 56 |
+
/// </returns>
|
| 57 |
+
virtual bool IsSynchronouslyBlocked() const
|
| 58 |
+
{
|
| 59 |
+
return (m_contextSwitchingFence == 2);
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/// <summary>
|
| 63 |
+
/// Yields the virtual processor to a different runnable internal context if one is found.
|
| 64 |
+
/// </summary>
|
| 65 |
+
virtual void Yield();
|
| 66 |
+
|
| 67 |
+
/// <summary>
|
| 68 |
+
/// Yields the virtual processor to a different runnable internal context if one is found.
|
| 69 |
+
///
|
| 70 |
+
/// This is intended for spin loops.
|
| 71 |
+
/// </summary>
|
| 72 |
+
virtual void SpinYield();
|
| 73 |
+
|
| 74 |
+
/// <summary>
|
| 75 |
+
/// See comments for Concurrency::Context::Oversubscribe.
|
| 76 |
+
/// </summary>
|
| 77 |
+
virtual void Oversubscribe(bool beginOversubscription);
|
| 78 |
+
|
| 79 |
+
/// <summary>
|
| 80 |
+
/// Destroys the base class object for an internal context.
|
| 81 |
+
/// </summary>
|
| 82 |
+
virtual ~InternalContextBase();
|
| 83 |
+
|
| 84 |
+
/// <summary>
|
| 85 |
+
/// Returns an identifier to the virtual processor the context is currently executing on, if any.
|
| 86 |
+
/// </summary>
|
| 87 |
+
virtual unsigned int GetVirtualProcessorId() const;
|
| 88 |
+
|
| 89 |
+
/// <summary>
|
| 90 |
+
/// Toggle the flag that ensures that scheduler is not deleted until adding is completely finished.
|
| 91 |
+
/// </summary>
|
| 92 |
+
/// <param name="value">
|
| 93 |
+
/// The value to set the flag to.
|
| 94 |
+
/// </param>
|
| 95 |
+
void CrossGroupRunnable(LONG value) { m_fCrossGroupRunnable = value; }
|
| 96 |
+
|
| 97 |
+
/// <summary>
|
| 98 |
+
/// Set the value of the oversubscribed virtual processor for a context that invokes Oversubscribe.
|
| 99 |
+
/// </summary>
|
| 100 |
+
void SetOversubscribedVProc(VirtualProcessor * pVirtualProcessor) { m_pOversubscribedVProc = pVirtualProcessor; }
|
| 101 |
+
|
| 102 |
+
/// <summary>
|
| 103 |
+
/// Called to retrieve the oversubscribed vproc and reset it to null.
|
| 104 |
+
/// </summary>
|
| 105 |
+
VirtualProcessor * GetAndResetOversubscribedVProc(VirtualProcessor * pExpectedVirtualProcessor);
|
| 106 |
+
|
| 107 |
+
/// <summary>
|
| 108 |
+
/// Returns a scheduler unique identifier for the context.
|
| 109 |
+
/// </summary>
|
| 110 |
+
/// <returns>
|
| 111 |
+
/// The Id of the context.
|
| 112 |
+
/// </returns>
|
| 113 |
+
virtual unsigned int GetId() const;
|
| 114 |
+
|
| 115 |
+
/// <summary>
|
| 116 |
+
/// Returns the scheduler to which this context belongs.
|
| 117 |
+
/// </summary>
|
| 118 |
+
/// <returns>
|
| 119 |
+
/// The owning scheduler.
|
| 120 |
+
/// </returns>
|
| 121 |
+
virtual IScheduler * GetScheduler();
|
| 122 |
+
|
| 123 |
+
/// <summary>
|
| 124 |
+
/// Returns the thread proxy which is executing this context. Until the Dispatch method has been called on the given
|
| 125 |
+
/// context, this will return NULL. Once the Dispatch method has been called, this returns the IThreadProxy which
|
| 126 |
+
/// was passed into the Dispatch method.
|
| 127 |
+
/// </summary>
|
| 128 |
+
/// <returns>
|
| 129 |
+
/// The thread proxy which dispatched this particular context, otherwise NULL.
|
| 130 |
+
/// </returns>
|
| 131 |
+
virtual IThreadProxy * GetProxy();
|
| 132 |
+
|
| 133 |
+
#if _DEBUG
|
| 134 |
+
// _DEBUG helper
|
| 135 |
+
DWORD GetThreadId() const;
|
| 136 |
+
#endif
|
| 137 |
+
|
| 138 |
+
/// <summary>
|
| 139 |
+
/// Sets the thread proxy which is executing this context. The caller must save this and return it upon a call to the GetProxy method.
|
| 140 |
+
/// Note that the resource manager guarantees stability of the thread proxy while inside the Dispatch method.
|
| 141 |
+
/// </summary>
|
| 142 |
+
/// <param name="pThreadProxy">
|
| 143 |
+
/// The thread proxy which dispatched this particular context.
|
| 144 |
+
/// </param>
|
| 145 |
+
/// <returns>
|
| 146 |
+
/// An indication of success.
|
| 147 |
+
/// </returns>
|
| 148 |
+
virtual void SetProxy(IThreadProxy *pThreadProxy);
|
| 149 |
+
|
| 150 |
+
/// <summary>
|
| 151 |
+
/// The method that is called when a thread proxy starts executing a particular context. The thread proxy which executes
|
| 152 |
+
/// the context is passed into this method and must be saved and returned on a call to the get_Proxy method.
|
| 153 |
+
/// </summary>
|
| 154 |
+
/// <param name="pDispatchState">
|
| 155 |
+
/// The state under which this IExecutionContext is being dispatched.
|
| 156 |
+
/// </param>
|
| 157 |
+
virtual void Dispatch(DispatchState * pDispatchState);
|
| 158 |
+
|
| 159 |
+
/// <summary>
|
| 160 |
+
/// Allocates a block of memory of the size specified.
|
| 161 |
+
/// </summary>
|
| 162 |
+
/// <param name="numBytes">
|
| 163 |
+
/// Number of bytes to allocate.
|
| 164 |
+
/// </param>
|
| 165 |
+
/// <returns>
|
| 166 |
+
/// A pointer to newly allocated memory.
|
| 167 |
+
/// </returns>
|
| 168 |
+
virtual void* Alloc(size_t numBytes);
|
| 169 |
+
|
| 170 |
+
/// <summary>
|
| 171 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 172 |
+
/// </summary>
|
| 173 |
+
/// <param name="pAllocation">
|
| 174 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 175 |
+
/// </param>
|
| 176 |
+
virtual void Free(void* pAllocation);
|
| 177 |
+
|
| 178 |
+
/// <summary>
|
| 179 |
+
/// Swaps the existing schedule group with the one supplied. This function should be called when the context already
|
| 180 |
+
/// has a schedule group. It decrements the existing group reference count, and references the new one if the caller
|
| 181 |
+
/// indicates so.
|
| 182 |
+
/// </summary>
|
| 183 |
+
/// <param name="pNewSegment">
|
| 184 |
+
/// The new group to assign to the context. This may be NULL.
|
| 185 |
+
/// </param>
|
| 186 |
+
/// <param name="referenceNewGroup">
|
| 187 |
+
/// Whether the context should reference the new group. In some cases there may be an existing reference
|
| 188 |
+
/// transferred to the context, in which case this parameter is false.
|
| 189 |
+
/// </param>
|
| 190 |
+
void SwapScheduleGroupSegment(ScheduleGroupSegmentBase* pNewSegment, bool referenceNewGroup = false);
|
| 191 |
+
|
| 192 |
+
/// <summary>
|
| 193 |
+
/// Increments the count of work coming in.
|
| 194 |
+
/// </summary>
|
| 195 |
+
void IncrementEnqueuedTaskCounter()
|
| 196 |
+
{
|
| 197 |
+
m_pVirtualProcessor->m_enqueuedTaskCounter++;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
void IncrementEnqueuedTaskCounterHelper();
|
| 201 |
+
|
| 202 |
+
/// <summary>
|
| 203 |
+
/// Increments the count of work being done.
|
| 204 |
+
/// </summary>
|
| 205 |
+
void IncrementDequeuedTaskCounter()
|
| 206 |
+
{
|
| 207 |
+
m_pVirtualProcessor->m_dequeuedTaskCounter++;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/// <summary>
|
| 211 |
+
/// Increments the count of work being done.
|
| 212 |
+
/// </summary>
|
| 213 |
+
void IncrementDequeuedTaskCounter(unsigned int count)
|
| 214 |
+
{
|
| 215 |
+
m_pVirtualProcessor->m_dequeuedTaskCounter += count;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
void IncrementDequeuedTaskCounterHelper(unsigned int count);
|
| 219 |
+
|
| 220 |
+
/// <summary>
|
| 221 |
+
/// In some cases internal context has not yet received a virtual processor so we have
|
| 222 |
+
/// to save the fact that the work was dequeued and we'll update it in Affinitize.
|
| 223 |
+
/// </summary>
|
| 224 |
+
void SaveDequeuedTask()
|
| 225 |
+
{
|
| 226 |
+
ASSERT(!m_fHasDequeuedTask);
|
| 227 |
+
m_fHasDequeuedTask = true;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
/// <summary>
|
| 231 |
+
/// Notifies that some work was skipped by an iteration of dispatch loop of this context
|
| 232 |
+
/// </summary>
|
| 233 |
+
void NotifyWorkSkipped()
|
| 234 |
+
{
|
| 235 |
+
m_fWorkSkipped = true;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
#if defined(_DEBUG)
|
| 239 |
+
/// <summary>
|
| 240 |
+
/// Gets the debug bits.
|
| 241 |
+
/// </summary>
|
| 242 |
+
DWORD GetDebugBits() const
|
| 243 |
+
{
|
| 244 |
+
return m_ctxDebugBits;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
/// <summary>
|
| 248 |
+
/// Sets a series of internal debugging bits for the context.
|
| 249 |
+
/// </summary>
|
| 250 |
+
/// <param name="bits">
|
| 251 |
+
/// A bitmapped series of CTX_DEBUGBIT_* flags to set within the context.
|
| 252 |
+
/// </param>
|
| 253 |
+
void SetDebugBits(DWORD bits)
|
| 254 |
+
{
|
| 255 |
+
m_ctxDebugBits |= bits;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/// <summary>
|
| 259 |
+
/// Clears a series of internal debugging bits for the context.
|
| 260 |
+
/// </summary>
|
| 261 |
+
/// <param name="bits">
|
| 262 |
+
/// A bitmapped series of CTX_DEBUGBIT_* flags to clear within the context.
|
| 263 |
+
/// </param>
|
| 264 |
+
void ClearDebugBits(DWORD bits)
|
| 265 |
+
{
|
| 266 |
+
m_ctxDebugBits &= ~bits;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
/// <summary>
|
| 270 |
+
/// Completely clears all debug bits.
|
| 271 |
+
/// </summary>
|
| 272 |
+
void ClearDebugBits()
|
| 273 |
+
{
|
| 274 |
+
m_ctxDebugBits = 0;
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
void NotifyAcquired()
|
| 278 |
+
{
|
| 279 |
+
m_lastAcquiredTid = GetCurrentThreadId();
|
| 280 |
+
}
|
| 281 |
+
#endif // _DEBUG
|
| 282 |
+
|
| 283 |
+
/// <summary>
|
| 284 |
+
/// Returns whether the context is in the idle pool or not. Finalization will call this during the sweep phase to
|
| 285 |
+
// determine all the blocked contexts. A context in the idle pool is considered "not blocked".
|
| 286 |
+
/// </summary>
|
| 287 |
+
bool IsIdle() const
|
| 288 |
+
{
|
| 289 |
+
return m_fIdle;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
/// <summary>
|
| 293 |
+
/// Prepare a context for execution by associating a scheduler group/chore with it. Scheduler
|
| 294 |
+
// shall call this routine before executing an internal context
|
| 295 |
+
/// </summary>
|
| 296 |
+
void PrepareForUse(ScheduleGroupSegmentBase* pSegment, _Chore *pChore, bool choreStolen);
|
| 297 |
+
|
| 298 |
+
/// <summary>
|
| 299 |
+
/// Returns whether the context is prepared for execution or must be initialized prior to use. An unprepared context
|
| 300 |
+
/// must be initialized via PrepareForUse().
|
| 301 |
+
/// </summary>
|
| 302 |
+
bool IsPrepared() const
|
| 303 |
+
{
|
| 304 |
+
return (m_pSegment != NULL);
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
/// <summary>
|
| 308 |
+
/// Remove a context from execution by dis-associating it from any scheduler group/chore.
|
| 309 |
+
/// </summary>
|
| 310 |
+
void RemoveFromUse();
|
| 311 |
+
|
| 312 |
+
protected:
|
| 313 |
+
|
| 314 |
+
//
|
| 315 |
+
// Protected types
|
| 316 |
+
//
|
| 317 |
+
|
| 318 |
+
enum ReasonForSwitch
|
| 319 |
+
{
|
| 320 |
+
GoingIdle,
|
| 321 |
+
Blocking,
|
| 322 |
+
Yielding,
|
| 323 |
+
Nesting
|
| 324 |
+
};
|
| 325 |
+
|
| 326 |
+
//
|
| 327 |
+
// Protected data members
|
| 328 |
+
//
|
| 329 |
+
|
| 330 |
+
// The thread proxy that is executing this context's dispatch loop, if any.
|
| 331 |
+
IThreadProxy * volatile m_pThreadProxy; // 4/8
|
| 332 |
+
|
| 333 |
+
//
|
| 334 |
+
// Protected methods
|
| 335 |
+
//
|
| 336 |
+
|
| 337 |
+
/// <summary>
|
| 338 |
+
/// Spins until the 'this' context is in a firmly blocked state
|
| 339 |
+
/// </summary>
|
| 340 |
+
void SpinUntilBlocked();
|
| 341 |
+
|
| 342 |
+
/// <summary>
|
| 343 |
+
/// Adds the context to a runnables collection, either on the virtual processor, or the schedule group
|
| 344 |
+
/// </summary>
|
| 345 |
+
/// <param name="bias">
|
| 346 |
+
/// A location specifying where to bias the awakening of virtual processors to.
|
| 347 |
+
/// </param>
|
| 348 |
+
virtual void AddToRunnables(location bias = location());
|
| 349 |
+
|
| 350 |
+
/// <summary>
|
| 351 |
+
/// Switches from one internal context to another.
|
| 352 |
+
/// </summary>
|
| 353 |
+
void SwitchTo(InternalContextBase* pContext, ReasonForSwitch reason);
|
| 354 |
+
|
| 355 |
+
/// <summary>
|
| 356 |
+
/// Switches out the internal context. Useful when the virtual processor is to be retired.
|
| 357 |
+
/// Is also used when un-nesting a scheduler and the context is returning to its original scheduler.
|
| 358 |
+
/// </summary>
|
| 359 |
+
/// <param name="reason">
|
| 360 |
+
/// The reason for switching out of this vproc
|
| 361 |
+
/// </param>
|
| 362 |
+
/// <returns>
|
| 363 |
+
/// True if the context has been canceled.
|
| 364 |
+
/// </returns>
|
| 365 |
+
bool SwitchOut(ReasonForSwitch reason);
|
| 366 |
+
|
| 367 |
+
/// <summary>
|
| 368 |
+
/// Cancels the context, causing it to exit the dispatch loop if it is executing on a virtual processor
|
| 369 |
+
/// </summary>
|
| 370 |
+
virtual void Cancel();
|
| 371 |
+
|
| 372 |
+
/// <summary>
|
| 373 |
+
/// If internal context does not own this virtual processor then claim it back. This might require
|
| 374 |
+
/// waiting until it becomes available.
|
| 375 |
+
/// </summary>
|
| 376 |
+
void ReclaimVirtualProcessor();
|
| 377 |
+
|
| 378 |
+
/// <summary>
|
| 379 |
+
/// This function is called to execute the associated chore if one is available. The chore can be a stolen unrealized
|
| 380 |
+
/// chore or realized chore.
|
| 381 |
+
/// </summary>
|
| 382 |
+
/// <returns>
|
| 383 |
+
/// Returns true if an associated chore was executed, false otherwise.
|
| 384 |
+
/// </returns>
|
| 385 |
+
bool ExecutedAssociatedChore();
|
| 386 |
+
|
| 387 |
+
/// <summary>
|
| 388 |
+
/// Performs the necessary cleanup for a canceled context in its dispatch routine.
|
| 389 |
+
/// <summary>
|
| 390 |
+
void CleanupDispatchedContextOnCancel();
|
| 391 |
+
|
| 392 |
+
/// <summary>
|
| 393 |
+
/// Called in the dispatch loop to check if the virtual processor the context is running on is marked for retirement,
|
| 394 |
+
/// and retires the virtual processor if it is.
|
| 395 |
+
/// <summary>
|
| 396 |
+
/// <returns>
|
| 397 |
+
/// True if the virtual processor was retired, false otherwise.
|
| 398 |
+
/// </returns>
|
| 399 |
+
bool IsVirtualProcessorRetired();
|
| 400 |
+
|
| 401 |
+
/// <summary>
|
| 402 |
+
/// Searches for work using the search algorithm specified by the scheduler's policy. Also prepares the context to execute
|
| 403 |
+
/// work by reclaiming the virtual processor if necessary.
|
| 404 |
+
/// </summary>
|
| 405 |
+
/// <param name=pWork>
|
| 406 |
+
/// A pointer to a work item which is filled in if work was found.
|
| 407 |
+
/// </param>
|
| 408 |
+
/// <returns>
|
| 409 |
+
/// True if work was found, false otherwise.
|
| 410 |
+
/// </returns>
|
| 411 |
+
bool WorkWasFound(WorkItem * pWork);
|
| 412 |
+
|
| 413 |
+
/// <summary>
|
| 414 |
+
/// Switches to the runnable context represented by the work item.
|
| 415 |
+
/// </summary>
|
| 416 |
+
/// <param name=pWork>
|
| 417 |
+
/// A pointer to a work item to be executed.
|
| 418 |
+
/// </param>
|
| 419 |
+
void SwitchToRunnableContext(WorkItem * pWork);
|
| 420 |
+
|
| 421 |
+
/// <summary>
|
| 422 |
+
/// Executes the chore (realized or unrealized) specified by the work item.
|
| 423 |
+
/// </summary>
|
| 424 |
+
/// <param name=pWork>
|
| 425 |
+
/// A pointer to a work item that represents a realized or unrealized chore.
|
| 426 |
+
/// </param>
|
| 427 |
+
void ExecuteChoreInline(WorkItem * pWork);
|
| 428 |
+
|
| 429 |
+
/// <summary>
|
| 430 |
+
/// This method implements the wait-for-work and cancellation protocol.
|
| 431 |
+
/// </summary>
|
| 432 |
+
void WaitForWork(void);
|
| 433 |
+
|
| 434 |
+
/// <summary>
|
| 435 |
+
/// Performs cleanup of the internal thread context.
|
| 436 |
+
/// </summary>
|
| 437 |
+
void Cleanup();
|
| 438 |
+
|
| 439 |
+
/// <summary>
|
| 440 |
+
/// Called before this executes on a given virtual processor.
|
| 441 |
+
/// </summary>
|
| 442 |
+
virtual void PrepareToRun(VirtualProcessor *pVProc)
|
| 443 |
+
{
|
| 444 |
+
#if defined(_DEBUG)
|
| 445 |
+
m_lastRunPrepareTimeStamp = _ReadTimeStampCounter();
|
| 446 |
+
m_prepareCount++;
|
| 447 |
+
m_lastAffinitizedTid = GetCurrentThreadId();
|
| 448 |
+
#endif // _DEBUG
|
| 449 |
+
m_pVirtualProcessor = pVProc;
|
| 450 |
+
CONCRT_COREASSERT(m_pSegment != NULL);
|
| 451 |
+
InterlockedExchange(&m_blockedState, CONTEXT_NOT_BLOCKED);
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// Virtual processor the context is executing on.
|
| 455 |
+
#if defined(_DEBUG)
|
| 456 |
+
void _PutVirtualProcessor(VirtualProcessor *pVirtualProcessor)
|
| 457 |
+
{
|
| 458 |
+
//
|
| 459 |
+
// If this assertion fires, someone is changing m_pVirtualProcessor outside a critical region. Doing this violates safety
|
| 460 |
+
// on a UMS scheduler. m_pVirtualProcessor is not guaranteed to be stable on a UMS context. All manipulation must happen
|
| 461 |
+
// inside a critical region.
|
| 462 |
+
//
|
| 463 |
+
CONCRT_COREASSERT(_m_pVirtualProcessor == NULL || IsInsideCriticalRegion());
|
| 464 |
+
_m_pVirtualProcessor = pVirtualProcessor;
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
VirtualProcessor *_GetVirtualProcessor() const
|
| 468 |
+
{
|
| 469 |
+
//
|
| 470 |
+
// If this assertion fires, someone is examining m_pVirtualProcessor outside a critical region. Doing this violates safety
|
| 471 |
+
// on a UMS scheduler. m_pVirtualProcessor is not guaranteed to be stable on a UMS context. All manipulation must happen
|
| 472 |
+
// inside a critical region.
|
| 473 |
+
//
|
| 474 |
+
CONCRT_COREASSERT(_m_pVirtualProcessor == NULL || IsInsideCriticalRegion());
|
| 475 |
+
return _m_pVirtualProcessor;
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
__declspec(property(get=_GetVirtualProcessor, put=_PutVirtualProcessor)) VirtualProcessor *m_pVirtualProcessor;
|
| 479 |
+
VirtualProcessor * volatile _m_pVirtualProcessor;
|
| 480 |
+
|
| 481 |
+
VirtualProcessor *UNSAFE_CurrentVirtualProcessor() const
|
| 482 |
+
{
|
| 483 |
+
return _m_pVirtualProcessor;
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
void UNSAFE_SetVirtualProcessor(VirtualProcessor *pVirtualProcessor)
|
| 487 |
+
{
|
| 488 |
+
_m_pVirtualProcessor = pVirtualProcessor;
|
| 489 |
+
}
|
| 490 |
+
#else
|
| 491 |
+
VirtualProcessor * volatile m_pVirtualProcessor;
|
| 492 |
+
|
| 493 |
+
VirtualProcessor *UNSAFE_CurrentVirtualProcessor() const
|
| 494 |
+
{
|
| 495 |
+
return m_pVirtualProcessor;
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
void UNSAFE_SetVirtualProcessor(VirtualProcessor *pVirtualProcessor)
|
| 499 |
+
{
|
| 500 |
+
m_pVirtualProcessor = pVirtualProcessor;
|
| 501 |
+
}
|
| 502 |
+
#endif
|
| 503 |
+
|
| 504 |
+
private:
|
| 505 |
+
friend class ExternalContextBase;
|
| 506 |
+
friend class SchedulerBase;
|
| 507 |
+
friend class ThreadScheduler;
|
| 508 |
+
friend class VirtualProcessor;
|
| 509 |
+
friend class SchedulingRing;
|
| 510 |
+
friend class location;
|
| 511 |
+
template <typename T> friend class Mailbox;
|
| 512 |
+
template <class T, class Counter> friend class Stack;
|
| 513 |
+
template <typename T> friend class SQueue;
|
| 514 |
+
|
| 515 |
+
// This helper is used to avoid circular reference:
|
| 516 |
+
// Mailbox -> InternalContextBase -> ContextBase -> WorkStealingQueue -> Mailbox
|
| 517 |
+
friend unsigned int GetProcessorMaskId(InternalContextBase * pContext);
|
| 518 |
+
|
| 519 |
+
//
|
| 520 |
+
// Private data
|
| 521 |
+
//
|
| 522 |
+
|
| 523 |
+
// Pointer to an oversubscribed virtual processor if one is present.
|
| 524 |
+
VirtualProcessor * volatile m_pOversubscribedVProc;
|
| 525 |
+
|
| 526 |
+
// Chore associated with the context - this could be a realized chore or a stolen chore. The chore is associated with the context
|
| 527 |
+
// 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
|
| 528 |
+
// before it starts looking for other work. This is used for indirect aliasing of unstructured task collections.
|
| 529 |
+
_Chore *m_pAssociatedChore;
|
| 530 |
+
|
| 531 |
+
// Counter that indicates how many times the internal context has spun waiting for work.
|
| 532 |
+
unsigned int m_searchCount;
|
| 533 |
+
|
| 534 |
+
// Flag that indicates whether the internal context is canceled.
|
| 535 |
+
volatile bool m_fCanceled;
|
| 536 |
+
|
| 537 |
+
// Flag that indicates whether the associated chore is a stolen unrealized chore or a realized chore.
|
| 538 |
+
bool m_fAssociatedChoreStolen{};
|
| 539 |
+
|
| 540 |
+
// Flag that indicates whether internal context is in the final search for work state.
|
| 541 |
+
bool m_fIsVisibleVirtualProcessor;
|
| 542 |
+
|
| 543 |
+
// Flag that indicates whether internal context has dequeued a piece of work without being able
|
| 544 |
+
// to immediately update the statistics numbers on a virtual processor (it was not affinitized).
|
| 545 |
+
bool m_fHasDequeuedTask : 1;
|
| 546 |
+
|
| 547 |
+
// Indicates that some work was skipped in the dispatch loop. Currently, this is set if we failed to check some of the work stealing
|
| 548 |
+
// queues due to in-progress task collection cancellation.
|
| 549 |
+
bool m_fWorkSkipped : 1;
|
| 550 |
+
|
| 551 |
+
// Debugging purposes: this informs whether the context was *EVER* put on a free list or whether it is a fresh context.
|
| 552 |
+
bool m_fEverRecycled : 1;
|
| 553 |
+
|
| 554 |
+
// Debug information (particularly useful for UMS)
|
| 555 |
+
|
| 556 |
+
//
|
| 557 |
+
// Time logging for forward progress determinations.
|
| 558 |
+
//
|
| 559 |
+
__int64 m_workStartTimeStamp{};
|
| 560 |
+
__int64 m_lastRunPrepareTimeStamp{};
|
| 561 |
+
DWORD m_prepareCount{};
|
| 562 |
+
|
| 563 |
+
DWORD m_ctxDebugBits{};
|
| 564 |
+
|
| 565 |
+
// The last TID this context was dispatched on. You can normally get this from m_pThreadProxy.
|
| 566 |
+
DWORD m_lastDispatchedTid{};
|
| 567 |
+
|
| 568 |
+
// The last TID this context was acquired/created on.
|
| 569 |
+
DWORD m_lastAcquiredTid{};
|
| 570 |
+
|
| 571 |
+
// The last TID this context was affinitized on.
|
| 572 |
+
DWORD m_lastAffinitizedTid{};
|
| 573 |
+
|
| 574 |
+
//
|
| 575 |
+
// Tracks the last assigned thread proxy (normally the same as m_pThreadProxy) -- but may not be for recycled contexts.
|
| 576 |
+
//
|
| 577 |
+
IThreadProxy *m_pAssignedThreadProxy{};
|
| 578 |
+
IThreadProxy *m_pLastAssignedThreadProxy{};
|
| 579 |
+
|
| 580 |
+
// A flag that is used by contexts adding runnables to a scheduler. When those contexts (the ones performing the add)
|
| 581 |
+
// do not implicitly have a reference to the schedule group the runnable belongs to, setting this flag on the runnable
|
| 582 |
+
// context they are adding to the scheduler's queues, ensures that the group does not get destroyed and the scheduler
|
| 583 |
+
// does not get finalized while they are touching scheduler/schedule group data.
|
| 584 |
+
volatile LONG m_fCrossGroupRunnable;
|
| 585 |
+
|
| 586 |
+
// Intrusive next pointer for SafeSQueue.
|
| 587 |
+
InternalContextBase *m_pNext{};
|
| 588 |
+
|
| 589 |
+
// Flag that indicates whether the internal context is in the idle pool or not
|
| 590 |
+
volatile bool m_fIdle;
|
| 591 |
+
|
| 592 |
+
//
|
| 593 |
+
// Private methods
|
| 594 |
+
//
|
| 595 |
+
|
| 596 |
+
/// <summary>
|
| 597 |
+
/// Called to find work to switch to, when the current context needs to block or nest a different scheduler.
|
| 598 |
+
/// The function may return NULL if no work was found and thread creation was disallowed by the thread
|
| 599 |
+
/// throttler.
|
| 600 |
+
/// </summary>
|
| 601 |
+
InternalContextBase* FindWorkForBlockingOrNesting(bool& fSFWContext, bool& fBoundUnrealized);
|
| 602 |
+
|
| 603 |
+
/// <summary>
|
| 604 |
+
/// Called when a context is nesting a scheduler. If nesting takes place on what is an internal context in
|
| 605 |
+
/// the 'parent' scheduler, the context must return the virtual processor to the parent scheduler.
|
| 606 |
+
/// </summary>
|
| 607 |
+
void LeaveScheduler();
|
| 608 |
+
|
| 609 |
+
/// <summary>
|
| 610 |
+
/// Called when a context is un-nesting a scheduler. If the parent context is an internal context, it needs
|
| 611 |
+
/// to rejoin the parent scheduler by looking for a virtual processor it can execute on.
|
| 612 |
+
/// </summary>
|
| 613 |
+
void RejoinScheduler();
|
| 614 |
+
|
| 615 |
+
/// <summary>
|
| 616 |
+
/// Called when the RM wakes up the thread for some reason.
|
| 617 |
+
/// </summary>
|
| 618 |
+
virtual void RMAwaken()
|
| 619 |
+
{
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
};
|
| 623 |
+
|
| 624 |
+
unsigned int GetProcessorMaskId(InternalContextBase* pContext);
|
| 625 |
+
#pragma warning(pop)
|
| 626 |
+
} // namespace details
|
| 627 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Mailbox.h
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
#define SLOT_PENDING_EXPIRY 1
|
| 17 |
+
#define FIELD_RESERVED 1
|
| 18 |
+
|
| 19 |
+
namespace Concurrency
|
| 20 |
+
{
|
| 21 |
+
namespace details
|
| 22 |
+
{
|
| 23 |
+
// This helper is used to avoid circular reference:
|
| 24 |
+
// Mailbox -> InternalContextBase -> ContextBase -> WorkStealingQueue -> Mailbox
|
| 25 |
+
unsigned int GetProcessorMaskId(InternalContextBase * pContext);
|
| 26 |
+
|
| 27 |
+
// *** NOTES ***
|
| 28 |
+
//
|
| 29 |
+
// 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,
|
| 30 |
+
// associated with a given schedule group segment and hence has a natural affinity. This presents an interesting semantic with respect to work
|
| 31 |
+
// stealing tasks scheduled from that context. Imagine:
|
| 32 |
+
//
|
| 33 |
+
// CONTEXT A (affinity locA)
|
| 34 |
+
//
|
| 35 |
+
// tg.run(lambda1);
|
| 36 |
+
// tg.run(lambda2, loc2);
|
| 37 |
+
// tg.run(lambda3, loc3);
|
| 38 |
+
// tg.run(lambda4, loc4);
|
| 39 |
+
// tg.run(lambda5, loc5);
|
| 40 |
+
// tg.wait();
|
| 41 |
+
//
|
| 42 |
+
// In this circumstance, lambda1 through lambda5 are pushed onto the work stealing queue associated with CONTEXT A. Because context A has an associated
|
| 43 |
+
// 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
|
| 44 |
+
// tasks lambda2 through lambda5 are scheduled, the caller has requested that, if stolen, those tasks run on locations other than the natural affinity
|
| 45 |
+
// of the work stealing queue. In order to accommodate this in a work stealing scheduler, we mail lambda2 through lambda5 to a mailbox.
|
| 46 |
+
// The mailbox will be contained within a segment with affinity loc2, loc3, ..., loc5 within the schedule *GROUP* of CONTEXT A.
|
| 47 |
+
//
|
| 48 |
+
// This means that tasks lambda2 through lambda5 will be contained in two places in the scheduler simultaneously:
|
| 49 |
+
//
|
| 50 |
+
// - On the work stealing queue for context A (which has natural affinity to locA)
|
| 51 |
+
// - On a mailbox within the group of context A with affinity loc*
|
| 52 |
+
//
|
| 53 |
+
// 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,
|
| 54 |
+
// 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.
|
| 55 |
+
//
|
| 56 |
+
// 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
|
| 57 |
+
// 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
|
| 58 |
+
// which is scheduled to a (structured_)task_group has lifetime which is managed by the caller.
|
| 59 |
+
//
|
| 60 |
+
// 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
|
| 61 |
+
// 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
|
| 62 |
+
// 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
|
| 63 |
+
// for the given WSQ chore. The "slot" is Mailbox<T>::Slot. The chore cannot be touched until ClaimSlot is called successfully. The mailbox can do
|
| 64 |
+
// whatever is necessary under the covers to implement this interface.
|
| 65 |
+
//
|
| 66 |
+
|
| 67 |
+
//
|
| 68 |
+
// At present, there are some rather subtle lifetime rules about mailboxes and the objects which actually manage their storage.
|
| 69 |
+
//
|
| 70 |
+
// - A mailbox is bound to the lifetime of a schedule group segment. Mailboxes have two sub-objects: slots and segments. Both of these objects
|
| 71 |
+
// can outlive the mailbox!
|
| 72 |
+
//
|
| 73 |
+
// - 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
|
| 74 |
+
// returns, the slot is invalid. Calling a method on it again will result in undefined behavior.
|
| 75 |
+
//
|
| 76 |
+
// - 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
|
| 77 |
+
// of allocation. Excepting the amortized allocation, a mailbox is lock-free (though not wait-free). Mailbox segments have an implicit reference on them
|
| 78 |
+
// 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
|
| 79 |
+
// Dequeue code extra safety. This implies that Dequeue operations on a mailbox must happen on an internal context within a critical region.
|
| 80 |
+
//
|
| 81 |
+
|
| 82 |
+
//
|
| 83 |
+
/// <summary>
|
| 84 |
+
/// A lock-free fixed size FIFO of tasks associated with a particular object. The mailbox is typically used
|
| 85 |
+
/// for work stealing tasks affine to a particular location.
|
| 86 |
+
/// </summary>
|
| 87 |
+
template<typename T>
|
| 88 |
+
class Mailbox
|
| 89 |
+
{
|
| 90 |
+
private:
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Represents a segment of a mailbox which contains a fixed number of slots.
|
| 94 |
+
/// </summary>
|
| 95 |
+
struct Segment
|
| 96 |
+
{
|
| 97 |
+
/// <summary>
|
| 98 |
+
/// Constructs a new segment.
|
| 99 |
+
/// </summary>
|
| 100 |
+
Segment(SchedulerBase *pScheduler, const QuickBitSet &affinitySet, unsigned int size, unsigned int baseIdx) :
|
| 101 |
+
m_pScheduler(pScheduler), m_affinitySet(affinitySet), m_baseIdx(baseIdx), m_refs(0), m_pNext(NULL)
|
| 102 |
+
{
|
| 103 |
+
m_pQueue = _concrt_new T* volatile [size];
|
| 104 |
+
memset((void*)(m_pQueue), 0, sizeof(T* volatile) * size);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
/// <summary>
|
| 108 |
+
/// Destroys a segment.
|
| 109 |
+
/// </summary>
|
| 110 |
+
~Segment()
|
| 111 |
+
{
|
| 112 |
+
delete[] m_pQueue;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
bool AllSlotsClaimed(unsigned int count)
|
| 116 |
+
{
|
| 117 |
+
// Note that if this segment has already had its deletion refs set after all slots were claimed, this will
|
| 118 |
+
// return false. However, for the purpose we are using it for (deciding whether or not to set deletion refs),
|
| 119 |
+
// this is not a problem.
|
| 120 |
+
return (m_refs + count == 0);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/// <summary>
|
| 124 |
+
/// Removes a reference from the segment.
|
| 125 |
+
/// </summary>
|
| 126 |
+
void Dereference()
|
| 127 |
+
{
|
| 128 |
+
if (static_cast<unsigned int>(InterlockedDecrement(reinterpret_cast<volatile long *>(&m_refs))) == 0)
|
| 129 |
+
Expire();
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// Expires a segment.
|
| 134 |
+
/// </summary>
|
| 135 |
+
void Expire()
|
| 136 |
+
{
|
| 137 |
+
//
|
| 138 |
+
// 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
|
| 139 |
+
// operations in search-for-work at ANY point. As such, the deletion gets deferred to the scheduler's next safe point.
|
| 140 |
+
//
|
| 141 |
+
// This also guards against two Dequeuers (which are only on internal contexts during critical regions) from touching freed memory in
|
| 142 |
+
// locating their segment. Enqueues are guarded with a different mechanism.
|
| 143 |
+
//
|
| 144 |
+
m_deletionSafePoint.InvokeAtNextSafePoint(reinterpret_cast<SafePointInvocation::InvocationFunction>(&Segment::StaticDelete),
|
| 145 |
+
reinterpret_cast<void *>(this),
|
| 146 |
+
m_pScheduler);
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/// <summary>
|
| 150 |
+
/// Marks how many dereferences must happen before the segment can delete itself.
|
| 151 |
+
/// </summary>
|
| 152 |
+
void SetDeletionReferences(unsigned int count)
|
| 153 |
+
{
|
| 154 |
+
if ((static_cast<unsigned int>(InterlockedExchangeAdd(reinterpret_cast<volatile long *>(&m_refs), count)) + count) == 0)
|
| 155 |
+
Expire();
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// <summary>
|
| 159 |
+
/// Safe point routine to delete a segment.
|
| 160 |
+
/// </summary>
|
| 161 |
+
static void StaticDelete(Segment *pSegment)
|
| 162 |
+
{
|
| 163 |
+
delete pSegment;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
// The scheduler to which the segment belongs.
|
| 167 |
+
SchedulerBase *m_pScheduler;
|
| 168 |
+
|
| 169 |
+
// The affinity of the segment.
|
| 170 |
+
QuickBitSet m_affinitySet;
|
| 171 |
+
|
| 172 |
+
// The queue of objects within the segment.
|
| 173 |
+
T* volatile * m_pQueue;
|
| 174 |
+
|
| 175 |
+
// The base index of the segment.
|
| 176 |
+
unsigned int m_baseIdx;
|
| 177 |
+
|
| 178 |
+
// The number of references remaining on the segment.
|
| 179 |
+
volatile unsigned int m_refs;
|
| 180 |
+
|
| 181 |
+
// The next segment within the mailbox.
|
| 182 |
+
Segment * m_pNext;
|
| 183 |
+
|
| 184 |
+
// The safe point at which the segment will be deleted.
|
| 185 |
+
SafePointInvocation m_deletionSafePoint;
|
| 186 |
+
};
|
| 187 |
+
|
| 188 |
+
public:
|
| 189 |
+
|
| 190 |
+
/// <summary>
|
| 191 |
+
/// An opaque handle to a slot of a mailbox. When an object is enqueued in the mailbox, a slot is returned. If the item
|
| 192 |
+
/// is placed on another list, the slot must be claimed before the object is utilized.
|
| 193 |
+
/// </summary>
|
| 194 |
+
class Slot
|
| 195 |
+
{
|
| 196 |
+
public:
|
| 197 |
+
|
| 198 |
+
Slot() : m_pSegment(NULL), m_relativeIdx(0)
|
| 199 |
+
{
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
Slot(const Slot& src) : m_pSegment(src.m_pSegment), m_relativeIdx(src.m_relativeIdx)
|
| 203 |
+
{
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
Slot& operator=(const Slot& rhs)
|
| 207 |
+
{
|
| 208 |
+
m_pSegment = rhs.m_pSegment;
|
| 209 |
+
m_relativeIdx = rhs.m_relativeIdx;
|
| 210 |
+
|
| 211 |
+
return *this;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
bool IsEmpty() const
|
| 215 |
+
{
|
| 216 |
+
return m_pSegment == NULL;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// <summary>
|
| 220 |
+
/// Claims an object from a slot in an out-of-order and thread-safe manner. If true is returned, this indicates that
|
| 221 |
+
/// the caller has exclusive ownership of the object within that slot.
|
| 222 |
+
/// </summary>
|
| 223 |
+
bool Claim(T ** pClaimedObject = nullptr)
|
| 224 |
+
{
|
| 225 |
+
T* pObject = m_pSegment->m_pQueue[m_relativeIdx];
|
| 226 |
+
ASSERT(pObject != NULL);
|
| 227 |
+
|
| 228 |
+
if (pObject != reinterpret_cast<T*>(SLOT_PENDING_EXPIRY))
|
| 229 |
+
{
|
| 230 |
+
T* pXchgObject = reinterpret_cast<T*>(
|
| 231 |
+
InterlockedExchangePointer(reinterpret_cast<void * volatile *>(m_pSegment->m_pQueue + m_relativeIdx),
|
| 232 |
+
reinterpret_cast<void *>(SLOT_PENDING_EXPIRY)));
|
| 233 |
+
|
| 234 |
+
if (pXchgObject == pObject)
|
| 235 |
+
{
|
| 236 |
+
if (pClaimedObject)
|
| 237 |
+
*pClaimedObject = pObject;
|
| 238 |
+
return true;
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
m_pSegment->Dereference();
|
| 244 |
+
|
| 245 |
+
return false;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
bool DeferToAffineSearchers() const
|
| 249 |
+
{
|
| 250 |
+
InternalContextBase * pContext = static_cast<InternalContextBase *>(SchedulerBase::FastCurrentContext());
|
| 251 |
+
return (m_pSegment->m_pScheduler->HasSearchers(m_pSegment->m_affinitySet) &&
|
| 252 |
+
!m_pSegment->m_affinitySet.IsSet(GetProcessorMaskId(pContext)));
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
private:
|
| 256 |
+
|
| 257 |
+
friend class Mailbox;
|
| 258 |
+
|
| 259 |
+
Slot(Segment *pSegment, unsigned int relativeIdx) : m_pSegment(pSegment), m_relativeIdx(relativeIdx)
|
| 260 |
+
{
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
Segment *m_pSegment;
|
| 264 |
+
unsigned int m_relativeIdx;
|
| 265 |
+
|
| 266 |
+
};
|
| 267 |
+
|
| 268 |
+
/// <summary>
|
| 269 |
+
/// Constructs a new mailbox with the specified segment size.
|
| 270 |
+
/// </summary>
|
| 271 |
+
/// <param name="pScheduler">
|
| 272 |
+
/// The scheduler to which this mailbox belongs.
|
| 273 |
+
/// </param>
|
| 274 |
+
/// <param name="fDeferAlloc">
|
| 275 |
+
/// Indicates whether or not to defer allocation of the first segment until the first enqueue.
|
| 276 |
+
/// </param>
|
| 277 |
+
/// <param name="segmentSize">
|
| 278 |
+
/// The size of the mailbox. Note that the mailbox size is fixed once constructed.
|
| 279 |
+
/// </param>
|
| 280 |
+
|
| 281 |
+
Mailbox(SchedulerBase *pScheduler, const QuickBitSet&, bool fDeferAlloc = false, unsigned int segmentSize = s_segmentSize)
|
| 282 |
+
: m_pScheduler(pScheduler)
|
| 283 |
+
, m_segmentSize(segmentSize)
|
| 284 |
+
, m_pTailSegment(NULL)
|
| 285 |
+
, m_pHeadSegment(NULL)
|
| 286 |
+
, m_head(0)
|
| 287 |
+
, m_tail(0)
|
| 288 |
+
{
|
| 289 |
+
ASSERT((segmentSize & (segmentSize - 1)) == 0);
|
| 290 |
+
|
| 291 |
+
Initialize(m_affinitySet);
|
| 292 |
+
|
| 293 |
+
if (!fDeferAlloc)
|
| 294 |
+
{
|
| 295 |
+
m_pTailSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, segmentSize, 0);
|
| 296 |
+
m_pHeadSegment = m_pTailSegment;
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/// <summary>
|
| 301 |
+
/// Destroys a mailbox.
|
| 302 |
+
/// </summary>
|
| 303 |
+
~Mailbox()
|
| 304 |
+
{
|
| 305 |
+
Segment *pSegment = m_pHeadSegment;
|
| 306 |
+
while (pSegment != NULL)
|
| 307 |
+
{
|
| 308 |
+
Segment *pNextSegment = pSegment->m_pNext;
|
| 309 |
+
|
| 310 |
+
if (pSegment != m_pTailSegment)
|
| 311 |
+
pSegment->SetDeletionReferences(m_segmentSize);
|
| 312 |
+
else
|
| 313 |
+
{
|
| 314 |
+
//
|
| 315 |
+
// How many items are in this segment? That is how many must dereference the segment in order for its memory to be freed.
|
| 316 |
+
// Set this number. Note that this should *ONLY* be for the tail segment.
|
| 317 |
+
//
|
| 318 |
+
unsigned int numElements = m_tail - pSegment->m_baseIdx;
|
| 319 |
+
ASSERT(numElements <= m_segmentSize);
|
| 320 |
+
|
| 321 |
+
pSegment->SetDeletionReferences(numElements);
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
pSegment = pNextSegment;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
/// <summary>
|
| 330 |
+
/// Initializes key fields of the mailbox.
|
| 331 |
+
/// </summary>
|
| 332 |
+
void Initialize(const QuickBitSet& bitSet)
|
| 333 |
+
{
|
| 334 |
+
m_affinitySet = bitSet;
|
| 335 |
+
if (m_pHeadSegment)
|
| 336 |
+
m_pHeadSegment->m_affinitySet = bitSet;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
/// <summary>
|
| 340 |
+
/// Enqueues an object onto the mailbox and returns a pointer to the slot if the enqueue is successful. Note that
|
| 341 |
+
/// the Slot object may only be used in methods on the mailbox.
|
| 342 |
+
/// </summary>
|
| 343 |
+
/// <param name="pObject">
|
| 344 |
+
/// The object to enqueue.
|
| 345 |
+
/// </param>
|
| 346 |
+
Slot Enqueue(T* pObject)
|
| 347 |
+
{
|
| 348 |
+
//
|
| 349 |
+
// Complete the pushes in order to avoid LocateMailboxSegment touching an invalid segment when an enqueue crosses a boundary in conjunction
|
| 350 |
+
// with a dequeue/claim -> free.
|
| 351 |
+
//
|
| 352 |
+
m_enqueueLock._Acquire();
|
| 353 |
+
|
| 354 |
+
Segment *pSegment = LocateMailboxSegment(m_tail, true);
|
| 355 |
+
|
| 356 |
+
unsigned int relativeIdx = m_tail - pSegment->m_baseIdx;
|
| 357 |
+
pSegment->m_pQueue[relativeIdx] = pObject;
|
| 358 |
+
|
| 359 |
+
// The Dequeue function will calculate the number of available messages based on m_tail.
|
| 360 |
+
// This memory fence will flush new m_tail to Dequeue. Be attention that there is no fence in the last lock release function.
|
| 361 |
+
// If the write to m_tail is observed by the Dequeue, all write operations before this point must be observed by Dequeue as well.
|
| 362 |
+
_InterlockedIncrement(reinterpret_cast<volatile long *>(&m_tail));
|
| 363 |
+
|
| 364 |
+
m_enqueueLock._Release();
|
| 365 |
+
return Slot(pSegment, relativeIdx);
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
/// <summary>
|
| 369 |
+
/// Dequeues an object from the mailbox.
|
| 370 |
+
/// </summary>
|
| 371 |
+
/// <param name="pDequeuedElement">
|
| 372 |
+
/// If the dequeue is successful, the dequeued element will be placed here.
|
| 373 |
+
/// </param>
|
| 374 |
+
///
|
| 375 |
+
bool Dequeue(T **pDequeuedElement)
|
| 376 |
+
{
|
| 377 |
+
//
|
| 378 |
+
// Keep dequeueing until we either get something or the queue is empty. We may dequeue a slot pending expiry.
|
| 379 |
+
//
|
| 380 |
+
for(;;)
|
| 381 |
+
{
|
| 382 |
+
unsigned int head = m_head;
|
| 383 |
+
for (;;)
|
| 384 |
+
{
|
| 385 |
+
if (head == m_tail)
|
| 386 |
+
return false;
|
| 387 |
+
|
| 388 |
+
unsigned int xchgHead = static_cast<unsigned int> (
|
| 389 |
+
InterlockedCompareExchange(reinterpret_cast<volatile long *>(&m_head), head + 1, head)
|
| 390 |
+
);
|
| 391 |
+
|
| 392 |
+
if (xchgHead == head)
|
| 393 |
+
break;
|
| 394 |
+
|
| 395 |
+
head = xchgHead;
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
Segment *pSegment = LocateMailboxSegment(head, false);
|
| 399 |
+
|
| 400 |
+
//
|
| 401 |
+
// 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
|
| 402 |
+
// all their slots have been claimed. This is so that we do not inadvertently remove a segment a different thread in this routine
|
| 403 |
+
// is trying to to locate. Segments can only be located if they are between head and tail. The update must handle multiple dequeues
|
| 404 |
+
// happening simultaneously and trying to update this simultaneously!
|
| 405 |
+
//
|
| 406 |
+
// There is no ABA here because segments are freed at a safe point and the calling thread is always an internal context which participates
|
| 407 |
+
// in this mechanism.
|
| 408 |
+
//
|
| 409 |
+
if (pSegment != m_pHeadSegment)
|
| 410 |
+
{
|
| 411 |
+
// 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.
|
| 412 |
+
// i.e. this segment must still be in the set [head, tail].
|
| 413 |
+
CONCRT_COREASSERT(pSegment->m_baseIdx >= m_pHeadSegment->m_baseIdx);
|
| 414 |
+
|
| 415 |
+
Segment *pHeadSegment = m_pHeadSegment;
|
| 416 |
+
Segment *pReadSegment = pHeadSegment;
|
| 417 |
+
|
| 418 |
+
// Travel forward from the head as long as we continue to find segments that have had all slots claimed.
|
| 419 |
+
for(;;)
|
| 420 |
+
{
|
| 421 |
+
while (pReadSegment->AllSlotsClaimed(m_segmentSize))
|
| 422 |
+
{
|
| 423 |
+
pReadSegment = pReadSegment->m_pNext;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
// If we've found a chain of segments (or a single segment) that has all slots claimed, try to change the head
|
| 427 |
+
if (pReadSegment->m_baseIdx > pHeadSegment->m_baseIdx)
|
| 428 |
+
{
|
| 429 |
+
Segment *pXchgSegment = reinterpret_cast<Segment *>(
|
| 430 |
+
InterlockedCompareExchangePointer(reinterpret_cast<void * volatile *>(&m_pHeadSegment),
|
| 431 |
+
reinterpret_cast<void *>(pReadSegment),
|
| 432 |
+
reinterpret_cast<void *>(pHeadSegment))
|
| 433 |
+
);
|
| 434 |
+
|
| 435 |
+
if (pXchgSegment == pHeadSegment)
|
| 436 |
+
{
|
| 437 |
+
//
|
| 438 |
+
// The person who removes a segment (or a series of segments) from the list via the head is responsible for
|
| 439 |
+
// setting their deletion references so that they properly delete! The segments in the sublist described by
|
| 440 |
+
// the half open range [pXchgSegment, pSegment) must be set.
|
| 441 |
+
//
|
| 442 |
+
Segment *pDelRef = pXchgSegment;
|
| 443 |
+
while (pDelRef != pReadSegment)
|
| 444 |
+
{
|
| 445 |
+
pDelRef->SetDeletionReferences(m_segmentSize);
|
| 446 |
+
pDelRef = pDelRef->m_pNext;
|
| 447 |
+
}
|
| 448 |
+
break;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
pHeadSegment = pReadSegment = pXchgSegment;
|
| 452 |
+
}
|
| 453 |
+
else
|
| 454 |
+
{
|
| 455 |
+
break;
|
| 456 |
+
}
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
CONCRT_COREASSERT(m_pHeadSegment != NULL);
|
| 460 |
+
CONCRT_COREASSERT(pSegment->m_baseIdx >= m_pHeadSegment->m_baseIdx);
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
unsigned int relativeIdx = head - pSegment->m_baseIdx;
|
| 464 |
+
|
| 465 |
+
// If the slot we get has not been claimed by anyone else,
|
| 466 |
+
// we will claim it and dequeue it, otherwise, keep searching next.
|
| 467 |
+
if (Slot(pSegment, relativeIdx).Claim(pDequeuedElement))
|
| 468 |
+
return true;
|
| 469 |
+
}
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
/// <summary>
|
| 473 |
+
/// Returns whether the mailbox is empty or not.
|
| 474 |
+
/// </summary>
|
| 475 |
+
bool IsEmpty() const
|
| 476 |
+
{
|
| 477 |
+
return (m_head == m_tail);
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
private:
|
| 481 |
+
|
| 482 |
+
/// <summary>
|
| 483 |
+
/// Expires a slot.
|
| 484 |
+
/// </summary>
|
| 485 |
+
void ExpireSlot(Segment *pSegment, unsigned int relativeIdx)
|
| 486 |
+
{
|
| 487 |
+
pSegment->Dereference();
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
Segment *Grow(Segment *pPreviousSegment)
|
| 491 |
+
{
|
| 492 |
+
// This "Grow" function is always protected by the lock in "enqueue".
|
| 493 |
+
|
| 494 |
+
Segment *pNewSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, m_segmentSize, pPreviousSegment->m_baseIdx + m_segmentSize);
|
| 495 |
+
m_pTailSegment = pNewSegment;
|
| 496 |
+
return pPreviousSegment->m_pNext = pNewSegment;
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
/// <summary>
|
| 500 |
+
/// Performs one time demand initialization of the mailbox if the segments were set to be allocated on demand.
|
| 501 |
+
/// </summary>
|
| 502 |
+
void DemandInitialize()
|
| 503 |
+
{
|
| 504 |
+
if (m_pTailSegment == NULL)
|
| 505 |
+
{
|
| 506 |
+
Segment *pXchgSegment = reinterpret_cast<Segment *>(
|
| 507 |
+
InterlockedCompareExchangePointer(reinterpret_cast<void * volatile *>(&m_pTailSegment),
|
| 508 |
+
reinterpret_cast<Segment *>(FIELD_RESERVED),
|
| 509 |
+
NULL)
|
| 510 |
+
);
|
| 511 |
+
|
| 512 |
+
if (pXchgSegment == NULL)
|
| 513 |
+
{
|
| 514 |
+
Segment *pNewSegment = _concrt_new Segment(m_pScheduler, m_affinitySet, m_segmentSize, 0);
|
| 515 |
+
m_pTailSegment = pNewSegment;
|
| 516 |
+
// sfence
|
| 517 |
+
m_pHeadSegment = pNewSegment;
|
| 518 |
+
}
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
if (m_pHeadSegment == NULL)
|
| 522 |
+
{
|
| 523 |
+
_SpinWaitBackoffNone spinWait(_Sleep0);
|
| 524 |
+
while(m_pHeadSegment == NULL)
|
| 525 |
+
{
|
| 526 |
+
spinWait._SpinOnce();
|
| 527 |
+
}
|
| 528 |
+
}
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
/// <summary>
|
| 532 |
+
/// Locates the appropriate mailbox segment for the specified absolute index. This is only utilized during enqueue and dequeue and *NOT* during
|
| 533 |
+
/// an arbitrary slot claim!
|
| 534 |
+
/// </summary>
|
| 535 |
+
Segment *LocateMailboxSegment(unsigned int absoluteIdx, bool fStartTail)
|
| 536 |
+
{
|
| 537 |
+
if (m_pHeadSegment == NULL)
|
| 538 |
+
DemandInitialize();
|
| 539 |
+
|
| 540 |
+
// lfence
|
| 541 |
+
|
| 542 |
+
Segment *pSegment = fStartTail ? m_pTailSegment : m_pHeadSegment;
|
| 543 |
+
ASSERT(absoluteIdx >= pSegment->m_baseIdx);
|
| 544 |
+
|
| 545 |
+
Segment *pPreviousSegment = pSegment;
|
| 546 |
+
while (pSegment && absoluteIdx >= pSegment->m_baseIdx + m_segmentSize)
|
| 547 |
+
{
|
| 548 |
+
pSegment = pSegment->m_pNext;
|
| 549 |
+
if (pSegment == NULL)
|
| 550 |
+
{
|
| 551 |
+
ASSERT(fStartTail); // Only enqueue will "Grow" the queue.
|
| 552 |
+
pSegment = Grow(pPreviousSegment);
|
| 553 |
+
}
|
| 554 |
+
pPreviousSegment = pSegment;
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
return pSegment;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
//
|
| 561 |
+
// Determines the size of a mailbox segment. Every mailbox pre-allocates a single segment. The size should be large enough to amortize heap
|
| 562 |
+
// allocation but small enough not to be prohibitively waste memory.
|
| 563 |
+
//
|
| 564 |
+
// This value should be a power of two.
|
| 565 |
+
//
|
| 566 |
+
static const unsigned int s_segmentSize = 64;
|
| 567 |
+
|
| 568 |
+
// The scheduler to which the mailbox belongs
|
| 569 |
+
SchedulerBase *m_pScheduler;
|
| 570 |
+
|
| 571 |
+
// The mailbox's affinity set
|
| 572 |
+
QuickBitSet m_affinitySet;
|
| 573 |
+
|
| 574 |
+
// The size of segments for this mailbox.
|
| 575 |
+
unsigned int m_segmentSize;
|
| 576 |
+
|
| 577 |
+
// The head and tail segments for the mailbox. These are within [m_head, m_tail].
|
| 578 |
+
Segment * volatile m_pTailSegment;
|
| 579 |
+
Segment * volatile m_pHeadSegment;
|
| 580 |
+
|
| 581 |
+
// The current head pointer
|
| 582 |
+
volatile unsigned int m_head;
|
| 583 |
+
|
| 584 |
+
// The current tail pointer
|
| 585 |
+
volatile unsigned int m_tail;
|
| 586 |
+
|
| 587 |
+
// Protect enqueue function, which should only accept one message for a time.
|
| 588 |
+
_NonReentrantLock m_enqueueLock;
|
| 589 |
+
};
|
| 590 |
+
} // namespace details
|
| 591 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.cpp
ADDED
|
@@ -0,0 +1,921 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Platform.cpp
|
| 9 |
+
//
|
| 10 |
+
// Platform API abstraction.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#include "concrtinternal.h"
|
| 14 |
+
#include <process.h>
|
| 15 |
+
#include <Windows.h>
|
| 16 |
+
|
| 17 |
+
#pragma warning (push)
|
| 18 |
+
#pragma warning (disable: 4702 4100)
|
| 19 |
+
|
| 20 |
+
namespace Concurrency { namespace details { namespace platform {
|
| 21 |
+
|
| 22 |
+
/************** Events ***************************/
|
| 23 |
+
|
| 24 |
+
/// <summary>
|
| 25 |
+
/// Creates an auto reset event
|
| 26 |
+
/// </summary>
|
| 27 |
+
HANDLE __CreateAutoResetEvent(bool initialSet)
|
| 28 |
+
{
|
| 29 |
+
DWORD flags = 0;
|
| 30 |
+
|
| 31 |
+
if (initialSet)
|
| 32 |
+
{
|
| 33 |
+
flags |= CREATE_EVENT_INITIAL_SET;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
HANDLE hEvent = CreateEventExW(NULL, NULL, flags, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE);
|
| 37 |
+
if (hEvent == NULL)
|
| 38 |
+
{
|
| 39 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
return hEvent;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// <summary>
|
| 46 |
+
/// Creates a manual reset event
|
| 47 |
+
/// </summary>
|
| 48 |
+
HANDLE __CreateManualResetEvent(bool initialSet)
|
| 49 |
+
{
|
| 50 |
+
DWORD flags = CREATE_EVENT_MANUAL_RESET;
|
| 51 |
+
|
| 52 |
+
if (initialSet)
|
| 53 |
+
{
|
| 54 |
+
flags |= CREATE_EVENT_INITIAL_SET;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
HANDLE hEvent = CreateEventExW(NULL, NULL, flags, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE);
|
| 58 |
+
if (hEvent == NULL)
|
| 59 |
+
{
|
| 60 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
return hEvent;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/************** Tickcount ***************************/
|
| 67 |
+
|
| 68 |
+
/// <summary>
|
| 69 |
+
/// Gets the current tick count
|
| 70 |
+
/// </summary>
|
| 71 |
+
ULONGLONG __GetTickCount64()
|
| 72 |
+
{
|
| 73 |
+
return GetTickCount64();
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/************** Windows critical section ***************************/
|
| 77 |
+
|
| 78 |
+
/// <summary>
|
| 79 |
+
/// Initializes the critical section
|
| 80 |
+
/// </summary>
|
| 81 |
+
BOOL __InitializeCriticalSectionEx(CRITICAL_SECTION * cs, DWORD spinCount)
|
| 82 |
+
{
|
| 83 |
+
return InitializeCriticalSectionEx(cs, spinCount, 0);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
/************** Thread Local Storage ***************************/
|
| 87 |
+
|
| 88 |
+
/// <summary>
|
| 89 |
+
/// Allocates a TLS slot
|
| 90 |
+
/// </summary>
|
| 91 |
+
DWORD __TlsAlloc()
|
| 92 |
+
{
|
| 93 |
+
#if defined(_ONECORE)
|
| 94 |
+
// We use Fls (Fiber local storage) as TLS is not supported for MSDK.
|
| 95 |
+
DWORD index = FlsAlloc(nullptr);
|
| 96 |
+
if (index == FLS_OUT_OF_INDEXES)
|
| 97 |
+
#else
|
| 98 |
+
// Use TLS for desktop because multiple schedulers are supported.
|
| 99 |
+
DWORD index = TlsAlloc();
|
| 100 |
+
if (index == TLS_OUT_OF_INDEXES)
|
| 101 |
+
#endif
|
| 102 |
+
{
|
| 103 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return index;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
/// <summary>
|
| 110 |
+
/// Frees a TLS slot
|
| 111 |
+
/// </summary>
|
| 112 |
+
void __TlsFree(DWORD index)
|
| 113 |
+
{
|
| 114 |
+
#if defined(_ONECORE)
|
| 115 |
+
if (index != FLS_OUT_OF_INDEXES)
|
| 116 |
+
{
|
| 117 |
+
FlsFree(index);
|
| 118 |
+
// Ignore error
|
| 119 |
+
}
|
| 120 |
+
#else
|
| 121 |
+
TlsFree(index);
|
| 122 |
+
#endif
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/// <summary>
|
| 126 |
+
/// Gets the value stored in the specified TLS slot
|
| 127 |
+
/// </summary>
|
| 128 |
+
PVOID __TlsGetValue(DWORD index)
|
| 129 |
+
{
|
| 130 |
+
#if defined(_ONECORE)
|
| 131 |
+
// Leave it up to the caller to decide if there was an error when
|
| 132 |
+
// the return value is NULL.
|
| 133 |
+
return FlsGetValue(index);
|
| 134 |
+
#else
|
| 135 |
+
return TlsGetValue(index);
|
| 136 |
+
#endif
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
/// <summary>
|
| 140 |
+
/// Stores a value in the specified TLS slot
|
| 141 |
+
/// </summary>
|
| 142 |
+
void __TlsSetValue(DWORD index, PVOID value)
|
| 143 |
+
{
|
| 144 |
+
#if defined(_ONECORE)
|
| 145 |
+
if (!FlsSetValue(index, value))
|
| 146 |
+
#else
|
| 147 |
+
if (!TlsSetValue(index, value))
|
| 148 |
+
#endif
|
| 149 |
+
{
|
| 150 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
/************** Thread Priority ***************************/
|
| 155 |
+
|
| 156 |
+
/// <summary>
|
| 157 |
+
/// Sets the thread priority
|
| 158 |
+
/// </summary>
|
| 159 |
+
void __SetThreadPriority(HANDLE hThread, int priority)
|
| 160 |
+
{
|
| 161 |
+
#if defined(_ONECORE)
|
| 162 |
+
// Dynamic thread priority modification is not supported under MSDK
|
| 163 |
+
ENSURE_NOT_APP();
|
| 164 |
+
#else
|
| 165 |
+
if (SetThreadPriority(hThread, priority) == 0)
|
| 166 |
+
{
|
| 167 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 168 |
+
}
|
| 169 |
+
#endif // _ONECORE
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/// <summary>
|
| 173 |
+
/// Retrieves the thread priority
|
| 174 |
+
/// </summary>
|
| 175 |
+
int __GetThreadPriority(HANDLE hThread)
|
| 176 |
+
{
|
| 177 |
+
#if defined(_CRT_APP)
|
| 178 |
+
// MSDK does not support GetThreadPriority
|
| 179 |
+
ENSURE_NOT_APP();
|
| 180 |
+
return THREAD_PRIORITY_ERROR_RETURN;
|
| 181 |
+
#else
|
| 182 |
+
return GetThreadPriority(hThread);
|
| 183 |
+
#endif // defined(_CRT_APP)
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
/************** Thread Affinity ***************************/
|
| 187 |
+
|
| 188 |
+
/// <summary>
|
| 189 |
+
/// Retrieves the thread group affinity
|
| 190 |
+
/// </summary>
|
| 191 |
+
BOOL __GetThreadGroupAffinity(HANDLE hThread, PGROUP_AFFINITY affinity)
|
| 192 |
+
{
|
| 193 |
+
// Don't do anything when targeting OneCore (We could set it to active processor mask in the future)
|
| 194 |
+
#if !defined(_ONECORE)
|
| 195 |
+
CONCRT_VERIFY(GetThreadGroupAffinity(hThread, affinity));
|
| 196 |
+
#endif // !defined(_ONECORE)
|
| 197 |
+
|
| 198 |
+
return 1;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/// <summary>
|
| 202 |
+
/// Sets the thread group affinity
|
| 203 |
+
/// </summary>
|
| 204 |
+
BOOL __SetThreadGroupAffinity(HANDLE hThread, const GROUP_AFFINITY * affinity)
|
| 205 |
+
{
|
| 206 |
+
// Don't do anything when targeting MSDK
|
| 207 |
+
#if !defined(_ONECORE)
|
| 208 |
+
CONCRT_VERIFY(SetThreadGroupAffinity(hThread, affinity, NULL));
|
| 209 |
+
#endif // !defined(_ONECORE)
|
| 210 |
+
|
| 211 |
+
return 1;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
/************** System Info ***************************/
|
| 215 |
+
|
| 216 |
+
/// <summary>
|
| 217 |
+
/// Retrieves the information about the relationships of logical processors and related hardware
|
| 218 |
+
/// </summary>
|
| 219 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX __GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relation, PDWORD retLength)
|
| 220 |
+
{
|
| 221 |
+
#if defined(_ONECORE)
|
| 222 |
+
// MSDK does not support this API. It is an error to call this API
|
| 223 |
+
ENSURE_NOT_APP();
|
| 224 |
+
#else
|
| 225 |
+
|
| 226 |
+
ASSERT(retLength != nullptr);
|
| 227 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pSysInfo = nullptr;
|
| 228 |
+
|
| 229 |
+
GetLogicalProcessorInformationEx(relation, NULL, retLength);
|
| 230 |
+
|
| 231 |
+
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
|
| 232 |
+
{
|
| 233 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
DWORD len = *retLength;
|
| 237 |
+
ASSERT(len > 0);
|
| 238 |
+
|
| 239 |
+
pSysInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) malloc(len);
|
| 240 |
+
|
| 241 |
+
if (pSysInfo == NULL)
|
| 242 |
+
{
|
| 243 |
+
throw std::bad_alloc();
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
if (!GetLogicalProcessorInformationEx(relation, pSysInfo, retLength))
|
| 247 |
+
{
|
| 248 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
return pSysInfo;
|
| 252 |
+
#endif // defined(_ONECORE)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/// <summary>
|
| 256 |
+
/// Retrieves the information about logical processors and related hardware
|
| 257 |
+
/// </summary>
|
| 258 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION __GetLogicalProcessorInformation(PDWORD retLength)
|
| 259 |
+
{
|
| 260 |
+
#if defined(_ONECORE)
|
| 261 |
+
// MSDK does not support this API. It is an error to call this API
|
| 262 |
+
ENSURE_NOT_APP();
|
| 263 |
+
#else
|
| 264 |
+
#if (defined(_M_IX86) || defined(_M_X64))
|
| 265 |
+
ASSERT(retLength != nullptr);
|
| 266 |
+
|
| 267 |
+
GetLogicalProcessorInformation(NULL, retLength);
|
| 268 |
+
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
|
| 269 |
+
{
|
| 270 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
DWORD len = *retLength;
|
| 274 |
+
ASSERT(len > 0);
|
| 275 |
+
|
| 276 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pSysInfo = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION) malloc(len);
|
| 277 |
+
if (pSysInfo == NULL)
|
| 278 |
+
{
|
| 279 |
+
throw std::bad_alloc();
|
| 280 |
+
}
|
| 281 |
+
if (!GetLogicalProcessorInformation(pSysInfo, retLength))
|
| 282 |
+
{
|
| 283 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
return pSysInfo;
|
| 287 |
+
#else
|
| 288 |
+
throw invalid_operation();
|
| 289 |
+
#endif // (defined(_M_IX86) || defined(_M_X64))
|
| 290 |
+
#endif // defined(_ONECORE)
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
/// <summary>
|
| 294 |
+
/// Retrieves the processor group and number of the logical processor where the thread is running
|
| 295 |
+
/// </summary>
|
| 296 |
+
void __GetCurrentProcessorNumberEx(PPROCESSOR_NUMBER procNum)
|
| 297 |
+
{
|
| 298 |
+
#if defined(_ONECORE)
|
| 299 |
+
ENSURE_NOT_APP();
|
| 300 |
+
#else
|
| 301 |
+
GetCurrentProcessorNumberEx(procNum);
|
| 302 |
+
#endif // defined(_ONECORE)
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
/// <summary>
|
| 306 |
+
/// Returns the highest numa node number
|
| 307 |
+
/// </summary>
|
| 308 |
+
ULONG __GetNumaHighestNodeNumber()
|
| 309 |
+
{
|
| 310 |
+
ULONG highestNodeNumber;
|
| 311 |
+
#if defined(_ONECORE)
|
| 312 |
+
// For MSDK we assume a single NUMA node
|
| 313 |
+
highestNodeNumber = 0;
|
| 314 |
+
#else
|
| 315 |
+
if (!GetNumaHighestNodeNumber(&highestNodeNumber))
|
| 316 |
+
{
|
| 317 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 318 |
+
}
|
| 319 |
+
#endif // defined(_ONECORE)
|
| 320 |
+
return highestNodeNumber;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
/************** Thread yield ***************************/
|
| 324 |
+
|
| 325 |
+
/// <summary>
|
| 326 |
+
/// Yield execution to another ready thread
|
| 327 |
+
/// </summary>
|
| 328 |
+
void __SwitchToThread()
|
| 329 |
+
{
|
| 330 |
+
#if defined(_ONECORE)
|
| 331 |
+
// TODO: Do we need to yield our time quantum?
|
| 332 |
+
#else
|
| 333 |
+
SwitchToThread();
|
| 334 |
+
#endif
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
/// <summary>
|
| 338 |
+
/// Yield execution to another ready thread (ms is assumed to be 0 or 1)
|
| 339 |
+
/// </summary>
|
| 340 |
+
void __Sleep(DWORD ms)
|
| 341 |
+
{
|
| 342 |
+
Sleep(ms);
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
//***********************************************/
|
| 346 |
+
// Timer /
|
| 347 |
+
//***********************************************/
|
| 348 |
+
|
| 349 |
+
/// <summary>
|
| 350 |
+
/// Creates a timer
|
| 351 |
+
/// </summary>
|
| 352 |
+
BOOL __CreateTimerQueueTimer(
|
| 353 |
+
PHANDLE phNewTimer,
|
| 354 |
+
HANDLE timerQueue,
|
| 355 |
+
WAITORTIMERCALLBACK lpStartAddress,
|
| 356 |
+
PVOID lpParameter,
|
| 357 |
+
DWORD dueTime,
|
| 358 |
+
DWORD period,
|
| 359 |
+
ULONG flags
|
| 360 |
+
)
|
| 361 |
+
{
|
| 362 |
+
#if defined(_ONECORE)
|
| 363 |
+
ENSURE_NOT_APP();
|
| 364 |
+
#else
|
| 365 |
+
return CreateTimerQueueTimer(phNewTimer,
|
| 366 |
+
timerQueue,
|
| 367 |
+
lpStartAddress,
|
| 368 |
+
lpParameter,
|
| 369 |
+
dueTime,
|
| 370 |
+
period,
|
| 371 |
+
flags);
|
| 372 |
+
#endif // defined(_ONECORE)
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
/// <summary>
|
| 376 |
+
/// Deletes the timer
|
| 377 |
+
/// </summary>
|
| 378 |
+
void __DeleteTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, HANDLE completionEvent)
|
| 379 |
+
{
|
| 380 |
+
#if defined(_ONECORE)
|
| 381 |
+
ENSURE_NOT_APP();
|
| 382 |
+
#else
|
| 383 |
+
for(int maximalRetry = 16; maximalRetry > 0; --maximalRetry)
|
| 384 |
+
{
|
| 385 |
+
if (!DeleteTimerQueueTimer(timerQueue, hTimer, completionEvent))
|
| 386 |
+
{
|
| 387 |
+
if (GetLastError() == ERROR_IO_PENDING)
|
| 388 |
+
break;
|
| 389 |
+
}
|
| 390 |
+
else
|
| 391 |
+
{
|
| 392 |
+
break;
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
#endif // defined(_ONECORE)
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
/// <summary>
|
| 399 |
+
/// Changes the due time of the timer.
|
| 400 |
+
/// </summary>
|
| 401 |
+
BOOL __ChangeTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, ULONG dueTime, ULONG period)
|
| 402 |
+
{
|
| 403 |
+
#if defined(_ONECORE)
|
| 404 |
+
ENSURE_NOT_APP();
|
| 405 |
+
#else
|
| 406 |
+
return ChangeTimerQueueTimer(timerQueue, hTimer, dueTime, period);
|
| 407 |
+
#endif // defined(_ONECORE)
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
//***********************************************/
|
| 411 |
+
// CreateThread /
|
| 412 |
+
//***********************************************/
|
| 413 |
+
|
| 414 |
+
/// <summary>
|
| 415 |
+
/// Creates a thread
|
| 416 |
+
/// </summary>
|
| 417 |
+
HANDLE __CreateThread(LPSECURITY_ATTRIBUTES lpAttributes,
|
| 418 |
+
size_t stackSize,
|
| 419 |
+
LPTHREAD_START_ROUTINE startAddress,
|
| 420 |
+
LPVOID param,
|
| 421 |
+
DWORD flags,
|
| 422 |
+
LPDWORD threadId)
|
| 423 |
+
{
|
| 424 |
+
return CreateThread(lpAttributes, stackSize, startAddress, param, flags, threadId);
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
/// <summary>
|
| 428 |
+
/// Releases the thread handle
|
| 429 |
+
/// </summary>
|
| 430 |
+
void __CloseThreadHandle(HANDLE hThread)
|
| 431 |
+
{
|
| 432 |
+
CloseHandle(hThread);
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
/// <summary>
|
| 436 |
+
/// Waits for the thread to exit
|
| 437 |
+
/// </summary>
|
| 438 |
+
DWORD __WaitForThread(HANDLE hThread, DWORD timeout)
|
| 439 |
+
{
|
| 440 |
+
return WaitForSingleObjectEx(hThread, timeout, FALSE);
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
/// <summary>
|
| 444 |
+
/// Signals hSignal object and waits for hWait. Returns the reason for returning from wait
|
| 445 |
+
/// </summary>
|
| 446 |
+
DWORD __SignalObjectAndWait(HANDLE hSignal, HANDLE hWait, DWORD ms, BOOL alertable)
|
| 447 |
+
{
|
| 448 |
+
#if defined(_ONECORE)
|
| 449 |
+
SetEvent(hSignal);
|
| 450 |
+
return WaitForSingleObjectEx(hWait, ms, alertable);
|
| 451 |
+
#else
|
| 452 |
+
return SignalObjectAndWait(hSignal, hWait, ms, alertable);
|
| 453 |
+
#endif
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
//***********************************************/
|
| 458 |
+
// RegisterWaitForSingleObject /
|
| 459 |
+
//***********************************************/
|
| 460 |
+
|
| 461 |
+
/// <summary>
|
| 462 |
+
/// Represents a collection of events and a background thread for handling those event notifications. Essentially
|
| 463 |
+
/// it performs the equivalent functionality of RegisterWaitForSingleObject.
|
| 464 |
+
/// </summary>
|
| 465 |
+
class WaiterThread
|
| 466 |
+
{
|
| 467 |
+
public:
|
| 468 |
+
WaiterThread() : m_numEvents(0), m_numWaiting(0), m_pendingRemove(0)
|
| 469 |
+
{
|
| 470 |
+
for (int i = 0; i < MAXIMUM_WAIT_OBJECTS; i++)
|
| 471 |
+
{
|
| 472 |
+
m_waitHandles[i] = &m_eventData[i];
|
| 473 |
+
}
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
/// <summary>
|
| 477 |
+
/// Create the background thread
|
| 478 |
+
/// </summary>
|
| 479 |
+
void start()
|
| 480 |
+
{
|
| 481 |
+
// Create the background thread
|
| 482 |
+
HANDLE threadHandle = __CreateThread(NULL,
|
| 483 |
+
0,
|
| 484 |
+
WaiterThread::wait_bridge,
|
| 485 |
+
this,
|
| 486 |
+
0,
|
| 487 |
+
NULL);
|
| 488 |
+
|
| 489 |
+
__CloseThreadHandle(threadHandle);
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
/// <summary>
|
| 493 |
+
/// Indicate that the handler should be deleted when the background thread exits
|
| 494 |
+
/// </summary>
|
| 495 |
+
void stop()
|
| 496 |
+
{
|
| 497 |
+
auto waiterData = m_waitHandles[0];
|
| 498 |
+
waiterData->handler = nullptr;
|
| 499 |
+
notify(true);
|
| 500 |
+
|
| 501 |
+
// The background thread will eventually exit and reclaim this handler
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
/// <summary>
|
| 505 |
+
/// Indicates whether there are slots available in this handler
|
| 506 |
+
/// </summary>
|
| 507 |
+
bool is_available()
|
| 508 |
+
{
|
| 509 |
+
return m_numEvents < MAXIMUM_WAIT_OBJECTS;
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
/// <summary>
|
| 513 |
+
/// Adds a waiter for the given handle
|
| 514 |
+
/// </summary>
|
| 515 |
+
HANDLE add_handle(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context)
|
| 516 |
+
{
|
| 517 |
+
HANDLE hWait = nullptr;
|
| 518 |
+
{
|
| 519 |
+
_NonReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 520 |
+
|
| 521 |
+
if (m_numEvents == 0)
|
| 522 |
+
{
|
| 523 |
+
// Create the wake event
|
| 524 |
+
HANDLE hWake = CreateEventExW(NULL, NULL, 0, STANDARD_RIGHTS_ALL | EVENT_MODIFY_STATE);
|
| 525 |
+
if (hWake== NULL)
|
| 526 |
+
{
|
| 527 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
add_wait(hWake, wake_bridge, this);
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
// Add the user event
|
| 534 |
+
hWait = add_wait(hEvent, callback, context);
|
| 535 |
+
|
| 536 |
+
// Snap shot numWaiting
|
| 537 |
+
if (m_numWaiting == 0)
|
| 538 |
+
{
|
| 539 |
+
// Not started yet
|
| 540 |
+
m_numWaiting = m_numEvents;
|
| 541 |
+
}
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
// Notify the background thread after releasing the lock
|
| 545 |
+
notify(false);
|
| 546 |
+
return hWait;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
/// <summary>
|
| 550 |
+
/// Remove the waiter for the given handle
|
| 551 |
+
/// </summary>
|
| 552 |
+
static void remove_handle(HANDLE hWait)
|
| 553 |
+
{
|
| 554 |
+
auto waiterData = static_cast<WAITER_DATA *>(hWait);
|
| 555 |
+
auto handler = static_cast<WaiterThread *>(waiterData->handler);
|
| 556 |
+
handler->remove_wait(waiterData);
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
private:
|
| 560 |
+
|
| 561 |
+
typedef struct _WAITER_DATA
|
| 562 |
+
{
|
| 563 |
+
void * handler;
|
| 564 |
+
WAITORTIMERCALLBACK callback;
|
| 565 |
+
PVOID context;
|
| 566 |
+
} WAITER_DATA;
|
| 567 |
+
|
| 568 |
+
/// <summary>
|
| 569 |
+
/// Add the waiter to the list
|
| 570 |
+
/// </summary>
|
| 571 |
+
HANDLE add_wait(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context)
|
| 572 |
+
{
|
| 573 |
+
WAITER_DATA * waiterData = m_waitHandles[m_numEvents];
|
| 574 |
+
waiterData->callback = callback;
|
| 575 |
+
waiterData->context = context;
|
| 576 |
+
waiterData->handler = this;
|
| 577 |
+
|
| 578 |
+
m_hEvents[m_numEvents] = hEvent;
|
| 579 |
+
m_numEvents++;
|
| 580 |
+
|
| 581 |
+
return static_cast<HANDLE>(waiterData);
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
/// <summary>
|
| 585 |
+
/// Indicates that the waiter is to be removed from the list. The background
|
| 586 |
+
/// thread is notified which in turn would remove it from the list.
|
| 587 |
+
/// </summary>
|
| 588 |
+
void remove_wait(WAITER_DATA * waiterData)
|
| 589 |
+
{
|
| 590 |
+
waiterData->handler = nullptr;
|
| 591 |
+
notify(true);
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
/// <summary>
|
| 595 |
+
/// Notify the background thread
|
| 596 |
+
/// </summary>
|
| 597 |
+
void notify(bool isRemoval)
|
| 598 |
+
{
|
| 599 |
+
if (isRemoval)
|
| 600 |
+
{
|
| 601 |
+
// Wake up the background thread for the first removal
|
| 602 |
+
if (_InterlockedIncrement(&m_pendingRemove) == 1)
|
| 603 |
+
{
|
| 604 |
+
SetEvent(m_hEvents[0]);
|
| 605 |
+
}
|
| 606 |
+
}
|
| 607 |
+
else
|
| 608 |
+
{
|
| 609 |
+
// Avoid waking up the background thread for every event we add...
|
| 610 |
+
if (m_numEvents - m_numWaiting == 1)
|
| 611 |
+
{
|
| 612 |
+
SetEvent(m_hEvents[0]);
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
/// <summary>
|
| 618 |
+
/// Invokes the callback
|
| 619 |
+
/// </summary>
|
| 620 |
+
void invoke_handler(DWORD index)
|
| 621 |
+
{
|
| 622 |
+
ASSERT(index < MAXIMUM_WAIT_OBJECTS);
|
| 623 |
+
|
| 624 |
+
auto waiterData = m_waitHandles[index];
|
| 625 |
+
|
| 626 |
+
// Skip the callback if the callback was removed
|
| 627 |
+
// Special case the wake handler
|
| 628 |
+
if ((index == 0) || (waiterData->handler != nullptr))
|
| 629 |
+
{
|
| 630 |
+
waiterData->callback(waiterData->context, FALSE);
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
/// <summary>
|
| 635 |
+
/// The main wait loop
|
| 636 |
+
/// </summary>
|
| 637 |
+
void wait_handler()
|
| 638 |
+
{
|
| 639 |
+
while (m_numWaiting > 0)
|
| 640 |
+
{
|
| 641 |
+
// Wait for the array of events
|
| 642 |
+
DWORD waitResult = WaitForMultipleObjectsEx((DWORD)m_numWaiting, m_hEvents, false, INFINITE, FALSE);
|
| 643 |
+
if (waitResult == WAIT_FAILED)
|
| 644 |
+
{
|
| 645 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
// Invoke the callback
|
| 649 |
+
DWORD waitHandleIndex = waitResult - WAIT_OBJECT_0;
|
| 650 |
+
ASSERT(waitHandleIndex < m_numWaiting);
|
| 651 |
+
invoke_handler(waitHandleIndex);
|
| 652 |
+
|
| 653 |
+
// If the callback removed a waiter or if it was already removed, process it here
|
| 654 |
+
if ((m_numWaiting > 0) && (WaitForSingleObjectEx(m_hEvents[0], 0, FALSE) == WAIT_OBJECT_0))
|
| 655 |
+
{
|
| 656 |
+
invoke_handler(0);
|
| 657 |
+
}
|
| 658 |
+
}
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
/// <summary>
|
| 662 |
+
/// static bridge that calls the wait loop
|
| 663 |
+
/// </summary>
|
| 664 |
+
static DWORD WINAPI wait_bridge(PVOID context)
|
| 665 |
+
{
|
| 666 |
+
auto handler = static_cast<WaiterThread *>(context);
|
| 667 |
+
handler->wait_handler();
|
| 668 |
+
delete handler;
|
| 669 |
+
return 0;
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
/// <summary>
|
| 673 |
+
/// The main handler for the back ground thread
|
| 674 |
+
/// </summary>
|
| 675 |
+
void wake_handler()
|
| 676 |
+
{
|
| 677 |
+
_NonReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 678 |
+
|
| 679 |
+
auto pendingRemove = _InterlockedExchange(&m_pendingRemove, 0);
|
| 680 |
+
|
| 681 |
+
if (pendingRemove != 0)
|
| 682 |
+
{
|
| 683 |
+
process_remove();
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
// Update the num waiters (which is common for add and remove of handlers)
|
| 687 |
+
m_numWaiting = m_numEvents;
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
/// <summary>
|
| 691 |
+
/// Static bridge for the wake handler
|
| 692 |
+
/// </summary>
|
| 693 |
+
static void CALLBACK wake_bridge(PVOID context, BOOLEAN)
|
| 694 |
+
{
|
| 695 |
+
auto handler = static_cast<WaiterThread *>(context);
|
| 696 |
+
handler->wake_handler();
|
| 697 |
+
}
|
| 698 |
+
|
| 699 |
+
/// <summary>
|
| 700 |
+
/// Removes waiters and compacts the array of handles
|
| 701 |
+
/// </summary>
|
| 702 |
+
void process_remove()
|
| 703 |
+
{
|
| 704 |
+
// Walk all the handler and remove the ones that are marked (handler == nullptr)
|
| 705 |
+
// Skip the first event which is our wake handler
|
| 706 |
+
DWORD i = 1;
|
| 707 |
+
while (i < m_numEvents)
|
| 708 |
+
{
|
| 709 |
+
auto waiterData = m_waitHandles[i];
|
| 710 |
+
|
| 711 |
+
if (waiterData->handler == nullptr)
|
| 712 |
+
{
|
| 713 |
+
// Remove the event
|
| 714 |
+
CloseHandle(m_hEvents[i]);
|
| 715 |
+
m_numEvents--;
|
| 716 |
+
|
| 717 |
+
if (i != m_numEvents)
|
| 718 |
+
{
|
| 719 |
+
// Swap the last event
|
| 720 |
+
m_hEvents[i] = m_hEvents[m_numEvents];
|
| 721 |
+
m_hEvents[m_numEvents] = NULL;
|
| 722 |
+
|
| 723 |
+
m_waitHandles[i] = m_waitHandles[m_numEvents];
|
| 724 |
+
m_waitHandles[m_numEvents] = waiterData;
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
// Process this event again
|
| 728 |
+
continue;
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
i++;
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
// If the last user event is removed attempt to remove the
|
| 735 |
+
// wake handler. It is not safe to remove the wake event without
|
| 736 |
+
// it being marked for removal by register_wait.
|
| 737 |
+
if ((m_numEvents == 1) && (m_waitHandles[0]->handler == nullptr))
|
| 738 |
+
{
|
| 739 |
+
CloseHandle(m_hEvents[0]);
|
| 740 |
+
m_hEvents[0] = NULL; // For debugging
|
| 741 |
+
m_numEvents--;
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
m_numWaiting = m_numEvents;
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
private:
|
| 749 |
+
|
| 750 |
+
// Array of handles that is being waited on
|
| 751 |
+
HANDLE m_hEvents[MAXIMUM_WAIT_OBJECTS]{};
|
| 752 |
+
|
| 753 |
+
// The handlers corresponding to the event array (matching index)
|
| 754 |
+
WAITER_DATA * m_waitHandles[MAXIMUM_WAIT_OBJECTS];
|
| 755 |
+
|
| 756 |
+
// All the handles (including ones that are removed/not yet added etc).
|
| 757 |
+
WAITER_DATA m_eventData[MAXIMUM_WAIT_OBJECTS]{};
|
| 758 |
+
|
| 759 |
+
// Total number of events including the ones that are not yet waited upon
|
| 760 |
+
DWORD m_numEvents;
|
| 761 |
+
|
| 762 |
+
// The number of events that are being waited on
|
| 763 |
+
DWORD m_numWaiting;
|
| 764 |
+
|
| 765 |
+
// The number of pending remove requests
|
| 766 |
+
volatile long m_pendingRemove;
|
| 767 |
+
|
| 768 |
+
// Lock for insertion and deletion of handles
|
| 769 |
+
_NonReentrantBlockingLock m_lock;
|
| 770 |
+
};
|
| 771 |
+
|
| 772 |
+
/// <summary>
|
| 773 |
+
/// Manages all the waiter threads. A waiter thread can only handle upto
|
| 774 |
+
/// MAXIMUM_WAIT_OBJECTS events. This class maintains multiple such waiter threads
|
| 775 |
+
/// </summary>
|
| 776 |
+
class WaiterThreadPool
|
| 777 |
+
{
|
| 778 |
+
public:
|
| 779 |
+
|
| 780 |
+
WaiterThreadPool() : m_waiter(nullptr)
|
| 781 |
+
{
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
/// <summary>
|
| 785 |
+
/// Destructor
|
| 786 |
+
/// </summary>
|
| 787 |
+
~WaiterThreadPool()
|
| 788 |
+
{
|
| 789 |
+
if (m_waiter != nullptr)
|
| 790 |
+
{
|
| 791 |
+
m_waiter->stop();
|
| 792 |
+
}
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
/// <summary>
|
| 796 |
+
/// Creates an event handler if required and registers a waiter for the given event in that handler
|
| 797 |
+
/// instance
|
| 798 |
+
/// </summary>
|
| 799 |
+
HANDLE add_waiter(HANDLE hSource, WAITORTIMERCALLBACK callback, PVOID context)
|
| 800 |
+
{
|
| 801 |
+
HANDLE hEvent;
|
| 802 |
+
if (!DuplicateHandle(GetCurrentProcess(),
|
| 803 |
+
hSource,
|
| 804 |
+
GetCurrentProcess(),
|
| 805 |
+
&hEvent,
|
| 806 |
+
0,
|
| 807 |
+
FALSE,
|
| 808 |
+
DUPLICATE_SAME_ACCESS))
|
| 809 |
+
{
|
| 810 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
HANDLE hWait = nullptr;
|
| 814 |
+
WaiterThread * newWaiter = nullptr;
|
| 815 |
+
{
|
| 816 |
+
_NonReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 817 |
+
|
| 818 |
+
// Get the event handler
|
| 819 |
+
if ((m_waiter == nullptr) || (!m_waiter->is_available()))
|
| 820 |
+
{
|
| 821 |
+
if (m_waiter != nullptr)
|
| 822 |
+
{
|
| 823 |
+
m_waiter->stop();
|
| 824 |
+
m_waiter = nullptr;
|
| 825 |
+
}
|
| 826 |
+
|
| 827 |
+
m_waiter = new WaiterThread();
|
| 828 |
+
newWaiter = m_waiter;
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
// Add the wait event under the lock
|
| 832 |
+
hWait = m_waiter->add_handle(hEvent, callback, context);
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
// Start the handler after we release the lock
|
| 836 |
+
if (newWaiter != nullptr)
|
| 837 |
+
{
|
| 838 |
+
newWaiter->start();
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
return hWait;
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
private:
|
| 845 |
+
|
| 846 |
+
WaiterThread * m_waiter;
|
| 847 |
+
_NonReentrantBlockingLock m_lock;
|
| 848 |
+
};
|
| 849 |
+
|
| 850 |
+
// Maintains a default global waiter threadpool instance
|
| 851 |
+
// which will be released on process exit
|
| 852 |
+
static WaiterThreadPool * s_waiterPool = nullptr;
|
| 853 |
+
class DefaultWaiterPool
|
| 854 |
+
{
|
| 855 |
+
public:
|
| 856 |
+
DefaultWaiterPool()
|
| 857 |
+
{
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
~DefaultWaiterPool()
|
| 861 |
+
{
|
| 862 |
+
if (s_waiterPool != nullptr)
|
| 863 |
+
{
|
| 864 |
+
delete s_waiterPool;
|
| 865 |
+
s_waiterPool = nullptr;
|
| 866 |
+
}
|
| 867 |
+
}
|
| 868 |
+
|
| 869 |
+
static WaiterThreadPool * get_waiter()
|
| 870 |
+
{
|
| 871 |
+
#pragma warning(suppress: 28112) // False positive warning, VSO-1807048
|
| 872 |
+
if (s_waiterPool == nullptr)
|
| 873 |
+
{
|
| 874 |
+
// Allocate on demand
|
| 875 |
+
auto waiterPool = new WaiterThreadPool;
|
| 876 |
+
if (_InterlockedCompareExchangePointer((volatile PVOID *)&s_waiterPool, waiterPool, nullptr) != nullptr)
|
| 877 |
+
{
|
| 878 |
+
delete waiterPool;
|
| 879 |
+
}
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
#pragma warning(suppress: 28112) // False positive warning, VSO-1807048
|
| 883 |
+
return s_waiterPool;
|
| 884 |
+
}
|
| 885 |
+
};
|
| 886 |
+
|
| 887 |
+
static DefaultWaiterPool s_defaultWaiterPool;
|
| 888 |
+
|
| 889 |
+
HANDLE __RegisterWaitForSingleObject(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context)
|
| 890 |
+
{
|
| 891 |
+
HANDLE hWait;
|
| 892 |
+
#if defined(_ONECORE)
|
| 893 |
+
auto waiterPool = DefaultWaiterPool::get_waiter();
|
| 894 |
+
hWait = waiterPool->add_waiter(hEvent, callback, context);
|
| 895 |
+
#else // !(_ONECORE)
|
| 896 |
+
// Request a thread pool thread to wait for this thread exit.
|
| 897 |
+
if (!RegisterWaitForSingleObject(&hWait,
|
| 898 |
+
hEvent,
|
| 899 |
+
callback,
|
| 900 |
+
context, INFINITE, (WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)))
|
| 901 |
+
{
|
| 902 |
+
throw scheduler_resource_allocation_error(HRESULT_FROM_WIN32(GetLastError()));
|
| 903 |
+
}
|
| 904 |
+
#endif // !(_ONECORE)
|
| 905 |
+
return hWait;
|
| 906 |
+
}
|
| 907 |
+
|
| 908 |
+
void __UnregisterWait(HANDLE hWait)
|
| 909 |
+
{
|
| 910 |
+
#if defined(_ONECORE)
|
| 911 |
+
WaiterThread::remove_handle(hWait);
|
| 912 |
+
#else
|
| 913 |
+
// Ignore both pseudo-failure (when a callback is already running) and real failure
|
| 914 |
+
// (as this is called by ExternalContextBase::ImplicitDetachHandlerXP() which cannot report failure).
|
| 915 |
+
(void) UnregisterWait(hWait);
|
| 916 |
+
#endif // !(_ONECORE)
|
| 917 |
+
}
|
| 918 |
+
|
| 919 |
+
}}} // namespace Concurrency::details::platform
|
| 920 |
+
|
| 921 |
+
#pragma warning (pop)
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/Platform.h
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// Platform.h : abstracts the underlying platform APIs
|
| 9 |
+
//
|
| 10 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 11 |
+
#pragma once
|
| 12 |
+
|
| 13 |
+
// Windows headers that we need
|
| 14 |
+
|
| 15 |
+
#include <Windows.h>
|
| 16 |
+
#include <winnt.h>
|
| 17 |
+
#include <OAIdl.h>
|
| 18 |
+
|
| 19 |
+
#include <roapi.h>
|
| 20 |
+
|
| 21 |
+
#undef Yield // The windows headers #define Yield, a name we want to use
|
| 22 |
+
|
| 23 |
+
#include <wmistr.h>
|
| 24 |
+
#include <evntrace.h>
|
| 25 |
+
#include <crtdefs.h>
|
| 26 |
+
|
| 27 |
+
namespace Concurrency { namespace details { namespace platform {
|
| 28 |
+
|
| 29 |
+
/****************** Events ***************************/
|
| 30 |
+
|
| 31 |
+
/// <summary>
|
| 32 |
+
/// Creates an auto reset event
|
| 33 |
+
/// </summary>
|
| 34 |
+
HANDLE __CreateAutoResetEvent(bool initialSet = false);
|
| 35 |
+
|
| 36 |
+
/// <summary>
|
| 37 |
+
/// Creates a manual reset event
|
| 38 |
+
/// </summary>
|
| 39 |
+
HANDLE __CreateManualResetEvent(bool initialSet = false);
|
| 40 |
+
|
| 41 |
+
/************** Tickcount ***************************/
|
| 42 |
+
|
| 43 |
+
/// <summary>
|
| 44 |
+
/// Gets the current tick count
|
| 45 |
+
/// </summary>
|
| 46 |
+
ULONGLONG __GetTickCount64();
|
| 47 |
+
|
| 48 |
+
/************** Windows critical section ***************************/
|
| 49 |
+
|
| 50 |
+
/// <summary>
|
| 51 |
+
/// Initializes the critical section
|
| 52 |
+
/// </summary>
|
| 53 |
+
BOOL __InitializeCriticalSectionEx(CRITICAL_SECTION * cs, DWORD spinCount);
|
| 54 |
+
|
| 55 |
+
/************** Thread Local Storage *****************************/
|
| 56 |
+
|
| 57 |
+
/// <summary>
|
| 58 |
+
/// Allocates a TLS slot
|
| 59 |
+
/// </summary>
|
| 60 |
+
DWORD __TlsAlloc();
|
| 61 |
+
|
| 62 |
+
/// <summary>
|
| 63 |
+
/// Frees a TLS slot
|
| 64 |
+
/// </summary>
|
| 65 |
+
void __TlsFree(DWORD index);
|
| 66 |
+
|
| 67 |
+
/// <summary>
|
| 68 |
+
/// Gets the value stored in the specified TLS slot
|
| 69 |
+
/// </summary>
|
| 70 |
+
PVOID __TlsGetValue(DWORD index);
|
| 71 |
+
|
| 72 |
+
/// <summary>
|
| 73 |
+
/// Stores a value in the specified TLS slot
|
| 74 |
+
/// </summary>
|
| 75 |
+
void __TlsSetValue(DWORD index, PVOID value);
|
| 76 |
+
|
| 77 |
+
/************** Thread Priority ***************************/
|
| 78 |
+
|
| 79 |
+
/// <summary>
|
| 80 |
+
/// Sets the thread priority
|
| 81 |
+
/// </summary>
|
| 82 |
+
void __SetThreadPriority(HANDLE hThread, int priority);
|
| 83 |
+
|
| 84 |
+
/// <summary>
|
| 85 |
+
/// Retrieves the thread priority
|
| 86 |
+
/// </summary>
|
| 87 |
+
int __GetThreadPriority(HANDLE hThread);
|
| 88 |
+
|
| 89 |
+
/************** Thread Affinity ***************************/
|
| 90 |
+
|
| 91 |
+
/// <summary>
|
| 92 |
+
/// Retrieves the thread group affinity
|
| 93 |
+
/// </summary>
|
| 94 |
+
BOOL __GetThreadGroupAffinity(HANDLE hThread, PGROUP_AFFINITY affinity);
|
| 95 |
+
|
| 96 |
+
/// <summary>
|
| 97 |
+
/// Sets the thread group affinity
|
| 98 |
+
/// </summary>
|
| 99 |
+
BOOL __SetThreadGroupAffinity(HANDLE hThread, const GROUP_AFFINITY * affinity);
|
| 100 |
+
|
| 101 |
+
/************** Thread yield ***************************/
|
| 102 |
+
|
| 103 |
+
/// <summary>
|
| 104 |
+
/// Yield execution to another ready thread
|
| 105 |
+
/// </summary>
|
| 106 |
+
void __SwitchToThread();
|
| 107 |
+
|
| 108 |
+
/// <summary>
|
| 109 |
+
/// Yield execution to another ready thread (ms is assumed to be 0 or 1)
|
| 110 |
+
/// </summary>
|
| 111 |
+
void __Sleep(DWORD ms);
|
| 112 |
+
|
| 113 |
+
/************ Thread *********************************************/
|
| 114 |
+
/// <summary>
|
| 115 |
+
/// Creates a thread
|
| 116 |
+
/// </summary>
|
| 117 |
+
HANDLE __CreateThread(LPSECURITY_ATTRIBUTES lpAttributes,
|
| 118 |
+
size_t stackSize,
|
| 119 |
+
LPTHREAD_START_ROUTINE startAddress,
|
| 120 |
+
LPVOID param,
|
| 121 |
+
DWORD flags,
|
| 122 |
+
LPDWORD threadId);
|
| 123 |
+
|
| 124 |
+
/// <summary>
|
| 125 |
+
/// Releases the thread handle
|
| 126 |
+
/// </summary>
|
| 127 |
+
void __CloseThreadHandle(HANDLE hThread);
|
| 128 |
+
|
| 129 |
+
/// <summary>
|
| 130 |
+
/// Waits for the thread to exit
|
| 131 |
+
/// </summary>
|
| 132 |
+
DWORD __WaitForThread(HANDLE hThread, DWORD timeout);
|
| 133 |
+
|
| 134 |
+
/// <summary>
|
| 135 |
+
/// Signals hSignal object and waits for hWait. Returns the reason for returning from wait
|
| 136 |
+
/// </summary>
|
| 137 |
+
DWORD __SignalObjectAndWait(HANDLE hSignal, HANDLE hWait, DWORD ms, BOOL alertable);
|
| 138 |
+
|
| 139 |
+
/************ Timer *********************************************/
|
| 140 |
+
/// <summary>
|
| 141 |
+
/// Creates a timer
|
| 142 |
+
/// </summary>
|
| 143 |
+
BOOL __CreateTimerQueueTimer(
|
| 144 |
+
PHANDLE phNewTimer,
|
| 145 |
+
HANDLE timerQueue,
|
| 146 |
+
WAITORTIMERCALLBACK lpStartAddress,
|
| 147 |
+
PVOID lpParameter,
|
| 148 |
+
DWORD dueTime,
|
| 149 |
+
DWORD period,
|
| 150 |
+
ULONG flags
|
| 151 |
+
);
|
| 152 |
+
|
| 153 |
+
/// <summary>
|
| 154 |
+
/// Deletes the timer
|
| 155 |
+
/// </summary>
|
| 156 |
+
void __DeleteTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, HANDLE completionEvent);
|
| 157 |
+
|
| 158 |
+
/// <summary>
|
| 159 |
+
/// Changes the due time of the timer.
|
| 160 |
+
/// </summary>
|
| 161 |
+
BOOL __ChangeTimerQueueTimer(HANDLE timerQueue, HANDLE hTimer, ULONG dueTime, ULONG period);
|
| 162 |
+
|
| 163 |
+
/************** RegisterWaitForsingleObject ***********/
|
| 164 |
+
|
| 165 |
+
/// <summary>
|
| 166 |
+
/// Registers a waiter for the given handle. The callback is invoked when the handle is signalled
|
| 167 |
+
/// </summary>
|
| 168 |
+
HANDLE __RegisterWaitForSingleObject(HANDLE hEvent, WAITORTIMERCALLBACK callback, PVOID context);
|
| 169 |
+
|
| 170 |
+
/// <summary>
|
| 171 |
+
/// Removes the waiter for the given handle. Pending callbacks are cancelled. If a callback is
|
| 172 |
+
/// already running then this will NOT wait for the callback to complete.
|
| 173 |
+
/// </summary>
|
| 174 |
+
void __UnregisterWait(HANDLE hWait);
|
| 175 |
+
|
| 176 |
+
/************** System Info ***************************/
|
| 177 |
+
|
| 178 |
+
/// <summary>
|
| 179 |
+
/// Retrieves the information about the relationships of logical processors and related hardware
|
| 180 |
+
/// </summary>
|
| 181 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX __GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relation, PDWORD retLength);
|
| 182 |
+
|
| 183 |
+
/// <summary>
|
| 184 |
+
/// Retrieves the information about logical processors and related hardware
|
| 185 |
+
/// </summary
|
| 186 |
+
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION __GetLogicalProcessorInformation(PDWORD retLength);
|
| 187 |
+
|
| 188 |
+
/// <summary>
|
| 189 |
+
/// Retrieves the processor group and number of the logical processor where the thread is running
|
| 190 |
+
/// </summary>
|
| 191 |
+
void __GetCurrentProcessorNumberEx(PPROCESSOR_NUMBER procNum);
|
| 192 |
+
|
| 193 |
+
/// <summary>
|
| 194 |
+
/// Returns the highest numa node number
|
| 195 |
+
/// </summary>
|
| 196 |
+
ULONG __GetNumaHighestNodeNumber();
|
| 197 |
+
|
| 198 |
+
/// <summary>
|
| 199 |
+
/// Returns current thread ID
|
| 200 |
+
/// </summary>
|
| 201 |
+
#if defined(_CRTBLD) && !defined(CRTDLL2)
|
| 202 |
+
_CONCRTIMP
|
| 203 |
+
#endif
|
| 204 |
+
long __cdecl GetCurrentThreadId();
|
| 205 |
+
|
| 206 |
+
}}} // namespace Concurrency::details::platform
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.cpp
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// RealizedChore.cpp
|
| 9 |
+
//
|
| 10 |
+
// Miscellaneous implementations of things related to realized chores
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
/// <summary>
|
| 19 |
+
/// Method that executes the realized chore. Not inline-able because debugger needs to
|
| 20 |
+
/// locate executing realized chores by looking for this method's signature in the call
|
| 21 |
+
/// frame.
|
| 22 |
+
/// </summary>
|
| 23 |
+
__declspec(noinline)
|
| 24 |
+
void RealizedChore::Invoke()
|
| 25 |
+
{
|
| 26 |
+
m_pFunction(m_pParameters);
|
| 27 |
+
}
|
| 28 |
+
}
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/RealizedChore.h
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// RealizedChore.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the realized chore type declaration.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
namespace Concurrency
|
| 16 |
+
{
|
| 17 |
+
namespace details
|
| 18 |
+
{
|
| 19 |
+
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// The class RealizedChore is used to implement light-weight tasks and Agents.
|
| 22 |
+
/// </summary>
|
| 23 |
+
|
| 24 |
+
class RealizedChore : public _Chore
|
| 25 |
+
{
|
| 26 |
+
|
| 27 |
+
public:
|
| 28 |
+
|
| 29 |
+
/// <summary>
|
| 30 |
+
/// Constructor.
|
| 31 |
+
/// </summary>
|
| 32 |
+
RealizedChore(TaskProc pFunction, void* pParameters)
|
| 33 |
+
{
|
| 34 |
+
Initialize(pFunction, pParameters);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/// <summary>
|
| 38 |
+
/// Initializes a realized chore, on construction and reuse.
|
| 39 |
+
/// </summary>
|
| 40 |
+
void Initialize(TaskProc pFunction, void* pParameters)
|
| 41 |
+
{
|
| 42 |
+
m_pFunction = pFunction;
|
| 43 |
+
m_pParameters = pParameters;
|
| 44 |
+
m_pNext = NULL;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Method that executes the realized chore.
|
| 49 |
+
/// </summary>
|
| 50 |
+
__declspec(noinline)
|
| 51 |
+
void Invoke();
|
| 52 |
+
|
| 53 |
+
private:
|
| 54 |
+
template <typename T> friend class SQueue;
|
| 55 |
+
template <class T> friend class LockFreeStack;
|
| 56 |
+
|
| 57 |
+
// Parameter to the chore procedure.
|
| 58 |
+
void *m_pParameters;
|
| 59 |
+
|
| 60 |
+
#pragma warning(push)
|
| 61 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 62 |
+
union
|
| 63 |
+
{
|
| 64 |
+
// Next pointer for the locked runnables queue.
|
| 65 |
+
RealizedChore *m_pNext;
|
| 66 |
+
|
| 67 |
+
// List entry for lock free slist (free pool)
|
| 68 |
+
SLIST_ENTRY m_slNext;
|
| 69 |
+
};
|
| 70 |
+
#pragma warning(pop)
|
| 71 |
+
};
|
| 72 |
+
} // namespace details
|
| 73 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.cpp
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ResourceManager.h
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ResourceManager.h
|
| 9 |
+
//
|
| 10 |
+
// Implementation of IResourceManager.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
#pragma warning(push)
|
| 21 |
+
#pragma warning(disable: 4265) // non-virtual destructor in base class
|
| 22 |
+
class ResourceManager final : public ::Concurrency::IResourceManager
|
| 23 |
+
{
|
| 24 |
+
public:
|
| 25 |
+
/// <summary>
|
| 26 |
+
/// Increments the reference count on a resource manager.
|
| 27 |
+
/// </summary>
|
| 28 |
+
/// <returns>
|
| 29 |
+
/// Returns the resulting reference count.
|
| 30 |
+
/// </returns>
|
| 31 |
+
virtual unsigned int Reference();
|
| 32 |
+
|
| 33 |
+
/// <summary>
|
| 34 |
+
/// Decrements the reference count on a resource manager.
|
| 35 |
+
/// </summary>
|
| 36 |
+
/// <returns>
|
| 37 |
+
/// Returns the resulting reference count.
|
| 38 |
+
/// </returns>
|
| 39 |
+
virtual unsigned int Release();
|
| 40 |
+
|
| 41 |
+
/// <summary>
|
| 42 |
+
/// Associates an IScheduler with the ISchedulerProxy that represents the part
|
| 43 |
+
/// of IResourceManager associated with the IScheduler.
|
| 44 |
+
/// </summary>
|
| 45 |
+
/// <param name="pScheduler">
|
| 46 |
+
/// The scheduler to be associated.
|
| 47 |
+
/// </param>
|
| 48 |
+
/// <param name="version">
|
| 49 |
+
/// The version of the RM<->Scheduler communication channel that is being utilized.
|
| 50 |
+
/// </param>
|
| 51 |
+
virtual ISchedulerProxy * RegisterScheduler(IScheduler *pScheduler, unsigned int version);
|
| 52 |
+
|
| 53 |
+
/// <summary>
|
| 54 |
+
/// Returns the number of nodes available to the Resource Manager.
|
| 55 |
+
/// </summary>
|
| 56 |
+
/// <returns>
|
| 57 |
+
/// The number of nodes available to the Resource Manager.
|
| 58 |
+
/// </returns>
|
| 59 |
+
/**/
|
| 60 |
+
virtual unsigned int GetAvailableNodeCount() const
|
| 61 |
+
{
|
| 62 |
+
// TRANSITION: At some point when RM honors process affinity, etc..., go back and ensure that this is the correct value to return!
|
| 63 |
+
return m_nodeCount;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/// <summary>
|
| 67 |
+
/// Returns the first node in enumeration order as defined by the Resource Manager.
|
| 68 |
+
/// </summary>
|
| 69 |
+
/// <returns>
|
| 70 |
+
/// The first node in enumeration order as defined by the Resource Manager.
|
| 71 |
+
/// </returns>
|
| 72 |
+
/// <seealso cref="ITopologyNode::GetExecutionResourceCount Method"/>
|
| 73 |
+
/**/
|
| 74 |
+
virtual ITopologyNode* GetFirstNode() const
|
| 75 |
+
{
|
| 76 |
+
return m_pGlobalNodes->m_pTopologyObject;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/// <summary>
|
| 80 |
+
/// Creates an instance of the resource manager.
|
| 81 |
+
/// </summary>
|
| 82 |
+
static ResourceManager* CreateSingleton();
|
| 83 |
+
|
| 84 |
+
/// <summary>
|
| 85 |
+
/// Returns the OS version.
|
| 86 |
+
/// </summary>
|
| 87 |
+
static IResourceManager::OSVersion Version();
|
| 88 |
+
|
| 89 |
+
/// <summary>
|
| 90 |
+
/// Returns the number of nodes (processor packages or NUMA nodes)
|
| 91 |
+
/// </summary>
|
| 92 |
+
static unsigned int GetNodeCount();
|
| 93 |
+
|
| 94 |
+
/// <summary>
|
| 95 |
+
/// Returns the number of cores.
|
| 96 |
+
/// </summary>
|
| 97 |
+
static unsigned int GetCoreCount();
|
| 98 |
+
|
| 99 |
+
/// <summary>
|
| 100 |
+
/// Returns a pointer to the manager of factories for thread proxies.
|
| 101 |
+
/// </summary>
|
| 102 |
+
ThreadProxyFactoryManager * GetThreadProxyFactoryManager() { return &m_threadProxyFactoryManager; }
|
| 103 |
+
|
| 104 |
+
/// <summary>
|
| 105 |
+
/// These APIs return unique identifiers for use by schedulers, execution contexts and thread proxies.
|
| 106 |
+
/// </summary>
|
| 107 |
+
static unsigned int GetSchedulerId() { return InterlockedIncrement(&s_schedulerIdCount); }
|
| 108 |
+
static unsigned int GetExecutionContextId() { return InterlockedIncrement(&s_executionContextIdCount); }
|
| 109 |
+
static unsigned int GetThreadProxyId() { return InterlockedIncrement(&s_threadProxyIdCount); }
|
| 110 |
+
|
| 111 |
+
/// <summary>
|
| 112 |
+
/// These APIs restrict the execution resources used by the Concurrency Runtime's internal worker threads to the affinity set specified.
|
| 113 |
+
/// </summary>
|
| 114 |
+
static void SetTaskExecutionResources(DWORD_PTR dwAffinityMask);
|
| 115 |
+
static void SetTaskExecutionResources(USHORT count, PGROUP_AFFINITY pGroupAffinity);
|
| 116 |
+
|
| 117 |
+
/// <summary>
|
| 118 |
+
/// The main allocation routine that allocates cores for a newly created scheduler proxy.
|
| 119 |
+
/// </summary>
|
| 120 |
+
ExecutionResource * PerformAllocation(SchedulerProxy *pSchedulerProxy, bool fInitialAllocation, bool fSubscribeCurrentThread);
|
| 121 |
+
|
| 122 |
+
/// <summary>
|
| 123 |
+
/// This API registers the current thread with the resource manager, associating it with this scheduler proxy,
|
| 124 |
+
/// and returns an instance of IExecutionResource back to the scheduler, for bookkeeping and maintenance.
|
| 125 |
+
/// </summary>
|
| 126 |
+
ExecutionResource * SubscribeCurrentThread(SchedulerProxy *pSchedulerProxy);
|
| 127 |
+
|
| 128 |
+
/// <summary>
|
| 129 |
+
/// The allocation routine that allocates a single core for a newly registered external thread.
|
| 130 |
+
/// </summary>
|
| 131 |
+
ExecutionResource * PerformExternalThreadAllocation(SchedulerProxy *pSchedulerProxy);
|
| 132 |
+
|
| 133 |
+
/// <summary>
|
| 134 |
+
/// Removes an execution resource that was created for an external thread.
|
| 135 |
+
/// </summary>
|
| 136 |
+
void RemoveExecutionResource(ExecutionResource * pExecutionResource);
|
| 137 |
+
|
| 138 |
+
/// <summary>
|
| 139 |
+
/// Called in order to notify the resource manager that the given scheduler is shutting down. This
|
| 140 |
+
/// will cause the resource manager to immediately reclaim all resources granted to the scheduler.
|
| 141 |
+
/// </summary>
|
| 142 |
+
void Shutdown(SchedulerProxy *pProxy);
|
| 143 |
+
|
| 144 |
+
/// <summary>
|
| 145 |
+
/// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request
|
| 146 |
+
/// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request
|
| 147 |
+
/// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to
|
| 148 |
+
/// IScheduler::AddVirtualProcessors.
|
| 149 |
+
/// </summary>
|
| 150 |
+
/// <param name="pProxy">
|
| 151 |
+
/// The scheduler proxy that is making the allocation request.
|
| 152 |
+
/// </param>
|
| 153 |
+
/// <param name="doSubscribeCurrentThread">
|
| 154 |
+
/// Whether to subscribe the current thread and account for it during resource allocation.
|
| 155 |
+
/// </param>
|
| 156 |
+
/// <returns>
|
| 157 |
+
/// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise.
|
| 158 |
+
/// </returns>
|
| 159 |
+
IExecutionResource * RequestInitialVirtualProcessors(SchedulerProxy *pProxy, bool doSubscribeCurrentThread);
|
| 160 |
+
|
| 161 |
+
/// <summary>
|
| 162 |
+
/// Debug CRT test hook to create artificial topologies. With the retail CRT, this API simply returns.
|
| 163 |
+
/// </summary>
|
| 164 |
+
virtual void CreateNodeTopology(unsigned int nodeCount, unsigned int *pCoreCount, unsigned int **pNodeDistance, unsigned int *pProcessorGroups);
|
| 165 |
+
|
| 166 |
+
/// <summary>
|
| 167 |
+
/// The API returns after ensuring that all store buffers on processors that are running threads from this process,
|
| 168 |
+
/// are flushed. It does this by either calling a Win32 API that explicitly does this on versions of Windows that
|
| 169 |
+
/// support the functionality, or by changing the protection on a page that is locked into the working set, forcing
|
| 170 |
+
/// a TB flush on all processors in question.
|
| 171 |
+
/// </summary>
|
| 172 |
+
void FlushStoreBuffers();
|
| 173 |
+
|
| 174 |
+
/// <summary>
|
| 175 |
+
/// Returns the TLS slot where information about an execution resource is supposed to be stored.
|
| 176 |
+
/// </summary>
|
| 177 |
+
/// <remarks>
|
| 178 |
+
/// Used to check whether SubscribeCurrentThread already has an execution resource on which it is running.
|
| 179 |
+
/// </remarks>
|
| 180 |
+
DWORD GetExecutionResourceTls() const
|
| 181 |
+
{
|
| 182 |
+
return m_threadProxyFactoryManager.GetExecutionResourceTls();
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
/// <summary>
|
| 186 |
+
/// Decrements the use count on a particular global core. Used for removal of external threads.
|
| 187 |
+
/// </summary>
|
| 188 |
+
void DecrementCoreUseCount(unsigned int nodeId, unsigned int coreIndex)
|
| 189 |
+
{
|
| 190 |
+
// NOTE: Caller is responsible for holding the RM lock!
|
| 191 |
+
GlobalCore * pGlobalCore = &(m_pGlobalNodes[nodeId].m_pCores[coreIndex]);
|
| 192 |
+
pGlobalCore->m_useCount--;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
/// <summary>
|
| 196 |
+
/// Returns the current thread's node id and core id (relative to that node).
|
| 197 |
+
/// </summary>
|
| 198 |
+
unsigned int GetCurrentNodeAndCore(unsigned int * pCore);
|
| 199 |
+
|
| 200 |
+
/// <summary>
|
| 201 |
+
/// Returns the global subscription level of the underlying core.
|
| 202 |
+
/// </summary>
|
| 203 |
+
unsigned int CurrentSubscriptionLevel(unsigned int nodeId, unsigned int coreIndex);
|
| 204 |
+
|
| 205 |
+
/// <summary>
|
| 206 |
+
/// Returns true if there are any schedulers in the RM that need notifications sent, false, otherwise.
|
| 207 |
+
/// </summary>
|
| 208 |
+
bool SchedulersNeedNotifications()
|
| 209 |
+
{
|
| 210 |
+
return (m_numSchedulersNeedingNotifications > 0);
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
/// <summary>
|
| 214 |
+
/// Returns the number of schedulers that need core busy/idle notifications.
|
| 215 |
+
/// </summary>
|
| 216 |
+
unsigned int GetNumSchedulersForNotifications()
|
| 217 |
+
{
|
| 218 |
+
return m_numSchedulersNeedingNotifications;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
/// <summary>
|
| 222 |
+
/// Wakes up the dynamic RM worker from a wait state.
|
| 223 |
+
/// </summary>
|
| 224 |
+
void WakeupDynamicRMWorker()
|
| 225 |
+
{
|
| 226 |
+
SetEvent(m_hDynamicRMEvent);
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// <summary>
|
| 230 |
+
/// Sends NotifyResourcesExternallyIdle/NotifyResourcesExternallyBusy notifications to the schedulers that
|
| 231 |
+
/// qualify for them, to let them know that the hardware resources allocated to them are in use or out of use
|
| 232 |
+
/// by other schedulers that share those resources.
|
| 233 |
+
/// </summary>
|
| 234 |
+
/// <param name ="pNewlyAllocatedProxy">
|
| 235 |
+
/// The newly allocated scheduler proxy, if one was just allocated.
|
| 236 |
+
/// </param>
|
| 237 |
+
void SendResourceNotifications(SchedulerProxy * pNewlyAllocatedProxy = NULL);
|
| 238 |
+
|
| 239 |
+
/// <summary>
|
| 240 |
+
/// Allocates and initializes the data structure that will represent the allocated nodes for a scheduler proxy.
|
| 241 |
+
/// This function is called the first time a scheduler proxy requests an allocation.
|
| 242 |
+
/// </summary>
|
| 243 |
+
SchedulerNode * CreateAllocatedNodeData();
|
| 244 |
+
|
| 245 |
+
/// <summary>
|
| 246 |
+
/// Destroys the data structures representing nodes/cores allocated to a scheduler proxy when the proxy has
|
| 247 |
+
/// shutdown.
|
| 248 |
+
/// </summary>
|
| 249 |
+
void DestroyAllocatedNodeData(SchedulerNode * pAllocatedNodes);
|
| 250 |
+
|
| 251 |
+
/// <summary>
|
| 252 |
+
/// Gets the next node in enumeration order.
|
| 253 |
+
/// </summary>
|
| 254 |
+
GlobalNode *GetNextGlobalNode(const GlobalNode *pNode)
|
| 255 |
+
{
|
| 256 |
+
unsigned int idx = (unsigned int)((pNode - m_pGlobalNodes) + 1);
|
| 257 |
+
return ((idx < m_nodeCount) ? &m_pGlobalNodes[idx] : NULL);
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
private:
|
| 261 |
+
|
| 262 |
+
// State that controls what the dynamic RM worker thread does.
|
| 263 |
+
enum DynamicRMWorkerState
|
| 264 |
+
{
|
| 265 |
+
Standby,
|
| 266 |
+
LoadBalance,
|
| 267 |
+
Exit
|
| 268 |
+
};
|
| 269 |
+
|
| 270 |
+
struct AffinityRestriction
|
| 271 |
+
{
|
| 272 |
+
AffinityRestriction() :
|
| 273 |
+
m_count(0),
|
| 274 |
+
m_pGroupAffinity(NULL)
|
| 275 |
+
{
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
AffinityRestriction(USHORT count, HardwareAffinity * pGroupAffinity) :
|
| 279 |
+
m_count(count),
|
| 280 |
+
m_pGroupAffinity(pGroupAffinity)
|
| 281 |
+
{
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
~AffinityRestriction()
|
| 285 |
+
{
|
| 286 |
+
delete m_pGroupAffinity;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
HardwareAffinity * FindGroupAffinity(USHORT group)
|
| 290 |
+
{
|
| 291 |
+
for (USHORT i = 0; i < m_count; ++i)
|
| 292 |
+
{
|
| 293 |
+
if (m_pGroupAffinity[i].GetGroup() == group)
|
| 294 |
+
{
|
| 295 |
+
return &m_pGroupAffinity[i];
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
return NULL;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
void ApplyAffinityLimits(PGROUP_AFFINITY pGroupAffinity)
|
| 302 |
+
{
|
| 303 |
+
HardwareAffinity * pAffinity = FindGroupAffinity(pGroupAffinity->Group);
|
| 304 |
+
if (pAffinity != NULL)
|
| 305 |
+
{
|
| 306 |
+
pGroupAffinity->Mask &= pAffinity->GetMask();
|
| 307 |
+
}
|
| 308 |
+
else
|
| 309 |
+
{
|
| 310 |
+
// The user has not asked for this group to be included.
|
| 311 |
+
pGroupAffinity->Mask = 0;
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
USHORT GetCount()
|
| 316 |
+
{
|
| 317 |
+
return m_count;
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
private:
|
| 321 |
+
USHORT m_count;
|
| 322 |
+
HardwareAffinity * m_pGroupAffinity;
|
| 323 |
+
};
|
| 324 |
+
|
| 325 |
+
#if defined(CONCRT_TRACING)
|
| 326 |
+
|
| 327 |
+
struct GlobalCoreData
|
| 328 |
+
{
|
| 329 |
+
unsigned char m_nodeIndex;
|
| 330 |
+
unsigned char m_coreIndex;
|
| 331 |
+
unsigned char m_useCount;
|
| 332 |
+
unsigned char m_idleSchedulers;
|
| 333 |
+
};
|
| 334 |
+
|
| 335 |
+
// Maintains a trace for every core removed during preprocessing.
|
| 336 |
+
struct PreProcessingTraceData
|
| 337 |
+
{
|
| 338 |
+
SchedulerProxy * m_pProxy;
|
| 339 |
+
unsigned char m_nodeIndex;
|
| 340 |
+
unsigned char m_coreIndex;
|
| 341 |
+
bool m_fMarkedAsOwned : 1;
|
| 342 |
+
bool m_fBorrowedCoreRemoved : 1;
|
| 343 |
+
bool m_fSharedCoreRemoved : 1;
|
| 344 |
+
bool m_fIdleCore : 1;
|
| 345 |
+
};
|
| 346 |
+
|
| 347 |
+
// Maintains a trace for each core allocation
|
| 348 |
+
struct DynamicAllocationTraceData
|
| 349 |
+
{
|
| 350 |
+
SchedulerProxy * m_pGiver; // this is null if the core was unused or idle
|
| 351 |
+
SchedulerProxy * m_pReceiver;
|
| 352 |
+
unsigned char m_round;
|
| 353 |
+
unsigned char m_nodeIndex;
|
| 354 |
+
unsigned char m_coreIndex;
|
| 355 |
+
bool m_fUnusedCoreMigration : 1;
|
| 356 |
+
bool m_fIdleCoreSharing : 1;
|
| 357 |
+
bool m_fBorrowedByGiver : 1;
|
| 358 |
+
bool m_fIdleOnGiver : 1;
|
| 359 |
+
};
|
| 360 |
+
|
| 361 |
+
#endif
|
| 362 |
+
|
| 363 |
+
//
|
| 364 |
+
// Private data
|
| 365 |
+
//
|
| 366 |
+
|
| 367 |
+
// The singleton resource manager instance.
|
| 368 |
+
static ResourceManager *s_pResourceManager;
|
| 369 |
+
|
| 370 |
+
// 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
|
| 371 |
+
// >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
|
| 372 |
+
// affinity of the process in that group.
|
| 373 |
+
static DWORD_PTR s_processAffinityMask;
|
| 374 |
+
static DWORD_PTR s_systemAffinityMask;
|
| 375 |
+
|
| 376 |
+
// Pointer to a data structure that is initialized if the task execution affinity for ConcRT is limited via the API SetTaskExecutionResources.
|
| 377 |
+
static AffinityRestriction * s_pUserAffinityRestriction;
|
| 378 |
+
// 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.
|
| 379 |
+
static AffinityRestriction * s_pProcessAffinityRestriction;
|
| 380 |
+
|
| 381 |
+
// A lock that protects setting of the singleton instance.
|
| 382 |
+
static _StaticLock s_lock;
|
| 383 |
+
|
| 384 |
+
// The total number of hardware threads available to the RM.
|
| 385 |
+
static unsigned int s_coreCount;
|
| 386 |
+
|
| 387 |
+
// The number of nodes that hardware threads are grouped into.
|
| 388 |
+
static unsigned int s_nodeCount;
|
| 389 |
+
|
| 390 |
+
// Operating system characteristics.
|
| 391 |
+
static IResourceManager::OSVersion s_version;
|
| 392 |
+
|
| 393 |
+
// Termination indicator
|
| 394 |
+
static volatile LONG s_terminating;
|
| 395 |
+
|
| 396 |
+
// Static counters to generate unique identifiers.
|
| 397 |
+
static volatile LONG s_schedulerIdCount;
|
| 398 |
+
static volatile LONG s_executionContextIdCount;
|
| 399 |
+
static volatile LONG s_threadProxyIdCount;
|
| 400 |
+
|
| 401 |
+
// Variables used to obtain information about the topology of the system.
|
| 402 |
+
static DWORD s_logicalProcessorInformationLength;
|
| 403 |
+
static PSYSTEM_LOGICAL_PROCESSOR_INFORMATION s_pSysInfo;
|
| 404 |
+
|
| 405 |
+
// Constants that are used as parameters to the ReleaseSchedulerResources API
|
| 406 |
+
static const unsigned int ReleaseCoresDownToMin = static_cast<unsigned int>(-1);
|
| 407 |
+
static const unsigned int ReleaseOnlyBorrowedCores = static_cast<unsigned int>(-2);
|
| 408 |
+
|
| 409 |
+
// RM instance reference count
|
| 410 |
+
volatile LONG m_referenceCount;
|
| 411 |
+
|
| 412 |
+
// Number of schedulers currently using resources granted by the RM.
|
| 413 |
+
unsigned int m_numSchedulers;
|
| 414 |
+
|
| 415 |
+
// The maximum number of schedulers the dynamic RM worker has resources to handle, at any time. This can
|
| 416 |
+
// change during the lifetime of the process.
|
| 417 |
+
unsigned int m_maxSchedulers;
|
| 418 |
+
|
| 419 |
+
// Number of schedulers in the RM that need resource notifications.
|
| 420 |
+
unsigned int m_numSchedulersNeedingNotifications;
|
| 421 |
+
|
| 422 |
+
// The number of processor packages or NUMA nodes (whichever is greater) on the system. This is a mirror of s_nodeCount above.
|
| 423 |
+
unsigned int m_nodeCount;
|
| 424 |
+
|
| 425 |
+
// The number of HW threads on the machine. This is a mirror of s_coreCount above.
|
| 426 |
+
unsigned int m_coreCount;
|
| 427 |
+
|
| 428 |
+
// A field used during core migration to keep track of the number of idle cores - cores such that
|
| 429 |
+
// all schedulers they are assigned to are not using them.
|
| 430 |
+
unsigned int m_dynamicIdleCoresAvailable;
|
| 431 |
+
|
| 432 |
+
// Keeps track of the allocation round during dynamic core migration. Used for tracing.
|
| 433 |
+
unsigned int m_allocationRound;
|
| 434 |
+
|
| 435 |
+
// A state variable that is used to control how the dynamic worker behaves.
|
| 436 |
+
volatile DynamicRMWorkerState m_dynamicRMWorkerState;
|
| 437 |
+
|
| 438 |
+
// A lock that protects resource allocation and deallocation.
|
| 439 |
+
_NonReentrantBlockingLock m_lock;
|
| 440 |
+
|
| 441 |
+
// The global allocation map for all schedulers - array of processor nodes.
|
| 442 |
+
GlobalNode * m_pGlobalNodes;
|
| 443 |
+
|
| 444 |
+
// Handle to the dynamic RM worker thread.
|
| 445 |
+
HANDLE m_hDynamicRMThreadHandle;
|
| 446 |
+
|
| 447 |
+
// An event that is used to control the dynamic RM worker thread.
|
| 448 |
+
HANDLE m_hDynamicRMEvent;
|
| 449 |
+
|
| 450 |
+
// Data used for static and/or dynamic allocation.
|
| 451 |
+
AllocationData ** m_ppProxyData;
|
| 452 |
+
DynamicAllocationData ** m_ppGivingProxies;
|
| 453 |
+
DynamicAllocationData ** m_ppReceivingProxies;
|
| 454 |
+
|
| 455 |
+
// Lists to hold scheduler proxies.
|
| 456 |
+
List<SchedulerProxy, CollectionTypes::Count> m_schedulers;
|
| 457 |
+
|
| 458 |
+
// A collection of thread proxy factories
|
| 459 |
+
ThreadProxyFactoryManager m_threadProxyFactoryManager;
|
| 460 |
+
|
| 461 |
+
// A pointer to a page that is used to flush write buffers on versions of Windows < 6000.
|
| 462 |
+
char* m_pPageVirtualProtect;
|
| 463 |
+
|
| 464 |
+
#if defined(CONCRT_TRACING)
|
| 465 |
+
|
| 466 |
+
// Captures the initial global state during the DRM phase.
|
| 467 |
+
GlobalCoreData * m_drmInitialState;
|
| 468 |
+
unsigned int m_numTotalCores;
|
| 469 |
+
|
| 470 |
+
// Maintains a trace for every core removed during preprocessing.
|
| 471 |
+
PreProcessingTraceData m_preProcessTraces[100];
|
| 472 |
+
unsigned int m_preProcessTraceIndex;
|
| 473 |
+
|
| 474 |
+
// Maintains a trace for each core allocation
|
| 475 |
+
DynamicAllocationTraceData m_dynAllocationTraces[100];
|
| 476 |
+
unsigned int m_dynAllocationTraceIndex;
|
| 477 |
+
#endif
|
| 478 |
+
|
| 479 |
+
//
|
| 480 |
+
// Private methods
|
| 481 |
+
//
|
| 482 |
+
|
| 483 |
+
// Private constructor.
|
| 484 |
+
ResourceManager();
|
| 485 |
+
|
| 486 |
+
// Private destructor.
|
| 487 |
+
~ResourceManager();
|
| 488 |
+
|
| 489 |
+
/// <summary>
|
| 490 |
+
/// Initializes static variables related to the operating system version.
|
| 491 |
+
/// </summary>
|
| 492 |
+
static void RetrieveSystemVersionInformation();
|
| 493 |
+
|
| 494 |
+
/// <summary>
|
| 495 |
+
/// Captures the process affinity if it is not equal to the system affinity.
|
| 496 |
+
/// </summary>
|
| 497 |
+
static void CaptureProcessAffinity();
|
| 498 |
+
|
| 499 |
+
/// <summary>
|
| 500 |
+
/// Modify the passed in affinity based on any user or process affinity restrictions.
|
| 501 |
+
/// </summary>
|
| 502 |
+
static void ApplyAffinityRestrictions(PGROUP_AFFINITY pGroupAffinity);
|
| 503 |
+
static void ApplyAffinityRestrictions(PULONG_PTR pProcessorMask);
|
| 504 |
+
|
| 505 |
+
/// <summary>
|
| 506 |
+
/// Retrieves a buffer from the operating system that contains topology information.
|
| 507 |
+
/// </summary>
|
| 508 |
+
static void GetTopologyInformation(LOGICAL_PROCESSOR_RELATIONSHIP relationship);
|
| 509 |
+
|
| 510 |
+
/// <summary>
|
| 511 |
+
/// Cleans up the variables that store operating system topology information.
|
| 512 |
+
/// </summary>
|
| 513 |
+
static void CleanupTopologyInformation();
|
| 514 |
+
|
| 515 |
+
/// <summary>
|
| 516 |
+
/// Initializes static information related to the operating system and machine topology.
|
| 517 |
+
/// </summary>
|
| 518 |
+
static void InitializeSystemInformation(bool fSaveTopologyInfo = false);
|
| 519 |
+
|
| 520 |
+
/// <summary>
|
| 521 |
+
/// Creates a scheduler proxy for an IScheduler that registers with the RM.
|
| 522 |
+
/// </summary>
|
| 523 |
+
SchedulerProxy* CreateSchedulerProxy(IScheduler *pScheduler);
|
| 524 |
+
|
| 525 |
+
/// <summary>
|
| 526 |
+
/// Increments the reference count to RM but does not allow a 0 to 1 transition.
|
| 527 |
+
/// </summary>
|
| 528 |
+
/// <returns>
|
| 529 |
+
/// True if the RM was referenced; false, if the reference count was 0.
|
| 530 |
+
/// </returns>
|
| 531 |
+
bool SafeReference();
|
| 532 |
+
|
| 533 |
+
/// <summary>
|
| 534 |
+
/// Creates a structure of nodes and cores based on the machine topology.
|
| 535 |
+
/// </summary>
|
| 536 |
+
void DetermineTopology();
|
| 537 |
+
|
| 538 |
+
/// <summary>
|
| 539 |
+
/// Instructs existing schedulers to release cores. Then tries to allocate available cores for the new scheduler.
|
| 540 |
+
/// The parameter 'numberToFree' can have a couple of special values:
|
| 541 |
+
/// ReleaseCoresDownToMin - scheduler should release all cores above its minimum. Preference is giving to releasing borrowed cores.
|
| 542 |
+
/// ReleaseOnlyBorrowedCores - scheduler should release all its borrowed cores.
|
| 543 |
+
/// If the parameter is not a special value, a call should have previously been made for this scheduler with the value ReleaseOnlyBorrowedCores.
|
| 544 |
+
/// i.e., the scheduler should not have any borrowed cores to release.
|
| 545 |
+
/// </summary>
|
| 546 |
+
unsigned int ReleaseCoresOnExistingSchedulers(SchedulerProxy * pNewProxy, unsigned int request, unsigned int numberToFree);
|
| 547 |
+
|
| 548 |
+
/// <summary>
|
| 549 |
+
/// Tries to redistribute cores allocated to all schedulers, proportional to each schedulers value for 'DesiredHardwareThreads',
|
| 550 |
+
/// and allocates any freed cores to the new scheduler.
|
| 551 |
+
/// </summary>
|
| 552 |
+
unsigned int RedistributeCoresAmongAll(SchedulerProxy* pSchedulerProxy, unsigned int allocated, unsigned int minimum, unsigned int desired);
|
| 553 |
+
|
| 554 |
+
/// <summary>
|
| 555 |
+
/// Reserves cores for the new scheduler at higher use counts - this is used only to satisfy MinHWThreads.
|
| 556 |
+
/// </summary>
|
| 557 |
+
unsigned int ReserveAtHigherUseCounts(SchedulerProxy * pSchedulerProxy, unsigned int request);
|
| 558 |
+
|
| 559 |
+
/// <summary>
|
| 560 |
+
/// Worker routine that does actual core reservation, using the supplied use count. It tries to
|
| 561 |
+
/// pack reserved cores onto nodes by preferring nodes where more free cores are available.
|
| 562 |
+
/// </summary>
|
| 563 |
+
unsigned int ReserveCores(SchedulerProxy * pSchedulerProxy, unsigned int request, unsigned int useCount);
|
| 564 |
+
|
| 565 |
+
/// <summary>
|
| 566 |
+
/// Instructs a scheduler proxy to free up a fixed number of resources. This is only a temporary release of resources. The
|
| 567 |
+
/// use count on the global core is decremented and the scheduler proxy remembers the core as temporarily released. At a later
|
| 568 |
+
/// point, the release is either confirmed or rolled back, depending on whether the released core was used to satisfy a
|
| 569 |
+
/// different scheduler's allocation.
|
| 570 |
+
/// </summary>
|
| 571 |
+
/// <param name="pReceivingProxy">
|
| 572 |
+
/// The scheduler proxy for which the cores are being stolen - this is the proxy that is being currently allocated to.
|
| 573 |
+
/// </param>
|
| 574 |
+
/// <param name="pGivingProxy">
|
| 575 |
+
/// The scheduler proxy that needs to free up resources.
|
| 576 |
+
/// </param>
|
| 577 |
+
/// <param name="numberToFree">
|
| 578 |
+
/// The number of resources to free. This parameter can have a couple of special values:
|
| 579 |
+
/// ReleaseCoresDownToMin - scheduler should release all cores above its minimum. Preference is giving to releasing borrowed cores.
|
| 580 |
+
/// ReleaseOnlyBorrowedCores - scheduler should release all its borrowed cores.
|
| 581 |
+
/// If the parameter is not a special value, a call should have previously been made for this scheduler with the value ReleaseOnlyBorrowedCores.
|
| 582 |
+
/// i.e., the scheduler should not have any borrowed cores to release.
|
| 583 |
+
/// </param>
|
| 584 |
+
bool ReleaseSchedulerResources(SchedulerProxy * pReceivingProxy, SchedulerProxy *pGivingProxy, unsigned int numberToFree);
|
| 585 |
+
|
| 586 |
+
/// <summary>
|
| 587 |
+
/// Called to claim back any previously released cores that were not allocated to a different scheduler. If released
|
| 588 |
+
/// cores were allocated (stolen), the proxy needs to notify its scheduler to give up the related virtual processor
|
| 589 |
+
/// roots.
|
| 590 |
+
/// <summary>
|
| 591 |
+
void CommitStolenCores(SchedulerProxy * pSchedulerProxy);
|
| 592 |
+
|
| 593 |
+
/// <summary>
|
| 594 |
+
/// Starts up the dynamic RM worker thread if it is on standby, or creates a thread if one is not already created.
|
| 595 |
+
/// The worker thread wakes up at fixed intervals and load balances resources among schedulers, until it it put on standby.
|
| 596 |
+
/// </summary>
|
| 597 |
+
void CreateDynamicRMWorker();
|
| 598 |
+
|
| 599 |
+
/// <summary>
|
| 600 |
+
/// Routine that performs dynamic resource management among existing schedulers at fixed time intervals.
|
| 601 |
+
/// </summary>
|
| 602 |
+
void DynamicResourceManager();
|
| 603 |
+
|
| 604 |
+
/// <summary>
|
| 605 |
+
/// Performs a dynamic resource allocation based on feedback from hill climbing.
|
| 606 |
+
/// </summary>
|
| 607 |
+
void DoCoreMigration();
|
| 608 |
+
|
| 609 |
+
/// <summary>
|
| 610 |
+
/// When the number of schedulers in the RM goes from 2 to 1, this routine is invoked to make sure the remaining scheduler
|
| 611 |
+
/// has its desired number of cores, before putting the dynamic RM worker on standby. It is also called when there is just
|
| 612 |
+
/// one scheduler with external subscribed threads that it removes -> there is a chance that this move may allow us to allocate
|
| 613 |
+
/// more vprocs.
|
| 614 |
+
/// </summary>
|
| 615 |
+
bool DistributeCoresToSurvivingScheduler();
|
| 616 |
+
|
| 617 |
+
/// <summary>
|
| 618 |
+
/// This API is called by the dynamic RM worker thread when it starts up, and right after its state changed to
|
| 619 |
+
/// LoadBalance after being on Standby for a while. We need to find the existing schedulers, and discard the
|
| 620 |
+
/// statistics they have collected so far if any. Either we've never collected statistics for this scheduler before,
|
| 621 |
+
/// or too much/too little time has passed since we last collected statistics, and this information cannot be trusted.
|
| 622 |
+
/// </summary>
|
| 623 |
+
void DiscardExistingSchedulerStatistics();
|
| 624 |
+
|
| 625 |
+
/// <summary>
|
| 626 |
+
/// Ensures that the memory buffers needed for static and dynamic RM are of the right size, and initializes them.
|
| 627 |
+
/// </summary>
|
| 628 |
+
void InitializeRMBuffers();
|
| 629 |
+
|
| 630 |
+
/// <summary>
|
| 631 |
+
/// Populates data needed for allocation (static or dynamic).
|
| 632 |
+
/// </summary>
|
| 633 |
+
void PopulateCommonAllocationData(unsigned int index, SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData);
|
| 634 |
+
|
| 635 |
+
/// <summary>
|
| 636 |
+
/// Captures data needed for static allocation, for all existing schedulers. This includes determining which
|
| 637 |
+
/// cores on a scheduler are idle.
|
| 638 |
+
/// A number of preprocessing steps are are also preformed before we are ready to allocate cores for a new scheduler.
|
| 639 |
+
///
|
| 640 |
+
/// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away.
|
| 641 |
+
/// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed any more.
|
| 642 |
+
/// </summary>
|
| 643 |
+
void SetupStaticAllocationData(SchedulerProxy * pNewProxy, bool fSubscribeCurrentThread);
|
| 644 |
+
|
| 645 |
+
/// <summary>
|
| 646 |
+
/// Captures data needed for dynamic allocation for all existing schedulers. This includes gathering statistics
|
| 647 |
+
/// and invoking a per scheduler hill climbing instance, to get a suggested future allocation. Also, determines how may
|
| 648 |
+
/// idle cores a scheduler has.
|
| 649 |
+
/// </summary>
|
| 650 |
+
void PopulateDynamicAllocationData();
|
| 651 |
+
|
| 652 |
+
/// <summary>
|
| 653 |
+
/// Undo global state that was initialized to perform static allocation or dynamic core migration.
|
| 654 |
+
/// </summary>
|
| 655 |
+
void ResetGlobalAllocationData();
|
| 656 |
+
|
| 657 |
+
/// <summary>
|
| 658 |
+
/// Resets state that was set on the global cores during static or dynamic allocation.
|
| 659 |
+
/// </summary>
|
| 660 |
+
void ResetGlobalState();
|
| 661 |
+
|
| 662 |
+
/// <summary>
|
| 663 |
+
/// Toggles the idle state on a core and updates tracking counts.
|
| 664 |
+
/// </summary>
|
| 665 |
+
void ToggleRMIdleState(SchedulerNode * pAllocatedNode, SchedulerCore * pAllocatedCore,
|
| 666 |
+
GlobalNode * pGlobalNode, GlobalCore * pGlobalCore, AllocationData * pDRMData);
|
| 667 |
+
|
| 668 |
+
/// <summary>
|
| 669 |
+
/// A number of preprocessing steps are performed before we are ready to allocate cores. They include handling of borrowed and idle,
|
| 670 |
+
/// cores, as follows:
|
| 671 |
+
/// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away.
|
| 672 |
+
/// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore.
|
| 673 |
+
/// </summary>
|
| 674 |
+
void PreProcessStaticAllocationData();
|
| 675 |
+
|
| 676 |
+
/// <summary>
|
| 677 |
+
/// A number of preprocessing steps are preformed before we are ready to migrate cores. They include handling of borrowed, idle,
|
| 678 |
+
/// and shared cores, as follows:
|
| 679 |
+
///
|
| 680 |
+
/// - If a borrowed core is now in use by the other scheduler(s) that own that core, it is taken away.
|
| 681 |
+
/// - If the scheduler with the borrowed core is now the only scheduler using the core, it is not considered borrowed anymore.
|
| 682 |
+
/// - If hill climbing has suggested an allocation increase for a scheduler that has idle cores, or an allocation decrease that
|
| 683 |
+
/// does not take away all its idle cores, the RM overrides it, setting the suggested allocation for that scheduler to
|
| 684 |
+
/// max(minCores, allocatedCores - idleCores).
|
| 685 |
+
///
|
| 686 |
+
/// The new value of suggested allocation is used for the following:
|
| 687 |
+
/// - If the suggested allocation is less than the current allocation for a scheduler that has shared cores (cores oversubscribed
|
| 688 |
+
/// with a different scheduler), those cores are taken away here, since we want to minimize sharing.
|
| 689 |
+
/// </summary>
|
| 690 |
+
void PreProcessDynamicAllocationData();
|
| 691 |
+
|
| 692 |
+
/// <summary>
|
| 693 |
+
/// Preprocessing steps for borrowed cores - both static and dynamic allocation start out with a call to this API.
|
| 694 |
+
/// </summary>
|
| 695 |
+
void HandleBorrowedCores(SchedulerProxy * pSchedulerProxy, AllocationData * pAllocationData);
|
| 696 |
+
|
| 697 |
+
/// <summary>
|
| 698 |
+
/// Preprocessing steps for shared cores - this is used during dynamic core migration.
|
| 699 |
+
/// </summary>
|
| 700 |
+
void HandleSharedCores(SchedulerProxy * pSchedulerProxy, DynamicAllocationData * pAllocationData);
|
| 701 |
+
|
| 702 |
+
/// <summary>
|
| 703 |
+
/// This routine increases the suggested allocation to desired, for schedulers with the following characteristics:
|
| 704 |
+
/// 1) Hill climbing has *not* recommended an allocation decrease.
|
| 705 |
+
/// 2) They are using all the cores allocated to them (no idle cores).
|
| 706 |
+
/// In the second round of core migration, we try to satisfy these schedulers' desired allocation.
|
| 707 |
+
/// </summary>
|
| 708 |
+
void IncreaseFullyLoadedSchedulerAllocations();
|
| 709 |
+
|
| 710 |
+
/// <summary>
|
| 711 |
+
/// Decides on the number of additional cores to give a set of schedulers, given what the schedulers need and what is available.
|
| 712 |
+
/// </summary>
|
| 713 |
+
unsigned int AdjustDynamicAllocation(unsigned int coresAvailable, unsigned int coresNeeded, unsigned int numReceivers);
|
| 714 |
+
|
| 715 |
+
/// <summary>
|
| 716 |
+
/// Initializes receiving proxy data in preparation for core transfer. Calculates the number of partially filled nodes
|
| 717 |
+
/// for schedulers that are receiving cores, and sorts the receiving proxy data in increasing order of partial nodes.
|
| 718 |
+
/// </summary>
|
| 719 |
+
/// <returns>
|
| 720 |
+
/// Number of receivers that still need cores (allocation field of the receiving proxy data > 0).
|
| 721 |
+
/// </returns>
|
| 722 |
+
unsigned int PrepareReceiversForCoreTransfer(unsigned int numReceivers);
|
| 723 |
+
|
| 724 |
+
/// <summary>
|
| 725 |
+
/// Assigns one core at a time to a partially filled node on a receiving scheduler proxy, if possible
|
| 726 |
+
/// </summary>
|
| 727 |
+
bool FindCoreForPartiallyFilledNode(unsigned int& unusedCoreQuota,
|
| 728 |
+
unsigned int& usedCoreQuota,
|
| 729 |
+
DynamicAllocationData * pReceivingProxyData,
|
| 730 |
+
unsigned int numGivers);
|
| 731 |
+
|
| 732 |
+
/// <summary>
|
| 733 |
+
/// Attempts to assign cores to a receiver on a single empty node, taking cores from multiple givers if necessary.
|
| 734 |
+
/// </summary>
|
| 735 |
+
unsigned int FindBestFitExclusiveAllocation(unsigned int& unusedCoreQuota,
|
| 736 |
+
unsigned int& usedCoreQuota,
|
| 737 |
+
DynamicAllocationData * pReceivingProxyData,
|
| 738 |
+
unsigned int remainingReceivers,
|
| 739 |
+
unsigned int numGivers);
|
| 740 |
+
|
| 741 |
+
/// <summary>
|
| 742 |
+
/// Distributes unused cores and cores from scheduler proxies that are willing to give up cores to scheduler proxies that
|
| 743 |
+
/// need cores.
|
| 744 |
+
/// </summary>
|
| 745 |
+
void DistributeExclusiveCores(unsigned int totalCoresNeeded,
|
| 746 |
+
unsigned int unusedCoreQuota,
|
| 747 |
+
unsigned int usedCoreQuota,
|
| 748 |
+
unsigned int numReceivers,
|
| 749 |
+
unsigned int numGivers);
|
| 750 |
+
|
| 751 |
+
/// <summary>
|
| 752 |
+
/// Attempts to assign cores to a receiver on a single empty node, using idle cores.
|
| 753 |
+
/// </summary>
|
| 754 |
+
unsigned int FindBestFitIdleAllocation(unsigned int idleCoresAvailable, DynamicAllocationData * pReceivingProxyData, unsigned int remainingReceivers);
|
| 755 |
+
|
| 756 |
+
/// <summary>
|
| 757 |
+
/// Distributes idle cores to scheduler proxies that need cores.
|
| 758 |
+
/// </summary>
|
| 759 |
+
void DistributeIdleCores(unsigned int totalCoresAvailable, unsigned int numReceivers);
|
| 760 |
+
|
| 761 |
+
/// <summary>
|
| 762 |
+
/// Assigns a fixed number of unused or idle cores to a scheduler from a given node.
|
| 763 |
+
/// </summary>
|
| 764 |
+
void DynamicAssignCores(SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToMigrate, bool fIdle);
|
| 765 |
+
|
| 766 |
+
/// <summary>
|
| 767 |
+
/// Transfers a fixed number of cores from one scheduler to another.
|
| 768 |
+
/// </summary>
|
| 769 |
+
void DynamicMigrateCores(DynamicAllocationData * pGivingProxyData, SchedulerProxy * pReceivingProxy, unsigned int nodeIndex, unsigned int numCoresToMigrate);
|
| 770 |
+
|
| 771 |
+
#if defined (CONCRT_TRACING)
|
| 772 |
+
|
| 773 |
+
/// <summary>
|
| 774 |
+
/// Captures the initial state of the global map at the beginning of core migration, each cycle.
|
| 775 |
+
/// </summary>
|
| 776 |
+
void TraceInitialDRMState();
|
| 777 |
+
|
| 778 |
+
/// <summary>
|
| 779 |
+
/// Captures data relating to an action during DRM preprocessing.
|
| 780 |
+
/// </summary>
|
| 781 |
+
void TracePreProcessingAction(SchedulerProxy * pProxy, unsigned int nodeIndex, unsigned int coreIndex,
|
| 782 |
+
bool fMarkedAsOwned, bool fBorrowedCoreRemoved, bool fSharedCoreRemoved, bool fIdleCore);
|
| 783 |
+
|
| 784 |
+
/// <summary>
|
| 785 |
+
/// Captures data relating to an action during DRM core migration.
|
| 786 |
+
/// </summary>
|
| 787 |
+
void TraceCoreMigrationAction(SchedulerProxy * pGiver, SchedulerProxy * pReceiver, unsigned int round, unsigned int nodeIndex,
|
| 788 |
+
unsigned int coreIndex, bool fUnusedCoreMigration, bool fIdleCoreSharing, bool fBorrowedByGiver,
|
| 789 |
+
bool fIdleOnGiver);
|
| 790 |
+
|
| 791 |
+
#endif
|
| 792 |
+
/// <summary>
|
| 793 |
+
/// Performs borrowed core validation. A core can be borrowed by only one scheduler at a time.
|
| 794 |
+
/// </summary>
|
| 795 |
+
void ValidateBorrowedCores();
|
| 796 |
+
|
| 797 |
+
/// <summary>
|
| 798 |
+
/// Performs state validations during dynamic core migration.
|
| 799 |
+
/// </summary>
|
| 800 |
+
void ValidateDRMSchedulerState();
|
| 801 |
+
|
| 802 |
+
/// <summary>
|
| 803 |
+
/// Performs state validations during static allocation.
|
| 804 |
+
/// </summary>
|
| 805 |
+
void ValidateStaticSchedulerState(SchedulerProxy * pSchedulerProxy);
|
| 806 |
+
|
| 807 |
+
/// <summary>
|
| 808 |
+
/// Main thread procedure for the dynamic RM worker thread.
|
| 809 |
+
/// </summary>
|
| 810 |
+
/// <param name="lpParameter">
|
| 811 |
+
/// Resource manager pointer passed to the worker thread.
|
| 812 |
+
/// </param>
|
| 813 |
+
/// <returns>
|
| 814 |
+
/// Status on thread exit.
|
| 815 |
+
/// </returns>
|
| 816 |
+
static DWORD CALLBACK DynamicRMThreadProc(LPVOID lpParameter);
|
| 817 |
+
|
| 818 |
+
/// <summary>
|
| 819 |
+
/// Given a set of scaled floating point allocations that add up to nSum, rounds them to integers.
|
| 820 |
+
/// </summary>
|
| 821 |
+
static void RoundUpScaledAllocations(AllocationData ** ppData, unsigned int count, unsigned int nSum);
|
| 822 |
+
};
|
| 823 |
+
|
| 824 |
+
#pragma warning(pop)
|
| 825 |
+
} // namespace details
|
| 826 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.cpp
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ScheduleGroupBase.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation file for ScheduleGroupBase.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Constructs a schedule group with an initial reference count of 1.
|
| 22 |
+
/// </summary>
|
| 23 |
+
ScheduleGroupBase::ScheduleGroupBase(SchedulerBase *pScheduler, location* pGroupPlacement) :
|
| 24 |
+
m_pScheduler(pScheduler),
|
| 25 |
+
m_pAffineSegments(NULL),
|
| 26 |
+
m_pNonAffineSegments(NULL),
|
| 27 |
+
m_refCount(0)
|
| 28 |
+
{
|
| 29 |
+
Initialize(pGroupPlacement);
|
| 30 |
+
m_id = m_pScheduler->GetNewScheduleGroupId();
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/// <summary>
|
| 34 |
+
/// Performs initialization (or reinitialization) of a schedule group.
|
| 35 |
+
/// </summary>
|
| 36 |
+
void ScheduleGroupBase::Initialize(location* pGroupPlacement)
|
| 37 |
+
{
|
| 38 |
+
ASSERT(m_refCount == 0);
|
| 39 |
+
m_refCount = 1;
|
| 40 |
+
m_groupPlacement = *pGroupPlacement;
|
| 41 |
+
|
| 42 |
+
OMTRACE(MTRACE_EVT_INITIALIZED, this, NULL, NULL, 0);
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// <summary>
|
| 46 |
+
/// Constructs a new schedule group segment with a specific affinity in the specified ring.
|
| 47 |
+
/// </summary>
|
| 48 |
+
/// <param name="pOwningGroup">
|
| 49 |
+
/// The group to which this segment belongs.
|
| 50 |
+
/// </param>
|
| 51 |
+
/// <param name="pOwningRing">
|
| 52 |
+
/// The ring in which this segment is contained.
|
| 53 |
+
/// </param>
|
| 54 |
+
/// <param name="pSegmentAffinity">
|
| 55 |
+
/// The affinity of this segment.
|
| 56 |
+
/// </param>
|
| 57 |
+
ScheduleGroupSegmentBase::ScheduleGroupSegmentBase(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity) :
|
| 58 |
+
m_mailedTasks(pOwningGroup->GetScheduler(), pOwningGroup->GetScheduler()->GetBitSet(&m_affinity)),
|
| 59 |
+
m_workQueues(pOwningGroup->GetScheduler(), 256, 64),
|
| 60 |
+
m_detachedWorkQueues(pOwningGroup->GetScheduler(), 256, ListArray< ListArrayInlineLink<WorkQueue> >::DeletionThresholdInfinite), // No deletion
|
| 61 |
+
m_lastServiceTime(0)
|
| 62 |
+
{
|
| 63 |
+
Initialize(pOwningGroup, pOwningRing, pSegmentAffinity);
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/// <summary>
|
| 67 |
+
/// Initializes a schedule group segment.
|
| 68 |
+
/// </summary>
|
| 69 |
+
/// <param name="pOwningGroup">
|
| 70 |
+
/// The group to which this segment belongs.
|
| 71 |
+
/// </param>
|
| 72 |
+
/// <param name="pOwningRing">
|
| 73 |
+
/// The ring in which this segment is contained.
|
| 74 |
+
/// </param>
|
| 75 |
+
/// <param name="pSegmentAffinity">
|
| 76 |
+
/// The affinity of this segment.
|
| 77 |
+
/// </param>
|
| 78 |
+
void ScheduleGroupSegmentBase::Initialize(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location *pSegmentAffinity)
|
| 79 |
+
{
|
| 80 |
+
m_pOwningGroup = pOwningGroup;
|
| 81 |
+
m_pRing = pOwningRing;
|
| 82 |
+
m_affinity = *pSegmentAffinity;
|
| 83 |
+
m_priorityServiceLink.m_type = BoostedObject::BoostTypeScheduleGroupSegment;
|
| 84 |
+
m_priorityServiceLink.m_boostState = BoostedObject::BoostStateUnboosted;
|
| 85 |
+
|
| 86 |
+
m_affinitySet = pOwningGroup->GetScheduler()->GetBitSet(pSegmentAffinity);
|
| 87 |
+
if (pSegmentAffinity->_GetType() == location::_ExecutionResource)
|
| 88 |
+
{
|
| 89 |
+
m_maskIdIf = pOwningGroup->GetScheduler()->GetResourceMaskId(pSegmentAffinity->_GetId());
|
| 90 |
+
}
|
| 91 |
+
m_mailedTasks.Initialize(m_affinitySet);
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
/// <summary>
|
| 95 |
+
/// Creates a new segment with the specified affinity within the specified ring.
|
| 96 |
+
/// </summary>
|
| 97 |
+
/// <param name="pSegmentAffinity">
|
| 98 |
+
/// The affinity of the segment.
|
| 99 |
+
/// </param>
|
| 100 |
+
/// <param name="pOwningRing">
|
| 101 |
+
/// The ring into which the new segment will be placed. Some aspect of pSegmentAffinity must overlap with the node to which this ring
|
| 102 |
+
/// belongs.
|
| 103 |
+
/// </param>
|
| 104 |
+
/// <returns>
|
| 105 |
+
/// A new segment with the specified affinity within the specified ring.
|
| 106 |
+
/// </returns>
|
| 107 |
+
ScheduleGroupSegmentBase *ScheduleGroupBase::CreateSegment(location* pSegmentAffinity, SchedulingRing *pOwningRing)
|
| 108 |
+
{
|
| 109 |
+
ScheduleGroupSegmentBase **pSegmentList = pSegmentAffinity->_Is_system() ? &m_pNonAffineSegments : &m_pAffineSegments;
|
| 110 |
+
|
| 111 |
+
//
|
| 112 |
+
// At the moment, there is no point in free listing segments -- they are bound to the lifetime of the group. There should never be
|
| 113 |
+
// anything on the free list except at destruct time.
|
| 114 |
+
//
|
| 115 |
+
ScheduleGroupSegmentBase *pSegment = NULL;
|
| 116 |
+
|
| 117 |
+
if (pSegmentAffinity->_Is_system())
|
| 118 |
+
{
|
| 119 |
+
pSegment = pOwningRing->m_nonAffineSegments.PullFromFreePool();
|
| 120 |
+
}
|
| 121 |
+
else
|
| 122 |
+
{
|
| 123 |
+
pSegment = pOwningRing->m_affineSegments.PullFromFreePool();
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
if (pSegment == NULL)
|
| 127 |
+
{
|
| 128 |
+
pSegment = AllocateSegment(pOwningRing, pSegmentAffinity);
|
| 129 |
+
}
|
| 130 |
+
else
|
| 131 |
+
{
|
| 132 |
+
pSegment->Initialize(this, pOwningRing, pSegmentAffinity);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
pSegment->m_pNext = *pSegmentList;
|
| 136 |
+
*pSegmentList = pSegment;
|
| 137 |
+
|
| 138 |
+
//
|
| 139 |
+
// 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
|
| 140 |
+
// 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
|
| 141 |
+
// and scheduled work to this scheduler from there despite this scheduler not having any virtual processors from that node. There are two ways
|
| 142 |
+
// in which this might happen:
|
| 143 |
+
//
|
| 144 |
+
// 1: We decide that location::current can return specific locations from an external thread. Today this is not done.
|
| 145 |
+
// 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
|
| 146 |
+
// *currently* have any virtual processors there.
|
| 147 |
+
//
|
| 148 |
+
// 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.
|
| 149 |
+
// After all, we never know when dynamic RM will kick in and change that.
|
| 150 |
+
//
|
| 151 |
+
// Note that this does *NOT* necessarily mean that the work is strongly affine to a non-existent node/ring!
|
| 152 |
+
//
|
| 153 |
+
if (!pOwningRing->IsActive())
|
| 154 |
+
{
|
| 155 |
+
pOwningRing->Activate();
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
if (pSegmentAffinity->_Is_system())
|
| 159 |
+
{
|
| 160 |
+
pOwningRing->m_nonAffineSegments.Add(pSegment);
|
| 161 |
+
}
|
| 162 |
+
else
|
| 163 |
+
{
|
| 164 |
+
pOwningRing->m_affineSegments.Add(pSegment);
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
OMTRACE(MTRACE_EVT_CREATESEGMENT, this, NULL, NULL, pSegment);
|
| 168 |
+
|
| 169 |
+
return pSegment;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/// <summary>
|
| 173 |
+
/// Internal routine which finds an appropriate segment for a task placement.
|
| 174 |
+
/// </summary>
|
| 175 |
+
/// <param name="pSegmentAffinity">
|
| 176 |
+
/// A segment with this affinity will be located.
|
| 177 |
+
/// </param>
|
| 178 |
+
/// <param name="pRing">
|
| 179 |
+
/// A segment with pSegmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order
|
| 180 |
+
/// to keep work local.
|
| 181 |
+
/// </param>
|
| 182 |
+
/// <returns>
|
| 183 |
+
/// A segment with the specified affinity close to the specified location.
|
| 184 |
+
/// </returns>
|
| 185 |
+
ScheduleGroupSegmentBase *ScheduleGroupBase::FindSegment(location* pSegmentAffinity, SchedulingRing *pRing)
|
| 186 |
+
{
|
| 187 |
+
ScheduleGroupSegmentBase **pSegmentList = pSegmentAffinity->_Is_system() ? &m_pNonAffineSegments : &m_pAffineSegments;
|
| 188 |
+
ScheduleGroupSegmentBase *pSegment = *pSegmentList;
|
| 189 |
+
|
| 190 |
+
location origin = pRing->GetOwningNode()->GetLocation();
|
| 191 |
+
|
| 192 |
+
//
|
| 193 |
+
// @TODO:
|
| 194 |
+
//
|
| 195 |
+
// At some point, it might be beneficial to hash segments within the group instead of looking them up. There will be M * N segments
|
| 196 |
+
// within a group where M is the number of different locations utilized and N is the number of nodes which those locations span.
|
| 197 |
+
//
|
| 198 |
+
while (pSegment != NULL)
|
| 199 |
+
{
|
| 200 |
+
if (pSegment->GetAffinity() == *pSegmentAffinity && pSegment->GetSchedulingRing() == pRing)
|
| 201 |
+
{
|
| 202 |
+
break;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
pSegment = pSegment->m_pNext;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
return pSegment;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/// <summary>
|
| 212 |
+
/// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement
|
| 213 |
+
/// and the origin of the thread making the call.
|
| 214 |
+
/// </summary>
|
| 215 |
+
/// <param name="pSegmentAffinity">
|
| 216 |
+
/// A segment with affinity to this particular location will be located.
|
| 217 |
+
/// </param>
|
| 218 |
+
/// <param name="pOrigin">
|
| 219 |
+
/// A location representing the origin of the search. The scheduler will tend to fork a given pSegmentAffinity into segments by node in order
|
| 220 |
+
/// to keep locally scheduled work with the same affinity local.
|
| 221 |
+
/// </param>
|
| 222 |
+
/// <param name="fCreateNew">
|
| 223 |
+
/// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is
|
| 224 |
+
/// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found.
|
| 225 |
+
/// </param>
|
| 226 |
+
/// <returns>
|
| 227 |
+
/// A segment appropriate for scheduling work with affinity to pSegmentAffinity from code executing at pOrigin. Note that NULL may be returned
|
| 228 |
+
/// if fCreateNew is specified as false and no appropriate segment yet exists for the group.
|
| 229 |
+
/// </returns>
|
| 230 |
+
ScheduleGroupSegmentBase *ScheduleGroupBase::LocateSegment(location* pSegmentAffinity, bool fCreateNew)
|
| 231 |
+
{
|
| 232 |
+
//
|
| 233 |
+
// In general, we wish to find a segment local to our origin (the node where the current context is executing) that has a placement
|
| 234 |
+
// of pSegmentAffinity, or create a new segment should one not yet exist within the group.
|
| 235 |
+
//
|
| 236 |
+
// In practice, a segment will only be created specific to the current ring, if the current ring's affinity is "within" pSegmentAffinity.
|
| 237 |
+
// Otherwise, someone creating a group and saying something like:
|
| 238 |
+
//
|
| 239 |
+
// pGroup->ScheduleTask(..., N0);
|
| 240 |
+
// (..., N1);
|
| 241 |
+
// (..., N2);
|
| 242 |
+
// (..., Nn);
|
| 243 |
+
//
|
| 244 |
+
// might wind up creating n^2 segments within the group for no good reason.
|
| 245 |
+
//
|
| 246 |
+
// This will also allow unbiased work to fork per node and work on local portions. This is exactly the kind of separation we want.
|
| 247 |
+
//
|
| 248 |
+
// 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
|
| 249 |
+
// possible that the pSegmentAffinity to locate does not intersect our origin (even if the scheduler could place the current thread). In either of these
|
| 250 |
+
// cases, we revert back to previous behavior and round robin an appropriate ring. The ring's affinity must intersect pSegmentAffinity in some way!
|
| 251 |
+
|
| 252 |
+
//
|
| 253 |
+
SchedulingNode * pNode = m_pScheduler->FindCurrentNode();
|
| 254 |
+
SchedulingRing *pRing = (pNode != NULL) ? pNode->GetSchedulingRing() : m_pScheduler->GetNextSchedulingRing();
|
| 255 |
+
|
| 256 |
+
//
|
| 257 |
+
// Make sure pRing's affinity intersects pSegmentAffinity (or find a ring which does in round robin order).
|
| 258 |
+
//
|
| 259 |
+
location ringAffinity = pRing->GetOwningNode()->GetLocation();
|
| 260 |
+
location unbiased;
|
| 261 |
+
SchedulingRing * pFirstRing = pRing;
|
| 262 |
+
|
| 263 |
+
while (!ringAffinity._FastNodeIntersects(*pSegmentAffinity))
|
| 264 |
+
{
|
| 265 |
+
pRing = m_pScheduler->GetNextSchedulingRing(NULL, pRing);
|
| 266 |
+
ringAffinity = pRing->GetOwningNode()->GetLocation();
|
| 267 |
+
|
| 268 |
+
// If we've looped through all the SchedulingRings and haven't found an intersection, back off
|
| 269 |
+
// to an unbiased system-wide location. This can occur on certain machines that have NUMA
|
| 270 |
+
// nodes with no processors, thus they have valid node locations with no ring created by the
|
| 271 |
+
// scheduler since they can do no work.
|
| 272 |
+
if (pRing == pFirstRing)
|
| 273 |
+
{
|
| 274 |
+
ASSERT(pSegmentAffinity->_GetType() == location::_NumaNode);
|
| 275 |
+
pSegmentAffinity = &unbiased;
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
//
|
| 280 |
+
// 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
|
| 281 |
+
// the appropriate segment already exists.
|
| 282 |
+
//
|
| 283 |
+
ScheduleGroupSegmentBase *pSegment = FindSegment(pSegmentAffinity, pRing);
|
| 284 |
+
if (pSegment == NULL && fCreateNew)
|
| 285 |
+
{
|
| 286 |
+
m_segmentLock._Acquire();
|
| 287 |
+
pSegment = FindSegment(pSegmentAffinity, pRing);
|
| 288 |
+
if (pSegment == NULL)
|
| 289 |
+
{
|
| 290 |
+
pSegment = CreateSegment(pSegmentAffinity, pRing);
|
| 291 |
+
}
|
| 292 |
+
m_segmentLock._Release();
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
ASSERT(!pSegment || pSegment->GetSchedulingRing()->IsActive());
|
| 296 |
+
return pSegment;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
/// <summary>
|
| 300 |
+
/// Removes all schedule group segments from the group.
|
| 301 |
+
/// </summary>
|
| 302 |
+
void ScheduleGroupBase::RemoveSegments()
|
| 303 |
+
{
|
| 304 |
+
ScheduleGroupSegmentBase *pSegment = m_pNonAffineSegments;
|
| 305 |
+
ScheduleGroupSegmentBase *pNext = NULL;
|
| 306 |
+
|
| 307 |
+
while(pSegment)
|
| 308 |
+
{
|
| 309 |
+
pNext = pSegment->m_pNext;
|
| 310 |
+
pSegment->Remove();
|
| 311 |
+
pSegment = pNext;
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
pSegment = m_pAffineSegments;
|
| 315 |
+
while(pSegment)
|
| 316 |
+
{
|
| 317 |
+
pNext = pSegment->m_pNext;
|
| 318 |
+
pSegment->Remove();
|
| 319 |
+
pSegment = pNext;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
m_pNonAffineSegments = NULL;
|
| 323 |
+
m_pAffineSegments = NULL;
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
/// <summary>
|
| 327 |
+
/// Schedules a light-weight task within the schedule group.
|
| 328 |
+
/// </summary>
|
| 329 |
+
/// <param name="proc">
|
| 330 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 331 |
+
/// </param>
|
| 332 |
+
/// <param name="data">
|
| 333 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 334 |
+
/// </param>
|
| 335 |
+
/// <remarks>
|
| 336 |
+
/// Calling the <c>ScheduleTask</c> method implicitly places a reference count on the schedule group which is removed by the runtime
|
| 337 |
+
/// at an appropriate time after the task executes.
|
| 338 |
+
/// </remarks>
|
| 339 |
+
/// <seealso cref="ScheduleGroup::Reference Method"/>
|
| 340 |
+
void ScheduleGroupBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data)
|
| 341 |
+
{
|
| 342 |
+
ScheduleGroupSegmentBase *pSegment = LocateSegment(&m_groupPlacement, true);
|
| 343 |
+
pSegment->ScheduleTask(proc, data);
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
/// <summary>
|
| 347 |
+
/// Schedules a light-weight task within the schedule group. The light-weight task will also be biased towards executing at the specified location.
|
| 348 |
+
/// </summary>
|
| 349 |
+
/// <param name="proc">
|
| 350 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 351 |
+
/// </param>
|
| 352 |
+
/// <param name="data">
|
| 353 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 354 |
+
/// </param>
|
| 355 |
+
/// <param name="placement">
|
| 356 |
+
/// A reference to a location where the light-weight task will be biased towards executing at.
|
| 357 |
+
/// </param>
|
| 358 |
+
/// <remarks>
|
| 359 |
+
/// Calling the <c>ScheduleTask</c> method implicitly places a reference count on the schedule group which is removed by the runtime
|
| 360 |
+
/// at an appropriate time after the task executes.
|
| 361 |
+
/// </remarks>
|
| 362 |
+
/// <seealso cref="ScheduleGroup::Reference Method"/>
|
| 363 |
+
/// <seealso cref="location Class"/>
|
| 364 |
+
void ScheduleGroupBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void * data, location& placement)
|
| 365 |
+
{
|
| 366 |
+
ScheduleGroupSegmentBase *pSegment = LocateSegment(&placement, true);
|
| 367 |
+
pSegment->ScheduleTask(proc, data);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
/// <summary>
|
| 371 |
+
/// Adds runnable context to the schedule group. This is usually a previously blocked context that
|
| 372 |
+
/// was subsequently unblocked, but it could also be an internal context executing chores on behalf
|
| 373 |
+
/// of an external context.
|
| 374 |
+
/// </summary>
|
| 375 |
+
void ScheduleGroupSegmentBase::AddRunnableContext(InternalContextBase* pContext, location bias)
|
| 376 |
+
{
|
| 377 |
+
ASSERT(pContext->GetScheduleGroupSegment() == this);
|
| 378 |
+
//
|
| 379 |
+
// If the current context does not belong to this group, the caller is not guaranteed to have a reference to the
|
| 380 |
+
// schedule group. We call CrossGroupRunnable() to make sure that scheduler and schedule group are kept around long
|
| 381 |
+
// enough, that we can attempt to startup the virtual processor without fear of the scheduler being finalized, or the
|
| 382 |
+
// schedule group being destroyed.
|
| 383 |
+
//
|
| 384 |
+
ContextBase* pCurrentContext = SchedulerBase::FastCurrentContext();
|
| 385 |
+
|
| 386 |
+
if ((pCurrentContext == NULL) || (pCurrentContext->GetScheduleGroupSegment() != this))
|
| 387 |
+
{
|
| 388 |
+
// Set this flag to allow the calling thread to use 'this' safely once the context is pushed onto runnables.
|
| 389 |
+
// Note that this call does not need a fence because it is fenced by push to the runnable contexts collection.
|
| 390 |
+
pContext->CrossGroupRunnable(TRUE);
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
//
|
| 394 |
+
// If there is an "inactive pending thread" virtual processor, this runnable should be shoved to it instead of going through the normal
|
| 395 |
+
// wake path. There is *NO REASON* to require an SFW context to immediately switch to this.
|
| 396 |
+
//
|
| 397 |
+
SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler();
|
| 398 |
+
if (!(pScheduler->HasVirtualProcessorPendingThreadCreate() && pScheduler->PushRunnableToInactive(pContext, bias)))
|
| 399 |
+
{
|
| 400 |
+
// Add it to the actual collection.
|
| 401 |
+
AddToRunnablesCollection(pContext);
|
| 402 |
+
|
| 403 |
+
if (!m_affinity._Is_system() && bias == m_affinity)
|
| 404 |
+
{
|
| 405 |
+
NotifyAffinitizedWork();
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
if (pScheduler->HasVirtualProcessorAvailable())
|
| 409 |
+
{
|
| 410 |
+
pScheduler->StartupIdleVirtualProcessor(this, bias);
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
// Reset the flag, if it was set, since we're done with touching scheduler/context data.
|
| 415 |
+
// This flag is not fenced. This means the reader could end up spinning a little longer until the data is
|
| 416 |
+
// propagated by the cache coherency mechanism.
|
| 417 |
+
pContext->CrossGroupRunnable(FALSE);
|
| 418 |
+
// NOTE: It is not safe to touch 'this' after this point, if this was a cross group runnable.
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
/// <summary>
|
| 422 |
+
/// Steals an unrealized chore from a workqueue in the schedule group.
|
| 423 |
+
/// </summary>
|
| 424 |
+
/// <param name="fForceStealLocalized">
|
| 425 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 426 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 427 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 428 |
+
/// </param>
|
| 429 |
+
_UnrealizedChore* ScheduleGroupSegmentBase::StealUnrealizedChore(bool fForceStealLocalized)
|
| 430 |
+
{
|
| 431 |
+
//
|
| 432 |
+
// When we fail to steal from a work queue that's detached, it's an indication that the work queue
|
| 433 |
+
// is finally empty and can be retired.
|
| 434 |
+
//
|
| 435 |
+
|
| 436 |
+
_UnrealizedChore *pChore;
|
| 437 |
+
|
| 438 |
+
bool killEmptyQueues = false;
|
| 439 |
+
int maxIndex = m_workQueues.MaxIndex();
|
| 440 |
+
if (maxIndex > 0)
|
| 441 |
+
{
|
| 442 |
+
int skippedCount = 0;
|
| 443 |
+
const int maxSkippedCount = 16;
|
| 444 |
+
int skippedState[maxSkippedCount];
|
| 445 |
+
bool fEntered = false;
|
| 446 |
+
|
| 447 |
+
for (int j = 0; j < maxIndex; j++)
|
| 448 |
+
{
|
| 449 |
+
WorkQueue *pQueue = m_workQueues[j];
|
| 450 |
+
if (pQueue != NULL)
|
| 451 |
+
{
|
| 452 |
+
if ( !pQueue->IsEmpty())
|
| 453 |
+
{
|
| 454 |
+
if ((pChore = pQueue->TryToSteal(fForceStealLocalized, fEntered)) != NULL)
|
| 455 |
+
return pChore;
|
| 456 |
+
else if ( !fEntered)
|
| 457 |
+
{
|
| 458 |
+
if (skippedCount < maxSkippedCount-1)
|
| 459 |
+
{
|
| 460 |
+
skippedState[skippedCount++] = j;
|
| 461 |
+
continue;
|
| 462 |
+
}
|
| 463 |
+
else if ((pChore = pQueue->Steal(fForceStealLocalized)) != NULL)
|
| 464 |
+
return pChore;
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
killEmptyQueues |= (pQueue->IsDetached() && pQueue->IsEmpty());
|
| 468 |
+
}
|
| 469 |
+
else
|
| 470 |
+
killEmptyQueues |= pQueue->IsDetached();
|
| 471 |
+
}
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
if (skippedCount > 0)
|
| 475 |
+
{
|
| 476 |
+
for (int j = 0; j < skippedCount; j++)
|
| 477 |
+
{
|
| 478 |
+
WorkQueue *pQueue = m_workQueues[skippedState[j]];
|
| 479 |
+
if (pQueue != NULL)
|
| 480 |
+
{
|
| 481 |
+
if ( !pQueue->IsEmpty() && (pChore = pQueue->Steal(fForceStealLocalized)) != NULL)
|
| 482 |
+
return pChore;
|
| 483 |
+
else
|
| 484 |
+
killEmptyQueues |= (pQueue->IsDetached() && pQueue->IsEmpty());
|
| 485 |
+
}
|
| 486 |
+
}
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
if (m_mailedTasks.Dequeue(&pChore))
|
| 491 |
+
{
|
| 492 |
+
// The chore may not be from a detached workqueue, but since it is dequeued from a mailbox, we set it as detached
|
| 493 |
+
// which will add the stealing context to a list in the task collection instead of the owning contexts stealer collection.
|
| 494 |
+
pChore->_SetDetached(true);
|
| 495 |
+
return pChore;
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
int numDetachedArrays = m_detachedWorkQueues.MaxIndex();
|
| 499 |
+
if (numDetachedArrays > 0 && killEmptyQueues)
|
| 500 |
+
{
|
| 501 |
+
for (int i = 0; i < m_workQueues.MaxIndex(); i++)
|
| 502 |
+
{
|
| 503 |
+
WorkQueue *pQueue = m_workQueues[i];
|
| 504 |
+
if (pQueue != NULL)
|
| 505 |
+
{
|
| 506 |
+
if (pQueue->IsDetached() && pQueue->IsUnstructuredEmpty())
|
| 507 |
+
{
|
| 508 |
+
SafelyDeleteDetachedWorkQueue(pQueue);
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
return NULL;
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
/// <summary>
|
| 518 |
+
/// Returns true if the group has any realized chores.
|
| 519 |
+
/// This is used during scheduler finalization when only one thread is active in the scheduler.
|
| 520 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 521 |
+
/// </summary>
|
| 522 |
+
bool ScheduleGroupSegmentBase::HasRealizedChores() const
|
| 523 |
+
{
|
| 524 |
+
return !m_realizedChores.Empty();
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
/// <summary>
|
| 528 |
+
/// Returns the first work queue in the schedule group that has unrealized chores.
|
| 529 |
+
/// This is only stable during scheduler finalization when only one thread is active in the scheduler.
|
| 530 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 531 |
+
/// </summary>
|
| 532 |
+
WorkQueue *ScheduleGroupSegmentBase::LocateUnrealizedChores()
|
| 533 |
+
{
|
| 534 |
+
for (int i = 0; i < m_workQueues.MaxIndex(); i++)
|
| 535 |
+
{
|
| 536 |
+
WorkQueue *pQueue = m_workQueues[i];
|
| 537 |
+
if (pQueue != NULL)
|
| 538 |
+
{
|
| 539 |
+
if (!pQueue->IsStructuredEmpty() || !pQueue->IsUnstructuredEmpty())
|
| 540 |
+
{
|
| 541 |
+
return pQueue;
|
| 542 |
+
}
|
| 543 |
+
else if (pQueue->IsDetached())
|
| 544 |
+
{
|
| 545 |
+
SafelyDeleteDetachedWorkQueue(pQueue);
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
if (!m_mailedTasks.IsEmpty())
|
| 551 |
+
return MAILBOX_LOCATION;
|
| 552 |
+
|
| 553 |
+
return NULL;
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
/// <summary>
|
| 557 |
+
/// Returns true if any of the workqueues in the schedule group has unrealized chores.
|
| 558 |
+
/// This is only stable during scheduler finalization when only one thread is active in the scheduler.
|
| 559 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 560 |
+
/// </summary>
|
| 561 |
+
bool ScheduleGroupSegmentBase::HasUnrealizedChores()
|
| 562 |
+
{
|
| 563 |
+
return LocateUnrealizedChores() != NULL;
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
/// <summary>
|
| 567 |
+
/// Called to safely delete a detached work queue -- this is lock free and utilizes safe points to perform
|
| 568 |
+
/// the deletion and dereference. It can be called during the normal SFW or during the finalization sweep
|
| 569 |
+
/// safely.
|
| 570 |
+
/// </summary>
|
| 571 |
+
bool ScheduleGroupSegmentBase::SafelyDeleteDetachedWorkQueue(WorkQueue *pQueue)
|
| 572 |
+
{
|
| 573 |
+
//
|
| 574 |
+
// The way in which we resolve race conditions between this and queue reattachment is by who is able to remove the
|
| 575 |
+
// element from the detached list array. We cannot kill the work queue until it's gone out of that list array.
|
| 576 |
+
//
|
| 577 |
+
if (m_detachedWorkQueues.Remove(&pQueue->m_detachment, false))
|
| 578 |
+
{
|
| 579 |
+
//
|
| 580 |
+
// There's always the possibility of a very subtle race where we check IsDetached and IsUnstructuredEmpty and then
|
| 581 |
+
// are preempted, the queue is reattached, work is added, and it's detached again in the same spot with work. We
|
| 582 |
+
// cannot free the queue in such circumstance. Only if it is empty AFTER removal from m_detachedWorkQueues are
|
| 583 |
+
// we safe.
|
| 584 |
+
//
|
| 585 |
+
if (pQueue->IsUnstructuredEmpty())
|
| 586 |
+
{
|
| 587 |
+
//
|
| 588 |
+
// Each detached work queue holds a reference on the group. It is referenced
|
| 589 |
+
// in ScheduleGroupBase::DetachActiveWorkQueue(). Since we are removing this
|
| 590 |
+
// empty work queue, we need to release the reference.
|
| 591 |
+
//
|
| 592 |
+
// There's an unfortunate reality here -- this work queue might be the LAST thing holding reference onto
|
| 593 |
+
// the schedule group. It's entirely possible that someone just stole and hasn't yet gotten to the point
|
| 594 |
+
// where a reference is added to the schedule group. If we arbitrarily release this reference, we might delete
|
| 595 |
+
// (or reuse) an active schedule group. This could cause all sorts of problems.
|
| 596 |
+
//
|
| 597 |
+
// Instead of trying to release that reference here, we will wait until the next safe point to do so. We
|
| 598 |
+
// are guaranteed no one is in the middle of stealing from this schedule group at that time.
|
| 599 |
+
//
|
| 600 |
+
// Note that this means that the stealer **MUST** stay within a critical region until after the WorkItem::TransferReferences
|
| 601 |
+
// call.
|
| 602 |
+
//
|
| 603 |
+
pQueue->RetireAtSafePoint(this);
|
| 604 |
+
return true;
|
| 605 |
+
}
|
| 606 |
+
else
|
| 607 |
+
{
|
| 608 |
+
CONCRT_COREASSERT(!m_pOwningGroup->GetScheduler()->InFinalizationSweep());
|
| 609 |
+
|
| 610 |
+
//
|
| 611 |
+
// The queue is not empty and we need to roll back. Since we never removed the queue from m_workQueues, the work will
|
| 612 |
+
// still be found by the scheduler without undue futzing around sleep states. The queue must, however, be placed
|
| 613 |
+
// back in m_detachedWorkQueues in a detached state.
|
| 614 |
+
//
|
| 615 |
+
// There's an unfortunate reality here too -- the slot used for the queue within the detached queues list might already
|
| 616 |
+
// be gone. Adding back to the detached queues might trigger a heap allocation. Given that this might be in SFW, a heap allocation
|
| 617 |
+
// triggering UMS would be bad. Hence -- if we need to roll back (unlikely), we must do this at a safe point.
|
| 618 |
+
//
|
| 619 |
+
pQueue->RedetachFromScheduleGroupAtSafePoint(this);
|
| 620 |
+
}
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
return false;
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
/// <summary>
|
| 627 |
+
/// Creates a realized (non workstealing) chore in the schedule group. Used to schedule light-weight
|
| 628 |
+
/// tasks and agents.
|
| 629 |
+
/// </summary>
|
| 630 |
+
void ScheduleGroupSegmentBase::ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data)
|
| 631 |
+
{
|
| 632 |
+
if (proc == NULL)
|
| 633 |
+
{
|
| 634 |
+
throw std::invalid_argument("proc");
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
SchedulerBase *pScheduler = m_pOwningGroup->GetScheduler();
|
| 638 |
+
RealizedChore *pChore = pScheduler->GetRealizedChore(proc, data);
|
| 639 |
+
TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::ScheduleTask(sgroup=%d,ring=0x%p,chore=0x%p)\n", Id(), m_pRing, pChore);
|
| 640 |
+
|
| 641 |
+
// Every task takes a reference on its schedule group. This is to ensure a schedule group has a ref count > 0 if
|
| 642 |
+
// no contexts are working on it, but queued tasks are present. The reference count is transferred to the context
|
| 643 |
+
// that eventually executes the task.
|
| 644 |
+
m_pOwningGroup->InternalReference();
|
| 645 |
+
|
| 646 |
+
m_realizedChores.Enqueue(pChore);
|
| 647 |
+
|
| 648 |
+
ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext();
|
| 649 |
+
|
| 650 |
+
if (pCurrentContext == NULL || pCurrentContext->GetScheduler() != pScheduler)
|
| 651 |
+
{
|
| 652 |
+
//
|
| 653 |
+
// This is a thread that is in no way tracked in ConcRT (no context assigned to it) or it is a context foreign to
|
| 654 |
+
// this scheduler, so we cannot have statistics directly associated with its context. Instead, there is an entry in
|
| 655 |
+
// the TLS section PER scheduler that points to the external statistics mapping. From that information, we can know
|
| 656 |
+
// whether we have seen this thread before and whether it was ever scheduling tasks on the current scheduler.
|
| 657 |
+
//
|
| 658 |
+
ExternalStatistics * externalStatistics = (ExternalStatistics *) platform::__TlsGetValue(pScheduler->m_dwExternalStatisticsIndex);
|
| 659 |
+
|
| 660 |
+
if (externalStatistics == NULL)
|
| 661 |
+
{
|
| 662 |
+
//
|
| 663 |
+
// This is the first piece of statistical data for this thread on this scheduler, so
|
| 664 |
+
// create a statistics class, add it to the list array of statistics on this scheduler and
|
| 665 |
+
// save it in the TLS slot reserved for statistics on this scheduler.
|
| 666 |
+
//
|
| 667 |
+
externalStatistics = _concrt_new ExternalStatistics();
|
| 668 |
+
pScheduler->AddExternalStatistics(externalStatistics);
|
| 669 |
+
platform::__TlsSetValue(pScheduler->m_dwExternalStatisticsIndex, externalStatistics);
|
| 670 |
+
}
|
| 671 |
+
else
|
| 672 |
+
{
|
| 673 |
+
//
|
| 674 |
+
// We already have some statistical data for this thread on this scheduler.
|
| 675 |
+
//
|
| 676 |
+
ASSERT(pScheduler->m_externalThreadStatistics.MaxIndex() > 0);
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
ASSERT(externalStatistics != NULL);
|
| 680 |
+
externalStatistics->IncrementEnqueuedTaskCounter();
|
| 681 |
+
}
|
| 682 |
+
else if (pCurrentContext->IsExternal())
|
| 683 |
+
{
|
| 684 |
+
static_cast<ExternalContextBase *>(pCurrentContext)->IncrementEnqueuedTaskCounter();
|
| 685 |
+
}
|
| 686 |
+
else
|
| 687 |
+
{
|
| 688 |
+
static_cast<InternalContextBase *>(pCurrentContext)->IncrementEnqueuedTaskCounter();
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
//
|
| 692 |
+
// 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
|
| 693 |
+
// processors as necessary to snap them back to affine work.
|
| 694 |
+
//
|
| 695 |
+
if (!m_affinity._Is_system())
|
| 696 |
+
{
|
| 697 |
+
NotifyAffinitizedWork();
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
// In most cases this if check will fail. To avoid the function call overhead in the common case, we check
|
| 701 |
+
// for virtual processors beforehand.
|
| 702 |
+
if (pScheduler->HasVirtualProcessorAvailableForNewWork())
|
| 703 |
+
{
|
| 704 |
+
pScheduler->StartupNewVirtualProcessor(this, m_affinity);
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
/// <summary>
|
| 711 |
+
/// Places a work queue in the detached queue. This will cause the work queue to remain eligible for stealing
|
| 712 |
+
/// while the queue can be detached from a context. The work queue will be recycled and handed back to a
|
| 713 |
+
/// context executing within the schedule group that needs a queue. If the queue is not recycled, it will be
|
| 714 |
+
/// abandoned and freed when it becomes empty (a steal on it while in detached mode fails).
|
| 715 |
+
/// </summary>
|
| 716 |
+
void ScheduleGroupSegmentBase::DetachActiveWorkQueue(WorkQueue *pWorkQueue)
|
| 717 |
+
{
|
| 718 |
+
m_pOwningGroup->InternalReference();
|
| 719 |
+
|
| 720 |
+
//
|
| 721 |
+
// Note: there is a distinct lack of relative atomicity between the flag set and the queue add. The worst thing that
|
| 722 |
+
// happens here is that we ask the list array to remove an element at an invalid index. It is prepared to handle
|
| 723 |
+
// that anyway.
|
| 724 |
+
//
|
| 725 |
+
pWorkQueue->SetDetached(true);
|
| 726 |
+
m_detachedWorkQueues.Add(&pWorkQueue->m_detachment);
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
/// <summary>
|
| 730 |
+
/// Called by a work queue in order to roll back an attempted kill that could not be committed due to reuse.
|
| 731 |
+
/// </summary>
|
| 732 |
+
void ScheduleGroupSegmentBase::RedetachQueue(WorkQueue *pWorkQueue)
|
| 733 |
+
{
|
| 734 |
+
//
|
| 735 |
+
// Roll back by reinserting into m_detachedWorkQueues. We detect the error before setting detached state to false or releasing
|
| 736 |
+
// reference, so this is the only operation which needs to happen. It just cannot happen during the steal due to the fact that
|
| 737 |
+
// there is a **SLIGHT** chance that the call will perform a heap allocation.
|
| 738 |
+
//
|
| 739 |
+
m_detachedWorkQueues.Add(&pWorkQueue->m_detachment);
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
/// <summary>
|
| 743 |
+
/// Attempts to acquire a detached work queue from the schedule group. If such a work queue is found, it
|
| 744 |
+
/// is removed from detached queue and returned. This allows recycling of work queues that are detached
|
| 745 |
+
/// yet still have unstructured work.
|
| 746 |
+
///</summary>
|
| 747 |
+
WorkQueue *ScheduleGroupSegmentBase::GetDetachedWorkQueue()
|
| 748 |
+
{
|
| 749 |
+
int maxIdx = m_detachedWorkQueues.MaxIndex();
|
| 750 |
+
for (int i = 0; i < maxIdx; i++)
|
| 751 |
+
{
|
| 752 |
+
ListArrayInlineLink<WorkQueue> *pLink = m_detachedWorkQueues[i];
|
| 753 |
+
|
| 754 |
+
//
|
| 755 |
+
// No code below this may dereference pLink unless it is removed from the list array. There is no guarantee
|
| 756 |
+
// of safety as this can be called from an external context or multiple internal contexts.
|
| 757 |
+
//
|
| 758 |
+
if (pLink != NULL && m_detachedWorkQueues.Remove(pLink, i, false))
|
| 759 |
+
{
|
| 760 |
+
WorkQueue *pWorkQueue = pLink->m_pObject;
|
| 761 |
+
|
| 762 |
+
pWorkQueue->SetDetached(false);
|
| 763 |
+
|
| 764 |
+
//
|
| 765 |
+
// This removed detached work queue incremented the reference count
|
| 766 |
+
// in ScheduleGroupBase::DetachActiveWorkQueue(). Release it now.
|
| 767 |
+
//
|
| 768 |
+
// This is safe because we are inside the schedule group getting a work queue. This means that there is already
|
| 769 |
+
// some context with a reference on the schedule group and it won't disappear out from underneath us by removing
|
| 770 |
+
// the detach reference.
|
| 771 |
+
//
|
| 772 |
+
m_pOwningGroup->InternalRelease();
|
| 773 |
+
|
| 774 |
+
return pWorkQueue;
|
| 775 |
+
}
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
return NULL;
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
/// <summary>
|
| 782 |
+
/// Called by a work queue in order to retire itself at a safe point.
|
| 783 |
+
/// </summary>
|
| 784 |
+
void ScheduleGroupSegmentBase::RetireDetachedQueue(WorkQueue *pWorkQueue)
|
| 785 |
+
{
|
| 786 |
+
CONCRT_VERIFY(m_workQueues.Remove(pWorkQueue));
|
| 787 |
+
|
| 788 |
+
//
|
| 789 |
+
// This removed detached work queue incremented the reference count
|
| 790 |
+
// in ScheduleGroupBase::DetachActiveWorkQueue(). Release it now.
|
| 791 |
+
//
|
| 792 |
+
m_pOwningGroup->InternalRelease();
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
RealizedChore * ScheduleGroupSegmentBase::GetRealizedChore()
|
| 796 |
+
{
|
| 797 |
+
if (m_realizedChores.Empty())
|
| 798 |
+
return NULL;
|
| 799 |
+
|
| 800 |
+
RealizedChore *pChore = m_realizedChores.Dequeue();
|
| 801 |
+
TRACE(TRACE_SCHEDULER, L"ScheduleGroup::GetRealizedChore(sgroup=%d,ring=0x%p,chore=0x%p)\n", Id(), m_pRing, pChore);
|
| 802 |
+
return pChore;
|
| 803 |
+
}
|
| 804 |
+
|
| 805 |
+
/// <summary>
|
| 806 |
+
/// Gets an internal context from either the idle pool or a newly allocated one and prepares it for
|
| 807 |
+
/// execution. A NULL return value from the routine is considered fatal (out of memory). This is the
|
| 808 |
+
/// API that should be used to obtain an internal context for execution. The context is associated
|
| 809 |
+
// with this schedule group.
|
| 810 |
+
/// </summary>
|
| 811 |
+
InternalContextBase * ScheduleGroupSegmentBase::GetInternalContext(_Chore *pChore, bool choreStolen)
|
| 812 |
+
{
|
| 813 |
+
// Get an internal context from the idle pool
|
| 814 |
+
InternalContextBase* pContext = m_pOwningGroup->GetScheduler()->GetInternalContext();
|
| 815 |
+
|
| 816 |
+
if (pContext != NULL)
|
| 817 |
+
{
|
| 818 |
+
// Associate it with this schedule group
|
| 819 |
+
pContext->PrepareForUse(this, pChore, choreStolen);
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
return pContext;
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
/// <summary>
|
| 826 |
+
/// Releases an internal context after execution into the idle pool. If the idle pool
|
| 827 |
+
/// is full, it could be freed.
|
| 828 |
+
/// </summary>
|
| 829 |
+
void ScheduleGroupSegmentBase::ReleaseInternalContext(InternalContextBase *pContext)
|
| 830 |
+
{
|
| 831 |
+
pContext->RemoveFromUse();
|
| 832 |
+
m_pOwningGroup->GetScheduler()->ReleaseInternalContext(pContext);
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
/// <summary>
|
| 836 |
+
/// Destroys a schedule group segment.
|
| 837 |
+
/// </summary>
|
| 838 |
+
ScheduleGroupSegmentBase::~ScheduleGroupSegmentBase()
|
| 839 |
+
{
|
| 840 |
+
//
|
| 841 |
+
// Make CERTAIN that the quick cache is cleared if this segment is contained within it.
|
| 842 |
+
//
|
| 843 |
+
if (m_affinity._GetType() == location::_ExecutionResource)
|
| 844 |
+
{
|
| 845 |
+
m_pOwningGroup->GetScheduler()->ClearQuickCacheSlotIf(m_maskIdIf, this);
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
// There shall be no work queues (detached or otherwise) when a schedule group segment
|
| 849 |
+
// is deleted. This assumption is made in our safe point mechanism. If one
|
| 850 |
+
// of the workqueues in a schedule group segment requests a safe point invocation after
|
| 851 |
+
// the one for schedule group deletion, the workqueues would be deleted before
|
| 852 |
+
// its callback is invoked.
|
| 853 |
+
ASSERT(m_workQueues.IsEmptyAtSafePoint());
|
| 854 |
+
ASSERT(m_detachedWorkQueues.IsEmptyAtSafePoint());
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
/// <summary>
|
| 858 |
+
/// Removes the segment.
|
| 859 |
+
/// </summary>
|
| 860 |
+
void ScheduleGroupSegmentBase::Remove()
|
| 861 |
+
{
|
| 862 |
+
OMTRACE(MTRACE_EVT_DESTROYSEGMENT, m_pOwningGroup, NULL, NULL, this);
|
| 863 |
+
// The order of operations here is important. Removing from the list array should be the last operation we perform on
|
| 864 |
+
// the segment.
|
| 865 |
+
m_pOwningGroup->m_pScheduler->RemovePrioritizedObject(&m_priorityServiceLink);
|
| 866 |
+
m_pRing->RemoveScheduleGroupSegment(this);
|
| 867 |
+
}
|
| 868 |
+
|
| 869 |
+
} // namespace details
|
| 870 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ScheduleGroupBase.h
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ScheduleGroupBase.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing ScheduleGroup related declarations.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
#define MAILBOX_LOCATION (reinterpret_cast<WorkQueue *>(1))
|
| 17 |
+
|
| 18 |
+
namespace Concurrency
|
| 19 |
+
{
|
| 20 |
+
namespace details
|
| 21 |
+
{
|
| 22 |
+
//
|
| 23 |
+
// A ScheduleGroupBase* object represents a schedule group as defined in the public API set. It is a container of work which is related
|
| 24 |
+
// and benefits from temporally and spatially close scheduling.
|
| 25 |
+
//
|
| 26 |
+
// A ScheduleGroupSegmentBase* object represents a segment of a schedule group with affinity to a particular location -- in this case affinity
|
| 27 |
+
// to a particular scheduling node.
|
| 28 |
+
//
|
| 29 |
+
|
| 30 |
+
class ScheduleGroupBase;
|
| 31 |
+
|
| 32 |
+
/// <summary>
|
| 33 |
+
/// A piece of a schedule group which is uniquely assigned to a given scheduling node/ring.
|
| 34 |
+
/// </summary>
|
| 35 |
+
class ScheduleGroupSegmentBase
|
| 36 |
+
{
|
| 37 |
+
public:
|
| 38 |
+
|
| 39 |
+
/// <summary>
|
| 40 |
+
/// Called by a work queue in order to retire itself at a safe point.
|
| 41 |
+
/// </summary>
|
| 42 |
+
void RetireDetachedQueue(WorkQueue *pWorkQueue);
|
| 43 |
+
|
| 44 |
+
/// <summary>
|
| 45 |
+
/// Called by a work queue in order to roll back an attempted kill that could not be committed due to reuse.
|
| 46 |
+
/// </summary>
|
| 47 |
+
void RedetachQueue(WorkQueue *pWorkQueue);
|
| 48 |
+
|
| 49 |
+
/// <summary>
|
| 50 |
+
/// Destroys a schedule group segment.
|
| 51 |
+
/// </summary>
|
| 52 |
+
virtual ~ScheduleGroupSegmentBase();
|
| 53 |
+
|
| 54 |
+
/// <summary>
|
| 55 |
+
/// Returns the group to which this segment belongs.
|
| 56 |
+
/// </summary>
|
| 57 |
+
ScheduleGroupBase *GetGroup() const
|
| 58 |
+
{
|
| 59 |
+
return m_pOwningGroup;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/// <summary>
|
| 63 |
+
/// Returns the scheduling ring to which this segment belongs.
|
| 64 |
+
/// </summary>
|
| 65 |
+
SchedulingRing *GetSchedulingRing() const
|
| 66 |
+
{
|
| 67 |
+
return m_pRing;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/// <summary>
|
| 71 |
+
/// Schedules a realized (non workstealing) chore in the schedule group segment. Used to schedule light-weight
|
| 72 |
+
/// tasks and agents.
|
| 73 |
+
/// </summary>
|
| 74 |
+
void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data);
|
| 75 |
+
|
| 76 |
+
/// <summary>
|
| 77 |
+
/// Marks the segment as serviced at a particular time mark.
|
| 78 |
+
/// </summary>
|
| 79 |
+
void ServiceMark(ULONGLONG markTime)
|
| 80 |
+
{
|
| 81 |
+
//
|
| 82 |
+
// Avoid cache contention on this by only writing the service time every so often. We only care about this on granularities of something
|
| 83 |
+
// like 1/2 seconds anyway -- it's effectively the priority boost time granularity that we care about.
|
| 84 |
+
//
|
| 85 |
+
if (TimeSinceServicing(markTime) > 100)
|
| 86 |
+
{
|
| 87 |
+
OMTRACE(MTRACE_EVT_MARK, this, NULL, NULL, markTime);
|
| 88 |
+
m_lastServiceTime = markTime;
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Returns the time delta between the last service time and the passed service time.
|
| 94 |
+
/// </summary>
|
| 95 |
+
ULONG TimeSinceServicing(ULONGLONG markTime)
|
| 96 |
+
{
|
| 97 |
+
return (ULONG) (markTime - m_lastServiceTime);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/// <summary>
|
| 101 |
+
/// Returns a segment from its internal list entry.
|
| 102 |
+
/// </summary>
|
| 103 |
+
static ScheduleGroupSegmentBase* FromBoostEntry(BoostedObject *pEntry)
|
| 104 |
+
{
|
| 105 |
+
return CONTAINING_RECORD(pEntry, ScheduleGroupSegmentBase, m_priorityServiceLink);
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/// <summary>
|
| 109 |
+
/// Notifies virtual processors that work affinitized to them has become available in the schedule group segment.
|
| 110 |
+
/// </summary>
|
| 111 |
+
virtual void NotifyAffinitizedWork() =0;
|
| 112 |
+
|
| 113 |
+
protected:
|
| 114 |
+
|
| 115 |
+
//
|
| 116 |
+
// Private methods
|
| 117 |
+
//
|
| 118 |
+
|
| 119 |
+
/// <summary>
|
| 120 |
+
/// Constructs a new schedule group segment with a specific affinity in the specified ring.
|
| 121 |
+
/// </summary>
|
| 122 |
+
/// <param name="pOwningGroup">
|
| 123 |
+
/// The group to which this segment belongs.
|
| 124 |
+
/// </param>
|
| 125 |
+
/// <param name="pOwningRing">
|
| 126 |
+
/// The ring in which this segment is contained.
|
| 127 |
+
/// </param>
|
| 128 |
+
/// <param name="pSegmentAffinity">
|
| 129 |
+
/// The affinity of this segment.
|
| 130 |
+
/// </param>
|
| 131 |
+
ScheduleGroupSegmentBase(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location* pSegmentAffinity);
|
| 132 |
+
|
| 133 |
+
/// <summary>
|
| 134 |
+
/// Initializes a schedule group segment.
|
| 135 |
+
/// </summary>
|
| 136 |
+
/// <param name="pOwningGroup">
|
| 137 |
+
/// The group to which this segment belongs.
|
| 138 |
+
/// </param>
|
| 139 |
+
/// <param name="pOwningRing">
|
| 140 |
+
/// The ring in which this segment is contained.
|
| 141 |
+
/// </param>
|
| 142 |
+
/// <param name="pSegmentAffinity">
|
| 143 |
+
/// The affinity of this segment.
|
| 144 |
+
/// </param>
|
| 145 |
+
void Initialize(ScheduleGroupBase *pOwningGroup, SchedulingRing *pOwningRing, location *pSegmentAffinity);
|
| 146 |
+
|
| 147 |
+
/// <summary>
|
| 148 |
+
/// Adds runnable context to the schedule group. This is usually a previously blocked context that
|
| 149 |
+
/// was subsequently unblocked, but it could also be an internal context executing chores on behalf
|
| 150 |
+
/// of an external context.
|
| 151 |
+
/// </summary>
|
| 152 |
+
void AddRunnableContext(InternalContextBase *pContext, location bias = location());
|
| 153 |
+
|
| 154 |
+
/// <summary>
|
| 155 |
+
/// Puts a runnable context into the runnables collection in the schedule group.
|
| 156 |
+
/// </summary>
|
| 157 |
+
virtual void AddToRunnablesCollection(InternalContextBase *pContext) =0;
|
| 158 |
+
|
| 159 |
+
virtual InternalContextBase *GetRunnableContext() = 0;
|
| 160 |
+
|
| 161 |
+
/// <summary>
|
| 162 |
+
/// Returns true if the group has any realized chores.
|
| 163 |
+
/// This is used during scheduler finalization when only one thread is active in the scheduler.
|
| 164 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 165 |
+
/// </summary>
|
| 166 |
+
bool HasRealizedChores() const;
|
| 167 |
+
|
| 168 |
+
/// <summary>
|
| 169 |
+
/// Returns the first work queue in the schedule group that has unrealized chores.
|
| 170 |
+
/// This is only stable during scheduler finalization when only one thread is active in the scheduler.
|
| 171 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 172 |
+
/// </summary>
|
| 173 |
+
/// <returns>
|
| 174 |
+
/// This method either returns a special constant MAILBOX_LOCATION if work was found in the mailbox or
|
| 175 |
+
/// a work queue in which an unrealized chore was found.
|
| 176 |
+
/// </returns>
|
| 177 |
+
WorkQueue *LocateUnrealizedChores();
|
| 178 |
+
|
| 179 |
+
/// <summary>
|
| 180 |
+
/// Returns true if any of the workqueues in the schedule group has unrealized chores.
|
| 181 |
+
/// This is only stable during scheduler finalization when only one thread is active in the scheduler.
|
| 182 |
+
/// At any other time, this information is stale since new work could get added to the scheduler.
|
| 183 |
+
/// </summary>
|
| 184 |
+
bool HasUnrealizedChores();
|
| 185 |
+
|
| 186 |
+
/// <summary>
|
| 187 |
+
/// Returns a realized chore if one exists in the queue.
|
| 188 |
+
/// </summary>
|
| 189 |
+
RealizedChore *GetRealizedChore();
|
| 190 |
+
|
| 191 |
+
/// <summary>
|
| 192 |
+
/// Acquires an internal context for execution
|
| 193 |
+
/// </summary>
|
| 194 |
+
InternalContextBase* GetInternalContext(_Chore *pChore = NULL, bool choreStolen = false);
|
| 195 |
+
|
| 196 |
+
/// <summary>
|
| 197 |
+
/// Releases an internal context after execution
|
| 198 |
+
/// </summary>
|
| 199 |
+
void ReleaseInternalContext(InternalContextBase *pContext);
|
| 200 |
+
|
| 201 |
+
/// <summary>
|
| 202 |
+
/// Steals an unrealized chore from a workqueue in the schedule group.
|
| 203 |
+
/// </summary>
|
| 204 |
+
/// <param name="fForceStealLocalized">
|
| 205 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 206 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 207 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 208 |
+
/// </param>
|
| 209 |
+
_UnrealizedChore* StealUnrealizedChore(bool fForceStealLocalized = false);
|
| 210 |
+
|
| 211 |
+
/// <summary>
|
| 212 |
+
/// Attempts to acquire a detached work queue from the schedule group. If such a work queue is found, it
|
| 213 |
+
/// is removed from detached queue and returned. This allows recycling of work queues that are detached
|
| 214 |
+
/// yet still have unstructured work.
|
| 215 |
+
///</summary>
|
| 216 |
+
WorkQueue *GetDetachedWorkQueue();
|
| 217 |
+
|
| 218 |
+
/// <summary>
|
| 219 |
+
/// Places a work queue in the detached queue. This will cause the work queue to remain eligible for stealing
|
| 220 |
+
/// while the queue can be detached from a context. The work queue will be recycled and handed back to a
|
| 221 |
+
/// context executing within the schedule group that needs
|
| 222 |
+
/// a queue. If the queue is not recycled, it will be abandoned and freed when it becomes empty (a steal on it
|
| 223 |
+
/// while in detached mode fails).
|
| 224 |
+
/// </summary>
|
| 225 |
+
void DetachActiveWorkQueue(WorkQueue *pWorkQueue);
|
| 226 |
+
|
| 227 |
+
/// <summary>
|
| 228 |
+
/// Called to safely delete a detached work queue -- this is lock free and utilizes safe points to perform
|
| 229 |
+
/// the deletion and dereference. It can be called during the normal SFW or during the finalization sweep
|
| 230 |
+
/// safely.
|
| 231 |
+
/// </summary>
|
| 232 |
+
bool SafelyDeleteDetachedWorkQueue(WorkQueue *pQueue);
|
| 233 |
+
|
| 234 |
+
/// <summary>
|
| 235 |
+
/// Returns a location representing the affinity of this segment. Note that if the location returned is the system location,
|
| 236 |
+
/// the segment has no specific placement affinity. It may still have a weaker natural affinity to a particular node by
|
| 237 |
+
/// nature of the fact that a segment is contained within a ring.
|
| 238 |
+
/// </summary>
|
| 239 |
+
const location& GetAffinity() const
|
| 240 |
+
{
|
| 241 |
+
return m_affinity;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
/// <summary>
|
| 245 |
+
/// Returns our cached affinity set.
|
| 246 |
+
/// </summary>
|
| 247 |
+
const QuickBitSet& GetAffinitySet() const
|
| 248 |
+
{
|
| 249 |
+
return m_affinitySet;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
/// <summary>
|
| 253 |
+
/// Removes the segment.
|
| 254 |
+
/// </summary>
|
| 255 |
+
void Remove();
|
| 256 |
+
|
| 257 |
+
//
|
| 258 |
+
// Private data
|
| 259 |
+
//
|
| 260 |
+
|
| 261 |
+
// Owning ring.
|
| 262 |
+
SchedulingRing *m_pRing;
|
| 263 |
+
|
| 264 |
+
// A location representing the affinity of this segment.
|
| 265 |
+
location m_affinity;
|
| 266 |
+
|
| 267 |
+
// The bitset representing m_affinity for quick masking.
|
| 268 |
+
QuickBitSet m_affinitySet;
|
| 269 |
+
|
| 270 |
+
// Quickly stashed maskId if the location for this segment is a core.
|
| 271 |
+
unsigned int m_maskIdIf;
|
| 272 |
+
|
| 273 |
+
// Each schedule group has three stores of work. It has a collection of runnable contexts (in the derived classes),
|
| 274 |
+
// a FIFO queue of realized chores and a list of workqueues that hold unrealized chores.
|
| 275 |
+
|
| 276 |
+
// A queue of realized chores.
|
| 277 |
+
SafeSQueue<RealizedChore, _HyperNonReentrantLock> m_realizedChores;
|
| 278 |
+
|
| 279 |
+
// The list of tasks which were mailed to this segment.
|
| 280 |
+
Mailbox<_UnrealizedChore> m_mailedTasks;
|
| 281 |
+
|
| 282 |
+
// A list array of all unrealized chore queues that are owned by contexts in this schedule group,
|
| 283 |
+
// protected by a r/w lock.
|
| 284 |
+
ListArray<WorkQueue> m_workQueues;
|
| 285 |
+
|
| 286 |
+
// A list array of work queues which still contain work within the schedule group but have become detached
|
| 287 |
+
// from their parent context (e.g.: a chore queues unstructured work and does not wait upon it before
|
| 288 |
+
// exiting). This is the first level "free list". Any context needing a work queue can grab one from
|
| 289 |
+
// here assuming it's executing the same schedule group.
|
| 290 |
+
ListArray< ListArrayInlineLink<WorkQueue> > m_detachedWorkQueues;
|
| 291 |
+
|
| 292 |
+
// The index that this schedule group is at in its containing ListArray
|
| 293 |
+
int m_listArrayIndex;
|
| 294 |
+
|
| 295 |
+
// Unique identifier
|
| 296 |
+
unsigned int m_id;
|
| 297 |
+
|
| 298 |
+
// The group to which this segment belongs
|
| 299 |
+
ScheduleGroupBase *m_pOwningGroup;
|
| 300 |
+
|
| 301 |
+
// The next segment within the group
|
| 302 |
+
ScheduleGroupSegmentBase * volatile m_pNext;
|
| 303 |
+
|
| 304 |
+
// The last time this segment was serviced.
|
| 305 |
+
ULONGLONG m_lastServiceTime;
|
| 306 |
+
|
| 307 |
+
//
|
| 308 |
+
// TRANSITION: This is a temporary patch on livelock until we can tie into priority for livelock prevention.
|
| 309 |
+
//
|
| 310 |
+
BoostedObject m_priorityServiceLink;
|
| 311 |
+
|
| 312 |
+
private:
|
| 313 |
+
|
| 314 |
+
friend class SchedulerBase;
|
| 315 |
+
friend class ScheduleGroupBase;
|
| 316 |
+
friend class ContextBase;
|
| 317 |
+
friend class ExternalContextBase;
|
| 318 |
+
friend class InternalContextBase;
|
| 319 |
+
friend class ThreadInternalContext;
|
| 320 |
+
friend class SchedulingNode;
|
| 321 |
+
friend class SchedulingRing;
|
| 322 |
+
friend class VirtualProcessor;
|
| 323 |
+
friend class WorkItem;
|
| 324 |
+
friend class WorkSearchContext;
|
| 325 |
+
template <class T> friend class ListArray;
|
| 326 |
+
|
| 327 |
+
// Intrusive links for list array.
|
| 328 |
+
SLIST_ENTRY m_listArrayFreeLink;
|
| 329 |
+
};
|
| 330 |
+
|
| 331 |
+
#pragma warning(push)
|
| 332 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 333 |
+
class ScheduleGroupBase : public ScheduleGroup
|
| 334 |
+
{
|
| 335 |
+
public:
|
| 336 |
+
//
|
| 337 |
+
// Public Methods
|
| 338 |
+
//
|
| 339 |
+
|
| 340 |
+
/// <summary>
|
| 341 |
+
/// Constructs a schedule group.
|
| 342 |
+
/// </summary>
|
| 343 |
+
ScheduleGroupBase(SchedulerBase *pScheduler, location* pGroupPlacement);
|
| 344 |
+
|
| 345 |
+
/// <summary>
|
| 346 |
+
/// Virtual destructor
|
| 347 |
+
/// </summary>
|
| 348 |
+
virtual ~ScheduleGroupBase()
|
| 349 |
+
{
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
/// <summary>
|
| 353 |
+
/// Performs initialization (or reinitialization) of a schedule group.
|
| 354 |
+
/// </summary>
|
| 355 |
+
void Initialize(location* pGroupPlacement);
|
| 356 |
+
|
| 357 |
+
/// <summary>
|
| 358 |
+
/// Locates a segment that is appropriate for scheduling a task within the schedule group given information about the task's placement
|
| 359 |
+
/// and the origin of the thread making the call.
|
| 360 |
+
/// </summary>
|
| 361 |
+
/// <param name="pSegmentAffinity">
|
| 362 |
+
/// A segment with affinity to this particular location will be located.
|
| 363 |
+
/// </param>
|
| 364 |
+
/// <param name="fCreateNew">
|
| 365 |
+
/// An indication as to whether the schedule group can create a new segment if an appropriate segment cannot be found. If this parameter is
|
| 366 |
+
/// specified as true, NULL will never be returned from this method; otherwise, it can be if no matching segment can be found.
|
| 367 |
+
/// </param>
|
| 368 |
+
/// <returns>
|
| 369 |
+
/// A segment appropriate for scheduling work with affinity to segmentAffinity from code executing at origin. Note that NULL may be returned
|
| 370 |
+
/// if fCreateNew is specified as false and no appropriate segment yet exists for the group.
|
| 371 |
+
/// </returns>
|
| 372 |
+
virtual ScheduleGroupSegmentBase *LocateSegment(location* pSegmentAffinity, bool fCreateNew);
|
| 373 |
+
|
| 374 |
+
/// <summary>
|
| 375 |
+
/// Returns a pointer to the scheduler this group belongs to.
|
| 376 |
+
/// </summary>
|
| 377 |
+
SchedulerBase * GetScheduler() { return m_pScheduler; }
|
| 378 |
+
|
| 379 |
+
// ***************************************************************************
|
| 380 |
+
//
|
| 381 |
+
// Public Interface Derivations:
|
| 382 |
+
//
|
| 383 |
+
|
| 384 |
+
/// <summary>
|
| 385 |
+
/// Returns a unique identifier to the schedule group.
|
| 386 |
+
/// </summary>
|
| 387 |
+
unsigned int Id() const
|
| 388 |
+
{
|
| 389 |
+
return m_id;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
/// <summary>
|
| 393 |
+
/// Increments the reference count of a schedule group. A reference count is held for
|
| 394 |
+
/// - every unstarted or incomplete realized chore that is part of the schedule group
|
| 395 |
+
/// - every context that is executing a chore that was stolen from an unrealized chore queue
|
| 396 |
+
/// within the schedule group
|
| 397 |
+
/// - every external context attached to the scheduler instance, IFF this is the anonymous
|
| 398 |
+
/// schedule group for the scheduler instance,
|
| 399 |
+
/// - an external caller, IFF this schedule group was created using one of the public task
|
| 400 |
+
/// creation APIs.
|
| 401 |
+
/// </summary>
|
| 402 |
+
/// <returns>
|
| 403 |
+
/// Returns the resulting reference count.
|
| 404 |
+
/// </returns>
|
| 405 |
+
virtual unsigned int Reference()
|
| 406 |
+
{
|
| 407 |
+
return (unsigned int)InternalReference();
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
/// <summary>
|
| 411 |
+
/// Decrements the reference count of a schedule group. Used for composition.
|
| 412 |
+
/// </summary>
|
| 413 |
+
/// <returns>
|
| 414 |
+
/// Returns the resulting reference count.
|
| 415 |
+
/// </returns>
|
| 416 |
+
virtual unsigned int Release()
|
| 417 |
+
{
|
| 418 |
+
return (unsigned int)InternalRelease();
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
/// <summary>
|
| 422 |
+
/// Schedules a light-weight task within the schedule group.
|
| 423 |
+
/// </summary>
|
| 424 |
+
/// <param name="proc">
|
| 425 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 426 |
+
/// </param>
|
| 427 |
+
/// <param name="data">
|
| 428 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 429 |
+
/// </param>
|
| 430 |
+
/// <remarks>
|
| 431 |
+
/// Calling the <c>ScheduleTask</c> method implicitly places a reference count on the schedule group which is removed by the runtime
|
| 432 |
+
/// at an appropriate time after the task executes.
|
| 433 |
+
/// </remarks>
|
| 434 |
+
/// <seealso cref="ScheduleGroup::Reference Method"/>
|
| 435 |
+
virtual void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void* data);
|
| 436 |
+
//
|
| 437 |
+
// End of Public Interface Derivations:
|
| 438 |
+
//
|
| 439 |
+
// ***************************************************************************
|
| 440 |
+
|
| 441 |
+
/// <summary>
|
| 442 |
+
/// Schedules a light-weight task within the schedule group. The light-weight task will also be biased towards executing at the specified location.
|
| 443 |
+
/// </summary>
|
| 444 |
+
/// <param name="proc">
|
| 445 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 446 |
+
/// </param>
|
| 447 |
+
/// <param name="data">
|
| 448 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 449 |
+
/// </param>
|
| 450 |
+
/// <param name="placement">
|
| 451 |
+
/// A reference to a location where the light-weight task will be biased towards executing at.
|
| 452 |
+
/// </param>
|
| 453 |
+
/// <remarks>
|
| 454 |
+
/// Calling the <c>ScheduleTask</c> method implicitly places a reference count on the schedule group which is removed by the runtime
|
| 455 |
+
/// at an appropriate time after the task executes.
|
| 456 |
+
/// </remarks>
|
| 457 |
+
/// <seealso cref="ScheduleGroup::Reference Method"/>
|
| 458 |
+
/// <seealso cref="location Class"/>
|
| 459 |
+
void ScheduleTask(_In_ TaskProc proc, _Inout_opt_ void * data, location& placement);
|
| 460 |
+
|
| 461 |
+
/// <summary>
|
| 462 |
+
/// Places a chore in a mailbox associated with the schedule group which is biased towards tasks being picked up from the specified
|
| 463 |
+
/// location.
|
| 464 |
+
/// </summary>
|
| 465 |
+
/// <param name="pChore">
|
| 466 |
+
/// The chore to mail.
|
| 467 |
+
/// </param>
|
| 468 |
+
/// <param name="pPlacement">
|
| 469 |
+
/// A pointer to a location where the chore will be mailed.
|
| 470 |
+
/// </param>
|
| 471 |
+
/// <returns>
|
| 472 |
+
/// The mailbox slot into which the chore was placed.
|
| 473 |
+
/// </returns>
|
| 474 |
+
/// <remarks>
|
| 475 |
+
/// A mailed chore should also be placed on its regular work stealing queue. The mailing must come first and once mailed, the chore body
|
| 476 |
+
/// cannot be referenced until the slot is successfully claimed via a call to the ClaimSlot method.
|
| 477 |
+
/// </remarks>
|
| 478 |
+
virtual Mailbox<_UnrealizedChore>::Slot MailChore(_UnrealizedChore * pChore,
|
| 479 |
+
location * pPlacement,
|
| 480 |
+
ScheduleGroupSegmentBase ** ppDestinationSegment) =0;
|
| 481 |
+
|
| 482 |
+
/// <summary>
|
| 483 |
+
/// Gets the first schedule group segment within the group that is either affine or non-affine as specified by fAffine.
|
| 484 |
+
/// </summary>
|
| 485 |
+
ScheduleGroupSegmentBase *GetFirstScheduleGroupSegment(bool fAffine)
|
| 486 |
+
{
|
| 487 |
+
return fAffine ? m_pAffineSegments : m_pNonAffineSegments;
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
/// <summary>
|
| 491 |
+
/// Gets the next schedule group segment within the group. This will return only affine or non-affine segments depending
|
| 492 |
+
/// on how GetFirstScheduleGroupSegment was called.
|
| 493 |
+
/// </summary>
|
| 494 |
+
ScheduleGroupSegmentBase *GetNextScheduleGroupSegment(ScheduleGroupSegmentBase *pSegment)
|
| 495 |
+
{
|
| 496 |
+
return pSegment->m_pNext;
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
protected:
|
| 500 |
+
friend class ScheduleGroupSegmentBase;
|
| 501 |
+
|
| 502 |
+
friend class SchedulerBase;
|
| 503 |
+
friend class ContextBase;
|
| 504 |
+
friend class ExternalContextBase;
|
| 505 |
+
friend class InternalContextBase;
|
| 506 |
+
friend class ThreadInternalContext;
|
| 507 |
+
friend class SchedulingNode;
|
| 508 |
+
friend class SchedulingRing;
|
| 509 |
+
friend class VirtualProcessor;
|
| 510 |
+
friend class WorkItem;
|
| 511 |
+
friend class WorkSearchContext;
|
| 512 |
+
template <class T> friend class ListArray;
|
| 513 |
+
|
| 514 |
+
enum {
|
| 515 |
+
CacheLocalScheduling = 1,
|
| 516 |
+
FairScheduling = 2,
|
| 517 |
+
AnonymousScheduleGroup = 4
|
| 518 |
+
};
|
| 519 |
+
|
| 520 |
+
//
|
| 521 |
+
// Private data
|
| 522 |
+
//
|
| 523 |
+
|
| 524 |
+
// Owning scheduler
|
| 525 |
+
SchedulerBase *m_pScheduler;
|
| 526 |
+
|
| 527 |
+
// The lock which guards creation of segments.
|
| 528 |
+
_NonReentrantLock m_segmentLock;
|
| 529 |
+
|
| 530 |
+
// A linked list of explicitly affine segments within this group
|
| 531 |
+
ScheduleGroupSegmentBase *m_pAffineSegments;
|
| 532 |
+
|
| 533 |
+
// A linked list of segments which are not explicitly affine.
|
| 534 |
+
ScheduleGroupSegmentBase *m_pNonAffineSegments;
|
| 535 |
+
|
| 536 |
+
// Reference count for the schedule group
|
| 537 |
+
volatile long m_refCount;
|
| 538 |
+
|
| 539 |
+
// The index that this schedule group is at in its containing ListArray
|
| 540 |
+
int m_listArrayIndex;
|
| 541 |
+
|
| 542 |
+
// Unique identifier
|
| 543 |
+
unsigned int m_id;
|
| 544 |
+
|
| 545 |
+
// The location that the group schedules to by default. A non-biased group will contain the system location.
|
| 546 |
+
location m_groupPlacement;
|
| 547 |
+
|
| 548 |
+
// flag indicating schedule group kind
|
| 549 |
+
BYTE m_kind;
|
| 550 |
+
|
| 551 |
+
//
|
| 552 |
+
// Private methods
|
| 553 |
+
//
|
| 554 |
+
|
| 555 |
+
/// <summary>
|
| 556 |
+
/// Removes all schedule group segments from the group.
|
| 557 |
+
/// </summary>
|
| 558 |
+
virtual void RemoveSegments();
|
| 559 |
+
|
| 560 |
+
/// <summary>
|
| 561 |
+
/// Non-virtual function that increments the reference count of a schedule group.
|
| 562 |
+
/// </summary>
|
| 563 |
+
LONG InternalReference()
|
| 564 |
+
{
|
| 565 |
+
if ((m_kind & AnonymousScheduleGroup) == 0)
|
| 566 |
+
{
|
| 567 |
+
ASSERT(m_refCount >= 0);
|
| 568 |
+
TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::InternalReference(rc=%d)\n", m_refCount+1);
|
| 569 |
+
LONG val = InterlockedIncrement(&m_refCount);
|
| 570 |
+
|
| 571 |
+
OMTRACE(MTRACE_EVT_REFERENCE, this, NULL, NULL, val);
|
| 572 |
+
|
| 573 |
+
return val;
|
| 574 |
+
}
|
| 575 |
+
return 0;
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// <summary>
|
| 579 |
+
/// Non-virtual function that decrements the reference count of a schedule group.
|
| 580 |
+
/// </summary>
|
| 581 |
+
LONG InternalRelease()
|
| 582 |
+
{
|
| 583 |
+
if ((m_kind & AnonymousScheduleGroup) == 0)
|
| 584 |
+
{
|
| 585 |
+
ASSERT(m_refCount > 0);
|
| 586 |
+
TRACE(TRACE_SCHEDULER, L"ScheduleGroupBase::InternalRelease(rc=%d)\n", m_refCount-1);
|
| 587 |
+
LONG newValue = InterlockedDecrement(&m_refCount);
|
| 588 |
+
|
| 589 |
+
OMTRACE(MTRACE_EVT_DEREFERENCE, this, NULL, NULL, newValue);
|
| 590 |
+
|
| 591 |
+
if (newValue == 0)
|
| 592 |
+
{
|
| 593 |
+
RemoveSegments();
|
| 594 |
+
m_pScheduler->RemoveScheduleGroup(this);
|
| 595 |
+
}
|
| 596 |
+
return newValue;
|
| 597 |
+
}
|
| 598 |
+
return 0;
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
bool IsFairScheduleGroup() const { return (m_kind & FairScheduling) != 0; }
|
| 602 |
+
|
| 603 |
+
/// <summary>
|
| 604 |
+
/// Allocates a new cache local schedule group segment within the specified group and ring with the specified affinity.
|
| 605 |
+
/// </summary>
|
| 606 |
+
/// <param name="pSegmentAffinity">
|
| 607 |
+
/// The affinity for the segment.
|
| 608 |
+
/// </param>
|
| 609 |
+
/// <param name="pOwningRing">
|
| 610 |
+
/// The scheduling ring to which the newly allocated segment will belong.
|
| 611 |
+
/// </param>
|
| 612 |
+
/// <returns>
|
| 613 |
+
/// A new cache local schedule group within the specified group and ring with the specified affinity.
|
| 614 |
+
/// </returns>
|
| 615 |
+
virtual ScheduleGroupSegmentBase* AllocateSegment(SchedulingRing *pOwningRing, location* pSegmentAffinity) = 0;
|
| 616 |
+
|
| 617 |
+
/// <summary>
|
| 618 |
+
/// Creates a new segment with the specified affinity within the specified ring.
|
| 619 |
+
/// </summary>
|
| 620 |
+
/// <param name="pSegmentAffinity">
|
| 621 |
+
/// The affinity of the segment.
|
| 622 |
+
/// </param>
|
| 623 |
+
/// <param name="pOwningRing">
|
| 624 |
+
/// The ring into which the new segment will be placed. Some aspect of segmentAffinity must overlap with the node to which this ring
|
| 625 |
+
/// belongs.
|
| 626 |
+
/// </param>
|
| 627 |
+
/// <returns>
|
| 628 |
+
/// A new segment with the specified affinity within the specified ring.
|
| 629 |
+
/// </returns>
|
| 630 |
+
ScheduleGroupSegmentBase *CreateSegment(location* pSegmentAffinity, SchedulingRing *pOwningRing);
|
| 631 |
+
|
| 632 |
+
/// <summary>
|
| 633 |
+
/// Internal routine which finds an appropriate segment for a task placement.
|
| 634 |
+
/// </summary>
|
| 635 |
+
/// <param name="pSegmentAffinity">
|
| 636 |
+
/// A segment with this affinity will be located.
|
| 637 |
+
/// </param>
|
| 638 |
+
/// <param name="pRing">
|
| 639 |
+
/// A segment with segmentAffinity within this ring will be found. A given location may be split into multiple segments by node in order
|
| 640 |
+
/// to keep work local.
|
| 641 |
+
/// </param>
|
| 642 |
+
/// <returns>
|
| 643 |
+
/// A segment with the specified affinity close to the specified location.
|
| 644 |
+
/// </returns>
|
| 645 |
+
virtual ScheduleGroupSegmentBase *FindSegment(location* pSegmentAffinity, SchedulingRing *pRing);
|
| 646 |
+
|
| 647 |
+
private:
|
| 648 |
+
|
| 649 |
+
// Intrusive links for list array.
|
| 650 |
+
SLIST_ENTRY m_listArrayFreeLink;
|
| 651 |
+
};
|
| 652 |
+
#pragma warning(pop)
|
| 653 |
+
} // namespace details
|
| 654 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.cpp
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerBase.h
ADDED
|
@@ -0,0 +1,1691 @@
|
|
|
|
|
|
|
|
|
|
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+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulerBase.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the metaphor for a concrt scheduler
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
//
|
| 16 |
+
// Defines how many (1 << x) pointers worth of padding there will be in between quick cache slots.
|
| 17 |
+
//
|
| 18 |
+
#ifdef _WIN64
|
| 19 |
+
//
|
| 20 |
+
// 64 bit:
|
| 21 |
+
// 1 << 4 == 8 pointers * 8 == 64 bytes (assumed cache pad)
|
| 22 |
+
//
|
| 23 |
+
#define QUICKCACHEPAD_SHIFT 4
|
| 24 |
+
#else // !_WIN64
|
| 25 |
+
//
|
| 26 |
+
// 32 bit:
|
| 27 |
+
// 1 << 5 == 16 pointers * 4 == 64 bytes (assumed cache pad)
|
| 28 |
+
//
|
| 29 |
+
#define QUICKCACHEPAD_SHIFT 5
|
| 30 |
+
#endif // _WIN64
|
| 31 |
+
|
| 32 |
+
namespace Concurrency
|
| 33 |
+
{
|
| 34 |
+
namespace details
|
| 35 |
+
{
|
| 36 |
+
// The base class that implements a scheduler instance
|
| 37 |
+
|
| 38 |
+
class SchedulerBase : public Scheduler
|
| 39 |
+
{
|
| 40 |
+
private:
|
| 41 |
+
|
| 42 |
+
//
|
| 43 |
+
// NESTED CLASSES:
|
| 44 |
+
//
|
| 45 |
+
|
| 46 |
+
/// <summary>
|
| 47 |
+
/// Represents information about the NUMA nodes on the machine.
|
| 48 |
+
/// </summary>
|
| 49 |
+
struct NumaInformation
|
| 50 |
+
{
|
| 51 |
+
QuickBitSet m_nodeMask;
|
| 52 |
+
QuickBitSet m_resourceMask;
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
///<summary>
|
| 56 |
+
/// An intrusive node type for context tracking outside of the normal placement of contexts upon
|
| 57 |
+
/// free/runnable lists.
|
| 58 |
+
///</summary>
|
| 59 |
+
class ContextNode
|
| 60 |
+
{
|
| 61 |
+
public:
|
| 62 |
+
|
| 63 |
+
ContextNode(InternalContextBase *pContext) : m_pContext(pContext)
|
| 64 |
+
{
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
SLIST_ENTRY m_slNext{};
|
| 68 |
+
InternalContextBase *m_pContext;
|
| 69 |
+
};
|
| 70 |
+
|
| 71 |
+
///<summary>
|
| 72 |
+
/// A node that tracks events needing to be signaled at finalization time.
|
| 73 |
+
///</summary>
|
| 74 |
+
class WaitNode
|
| 75 |
+
{
|
| 76 |
+
public:
|
| 77 |
+
|
| 78 |
+
WaitNode *m_pNext, *m_pPrev;
|
| 79 |
+
HANDLE m_hEvent;
|
| 80 |
+
};
|
| 81 |
+
|
| 82 |
+
///<summary>
|
| 83 |
+
/// A class that the scheduler uses to manage external context exit events for implicitly attached
|
| 84 |
+
/// external contexts.
|
| 85 |
+
///</summary>
|
| 86 |
+
class ContextExitEventHandler
|
| 87 |
+
{
|
| 88 |
+
public:
|
| 89 |
+
|
| 90 |
+
bool m_fCanceled;
|
| 91 |
+
// Count of handles the event handler is waiting on at any time.
|
| 92 |
+
unsigned short m_handleCount;
|
| 93 |
+
// Modified to reflect the new handle count after adding handles to the wait array and before notifying the
|
| 94 |
+
// watch dog of handle addition.
|
| 95 |
+
unsigned short m_newHandleCount;
|
| 96 |
+
// Event handle used to notify the event handler of certain events (new handle addition, shutdown).
|
| 97 |
+
HANDLE m_hWakeEventHandler;
|
| 98 |
+
SchedulerBase *m_pScheduler;
|
| 99 |
+
// prev, next pointers for the list of all handlers in the scheduler.
|
| 100 |
+
ContextExitEventHandler *m_pNext, *m_pPrev;
|
| 101 |
+
// list entry for a list of handlers with available slots for context handles. The scheduler uses this
|
| 102 |
+
// list when registering contexts.
|
| 103 |
+
ListEntry m_availableChain;
|
| 104 |
+
// The array of wait handles each thread waits on. Of these one is an event handle for notification
|
| 105 |
+
// and the rest are handles to OS contexts.
|
| 106 |
+
HANDLE m_waitHandleArray[MAXIMUM_WAIT_OBJECTS];
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
public:
|
| 110 |
+
|
| 111 |
+
/// <summary>
|
| 112 |
+
/// Creates a scheduler that only manages internal contexts. Implicitly calls Reference.
|
| 113 |
+
/// If Attach is called, the scheduler is no longer anonymous because it is also managing the external
|
| 114 |
+
/// context where Attach was called. To destroy an anonymous scheduler, Release needs to be called.
|
| 115 |
+
/// </summary>
|
| 116 |
+
/// <param name="policy">
|
| 117 |
+
/// [in] A const reference to the scheduler policy.
|
| 118 |
+
/// </param>
|
| 119 |
+
/// <returns>
|
| 120 |
+
/// A pointer to the new scheduler (never null)
|
| 121 |
+
/// </returns>
|
| 122 |
+
static _Ret_writes_(1) SchedulerBase* Create(_In_ const SchedulerPolicy& policy);
|
| 123 |
+
static _Ret_writes_(1) SchedulerBase* CreateWithoutInitializing(_In_ const SchedulerPolicy& policy);
|
| 124 |
+
|
| 125 |
+
// Constructor
|
| 126 |
+
SchedulerBase(_In_ const ::Concurrency::SchedulerPolicy& policy);
|
| 127 |
+
|
| 128 |
+
// dtor
|
| 129 |
+
virtual ~SchedulerBase();
|
| 130 |
+
|
| 131 |
+
public: // Public Scheduler interface
|
| 132 |
+
/// <returns>
|
| 133 |
+
/// Returns a unique identifier for this scheduler. No error state.
|
| 134 |
+
/// </returns>
|
| 135 |
+
virtual unsigned int Id() const { return m_id; }
|
| 136 |
+
|
| 137 |
+
/// <returns>
|
| 138 |
+
/// Returns a current number of virtual processors for this scheduler. No error state.
|
| 139 |
+
/// </returns>
|
| 140 |
+
virtual unsigned int GetNumberOfVirtualProcessors() const { return m_virtualProcessorCount; };
|
| 141 |
+
|
| 142 |
+
/// <returns>
|
| 143 |
+
/// Returns a copy of the policy this scheduler is using. No error state.
|
| 144 |
+
/// </returns>
|
| 145 |
+
virtual SchedulerPolicy GetPolicy() const;
|
| 146 |
+
|
| 147 |
+
/// <summary>
|
| 148 |
+
/// Increments a reference count to this scheduler to manage lifetimes over composition.</summary>
|
| 149 |
+
/// This reference count is known as the scheduler reference count.
|
| 150 |
+
/// </summary>
|
| 151 |
+
/// <returns>
|
| 152 |
+
/// The resulting reference count is returned. No error state.
|
| 153 |
+
/// </returns>
|
| 154 |
+
virtual unsigned int Reference();
|
| 155 |
+
|
| 156 |
+
/// <summary>
|
| 157 |
+
/// Decrements this scheduler's reference count to manage lifetimes over composition.
|
| 158 |
+
/// A scheduler starts the shutdown protocol when the scheduler reference count goes to zero.
|
| 159 |
+
/// <summary>
|
| 160 |
+
/// <returns>
|
| 161 |
+
/// The resulting reference count is returned. No error state.
|
| 162 |
+
/// </returns>
|
| 163 |
+
virtual unsigned int Release();
|
| 164 |
+
|
| 165 |
+
/// <summary>
|
| 166 |
+
/// Causes the OS event object 'event' to be set when the scheduler shuts down and destroys itself.
|
| 167 |
+
/// </summary>
|
| 168 |
+
/// <param name="event">
|
| 169 |
+
/// [in] A handle to avalid event object
|
| 170 |
+
/// </param>
|
| 171 |
+
virtual void RegisterShutdownEvent(_In_ HANDLE event);
|
| 172 |
+
|
| 173 |
+
/// <summary>
|
| 174 |
+
/// Attaches this scheduler to the calling thread. Implicitly calls Reference.
|
| 175 |
+
/// After this function is called, the calling thread is then managed by the scheduler and the scheduler becomes the current scheduler.
|
| 176 |
+
/// It is illegal for an internal context to call Attach on its current scheduler.
|
| 177 |
+
/// </summary>
|
| 178 |
+
virtual void Attach();
|
| 179 |
+
|
| 180 |
+
/// <summary>
|
| 181 |
+
/// Allows a user defined policy to be used to create the default scheduler. It is only valid to call this API when no default
|
| 182 |
+
/// scheduler exists. Once a default policy is set, it remains in effect until the next time the API is called (in the absence
|
| 183 |
+
/// of a default scheduler).
|
| 184 |
+
/// </summary>
|
| 185 |
+
/// <param name="pPolicy">
|
| 186 |
+
/// [in] A pointer to the policy to be set as the default. The runtime will make a copy of the policy
|
| 187 |
+
/// for its use, and the user is responsible for the lifetime of the policy that is passed in.
|
| 188 |
+
/// </param>
|
| 189 |
+
static void SetDefaultSchedulerPolicy(_In_ const SchedulerPolicy & _Policy);
|
| 190 |
+
|
| 191 |
+
/// <summary>
|
| 192 |
+
/// Resets the default scheduler policy, and the next time a default scheduler is created, it will use the runtime's default policy settings.
|
| 193 |
+
/// </summary>
|
| 194 |
+
static void ResetDefaultSchedulerPolicy();
|
| 195 |
+
|
| 196 |
+
/// <summary>
|
| 197 |
+
/// Creates a new schedule group within the scheduler associated with the calling context.
|
| 198 |
+
/// </summary>
|
| 199 |
+
/// <returns>
|
| 200 |
+
/// A pointer to the newly created schedule group. This <c>ScheduleGroup</c> object has an initial reference count placed on it.
|
| 201 |
+
/// </returns>
|
| 202 |
+
/// <remarks>
|
| 203 |
+
/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no
|
| 204 |
+
/// scheduler currently associated with the calling context.
|
| 205 |
+
/// <para>You must invoke the <see cref="ScheduleGroup::Release Method">Release</see> method on a schedule group when you are
|
| 206 |
+
/// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed.</para>
|
| 207 |
+
/// <para>Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before
|
| 208 |
+
/// you release your reference on the scheduler, via detaching the current context from it.</para>
|
| 209 |
+
/// </remarks>
|
| 210 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 211 |
+
/// <seealso cref="ScheduleGroup::Release Method"/>
|
| 212 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 213 |
+
virtual ScheduleGroup* CreateScheduleGroup()
|
| 214 |
+
{
|
| 215 |
+
location unbiased;
|
| 216 |
+
return InternalCreateScheduleGroup(&unbiased);
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// <summary>
|
| 220 |
+
/// Creates a new schedule group within the scheduler associated with the calling context. Tasks scheduled within the newly created
|
| 221 |
+
/// schedule group will be biased towards executing at the specified location.
|
| 222 |
+
/// </summary>
|
| 223 |
+
/// <param name="_Placement">
|
| 224 |
+
/// A reference to a location where the tasks within the schedule group will biased towards executing at.
|
| 225 |
+
/// </param>
|
| 226 |
+
/// <returns>
|
| 227 |
+
/// A pointer to the newly created schedule group. This <c>ScheduleGroup</c> object has an initial reference count placed on it.
|
| 228 |
+
/// </returns>
|
| 229 |
+
/// <remarks>
|
| 230 |
+
/// This method will result in the process' default scheduler being created and/or attached to the calling context if there is no
|
| 231 |
+
/// scheduler currently associated with the calling context.
|
| 232 |
+
/// <para>You must invoke the <see cref="ScheduleGroup::Release Method">Release</see> method on a schedule group when you are
|
| 233 |
+
/// done scheduling work to it. The scheduler will destroy the schedule group when all work queued to it has completed.</para>
|
| 234 |
+
/// <para>Note that if you explicitly created this scheduler, you must release all references to schedule groups within it, before
|
| 235 |
+
/// you release your reference on the scheduler, via detaching the current context from it.</para>
|
| 236 |
+
/// </remarks>
|
| 237 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 238 |
+
/// <seealso cref="ScheduleGroup::Release Method"/>
|
| 239 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 240 |
+
/// <seealso cref="location Class"/>
|
| 241 |
+
virtual ScheduleGroup * CreateScheduleGroup(location& _Placement)
|
| 242 |
+
{
|
| 243 |
+
return InternalCreateScheduleGroup(&_Placement);
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
/// <summary>
|
| 247 |
+
/// Schedules a light-weight task within the scheduler. The light-weight task will be placed in a schedule group of the runtime's choosing.
|
| 248 |
+
/// </summary>
|
| 249 |
+
/// <param name="proc">
|
| 250 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 251 |
+
/// </param>
|
| 252 |
+
/// <param name="data">
|
| 253 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 254 |
+
/// </param>
|
| 255 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 256 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 257 |
+
virtual void ScheduleTask(TaskProc proc, void *data);
|
| 258 |
+
|
| 259 |
+
/// <summary>
|
| 260 |
+
/// Schedules a light-weight task within the scheduler. The light-weight task will be placed
|
| 261 |
+
/// within a schedule group of the runtime's choosing. It will also be biased towards executing at the specified location.
|
| 262 |
+
/// </summary>
|
| 263 |
+
/// <param name="proc">
|
| 264 |
+
/// A pointer to the function to execute to perform the body of the light-weight task.
|
| 265 |
+
/// </param>
|
| 266 |
+
/// <param name="data">
|
| 267 |
+
/// A void pointer to the data that will be passed as a parameter to the body of the task.
|
| 268 |
+
/// </param>
|
| 269 |
+
/// <param name="placement">
|
| 270 |
+
/// A reference to a location where the light-weight task will be biased towards executing at.
|
| 271 |
+
/// </param>
|
| 272 |
+
/// <seealso cref="Task Scheduler (Concurrency Runtime)"/>
|
| 273 |
+
/// <seealso cref="ScheduleGroup Class"/>
|
| 274 |
+
/// <seealso cref="location Class"/>
|
| 275 |
+
virtual void ScheduleTask(TaskProc proc, void * data, location& placement);
|
| 276 |
+
|
| 277 |
+
/// <summary>
|
| 278 |
+
/// Determines whether a given location is available on the scheduler.
|
| 279 |
+
/// </summary>
|
| 280 |
+
/// <param name="_Placement">
|
| 281 |
+
/// A reference to the location to query the scheduler about.
|
| 282 |
+
/// </param>
|
| 283 |
+
/// <returns>
|
| 284 |
+
/// An indication of whether or not the location specified by the <paramref name="_Placement"/> argument is available on the scheduler.
|
| 285 |
+
/// </returns>
|
| 286 |
+
/// <remarks>
|
| 287 |
+
/// Note that the return value is an instantaneous sampling of whether the given location is available. In the presence of multiple
|
| 288 |
+
/// schedulers, dynamic resource management may add or take away resources from schedulers at any point. Should this happen, the given
|
| 289 |
+
/// location may change availability.
|
| 290 |
+
/// </remarks>
|
| 291 |
+
virtual bool IsAvailableLocation(const location& _Placement) const;
|
| 292 |
+
|
| 293 |
+
public: // Internal stuff
|
| 294 |
+
|
| 295 |
+
enum
|
| 296 |
+
{
|
| 297 |
+
//
|
| 298 |
+
// One shot starts with a single reference count placed implicitly by the module in which ConcRT is contained.
|
| 299 |
+
//
|
| 300 |
+
ONESHOT_NOT_INITIALIZED = 1,
|
| 301 |
+
ONESHOT_INITIALIZED_FLAG = 0x80000000
|
| 302 |
+
};
|
| 303 |
+
|
| 304 |
+
/// <summary>
|
| 305 |
+
/// Returns whether or not the scheduler has performed one shot static construction.
|
| 306 |
+
/// </summary>
|
| 307 |
+
static bool IsOneShotInitialized() { return ((s_oneShotInitializationState & ONESHOT_INITIALIZED_FLAG) != 0); }
|
| 308 |
+
|
| 309 |
+
/// <summary>
|
| 310 |
+
/// Detaches this scheduler from the current thread. It is required that the current scheduler on the thread be the same as 'this'
|
| 311 |
+
/// </summary>
|
| 312 |
+
void Detach();
|
| 313 |
+
|
| 314 |
+
/// <summary>
|
| 315 |
+
/// Generates a unique identifier for a context.
|
| 316 |
+
/// </summary>
|
| 317 |
+
unsigned int GetNewContextId();
|
| 318 |
+
|
| 319 |
+
/// <summary>
|
| 320 |
+
/// Generates a unique identifier for a schedule group.
|
| 321 |
+
/// </summary>
|
| 322 |
+
unsigned int GetNewScheduleGroupId();
|
| 323 |
+
|
| 324 |
+
/// <summary>
|
| 325 |
+
/// Generates a unique identifier for a work queue across schedulers.
|
| 326 |
+
/// </summary>
|
| 327 |
+
static unsigned int GetNewWorkQueueId();
|
| 328 |
+
|
| 329 |
+
/// <summary>
|
| 330 |
+
/// 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
|
| 331 |
+
/// is returned, it is a pre-bound and unstarted context.
|
| 332 |
+
/// </summary>
|
| 333 |
+
InternalContextBase *GetReservedContext()
|
| 334 |
+
{
|
| 335 |
+
return m_reservedContexts.Pop();
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
/// <summary>
|
| 339 |
+
/// Releases the list of reserved contexts to the idle pool. The thread proxy
|
| 340 |
+
/// is released before returning the contexts to the idle pool.
|
| 341 |
+
/// </summary>
|
| 342 |
+
void ReleaseReservedContexts();
|
| 343 |
+
|
| 344 |
+
/// <summary>
|
| 345 |
+
/// Acquires a new internal context of the appropriate type and returns it. This can come from either
|
| 346 |
+
/// a free list within the scheduler, or be one newly allocated from the heap.
|
| 347 |
+
/// </summary>
|
| 348 |
+
/// <param name="fThrottled">
|
| 349 |
+
/// An indication as to whether the creation should be throttled.
|
| 350 |
+
/// </param>
|
| 351 |
+
InternalContextBase *GetInternalContext(bool fThrottled = true);
|
| 352 |
+
|
| 353 |
+
/// <summary>
|
| 354 |
+
/// Acquires a new internal context of the appropriate type and notifies the scheduler when it is available. The scheduler can
|
| 355 |
+
/// choose what to do with said internal context. This creation happens in a deferred manner subject to throttling constraints.
|
| 356 |
+
/// </summary>
|
| 357 |
+
void DeferredGetInternalContext();
|
| 358 |
+
|
| 359 |
+
///<summary>
|
| 360 |
+
/// Releases an internal context to the scheduler's idle pool.
|
| 361 |
+
///</summary>
|
| 362 |
+
void ReleaseInternalContext(InternalContextBase *pContext, bool fUnbind = false);
|
| 363 |
+
|
| 364 |
+
/// <summary>
|
| 365 |
+
/// Gets a realized chore from the idle pool, creating a new one if the idle pool is empty.
|
| 366 |
+
/// </summary>
|
| 367 |
+
RealizedChore *GetRealizedChore(TaskProc pFunction, void* pParameters);
|
| 368 |
+
|
| 369 |
+
///<summary>
|
| 370 |
+
/// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full.
|
| 371 |
+
///</summary>
|
| 372 |
+
void ReleaseRealizedChore(RealizedChore *pChore);
|
| 373 |
+
|
| 374 |
+
/// <summary>
|
| 375 |
+
/// References the anonymous schedule group, creating it if it doesn't exists, and returns a pointer to it.
|
| 376 |
+
/// </summary>
|
| 377 |
+
ScheduleGroupBase* GetAnonymousScheduleGroup()
|
| 378 |
+
{
|
| 379 |
+
return m_pAnonymousScheduleGroup;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
/// <summary>
|
| 383 |
+
/// References a segment in the anonymous schedule group and returns a pointer to it.
|
| 384 |
+
/// </summary>
|
| 385 |
+
/// <returns>
|
| 386 |
+
/// A segment in the anonymous schedule group.
|
| 387 |
+
/// </returns>
|
| 388 |
+
ScheduleGroupSegmentBase *GetAnonymousScheduleGroupSegment();
|
| 389 |
+
|
| 390 |
+
static SchedulerBase* CurrentScheduler();
|
| 391 |
+
static SchedulerBase* FastCurrentScheduler();
|
| 392 |
+
static SchedulerBase* SafeFastCurrentScheduler();
|
| 393 |
+
static ContextBase* FastCurrentContext();
|
| 394 |
+
static ContextBase* SafeFastCurrentContext();
|
| 395 |
+
static ContextBase* CreateContextFromDefaultScheduler();
|
| 396 |
+
static ContextBase* CurrentContext()
|
| 397 |
+
{
|
| 398 |
+
if ( !IsOneShotInitialized())
|
| 399 |
+
return CreateContextFromDefaultScheduler();
|
| 400 |
+
ContextBase *pContext = (ContextBase*) platform::__TlsGetValue(t_dwContextIndex);
|
| 401 |
+
if (pContext == NULL)
|
| 402 |
+
return CreateContextFromDefaultScheduler();
|
| 403 |
+
return pContext;
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/// <summary>
|
| 407 |
+
/// Gets an IScheduler pointer for use in communication with the resource manager.
|
| 408 |
+
/// </summary>
|
| 409 |
+
virtual IScheduler* GetIScheduler() = 0;
|
| 410 |
+
|
| 411 |
+
/// <summary>
|
| 412 |
+
/// Gets an IResourceManager pointer for use in communication with the resource manager.
|
| 413 |
+
/// </summary>
|
| 414 |
+
IResourceManager *GetResourceManager() const
|
| 415 |
+
{
|
| 416 |
+
return m_pResourceManager;
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
/// <summary>
|
| 420 |
+
/// Gets an ISchedulerProxy pointer for use in communication with the resource manager.
|
| 421 |
+
/// </summary>
|
| 422 |
+
ISchedulerProxy *GetSchedulerProxy() const
|
| 423 |
+
{
|
| 424 |
+
return m_pSchedulerProxy;
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
/// <summary>
|
| 428 |
+
/// Find an available virtual processor in the scheduler.
|
| 429 |
+
/// </summary>
|
| 430 |
+
bool FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket,
|
| 431 |
+
location bias = location(),
|
| 432 |
+
ULONG type = VirtualProcessor::AvailabilityAny);
|
| 433 |
+
|
| 434 |
+
/// <summary>
|
| 435 |
+
/// Try to steal from foreign nodes.
|
| 436 |
+
/// </summary>
|
| 437 |
+
InternalContextBase *StealForeignLocalRunnableContext(SchedulingNode *pSkipNode);
|
| 438 |
+
|
| 439 |
+
/// <summary>
|
| 440 |
+
/// Start up a virtual processor in the scheduler, if one is found. The virtual processor must have the specified availability
|
| 441 |
+
/// characteristics.
|
| 442 |
+
/// </summary>
|
| 443 |
+
bool StartupVirtualProcessor(ScheduleGroupSegmentBase *pSegment,
|
| 444 |
+
location bias = location(),
|
| 445 |
+
ULONG type = VirtualProcessor::AvailabilityAny);
|
| 446 |
+
|
| 447 |
+
/// <summary>
|
| 448 |
+
/// Start up an idle virtual processor in the scheduler. This can be any virtual processor except one that is inactive due to
|
| 449 |
+
/// waiting for a thread creation.
|
| 450 |
+
/// </summary>
|
| 451 |
+
bool StartupIdleVirtualProcessor(ScheduleGroupSegmentBase *pSegment, location bias = location())
|
| 452 |
+
{
|
| 453 |
+
//
|
| 454 |
+
// 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
|
| 455 |
+
// context which will simply put it back to sleep and violate our concurrency constraints. Either an incoming runnable must push to the
|
| 456 |
+
// context or the throttler must wake it up.
|
| 457 |
+
//
|
| 458 |
+
return StartupVirtualProcessor(pSegment, bias, VirtualProcessor::AvailabilityAny & ~VirtualProcessor::AvailabilityInactivePendingThread);
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
/// <summary>
|
| 462 |
+
/// Start up an new virtual processor in the scheduler. New virtual processor refers
|
| 463 |
+
/// to any vproc that either has never been activated or has been deactivated due to lack
|
| 464 |
+
/// of work (wait for work).
|
| 465 |
+
/// </summary>
|
| 466 |
+
virtual void StartupNewVirtualProcessor(ScheduleGroupSegmentBase *pSegment, location bias = location())
|
| 467 |
+
{
|
| 468 |
+
StartupVirtualProcessor(pSegment, bias, (VirtualProcessor::AvailabilityType)(VirtualProcessor::AvailabilityIdle | VirtualProcessor::AvailabilityInactive));
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
/// <summary>
|
| 472 |
+
/// Attempts to push a runnable to an inactive virtual processor. If successful, true is returned.
|
| 473 |
+
/// </summary>
|
| 474 |
+
virtual bool PushRunnableToInactive(InternalContextBase *pRunnableContext, location bias = location());
|
| 475 |
+
|
| 476 |
+
/// <summary>
|
| 477 |
+
/// Called when a virtual processor becomes active (before it does) or becomes inactive (before it does).
|
| 478 |
+
/// </summary>
|
| 479 |
+
/// <param value="fActive">
|
| 480 |
+
/// True if a virtual processor is going from INACTIVE to ACTIVE, and false if it is going from ACTIVE to INACTIVE.
|
| 481 |
+
/// </param>
|
| 482 |
+
/// <returns>
|
| 483 |
+
/// For activation, the function returns true if the virtual processor was successfully activated, and false
|
| 484 |
+
/// if it could not be activated because the scheduler was shutting down. For inactivation, it always returns true.
|
| 485 |
+
/// </returns>
|
| 486 |
+
bool VirtualProcessorActive(bool fActive);
|
| 487 |
+
|
| 488 |
+
/// <summary>
|
| 489 |
+
/// Internal contexts and background threads call this when created and used inside the scheduler.
|
| 490 |
+
/// </summary>
|
| 491 |
+
void IncrementInternalContextCount();
|
| 492 |
+
|
| 493 |
+
/// <summary>
|
| 494 |
+
/// Internal contexts and background threads call this function in order to notify that they are about to exit.
|
| 495 |
+
/// The last caller will trigger scheduler finalization.
|
| 496 |
+
/// </summary>
|
| 497 |
+
void DecrementInternalContextCount();
|
| 498 |
+
|
| 499 |
+
/// <summary>
|
| 500 |
+
/// Returns the scheduling protocol policy element value this scheduler was created with.
|
| 501 |
+
/// </summary>
|
| 502 |
+
::Concurrency::SchedulingProtocolType GetSchedulingProtocol() { return m_schedulingProtocol; }
|
| 503 |
+
|
| 504 |
+
/// <summary>
|
| 505 |
+
/// Returns a pointer to the 'next' scheduling ring in a round-robin manner
|
| 506 |
+
/// </summary>
|
| 507 |
+
SchedulingRing *GetNextSchedulingRing();
|
| 508 |
+
|
| 509 |
+
// Specifying pOwningNode produces an order of scheduling rings, ordered by node distance.
|
| 510 |
+
// pCurrentNode is the current position in said order.
|
| 511 |
+
SchedulingRing *GetNextSchedulingRing(const SchedulingRing *pOwningRing, SchedulingRing *pCurrentRing);
|
| 512 |
+
|
| 513 |
+
/// <summary>
|
| 514 |
+
/// Sets the 'next' scheduling ring in a round-robin manner
|
| 515 |
+
/// </summary>
|
| 516 |
+
void SetNextSchedulingRing(SchedulingRing *pRing);
|
| 517 |
+
|
| 518 |
+
/// <summary>
|
| 519 |
+
/// Returns true if the scheduler has gone past a certain point in PhaseTwoShutdown (when it sets the shutdown completed flag).
|
| 520 |
+
/// This function is mainly used for debug asserts.
|
| 521 |
+
/// </summary>
|
| 522 |
+
bool HasCompletedShutdown();
|
| 523 |
+
|
| 524 |
+
/// <summary>
|
| 525 |
+
/// Returns true if the scheduler is in the finalization sweep, i.e, the SUSPEND_GATE_FLAG is set.
|
| 526 |
+
/// This function is mainly used for debug asserts.
|
| 527 |
+
/// </summary>
|
| 528 |
+
bool InFinalizationSweep();
|
| 529 |
+
|
| 530 |
+
/// <summary>
|
| 531 |
+
/// Internal contexts call the scheduler when they go idle for a specified amount of time in order to allow
|
| 532 |
+
/// things that happen on scheduler idle to happen (e.g.: sweeping for phase two shutdown).
|
| 533 |
+
/// They must also call the scheduler when they transition out of idle before executing a work item or performing
|
| 534 |
+
/// a context switch. This may halt scheduler shutdown or it may coordinate with scheduler shutdown depending on
|
| 535 |
+
/// the current phase of shutdown.
|
| 536 |
+
///
|
| 537 |
+
/// This call *MUST* be made from a scheduler critical region.
|
| 538 |
+
/// </summary>
|
| 539 |
+
/// <param name="fIdle">
|
| 540 |
+
/// Specifies whether the processor is going idle or non-idle.
|
| 541 |
+
/// </param>
|
| 542 |
+
void VirtualProcessorIdle(bool fIdle);
|
| 543 |
+
|
| 544 |
+
/// <summary>
|
| 545 |
+
/// Adds a new statistics class to track.
|
| 546 |
+
/// </summary>
|
| 547 |
+
/// <param name="pStats">
|
| 548 |
+
/// The statistics we are adding to the scheduler's ListArray<ExternalStatistics> for tracking.
|
| 549 |
+
/// </param>
|
| 550 |
+
void AddExternalStatistics(ExternalStatistics * pStats)
|
| 551 |
+
{
|
| 552 |
+
m_externalThreadStatistics.Add(pStats);
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
/// <summary>
|
| 556 |
+
/// Saves the statistical information from the retiring virtual processor.
|
| 557 |
+
/// </summary>
|
| 558 |
+
/// <param name="pVProc">
|
| 559 |
+
/// The virtual processor that is retiring and whose statistics we are trying to preserve.
|
| 560 |
+
/// </param>
|
| 561 |
+
/// <remarks>
|
| 562 |
+
/// The reason we use interlocked operation here is because multiple virtual processors can
|
| 563 |
+
/// be retiring at the same time and the error can be much greater than on a simple increment.
|
| 564 |
+
/// </remarks>
|
| 565 |
+
void SaveRetiredVirtualProcessorStatistics(VirtualProcessor * pVProc)
|
| 566 |
+
{
|
| 567 |
+
InterlockedExchangeAdd((volatile long *) &m_enqueuedTaskCounter, pVProc->GetEnqueuedTaskCount());
|
| 568 |
+
InterlockedExchangeAdd((volatile long *) &m_dequeuedTaskCounter, pVProc->GetDequeuedTaskCount());
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
/// <summary>
|
| 572 |
+
/// Resets the count of work coming in.
|
| 573 |
+
/// </summary>
|
| 574 |
+
/// <returns>
|
| 575 |
+
/// Previous value of the counter.
|
| 576 |
+
/// </returns>
|
| 577 |
+
unsigned int GetEnqueuedTaskCount()
|
| 578 |
+
{
|
| 579 |
+
ULONG currentValue = m_enqueuedTaskCounter;
|
| 580 |
+
unsigned int retVal = (unsigned int) (currentValue - m_enqueuedTaskCheckpoint);
|
| 581 |
+
|
| 582 |
+
// Update the checkpoint value with the current value
|
| 583 |
+
m_enqueuedTaskCheckpoint = currentValue;
|
| 584 |
+
|
| 585 |
+
ASSERT(retVal < INT_MAX);
|
| 586 |
+
return retVal;
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
/// <summary>
|
| 590 |
+
/// Resets the count of work being done.
|
| 591 |
+
/// </summary>
|
| 592 |
+
/// <returns>
|
| 593 |
+
/// Previous value of the counter.
|
| 594 |
+
/// </returns>
|
| 595 |
+
unsigned int GetDequeuedTaskCount()
|
| 596 |
+
{
|
| 597 |
+
ULONG currentValue = m_dequeuedTaskCounter;
|
| 598 |
+
unsigned int retVal = (unsigned int) (currentValue - m_dequeuedTaskCheckpoint);
|
| 599 |
+
|
| 600 |
+
// Update the checkpoint value with the current value
|
| 601 |
+
m_dequeuedTaskCheckpoint = currentValue;
|
| 602 |
+
|
| 603 |
+
ASSERT(retVal < INT_MAX);
|
| 604 |
+
return retVal;
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
/// <summary>
|
| 608 |
+
/// Returns a suballocator from the pool of suballocators in the process, or creates a new one. The RM only allows
|
| 609 |
+
/// a fixed number of allocators for external contexts in the process, whereas every virtual processor that requests
|
| 610 |
+
/// an allocator will get one.
|
| 611 |
+
/// </summary>
|
| 612 |
+
/// <param name="fExternalAllocator">
|
| 613 |
+
/// Specifies whether the allocator is being requested for an external context. If this is 'true' the RM will return
|
| 614 |
+
/// NULL if it has reached its limit of suballocators for external contexts. If this is 'false', the caller is requesting
|
| 615 |
+
/// the suballocator for a virtual processor, and the RM *must* allocate one (resources permitting).
|
| 616 |
+
/// </param>
|
| 617 |
+
static SubAllocator* GetSubAllocator(bool fExternalAllocator);
|
| 618 |
+
|
| 619 |
+
/// <summary>
|
| 620 |
+
/// Returns a suballocator back to the pool in the RM. The RM caches a fixed number of suballocators and will destroy the
|
| 621 |
+
/// rest.
|
| 622 |
+
/// </summary>
|
| 623 |
+
static void ReturnSubAllocator(SubAllocator* pAllocator);
|
| 624 |
+
|
| 625 |
+
/// <summary>
|
| 626 |
+
/// Enqueues a context into m_allContexts
|
| 627 |
+
/// </summary>
|
| 628 |
+
void AddContext(InternalContextBase * pContext);
|
| 629 |
+
|
| 630 |
+
/// <summary>
|
| 631 |
+
/// Returns the first scheduling node.
|
| 632 |
+
/// </summary>
|
| 633 |
+
/// <param name="pIdx">
|
| 634 |
+
/// The iterator position of the returned scheduling node will be placed here. This can only be
|
| 635 |
+
/// utilized as the pIdx parameter or the idxStart parameter of a GetNextSchedulingNode.
|
| 636 |
+
/// </param>
|
| 637 |
+
SchedulingNode *GetFirstSchedulingNode(int *pIdx)
|
| 638 |
+
{
|
| 639 |
+
*pIdx = 0;
|
| 640 |
+
return GetNextSchedulingNode(pIdx, -1);
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
/// <summary>
|
| 644 |
+
/// Returns the next scheduling node in an iteration.
|
| 645 |
+
/// </summary>
|
| 646 |
+
SchedulingNode *GetNextSchedulingNode(int *pIdx, int idxStart = 0)
|
| 647 |
+
{
|
| 648 |
+
int base = *pIdx + (idxStart == -1 ? 0 : 1);
|
| 649 |
+
int size = m_nodeCount;
|
| 650 |
+
for (int i = 0; i < size; i++)
|
| 651 |
+
{
|
| 652 |
+
int index = (i + base) % size;
|
| 653 |
+
if (index == idxStart)
|
| 654 |
+
return NULL;
|
| 655 |
+
|
| 656 |
+
SchedulingNode *pNode = m_nodes[index];
|
| 657 |
+
if (pNode != NULL)
|
| 658 |
+
{
|
| 659 |
+
*pIdx = index;
|
| 660 |
+
return pNode;
|
| 661 |
+
}
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
return NULL;
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
/// <summary>
|
| 668 |
+
/// Performs a reference on one shot static items. The caller should CheckOneShotStaticDestruction to remove
|
| 669 |
+
/// the reference count.
|
| 670 |
+
/// </summary>
|
| 671 |
+
static LONG ReferenceStaticOneShot()
|
| 672 |
+
{
|
| 673 |
+
return InterlockedIncrement(&s_oneShotInitializationState);
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
/// <summary>
|
| 677 |
+
/// Removes a previous reference on one shot static items.
|
| 678 |
+
/// </summary>
|
| 679 |
+
static LONG DereferenceStaticOneShot()
|
| 680 |
+
{
|
| 681 |
+
return InterlockedDecrement(&s_oneShotInitializationState);
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
/// <summary>
|
| 685 |
+
/// Called at unload/process exit to perform cleanup of one-shot initialization items.
|
| 686 |
+
/// </summary>
|
| 687 |
+
static void CheckOneShotStaticDestruction();
|
| 688 |
+
|
| 689 |
+
/// <summary>
|
| 690 |
+
/// Called when a particular virtual processor reaches a safe point. This function does very little unless there has
|
| 691 |
+
/// been a change in the version number of the safe point.
|
| 692 |
+
/// </summary>
|
| 693 |
+
/// <param name="pMarker">
|
| 694 |
+
/// The safe point marker for a given virtual processor. This is the virtual processor reaching a safe point.
|
| 695 |
+
/// </param>
|
| 696 |
+
/// <returns>
|
| 697 |
+
/// An indication of whether a commit should take place. If this is true, the caller should call CommitSafePoints when possible.
|
| 698 |
+
/// Note that this is a return value so that things like UMS virtual processors can exit critical regions before performing
|
| 699 |
+
/// the commit (to avoid, for instance, heap locks in critical regions).
|
| 700 |
+
/// </returns>
|
| 701 |
+
bool MarkSafePoint(SafePointMarker *pMarker);
|
| 702 |
+
|
| 703 |
+
/// <summary>
|
| 704 |
+
/// Called to make a determination of what version of data we can commit up to. This is the minimum data version that all virtual
|
| 705 |
+
/// processors have observed.
|
| 706 |
+
/// </summary>
|
| 707 |
+
void CommitSafePoints();
|
| 708 |
+
|
| 709 |
+
/// <summary>
|
| 710 |
+
/// The routine is used to trigger a safe point commit on all the vprocs by
|
| 711 |
+
/// updating the data version.
|
| 712 |
+
/// </summary>
|
| 713 |
+
void TriggerCommitSafePoints(SafePointMarker *pMarker);
|
| 714 |
+
|
| 715 |
+
/// <summary>
|
| 716 |
+
/// Determines how long in milliseconds until the next set of threads is allowed to be created.
|
| 717 |
+
/// </summary>
|
| 718 |
+
ULONG ThrottlingTime(ULONG stepWidth);
|
| 719 |
+
|
| 720 |
+
/// <summary>
|
| 721 |
+
/// Returns the delay before the next thread can be created.
|
| 722 |
+
/// </summary>
|
| 723 |
+
ULONG ThrottlingDelta()
|
| 724 |
+
{
|
| 725 |
+
ULONGLONG curTime = platform::__GetTickCount64();
|
| 726 |
+
ULONG delta = (ULONG)(curTime - m_lastThrottledCreateTime);
|
| 727 |
+
|
| 728 |
+
return delta;
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
/// <summary>
|
| 732 |
+
/// Puts a timestamp on the last time a throttled thread was created.
|
| 733 |
+
/// </summary>
|
| 734 |
+
void StampThrottledCreate()
|
| 735 |
+
{
|
| 736 |
+
m_lastThrottledCreateTime = platform::__GetTickCount64();
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
/// <summary>
|
| 740 |
+
/// Returns whether a virtual processor is available.
|
| 741 |
+
/// </summary>
|
| 742 |
+
bool HasVirtualProcessorAvailable() const
|
| 743 |
+
{
|
| 744 |
+
return m_virtualProcessorAvailableCount > 0;
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
/// <summary>
|
| 748 |
+
/// Returns whether a virtual processor is waiting for throttling.
|
| 749 |
+
/// </summary>
|
| 750 |
+
bool HasVirtualProcessorPendingThreadCreate() const
|
| 751 |
+
{
|
| 752 |
+
return m_virtualProcessorsPendingThreadCreate > 0;
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
/// <summary>
|
| 756 |
+
/// Returns whether a virtual processor is available to execute new work.
|
| 757 |
+
/// </summary>
|
| 758 |
+
bool HasVirtualProcessorAvailableForNewWork() const
|
| 759 |
+
{
|
| 760 |
+
//
|
| 761 |
+
// The observational race (lack of atomicity between the two reads) should not matter. If it does in some obscure
|
| 762 |
+
// case, a new atomic counter can be added.
|
| 763 |
+
//
|
| 764 |
+
return (m_virtualProcessorAvailableCount - m_virtualProcessorsPendingThreadCreate) > 0;
|
| 765 |
+
}
|
| 766 |
+
|
| 767 |
+
/// <summary>
|
| 768 |
+
/// Removes an unreferenced schedule group from the scheduler's list of groups.
|
| 769 |
+
/// </summary>
|
| 770 |
+
void RemoveScheduleGroup(ScheduleGroupBase *pGroup);
|
| 771 |
+
|
| 772 |
+
/// <summary>
|
| 773 |
+
/// Returns the scheduling node associated with the calling thread, if any. This method only returns a node if the current
|
| 774 |
+
/// context is an internal context.
|
| 775 |
+
/// </summary>
|
| 776 |
+
SchedulingNode * FindCurrentNode();
|
| 777 |
+
|
| 778 |
+
/// <summary>
|
| 779 |
+
/// Returns the scheduling node which pSrcLocation is a member of. Note that if srcLocation and this node's location do not intersect,
|
| 780 |
+
/// this will return NULL.
|
| 781 |
+
/// </summary>
|
| 782 |
+
SchedulingNode * FindNodeByLocation(location* pSrcLocation);
|
| 783 |
+
|
| 784 |
+
/// <summary>
|
| 785 |
+
/// Returns whether or not a location has a tight binding to an object on this scheduler.
|
| 786 |
+
/// </summary>
|
| 787 |
+
bool IsLocationBound(const location* pLoc) const
|
| 788 |
+
{
|
| 789 |
+
return (pLoc->_GetBindingId() == m_id);
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
/// <summary>
|
| 793 |
+
/// Returns a bit set for a given location to perform quick masking.
|
| 794 |
+
/// </summary>
|
| 795 |
+
QuickBitSet GetBitSet(const location* pLoc);
|
| 796 |
+
|
| 797 |
+
/// <summary>
|
| 798 |
+
/// Notifies the scheduler that a given virtual processor is listening for affinity events pertaining to its underlying
|
| 799 |
+
/// resource. Note that this is a reference counted API.
|
| 800 |
+
/// </summary>
|
| 801 |
+
/// <param name="maskId">
|
| 802 |
+
/// The mask id assigned for a given resource.
|
| 803 |
+
/// </param>
|
| 804 |
+
void ListenAffinity(unsigned int maskId)
|
| 805 |
+
{
|
| 806 |
+
m_nonAffineResourceListeners.InterlockedSet(maskId);
|
| 807 |
+
OMTRACE(MTRACE_EVT_LISTENINGTRUE, this, NULL, NULL, maskId);
|
| 808 |
+
ClearQuickCacheSlot(maskId);
|
| 809 |
+
}
|
| 810 |
+
|
| 811 |
+
/// <summary>
|
| 812 |
+
/// Notifies the scheduler that a given virtual processor is ignoring messages for affinity events pertaining to its underlying
|
| 813 |
+
/// resource. Note that this is a reference counted API.
|
| 814 |
+
/// </summary>
|
| 815 |
+
/// <param name="maskId">
|
| 816 |
+
/// The mask id assigned for a given resource.
|
| 817 |
+
/// </param>
|
| 818 |
+
void IgnoreAffinity(unsigned int maskId)
|
| 819 |
+
{
|
| 820 |
+
m_nonAffineResourceListeners.InterlockedClear(maskId);
|
| 821 |
+
OMTRACE(MTRACE_EVT_LISTENINGFALSE, this, NULL, NULL, maskId);
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
/// <summary>
|
| 825 |
+
/// Called when affine work comes into the scheduler, this posts any required notifications to virtual processors which are executing
|
| 826 |
+
/// non-affine work that they need to stop working on their current group and search for affine work again.
|
| 827 |
+
/// </summary>
|
| 828 |
+
void PostAffinityMessage(const QuickBitSet& srcMask)
|
| 829 |
+
{
|
| 830 |
+
if (srcMask.Intersects(m_nonAffineResourceListeners))
|
| 831 |
+
{
|
| 832 |
+
OMTRACE(MTRACE_EVT_POSTAFFINITYMESSAGE, this, NULL, NULL, srcMask.DbgAcquireBits(0));
|
| 833 |
+
m_affinityMessages.InterlockedSet(srcMask & m_nonAffineResourceListeners);
|
| 834 |
+
}
|
| 835 |
+
}
|
| 836 |
+
|
| 837 |
+
/// <summary>
|
| 838 |
+
/// Returns whether a given resource id has a message for affinity and, if so, acknowledges it.
|
| 839 |
+
/// </summary>
|
| 840 |
+
bool AcknowledgedAffinityMessage(unsigned int maskId)
|
| 841 |
+
{
|
| 842 |
+
bool hasMessage = m_affinityMessages.IsSet(maskId);
|
| 843 |
+
if (hasMessage)
|
| 844 |
+
m_affinityMessages.InterlockedClear(maskId);
|
| 845 |
+
|
| 846 |
+
return hasMessage;
|
| 847 |
+
}
|
| 848 |
+
|
| 849 |
+
/// <summary>
|
| 850 |
+
/// Returns the mask id for a given resource id.
|
| 851 |
+
/// </summary>
|
| 852 |
+
unsigned int GetResourceMaskId(unsigned int resourceId)
|
| 853 |
+
{
|
| 854 |
+
unsigned int val;
|
| 855 |
+
Hash<unsigned int, unsigned int>::ListNode *pNode = m_resourceBitMap.Find(resourceId, &val);
|
| 856 |
+
ASSERT(pNode != NULL);
|
| 857 |
+
return val;
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
/// <summary>
|
| 861 |
+
/// Returns the number of mask ids associated with the scheduler.
|
| 862 |
+
/// </summary>
|
| 863 |
+
unsigned int GetMaskIdCount() const
|
| 864 |
+
{
|
| 865 |
+
return ::Concurrency::GetProcessorCount();
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
/// <summary>
|
| 869 |
+
/// Acquires the quick cache slot.
|
| 870 |
+
/// </summary>
|
| 871 |
+
ScheduleGroupSegmentBase *AcquireQuickCacheSlot(unsigned int maskId)
|
| 872 |
+
{
|
| 873 |
+
//
|
| 874 |
+
// Make **SURE** this is short, sweet, and inlines.
|
| 875 |
+
//
|
| 876 |
+
if (m_pCoreAffinityQuickCache[static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT] > reinterpret_cast<ScheduleGroupSegmentBase *>(1))
|
| 877 |
+
{
|
| 878 |
+
return ActualGetQuickCacheSlot(maskId);
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
return NULL;
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
/// <summary>
|
| 885 |
+
/// Clears the quick cache slot.
|
| 886 |
+
/// </summary>
|
| 887 |
+
void ClearQuickCacheSlot(unsigned int maskId)
|
| 888 |
+
{
|
| 889 |
+
if (m_pCoreAffinityQuickCache[static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT] == reinterpret_cast<ScheduleGroupSegmentBase *>(1))
|
| 890 |
+
{
|
| 891 |
+
InterlockedCompareExchangePointer(reinterpret_cast <void * volatile *>(m_pCoreAffinityQuickCache + (static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT)),
|
| 892 |
+
reinterpret_cast <void *> (NULL),
|
| 893 |
+
reinterpret_cast <void *> (1));
|
| 894 |
+
}
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
/// <summary>
|
| 898 |
+
/// Clears a given quick cache slot if the slot contains a specific value.
|
| 899 |
+
/// </summary>
|
| 900 |
+
void ClearQuickCacheSlotIf(unsigned int maskId, ScheduleGroupSegmentBase *pSegment)
|
| 901 |
+
{
|
| 902 |
+
if (m_pCoreAffinityQuickCache[static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT] == pSegment)
|
| 903 |
+
{
|
| 904 |
+
InterlockedCompareExchangePointer(reinterpret_cast <void * volatile *>(m_pCoreAffinityQuickCache + (static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT)),
|
| 905 |
+
reinterpret_cast <void *> (NULL),
|
| 906 |
+
reinterpret_cast <void *> (pSegment));
|
| 907 |
+
}
|
| 908 |
+
}
|
| 909 |
+
|
| 910 |
+
/// <summary>
|
| 911 |
+
/// 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
|
| 912 |
+
/// affinitized to a given execution resource, the segment containing that work item is stashed in the quick cache slot for the corresponding
|
| 913 |
+
/// execution resource. This is a fast check which is made repeatedly during search-for-work. This allows a virtual processor which is idle
|
| 914 |
+
/// 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
|
| 915 |
+
/// more rapid virtual processor spin-up for certain affinity scenarios.
|
| 916 |
+
/// </summary>
|
| 917 |
+
void SetQuickCacheSlot(unsigned int maskId, ScheduleGroupSegmentBase *pSegment)
|
| 918 |
+
{
|
| 919 |
+
if (m_pCoreAffinityQuickCache[static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT] == NULL)
|
| 920 |
+
{
|
| 921 |
+
InterlockedCompareExchangePointer(reinterpret_cast <void * volatile *>(m_pCoreAffinityQuickCache + (static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT)),
|
| 922 |
+
reinterpret_cast <void *> (pSegment),
|
| 923 |
+
reinterpret_cast <void *> (NULL));
|
| 924 |
+
}
|
| 925 |
+
}
|
| 926 |
+
|
| 927 |
+
/// <summary>
|
| 928 |
+
/// Notifies the scheduler that a thread serving a virtual processor with the given mask id is actively searching for work. This
|
| 929 |
+
/// will prevent other virtual processors from picking up work which is affine to maskId but not affine to the other virtual processor.
|
| 930 |
+
/// </summary>
|
| 931 |
+
void NotifySearching(unsigned int maskId, bool fSearching)
|
| 932 |
+
{
|
| 933 |
+
if (fSearching)
|
| 934 |
+
{
|
| 935 |
+
m_idleSearch.InterlockedSet(maskId);
|
| 936 |
+
OMTRACE(MTRACE_EVT_SEARCHINGTRUE, this, NULL, NULL, maskId);
|
| 937 |
+
ClearQuickCacheSlot(maskId);
|
| 938 |
+
}
|
| 939 |
+
else
|
| 940 |
+
{
|
| 941 |
+
m_idleSearch.InterlockedClear(maskId);
|
| 942 |
+
OMTRACE(MTRACE_EVT_SEARCHINGFALSE, this, NULL, NULL, maskId);
|
| 943 |
+
|
| 944 |
+
}
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
/// <summary>
|
| 948 |
+
/// Returns whether or not any of the set of virtual processors represented by bitSet is searching for work.
|
| 949 |
+
/// </summary>
|
| 950 |
+
bool HasSearchers(const QuickBitSet& bitSet) const
|
| 951 |
+
{
|
| 952 |
+
return m_idleSearch.Intersects(bitSet);
|
| 953 |
+
}
|
| 954 |
+
|
| 955 |
+
/// <summary>
|
| 956 |
+
/// Checks whether a periodic scan is necessary, and if so, performs it.
|
| 957 |
+
/// </summary>
|
| 958 |
+
void PeriodicScan(ULONGLONG serviceTime)
|
| 959 |
+
{
|
| 960 |
+
//
|
| 961 |
+
// Right now, we only perform livelock service scan every 2 seconds.
|
| 962 |
+
//
|
| 963 |
+
if (serviceTime - m_lastServiceScan > 2000)
|
| 964 |
+
PerformServiceScan(serviceTime);
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
/// <summary>
|
| 968 |
+
/// Increments the count of active resources by a given resource's mask id.
|
| 969 |
+
/// </summary>
|
| 970 |
+
void IncrementActiveResourcesByMask(unsigned int maskId)
|
| 971 |
+
{
|
| 972 |
+
m_activeSet.InterlockedSet(maskId);
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
/// <summary>
|
| 976 |
+
/// Decrements the count of active resources by a given resource's mask id.
|
| 977 |
+
/// </summary>
|
| 978 |
+
void DecrementActiveResourcesByMask(unsigned int maskId)
|
| 979 |
+
{
|
| 980 |
+
m_activeSet.InterlockedClear(maskId);
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
//**************************************************
|
| 984 |
+
//
|
| 985 |
+
// TRANSITION: This is temporary until such time as we can hook into priority to solve livelock issues.
|
| 986 |
+
//
|
| 987 |
+
|
| 988 |
+
bool HasPriorityObjects() const
|
| 989 |
+
{
|
| 990 |
+
return !m_priorityObjects.Empty();
|
| 991 |
+
}
|
| 992 |
+
|
| 993 |
+
BoostedObject *GetNextPriorityObject();
|
| 994 |
+
|
| 995 |
+
void RemovePrioritizedObject(BoostedObject *pEntry);
|
| 996 |
+
|
| 997 |
+
//
|
| 998 |
+
// TRANSITION: End of temporary section
|
| 999 |
+
//
|
| 1000 |
+
//**************************************************
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
protected:
|
| 1004 |
+
|
| 1005 |
+
SchedulerPolicy m_policy;
|
| 1006 |
+
|
| 1007 |
+
// scheduler policy fields
|
| 1008 |
+
::Concurrency::SchedulerType m_schedulerKind;
|
| 1009 |
+
::Concurrency::SchedulingProtocolType m_schedulingProtocol;
|
| 1010 |
+
unsigned short m_localContextCacheSize;
|
| 1011 |
+
|
| 1012 |
+
// The total number of virtual processors in the scheduler, not including oversubscribed virtual processors.
|
| 1013 |
+
// This number is adjusted as dynamic RM adds and removes cores.
|
| 1014 |
+
volatile LONG m_virtualProcessorCount{};
|
| 1015 |
+
|
| 1016 |
+
// The default scheduler
|
| 1017 |
+
static SchedulerBase* s_pDefaultScheduler;
|
| 1018 |
+
static _StaticLock s_defaultSchedulerLock;
|
| 1019 |
+
|
| 1020 |
+
// The default scheduler policy
|
| 1021 |
+
static SchedulerPolicy* s_pDefaultSchedulerPolicy;
|
| 1022 |
+
|
| 1023 |
+
// TLS data
|
| 1024 |
+
static DWORD t_dwContextIndex;
|
| 1025 |
+
DWORD m_dwExternalStatisticsIndex;
|
| 1026 |
+
|
| 1027 |
+
//
|
| 1028 |
+
// NOTE: Must cleanup up m_nodes before m_rings
|
| 1029 |
+
//
|
| 1030 |
+
NumaInformation* m_numaInformation{};
|
| 1031 |
+
SchedulingNode** m_nodes{};
|
| 1032 |
+
SchedulingRing** m_rings{};
|
| 1033 |
+
int m_numaCount{};
|
| 1034 |
+
int m_nodeCount{};
|
| 1035 |
+
|
| 1036 |
+
//
|
| 1037 |
+
// The active set of virtual processors on this scheduler.
|
| 1038 |
+
//
|
| 1039 |
+
ReferenceCountedQuickBitSet m_activeSet;
|
| 1040 |
+
|
| 1041 |
+
//
|
| 1042 |
+
// Tracking for virtual processors which need messages of notification for affine work scheduling, etc...
|
| 1043 |
+
//
|
| 1044 |
+
ReferenceCountedQuickBitSet m_idleSearch;
|
| 1045 |
+
ReferenceCountedQuickBitSet m_nonAffineResourceListeners;
|
| 1046 |
+
QuickBitSet m_affinityMessages;
|
| 1047 |
+
|
| 1048 |
+
//
|
| 1049 |
+
// Quick cache for core affine tasks.
|
| 1050 |
+
//
|
| 1051 |
+
ScheduleGroupSegmentBase* volatile * m_pCoreAffinityQuickCache{};
|
| 1052 |
+
|
| 1053 |
+
// The list of schedule groups within the scheduler. Note that while groups are owned by the scheduler, a group is merely
|
| 1054 |
+
// a collection of segments where the individual segments are owned by scheduling rings. This allows groups with affinity applied
|
| 1055 |
+
// as well as separation of work within a group by which node scheduled it.
|
| 1056 |
+
ListArray<ScheduleGroupBase> m_scheduleGroups;
|
| 1057 |
+
|
| 1058 |
+
// The single anonymous schedule group for the scheduler. The anonymous schedule group will have one segment per ring.
|
| 1059 |
+
ScheduleGroupBase *m_pAnonymousScheduleGroup{};
|
| 1060 |
+
|
| 1061 |
+
// Lock free list of all internal contexts in the scheduler
|
| 1062 |
+
LockFreePushStack<ContextNode> m_allContexts;
|
| 1063 |
+
|
| 1064 |
+
SafeRWList<WaitNode> m_finalEvents;
|
| 1065 |
+
|
| 1066 |
+
// A list array that keeps statistical information for all non-internal contexts
|
| 1067 |
+
ListArray<ExternalStatistics> m_externalThreadStatistics;
|
| 1068 |
+
|
| 1069 |
+
// Lock that guards the data structures for tracking context exit events.
|
| 1070 |
+
_NonReentrantBlockingLock m_listArrayDeletionLock;
|
| 1071 |
+
|
| 1072 |
+
/// <summary>
|
| 1073 |
+
/// Activate the given virtual processor
|
| 1074 |
+
/// </summary>
|
| 1075 |
+
void ActivateVirtualProcessor(VirtualProcessor *pVirtualProcessor, ScheduleGroupBase *pGroup);
|
| 1076 |
+
|
| 1077 |
+
/// <summary>
|
| 1078 |
+
/// Returns a newly constructed internal context appropriate to the given type of scheduler.
|
| 1079 |
+
/// </summary>
|
| 1080 |
+
virtual InternalContextBase *CreateInternalContext() =0;
|
| 1081 |
+
|
| 1082 |
+
/// <summary>
|
| 1083 |
+
/// Increments the reference counts required by a scheduler attach.
|
| 1084 |
+
/// </summary>
|
| 1085 |
+
void ReferenceForAttach();
|
| 1086 |
+
|
| 1087 |
+
/// <summary>
|
| 1088 |
+
/// Decrements the reference counts incremented for scheduler attach.
|
| 1089 |
+
/// </summary>
|
| 1090 |
+
void ReleaseForDetach();
|
| 1091 |
+
|
| 1092 |
+
/// <summary>
|
| 1093 |
+
/// Returns a current number of active virtual processors for this scheduler
|
| 1094 |
+
/// </summary>
|
| 1095 |
+
/// <returns>
|
| 1096 |
+
/// Returns a current number of active virtual processors for this scheduler. No error state.
|
| 1097 |
+
/// </returns>
|
| 1098 |
+
unsigned int GetNumberOfActiveVirtualProcessors() const { return m_activeVProcCount; };
|
| 1099 |
+
|
| 1100 |
+
///<summary>
|
| 1101 |
+
/// Notification after a virtual processor goes from INACTIVE to ACTIVE or ACTIVE to INACTIVE
|
| 1102 |
+
///</summary>
|
| 1103 |
+
/// <param value="fActive">
|
| 1104 |
+
/// True if a virtual processor is going from INACTIVE to ACTIVE, and false if it is going from ACTIVE to INACTIVE.
|
| 1105 |
+
/// </param>
|
| 1106 |
+
/// <param value="activeCount">
|
| 1107 |
+
/// Active virtual processor count after the transition
|
| 1108 |
+
/// </param>
|
| 1109 |
+
virtual void VirtualProcessorActiveNotification(bool fActive, LONG activeCount)
|
| 1110 |
+
{
|
| 1111 |
+
(fActive); (activeCount);
|
| 1112 |
+
}
|
| 1113 |
+
|
| 1114 |
+
/// <summary>
|
| 1115 |
+
/// Indicates the type of work which exists within the scheduler.
|
| 1116 |
+
/// </summary>
|
| 1117 |
+
enum PendingWorkType
|
| 1118 |
+
{
|
| 1119 |
+
/// <summary>
|
| 1120 |
+
/// No work exists within the scheduler.
|
| 1121 |
+
/// </summary>
|
| 1122 |
+
NoWork,
|
| 1123 |
+
|
| 1124 |
+
/// <summary>
|
| 1125 |
+
/// There is user work within the scheduler (chores, tasks, blocked contexts, etc...). There may or may not
|
| 1126 |
+
/// be ancillary work.
|
| 1127 |
+
/// </summary>
|
| 1128 |
+
UserWork,
|
| 1129 |
+
|
| 1130 |
+
/// <summary>
|
| 1131 |
+
/// There is ancillary work related to the scheduler (e.g.: queued timers for throttling, etc...)
|
| 1132 |
+
/// </summary>
|
| 1133 |
+
OnlyAncillaryWork
|
| 1134 |
+
};
|
| 1135 |
+
|
| 1136 |
+
/// <summary>
|
| 1137 |
+
/// Determines if there is pending work such as blocked context/unstarted chores etc in the
|
| 1138 |
+
/// scheduler. If there is no pending work, the scheduler will attempt to shutdown.
|
| 1139 |
+
/// </summary>
|
| 1140 |
+
virtual PendingWorkType TypeOfWorkPending();
|
| 1141 |
+
|
| 1142 |
+
/// <summary>
|
| 1143 |
+
/// Initialize scheduler event handlers/background threads
|
| 1144 |
+
/// </summary>
|
| 1145 |
+
virtual void InitializeSchedulerEventHandlers();
|
| 1146 |
+
|
| 1147 |
+
/// <summary>
|
| 1148 |
+
/// Destroy scheduler event handlers/background threads
|
| 1149 |
+
/// </summary>
|
| 1150 |
+
virtual void DestroySchedulerEventHandlers();
|
| 1151 |
+
|
| 1152 |
+
/// <summary>
|
| 1153 |
+
/// Cancel all the internal contexts.
|
| 1154 |
+
/// </summary>
|
| 1155 |
+
virtual void CancelAllContexts();
|
| 1156 |
+
|
| 1157 |
+
/// <summary>
|
| 1158 |
+
/// Returns the count of bound contexts on the scheduler.
|
| 1159 |
+
/// </summary>
|
| 1160 |
+
ULONG GetNumberOfBoundContexts() const
|
| 1161 |
+
{
|
| 1162 |
+
return (ULONG)m_boundContextCount;
|
| 1163 |
+
}
|
| 1164 |
+
|
| 1165 |
+
// Implementation for IScheduler interface APIs that is shared between to all derived classes.
|
| 1166 |
+
|
| 1167 |
+
/// <summary>
|
| 1168 |
+
/// Called by the resource manager in order to gather statistics for a given scheduler. The statistics gathered here
|
| 1169 |
+
/// will be used to drive dynamic feedback with the scheduler to determine when it is appropriate to assign more resources
|
| 1170 |
+
/// or take resources away. Note that these counts can be optimistic and do not necessarily have to reflect the current
|
| 1171 |
+
/// count with 100% synchronized accuracy.
|
| 1172 |
+
/// </summary>
|
| 1173 |
+
/// <param name="pTaskCompletionRate">
|
| 1174 |
+
/// The number of tasks which have been completed by the scheduler since the last call to the Statistics method.
|
| 1175 |
+
/// </param>
|
| 1176 |
+
/// <param name="pTaskArrivalRate">
|
| 1177 |
+
/// The number of tasks that have arrived in the scheduler since the last call to the Statistics method.
|
| 1178 |
+
/// </param>
|
| 1179 |
+
/// <param name="pNumberOfTasksEnqueued">
|
| 1180 |
+
/// The total number of tasks in all scheduler queues.
|
| 1181 |
+
/// </param>
|
| 1182 |
+
void Statistics(unsigned int *pTaskCompletionRate, unsigned int *pTaskArrivalRate, unsigned int *pNumberOfTasksEnqueued);
|
| 1183 |
+
|
| 1184 |
+
/// <summary>
|
| 1185 |
+
/// Called when the resource manager is giving virtual processors to a particular scheduler. The virtual processors are
|
| 1186 |
+
/// identified by an array of IVirtualProcessorRoot interfaces. This call is made to grant virtual processor roots
|
| 1187 |
+
/// at initial allocation during the course of ISchedulerProxy::RequestInitialVirtualProcessors, and during dynamic
|
| 1188 |
+
/// core migration.
|
| 1189 |
+
/// </summary>
|
| 1190 |
+
/// <param name="pVirtualProcessorRoots">
|
| 1191 |
+
/// An array of IVirtualProcessorRoot interfaces representing the virtual processors being added to the scheduler.
|
| 1192 |
+
/// </param>
|
| 1193 |
+
/// <param name="count">
|
| 1194 |
+
/// Number of IVirtualProcessorRoot interfaces in the array.
|
| 1195 |
+
/// </param>
|
| 1196 |
+
void AddVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count);
|
| 1197 |
+
|
| 1198 |
+
/// <summary>
|
| 1199 |
+
/// Called when the resource manager is taking away virtual processors from a particular scheduler. The scheduler should
|
| 1200 |
+
/// mark the supplied virtual processors such that they are removed asynchronously and return immediately. Note that
|
| 1201 |
+
/// the scheduler should make every attempt to remove the virtual processors as quickly as possible as the resource manager
|
| 1202 |
+
/// will reaffinitize threads executing upon them to other resources. Delaying stopping the virtual processors may result
|
| 1203 |
+
/// in unintentional oversubscription within the scheduler.
|
| 1204 |
+
/// </summary>
|
| 1205 |
+
/// <param name="pVirtualProcessorRoots">
|
| 1206 |
+
/// An array of IVirtualProcessorRoot interfaces representing the virtual processors which are to be removed.
|
| 1207 |
+
/// </param>
|
| 1208 |
+
/// <param name="count">
|
| 1209 |
+
/// Number of IVirtualProcessorRoot interfaces in the array.
|
| 1210 |
+
/// </param>
|
| 1211 |
+
void RemoveVirtualProcessors(IVirtualProcessorRoot **ppVirtualProcessorRoots, unsigned int count);
|
| 1212 |
+
|
| 1213 |
+
/// <summary>
|
| 1214 |
+
/// Invoked when the Gate Count goes to zero as a result of virtual processor state transitions, while the
|
| 1215 |
+
/// scheduler has been marked for shutdown. It proceeds to sweep the scheduler if it can set the suspend flag
|
| 1216 |
+
/// on the shutdown gate while the gate count is still 0 and the scheduler is marked for shutdown.
|
| 1217 |
+
/// </summary>
|
| 1218 |
+
void AttemptSchedulerSweep();
|
| 1219 |
+
|
| 1220 |
+
/// <summary>
|
| 1221 |
+
/// Returns whether the reserved context pool can be utilized to fetch contexts to bypass throttling.
|
| 1222 |
+
/// </summary>
|
| 1223 |
+
virtual bool AllowGeneralFetchOfReservedContexts()
|
| 1224 |
+
{
|
| 1225 |
+
return true;
|
| 1226 |
+
}
|
| 1227 |
+
|
| 1228 |
+
private:
|
| 1229 |
+
|
| 1230 |
+
friend class ContextBase;
|
| 1231 |
+
friend class ::Concurrency::CurrentScheduler;
|
| 1232 |
+
friend class ScheduleGroupBase;
|
| 1233 |
+
friend class ScheduleGroupSegmentBase;
|
| 1234 |
+
friend class FairScheduleGroup;
|
| 1235 |
+
friend class CacheLocalScheduleGroup;
|
| 1236 |
+
friend class InternalContextBase;
|
| 1237 |
+
friend class ExternalContextBase;
|
| 1238 |
+
friend class VirtualProcessor;
|
| 1239 |
+
friend class SchedulingRing;
|
| 1240 |
+
friend class SchedulingNode;
|
| 1241 |
+
friend class SafePointInvocation;
|
| 1242 |
+
|
| 1243 |
+
//
|
| 1244 |
+
// TRANSITION: This is a temporary patch for livelock prevention until we can hook into priority.
|
| 1245 |
+
// TRANSITION: This **MUST** have a hyper lock on it.
|
| 1246 |
+
//
|
| 1247 |
+
SafeRWList<BoostedObject, CollectionTypes::NoCount, _ReaderWriterLock> m_priorityObjects;
|
| 1248 |
+
|
| 1249 |
+
// The list of invocations for safe point registrations.
|
| 1250 |
+
SafeSQueue<SafePointInvocation, _HyperNonReentrantLock> m_safePointInvocations;
|
| 1251 |
+
|
| 1252 |
+
// Counter used to assign unique identifiers to contexts.
|
| 1253 |
+
volatile LONG m_contextIdCounter;
|
| 1254 |
+
|
| 1255 |
+
// Counter used to assign unique identifiers to schedule groups.
|
| 1256 |
+
volatile LONG m_scheduleGroupIdCounter;
|
| 1257 |
+
|
| 1258 |
+
// Counter used to assign unique identifiers to work queues.
|
| 1259 |
+
static volatile LONG s_workQueueIdCounter;
|
| 1260 |
+
|
| 1261 |
+
// The current safe point version for data. This indicates the newest data requiring observation by all virtual processors
|
| 1262 |
+
volatile ULONG m_safePointDataVersion;
|
| 1263 |
+
|
| 1264 |
+
// The current safe point commit version. This indicates the newest data that has been observed by all virtual processors
|
| 1265 |
+
volatile ULONG m_safePointCommitVersion;
|
| 1266 |
+
|
| 1267 |
+
// The pending version that is being committed by one of the vprocs.
|
| 1268 |
+
volatile ULONG m_safePointPendingVersion;
|
| 1269 |
+
|
| 1270 |
+
// Hash tables for conversion
|
| 1271 |
+
Hash<unsigned int, unsigned int> m_resourceNodeMap;
|
| 1272 |
+
Hash<unsigned int, unsigned int> m_resourceBitMap;
|
| 1273 |
+
|
| 1274 |
+
// scheduler id
|
| 1275 |
+
unsigned int m_id;
|
| 1276 |
+
|
| 1277 |
+
// Round-robin index for scheduling ring.
|
| 1278 |
+
unsigned int m_nextSchedulingRingIndex;
|
| 1279 |
+
|
| 1280 |
+
// Handle to a semaphore used to synchronize during scheduler finalization.
|
| 1281 |
+
HANDLE m_hSchedulerShutdownSync{};
|
| 1282 |
+
|
| 1283 |
+
//
|
| 1284 |
+
// Reference counts:
|
| 1285 |
+
//
|
| 1286 |
+
// m_refCount -- The externally visible reference count on the scheduler. Incremented for attachment
|
| 1287 |
+
// and for explicit calls to Reference. When this reference count falls to zero, the
|
| 1288 |
+
// scheduler initiates shutdown. When m_internalContextCount falls to zero, the
|
| 1289 |
+
// scheduler finalizes.
|
| 1290 |
+
//
|
| 1291 |
+
// m_attachCount -- The count of external contexts to which this scheduler is attached. This is primarily
|
| 1292 |
+
// present for debugging purposes.
|
| 1293 |
+
//
|
| 1294 |
+
// m_internalContextCountPlusOne -- The count of internal contexts on the scheduler plus one. Note that
|
| 1295 |
+
// it's +1 to explicitly handle any possibility of scheduler shutdown
|
| 1296 |
+
// before internal contexts are created.
|
| 1297 |
+
//
|
| 1298 |
+
// m_boundContextCount -- The count of internal contexts which are currently bound. This affects how the scheduler
|
| 1299 |
+
// throttles thread creation.
|
| 1300 |
+
//
|
| 1301 |
+
volatile LONG m_refCount;
|
| 1302 |
+
volatile LONG m_attachCount;
|
| 1303 |
+
volatile LONG m_internalContextCountPlusOne;
|
| 1304 |
+
volatile LONG m_initialReference;
|
| 1305 |
+
volatile LONG m_boundContextCount;
|
| 1306 |
+
|
| 1307 |
+
//
|
| 1308 |
+
// The virtual processor shutdown gate. This is used to implement scheduler shutdown, by ensuring a handshake
|
| 1309 |
+
// when all virtual processors go idle. When such happens, no virtual processor may go active again without
|
| 1310 |
+
// handshaking. During the period between handshakes, the scheduler is free to sweep schedule groups
|
| 1311 |
+
// to detect whether finalization is yet appropriate.
|
| 1312 |
+
//
|
| 1313 |
+
// Layout:
|
| 1314 |
+
// 31 - SHUTDOWN_INITIATED_FLAG -- indicates that the external reference count on the scheduler has fallen to zero,
|
| 1315 |
+
// and the scheduler should be able to finalize when all work queued to it has
|
| 1316 |
+
// completed. This flag may be reset at a later point if an internal context
|
| 1317 |
+
// ends up resurrecting the scheduler.
|
| 1318 |
+
// 30 - SUSPEND_GATE_FLAG -- indicates a suspend phase while the scheduler is trying to evaluate whether
|
| 1319 |
+
// it is ready to finalize. A scheduler may find blocked contexts during this
|
| 1320 |
+
// phase and back off from finalization, resetting the flag. No contexts are allowed
|
| 1321 |
+
// to execute work during this phase, and no new virtual processors may be added
|
| 1322 |
+
// to the scheduler while this bit is set.
|
| 1323 |
+
// 29 - SHUTDOWN_COMPLETED_FLAG -- indicates that the scheduler has completed shutdown. This is the point of no
|
| 1324 |
+
// return, for this scheduler. At this point no work should exist in the scheduler,
|
| 1325 |
+
// and attempts to add any new virtual processors will fail, since the scheduler
|
| 1326 |
+
// is about to be destroyed.
|
| 1327 |
+
//
|
| 1328 |
+
volatile LONG m_vprocShutdownGate;
|
| 1329 |
+
|
| 1330 |
+
// An indication of whether we have done a sweep without actual work.
|
| 1331 |
+
volatile LONG m_fSweepWithoutActualWork;
|
| 1332 |
+
|
| 1333 |
+
// An indication of how long it has been since the last sweep for livelocked segments.
|
| 1334 |
+
volatile ULONGLONG m_lastServiceScan;
|
| 1335 |
+
|
| 1336 |
+
static _StaticLock s_schedulerLock;
|
| 1337 |
+
static LONG s_initializedCount;
|
| 1338 |
+
|
| 1339 |
+
//
|
| 1340 |
+
// The one shot initialization state has two parts, a reference count occupying the lower 31 bits and a flag indicating whether
|
| 1341 |
+
// one shot initialization was performed in the top bit.
|
| 1342 |
+
//
|
| 1343 |
+
static LONG s_oneShotInitializationState;
|
| 1344 |
+
|
| 1345 |
+
IResourceManager *m_pResourceManager;
|
| 1346 |
+
ISchedulerProxy *m_pSchedulerProxy{};
|
| 1347 |
+
|
| 1348 |
+
// The count of virtual processors active in the scheduler.
|
| 1349 |
+
volatile LONG m_activeVProcCount;
|
| 1350 |
+
|
| 1351 |
+
// The number of virtual processors available to schedule more work.
|
| 1352 |
+
// This does *NOT* take into account those virtual processors which are *inactive pending thread*
|
| 1353 |
+
volatile LONG m_virtualProcessorAvailableCount{};
|
| 1354 |
+
|
| 1355 |
+
// The number of virtual processors available pending a thread creation.
|
| 1356 |
+
volatile LONG m_virtualProcessorsPendingThreadCreate;
|
| 1357 |
+
|
| 1358 |
+
// Statistics data counters
|
| 1359 |
+
volatile ULONG m_enqueuedTaskCounter;
|
| 1360 |
+
volatile ULONG m_dequeuedTaskCounter;
|
| 1361 |
+
|
| 1362 |
+
// Statistics data checkpoints
|
| 1363 |
+
ULONG m_enqueuedTaskCheckpoint;
|
| 1364 |
+
ULONG m_dequeuedTaskCheckpoint;
|
| 1365 |
+
|
| 1366 |
+
//
|
| 1367 |
+
// Throttling information:
|
| 1368 |
+
//
|
| 1369 |
+
ULONG m_threadsBeforeThrottling;
|
| 1370 |
+
ULONGLONG m_lastThrottledCreateTime;
|
| 1371 |
+
|
| 1372 |
+
HANDLE m_hThrottlingTimer;
|
| 1373 |
+
volatile LONG m_pendingDeferredCreates;
|
| 1374 |
+
|
| 1375 |
+
// Free list of internal contexts.
|
| 1376 |
+
LockFreeStack<InternalContextBase> m_internalContextPool;
|
| 1377 |
+
|
| 1378 |
+
// Free list of external contexts.
|
| 1379 |
+
LockFreeStack<ExternalContextBase> m_externalContextPool;
|
| 1380 |
+
|
| 1381 |
+
// Free list of realized chores.
|
| 1382 |
+
LockFreeStack<RealizedChore> m_realizedChorePool;
|
| 1383 |
+
|
| 1384 |
+
// List of reserved contexts
|
| 1385 |
+
LockFreeStack<InternalContextBase> m_reservedContexts;
|
| 1386 |
+
|
| 1387 |
+
// A stack that holds free suballocators.
|
| 1388 |
+
static LockFreeStack<SubAllocator> s_subAllocatorFreePool;
|
| 1389 |
+
|
| 1390 |
+
// Number of suballocators for use by external contexts that are active in the process.
|
| 1391 |
+
static volatile LONG s_numExternalAllocators;
|
| 1392 |
+
|
| 1393 |
+
// The max number of external contexts that could have suballocators at any given time.
|
| 1394 |
+
static const int s_maxExternalAllocators;
|
| 1395 |
+
|
| 1396 |
+
// The maximum depth of the free pool of allocators.
|
| 1397 |
+
static const int s_allocatorFreePoolLimit;
|
| 1398 |
+
|
| 1399 |
+
static void CheckStaticConstruction();
|
| 1400 |
+
static void StaticConstruction();
|
| 1401 |
+
static void StaticDestruction();
|
| 1402 |
+
static void OneShotStaticConstruction();
|
| 1403 |
+
static void OneShotStaticDestruction();
|
| 1404 |
+
|
| 1405 |
+
void Initialize();
|
| 1406 |
+
void Cleanup();
|
| 1407 |
+
|
| 1408 |
+
int GetValidSchedulingRingIndex(int idx);
|
| 1409 |
+
int GetNextValidSchedulingRingIndex(int idx);
|
| 1410 |
+
|
| 1411 |
+
/// <summary>
|
| 1412 |
+
/// Creates the correct type of virtual processor.
|
| 1413 |
+
/// </summary>
|
| 1414 |
+
virtual VirtualProcessor *CreateVirtualProcessor(SchedulingNode *pOwningNode, IVirtualProcessorRoot *pOwningRoot) = 0;
|
| 1415 |
+
|
| 1416 |
+
/// <summary>
|
| 1417 |
+
/// Creates an external context and attaches it to the calling thread. Called when a thread attaches to a scheduler.
|
| 1418 |
+
/// </summary>
|
| 1419 |
+
ExternalContextBase *AttachExternalContext(bool explicitAttach);
|
| 1420 |
+
|
| 1421 |
+
/// <summary>
|
| 1422 |
+
/// Detaches an external context from the scheduler it is attached to. Called when an external context actively detaches
|
| 1423 |
+
/// from a scheduler, or when the underlying thread for an implicitly attached external context exits.
|
| 1424 |
+
/// </summary>
|
| 1425 |
+
/// <param name="pContext">
|
| 1426 |
+
/// The external context being detached.
|
| 1427 |
+
/// </param>
|
| 1428 |
+
/// <param name="explicitDetach">
|
| 1429 |
+
/// Whether this was the result of an explicit detach or the thread exiting.
|
| 1430 |
+
/// </param>
|
| 1431 |
+
void DetachExternalContext(ExternalContextBase* pContext, bool explicitDetach);
|
| 1432 |
+
|
| 1433 |
+
/// <summary>
|
| 1434 |
+
/// Gets an external context from the idle pool, creating a new one if the idle pool is empty.
|
| 1435 |
+
/// </summary>
|
| 1436 |
+
ExternalContextBase *GetExternalContext(bool explicitAttach);
|
| 1437 |
+
|
| 1438 |
+
///<summary>
|
| 1439 |
+
/// Releases an external context of the to the scheduler's idle pool, destroying it if the idle pool is full.
|
| 1440 |
+
///</summary>
|
| 1441 |
+
void ReleaseExternalContext(ExternalContextBase *pContext);
|
| 1442 |
+
|
| 1443 |
+
/// <summary>
|
| 1444 |
+
/// Increments the reference count to the scheduler but does not allow a 0 to 1 transition. This API should
|
| 1445 |
+
/// be used to safely access a scheduler when the scheduler is not 'owned' by the caller.
|
| 1446 |
+
/// </summary>
|
| 1447 |
+
/// <returns>
|
| 1448 |
+
/// True if the scheduler was referenced, false, if the reference count was 0.
|
| 1449 |
+
/// </returns>
|
| 1450 |
+
bool SafeReference();
|
| 1451 |
+
|
| 1452 |
+
/// <summary>
|
| 1453 |
+
/// Returns the default scheduler creating one if it doesn't exist.
|
| 1454 |
+
/// </summary>
|
| 1455 |
+
/// <returns>
|
| 1456 |
+
/// A pointer to the default scheduler
|
| 1457 |
+
/// </returns>
|
| 1458 |
+
static SchedulerBase* GetDefaultScheduler();
|
| 1459 |
+
|
| 1460 |
+
//
|
| 1461 |
+
// Finalization:
|
| 1462 |
+
//
|
| 1463 |
+
|
| 1464 |
+
/// <summary>
|
| 1465 |
+
/// Called to initiate shutdown of the scheduler. This may directly proceed to phase two of shutdown (actively
|
| 1466 |
+
/// shutting down internal contexts) or it may wait for additional events (e.g.: all work to complete) before
|
| 1467 |
+
/// proceeding to phase two.
|
| 1468 |
+
/// </summary>
|
| 1469 |
+
void PhaseOneShutdown();
|
| 1470 |
+
|
| 1471 |
+
/// <summary>
|
| 1472 |
+
/// Actively informs all internal contexts to exit and breaks them out of their dispatch loops. When the last
|
| 1473 |
+
/// internal context dies, finalization will occur and we move to SchedulerBase::Finalize().
|
| 1474 |
+
/// </summary>
|
| 1475 |
+
void PhaseTwoShutdown();
|
| 1476 |
+
|
| 1477 |
+
/// <summary>
|
| 1478 |
+
/// Performs finalization of the scheduler deleting all structures, etc... This will also notify any listeners
|
| 1479 |
+
/// that the scheduler has actively shut down.
|
| 1480 |
+
/// </summary>
|
| 1481 |
+
void Finalize();
|
| 1482 |
+
|
| 1483 |
+
/// <summary>
|
| 1484 |
+
/// Once all virtual processors are idle, the scheduler calls this routine which performs a full sweep through all
|
| 1485 |
+
/// schedule groups looking for work. If work is found (even a blocked context), the scheduler backs off finalization;
|
| 1486 |
+
/// otherwise, it proceeds by asking all virtual processors for final check-in.
|
| 1487 |
+
/// </summary>
|
| 1488 |
+
void SweepSchedulerForFinalize();
|
| 1489 |
+
|
| 1490 |
+
/// <summary>
|
| 1491 |
+
/// Releases virtual processors that were suspended on the shutdown gate, while trying to go from IDLE to
|
| 1492 |
+
/// ACTIVE when the finalization sweep was in progress.
|
| 1493 |
+
/// </summary>
|
| 1494 |
+
/// <param name="releaseCount">
|
| 1495 |
+
/// Number of virtual processors that need to be released.
|
| 1496 |
+
/// </param>
|
| 1497 |
+
void ReleaseSuspendedVirtualProcessors(LONG releaseCount);
|
| 1498 |
+
|
| 1499 |
+
/// <summary>
|
| 1500 |
+
/// Called during scheduler finalization, after all virtual processors are suspended to check if any chores still
|
| 1501 |
+
/// exist in the scheduler. The calling thread is the only thread active in the scheduler at the time the function
|
| 1502 |
+
/// is called.
|
| 1503 |
+
/// </summary>
|
| 1504 |
+
/// <returns>
|
| 1505 |
+
/// A boolean value indicating whether any unstarted chores (realized or unrealized) were found.
|
| 1506 |
+
/// </returns>
|
| 1507 |
+
bool FoundUnstartedChores();
|
| 1508 |
+
|
| 1509 |
+
/// <summary>
|
| 1510 |
+
/// Called during scheduler finalization, before all virtual processors are suspended to check if any blocked
|
| 1511 |
+
/// contexts exist in the scheduler.
|
| 1512 |
+
/// </summary>
|
| 1513 |
+
/// <returns>
|
| 1514 |
+
/// A boolean value indicating whether any blocked contexts were found.
|
| 1515 |
+
/// </returns>
|
| 1516 |
+
bool FoundBlockedContexts();
|
| 1517 |
+
|
| 1518 |
+
///<summary>
|
| 1519 |
+
/// Called to perform a resurrection of the scheduler. When the scheduler reference count has fallen to zero,
|
| 1520 |
+
/// it's possible there's still work on the scheduler and that one of those work items will perform an action
|
| 1521 |
+
/// leading to additional reference. Such bringing of the reference count from zero to non-zero is only legal
|
| 1522 |
+
/// on an *INTERNAL* context and immediately halts shutdown.
|
| 1523 |
+
///</summary>
|
| 1524 |
+
void Resurrect();
|
| 1525 |
+
|
| 1526 |
+
/// <summary>
|
| 1527 |
+
/// Called to perform a commit of safe-point registrations up to **AND INCLUDING** a particular version.
|
| 1528 |
+
/// </summary>
|
| 1529 |
+
/// <param name="commitVersion">
|
| 1530 |
+
/// The data version that we commit to. A version of zero indicates a full commit.
|
| 1531 |
+
/// </param>
|
| 1532 |
+
void CommitToVersion(ULONG commitVersion);
|
| 1533 |
+
|
| 1534 |
+
/// <summary>
|
| 1535 |
+
/// Returns the commit version for safe points within the scheduler.
|
| 1536 |
+
/// </summary>
|
| 1537 |
+
ULONG ComputeSafePointCommitVersion();
|
| 1538 |
+
|
| 1539 |
+
/// <summary>
|
| 1540 |
+
/// Updates and returns the pending version for safe point commits.
|
| 1541 |
+
/// If there are no commits pending, 0 is returned.
|
| 1542 |
+
/// </summary>
|
| 1543 |
+
ULONG UpdatePendingVersion();
|
| 1544 |
+
|
| 1545 |
+
/// <summary>
|
| 1546 |
+
/// Updates the commit version to the given version and returns
|
| 1547 |
+
/// the pending commit version. If there are no commits pending, 0 is returned.
|
| 1548 |
+
/// </summary>
|
| 1549 |
+
/// <param name="commitVersion">
|
| 1550 |
+
/// The version up to which safe points have been committed.
|
| 1551 |
+
/// </param>
|
| 1552 |
+
ULONG UpdateCommitVersion(ULONG commitVersion);
|
| 1553 |
+
|
| 1554 |
+
/// <summary>
|
| 1555 |
+
/// Returns whether a particular version number is visible to us yet. Versions at the wrap-around point
|
| 1556 |
+
/// are not visible until we commit the wrap.
|
| 1557 |
+
/// </summary>
|
| 1558 |
+
bool IsVisibleVersion(ULONG version)
|
| 1559 |
+
{
|
| 1560 |
+
return (version >= m_safePointCommitVersion);
|
| 1561 |
+
}
|
| 1562 |
+
|
| 1563 |
+
/// <summary>
|
| 1564 |
+
/// Returns the version we are allowed to see from an observation. This handles wrap around.
|
| 1565 |
+
/// </summary>
|
| 1566 |
+
ULONG ObservedVersion(ULONG version)
|
| 1567 |
+
{
|
| 1568 |
+
return (IsVisibleVersion(version) ? version : ULONG_MAX);
|
| 1569 |
+
}
|
| 1570 |
+
|
| 1571 |
+
/// <summary>
|
| 1572 |
+
/// Publishes a new data version and returns the version number.
|
| 1573 |
+
/// </summary>
|
| 1574 |
+
ULONG PublishNewDataVersion()
|
| 1575 |
+
{
|
| 1576 |
+
ULONG dataVersion = InterlockedIncrement(reinterpret_cast<volatile LONG *>(&m_safePointDataVersion));
|
| 1577 |
+
|
| 1578 |
+
//
|
| 1579 |
+
// 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
|
| 1580 |
+
// to a data version being them.
|
| 1581 |
+
//
|
| 1582 |
+
while (dataVersion == 0 || dataVersion == ULONG_MAX)
|
| 1583 |
+
dataVersion = InterlockedIncrement(reinterpret_cast<volatile LONG *>(&m_safePointDataVersion));
|
| 1584 |
+
|
| 1585 |
+
return dataVersion;
|
| 1586 |
+
}
|
| 1587 |
+
|
| 1588 |
+
/// <summary>
|
| 1589 |
+
/// Registers a callback at the next safe point after this function call. This should never be directly used by clients.
|
| 1590 |
+
/// SafePointInvocation::Register(...) should be used instead.
|
| 1591 |
+
/// </summary>
|
| 1592 |
+
/// <param name="pInvocation">
|
| 1593 |
+
/// The invocation object which is being registered.
|
| 1594 |
+
/// </param>
|
| 1595 |
+
void InvokeOnSafePoint(SafePointInvocation *pInvocation);
|
| 1596 |
+
|
| 1597 |
+
/// <summary>
|
| 1598 |
+
/// Send a scheduler ETW event
|
| 1599 |
+
/// </summary>
|
| 1600 |
+
void TraceSchedulerEvent(ConcRT_EventType eventType, UCHAR level, unsigned int schedulerId)
|
| 1601 |
+
{
|
| 1602 |
+
if (g_TraceInfo._IsEnabled(level, SchedulerEventFlag))
|
| 1603 |
+
ThrowSchedulerEvent(eventType, level, schedulerId);
|
| 1604 |
+
}
|
| 1605 |
+
|
| 1606 |
+
/// <summary>
|
| 1607 |
+
/// Changes the due time for dispatching new threads
|
| 1608 |
+
/// </summary>
|
| 1609 |
+
void ChangeThrottlingTimer(ULONG dueTime);
|
| 1610 |
+
|
| 1611 |
+
/// <summary>
|
| 1612 |
+
/// Acts as a trampoline between the event wait and the timer wait as we cannot queue the timer in DeferredGetInternalContext
|
| 1613 |
+
/// due to limitations on what Win32 APIs can be called from a UMS primary.
|
| 1614 |
+
/// </summary>
|
| 1615 |
+
static void CALLBACK ThrottlerTrampoline(PVOID pData, BOOLEAN waitOrTimerFired);
|
| 1616 |
+
|
| 1617 |
+
/// <summary>
|
| 1618 |
+
/// Creates new contexts.
|
| 1619 |
+
/// </summary>
|
| 1620 |
+
void ThrottlerDispatch();
|
| 1621 |
+
|
| 1622 |
+
/// <summary>
|
| 1623 |
+
/// Called to notify the scheduler that a context is available from the throttling manager / background creation.
|
| 1624 |
+
/// </summary>
|
| 1625 |
+
/// <returns>
|
| 1626 |
+
/// An indication of whether a virtual processor was awoken due to the context being utilized.
|
| 1627 |
+
/// </returns>
|
| 1628 |
+
bool NotifyThrottledContext(InternalContextBase *pContext);
|
| 1629 |
+
|
| 1630 |
+
/// <summary>
|
| 1631 |
+
/// Create a schedule group within this scheduler.
|
| 1632 |
+
/// </summary>
|
| 1633 |
+
/// <param name="pPlacement">
|
| 1634 |
+
/// A pointer to a location where tasks within the schedule group will be biased towards executing at.
|
| 1635 |
+
/// </param>
|
| 1636 |
+
/// <returns>
|
| 1637 |
+
/// A pointer to a newly created schedule group.
|
| 1638 |
+
/// </returns>
|
| 1639 |
+
ScheduleGroup* InternalCreateScheduleGroup(location* pPlacement);
|
| 1640 |
+
|
| 1641 |
+
/// <summary>
|
| 1642 |
+
/// Internal claim of a quick cache slot.
|
| 1643 |
+
/// </summary>
|
| 1644 |
+
ScheduleGroupSegmentBase *ActualGetQuickCacheSlot(unsigned int maskId)
|
| 1645 |
+
{
|
| 1646 |
+
ScheduleGroupSegmentBase *pSegment = m_pCoreAffinityQuickCache[static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT];
|
| 1647 |
+
|
| 1648 |
+
if (pSegment > reinterpret_cast<ScheduleGroupSegmentBase *>(1))
|
| 1649 |
+
{
|
| 1650 |
+
ScheduleGroupSegmentBase *pXchgSegment = reinterpret_cast <ScheduleGroupSegmentBase *> (
|
| 1651 |
+
InterlockedCompareExchangePointer(reinterpret_cast <void * volatile *> (m_pCoreAffinityQuickCache + (static_cast<size_t>(maskId) << QUICKCACHEPAD_SHIFT)),
|
| 1652 |
+
reinterpret_cast <void *> (1),
|
| 1653 |
+
reinterpret_cast <void *> (pSegment))
|
| 1654 |
+
);
|
| 1655 |
+
|
| 1656 |
+
if (pSegment == pXchgSegment)
|
| 1657 |
+
return pSegment;
|
| 1658 |
+
}
|
| 1659 |
+
|
| 1660 |
+
return NULL;
|
| 1661 |
+
}
|
| 1662 |
+
|
| 1663 |
+
/// <summary>
|
| 1664 |
+
/// Performs the scheduler service scan.
|
| 1665 |
+
/// </summary>
|
| 1666 |
+
void PerformServiceScan(ULONGLONG serviceTime);
|
| 1667 |
+
|
| 1668 |
+
/// <summary>
|
| 1669 |
+
/// A simple bridge to ThrottlerDispatch. This bridge is used for Vista and up (except MSDK)
|
| 1670 |
+
/// </summary>
|
| 1671 |
+
static void CALLBACK ThrottlerDispatchBridge(PTP_CALLBACK_INSTANCE, void * pContext, PTP_TIMER)
|
| 1672 |
+
{
|
| 1673 |
+
ThrottlerDispatchBridgeXP(pContext, true);
|
| 1674 |
+
}
|
| 1675 |
+
|
| 1676 |
+
/// <summary>
|
| 1677 |
+
/// A simple bridge to ThrottlerDispatch. This bridge is used for XP and MSDK
|
| 1678 |
+
/// </summary>
|
| 1679 |
+
static void CALLBACK ThrottlerDispatchBridgeXP(PVOID pScheduler, BOOLEAN)
|
| 1680 |
+
{
|
| 1681 |
+
reinterpret_cast<SchedulerBase *>(pScheduler)->ThrottlerDispatch();
|
| 1682 |
+
}
|
| 1683 |
+
|
| 1684 |
+
static void ThrowSchedulerEvent(ConcRT_EventType eventType, UCHAR level, unsigned int schedulerId);
|
| 1685 |
+
|
| 1686 |
+
// Hide assignment operator and copy constructor
|
| 1687 |
+
SchedulerBase const &operator =(SchedulerBase const &);
|
| 1688 |
+
SchedulerBase(SchedulerBase const &);
|
| 1689 |
+
};
|
| 1690 |
+
} // namespace details
|
| 1691 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerPolicyBase.cpp
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulerPolicyBase.cpp
|
| 9 |
+
//
|
| 10 |
+
// Scheduler policy implementation
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Internal list of scheduler policy defaults.
|
| 22 |
+
/// </summary>
|
| 23 |
+
const unsigned int PolicyDefaults[] =
|
| 24 |
+
{
|
| 25 |
+
::Concurrency::ThreadScheduler, // SchedulerKind
|
| 26 |
+
MaxExecutionResources, // MaxConcurrency
|
| 27 |
+
1, // MinConcurrency
|
| 28 |
+
1, // TargetOversubscriptionFactor
|
| 29 |
+
8, // LocalContextCacheSize
|
| 30 |
+
0, // ContextStackSize
|
| 31 |
+
THREAD_PRIORITY_NORMAL, // ContextPriority
|
| 32 |
+
EnhanceScheduleGroupLocality, // SchedulingProtocol
|
| 33 |
+
ProgressFeedbackEnabled, // DynamicProgressFeedback
|
| 34 |
+
InitializeWinRTAsMTA, // WinRTInitialization
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
+
/// <summary>
|
| 38 |
+
/// Internal map from policy keys to descriptive strings.
|
| 39 |
+
/// </summary>
|
| 40 |
+
const char* const PolicyElementKeyStrings[] =
|
| 41 |
+
{
|
| 42 |
+
"SchedulerKind",
|
| 43 |
+
"MaxConcurrency",
|
| 44 |
+
"MinConcurrency",
|
| 45 |
+
"TargetOversubscriptionFactor",
|
| 46 |
+
"LocalContextCacheSize",
|
| 47 |
+
"ContextStackSize",
|
| 48 |
+
"ContextPriority",
|
| 49 |
+
"SchedulingProtocol",
|
| 50 |
+
"DynamicProgressFeedback",
|
| 51 |
+
"WinRTInitialization",
|
| 52 |
+
"MaxPolicyElementKey"
|
| 53 |
+
};
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/// <summary>
|
| 57 |
+
/// Creates a new default scheduler policy.
|
| 58 |
+
/// </summary>
|
| 59 |
+
SchedulerPolicy::SchedulerPolicy()
|
| 60 |
+
{
|
| 61 |
+
_Initialize(0, NULL);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/// <summary>
|
| 65 |
+
/// Creates a new scheduler policy that uses a named-parameter style of initialization. Unnamed parameters take defaults described above.
|
| 66 |
+
/// </summary>
|
| 67 |
+
SchedulerPolicy::SchedulerPolicy(size_t _PolicyKeyCount, ...)
|
| 68 |
+
{
|
| 69 |
+
va_list args;
|
| 70 |
+
va_start(args, _PolicyKeyCount);
|
| 71 |
+
_Initialize(_PolicyKeyCount, &args);
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/// <summary>
|
| 75 |
+
/// Initializes the scheduler policy.
|
| 76 |
+
/// </summary>
|
| 77 |
+
void SchedulerPolicy::_Initialize(size_t _PolicyKeyCount, va_list *_PArgs)
|
| 78 |
+
{
|
| 79 |
+
size_t bagSize = sizeof(unsigned int) * Concurrency::MaxPolicyElementKey;
|
| 80 |
+
_PolicyBag *pPolicyBag = _concrt_new _PolicyBag;
|
| 81 |
+
_M_pPolicyBag = pPolicyBag;
|
| 82 |
+
|
| 83 |
+
try
|
| 84 |
+
{
|
| 85 |
+
memcpy(pPolicyBag->_M_values._M_pPolicyBag, PolicyDefaults, bagSize);
|
| 86 |
+
|
| 87 |
+
for (size_t i = 0; i < _PolicyKeyCount; i++)
|
| 88 |
+
{
|
| 89 |
+
PolicyElementKey key = va_arg(*_PArgs, PolicyElementKey);
|
| 90 |
+
unsigned int value = va_arg(*_PArgs, unsigned int);
|
| 91 |
+
|
| 92 |
+
if ( !_ValidPolicyKey(key))
|
| 93 |
+
throw invalid_scheduler_policy_key(_StringFromPolicyKey(key));
|
| 94 |
+
|
| 95 |
+
if ( !_ValidPolicyValue(key, value))
|
| 96 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(key));
|
| 97 |
+
|
| 98 |
+
pPolicyBag->_M_values._M_pPolicyBag[key] = value;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
if (!_AreConcurrencyLimitsValid())
|
| 102 |
+
{
|
| 103 |
+
throw invalid_scheduler_policy_thread_specification();
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if (!_ArePolicyCombinationsValid())
|
| 107 |
+
{
|
| 108 |
+
throw invalid_scheduler_policy_value();
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
_ResolvePolicyValues();
|
| 112 |
+
|
| 113 |
+
}
|
| 114 |
+
catch (...)
|
| 115 |
+
{
|
| 116 |
+
delete pPolicyBag;
|
| 117 |
+
throw;
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/// <summary>
|
| 122 |
+
/// The most convenient way to define a new scheduler policy is to copy
|
| 123 |
+
/// an existing policy and modify it. The copy constructor is also needed
|
| 124 |
+
/// for all the usual reasons.
|
| 125 |
+
/// </summary>
|
| 126 |
+
SchedulerPolicy::SchedulerPolicy(const SchedulerPolicy &srcPolicy)
|
| 127 |
+
{
|
| 128 |
+
_M_pPolicyBag = _concrt_new _PolicyBag;
|
| 129 |
+
_Assign(srcPolicy);
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// The most convenient way to define a new scheduler policy is to copy
|
| 134 |
+
/// an existing policy and modify it. The copy constructor is also needed
|
| 135 |
+
/// for all the usual reasons.
|
| 136 |
+
/// </summary>
|
| 137 |
+
SchedulerPolicy& SchedulerPolicy::operator=(const SchedulerPolicy &rhsPolicy)
|
| 138 |
+
{
|
| 139 |
+
_Assign(rhsPolicy);
|
| 140 |
+
return *this;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/// <summary>
|
| 144 |
+
/// Make this policy a copy of the source policy.
|
| 145 |
+
/// </summary>
|
| 146 |
+
void SchedulerPolicy::_Assign(const SchedulerPolicy &rhsPolicy)
|
| 147 |
+
{
|
| 148 |
+
size_t bagSize = sizeof(unsigned int) * Concurrency::MaxPolicyElementKey;
|
| 149 |
+
memcpy(_M_pPolicyBag->_M_values._M_pPolicyBag, rhsPolicy._M_pPolicyBag->_M_values._M_pPolicyBag, bagSize);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
/// <summary>
|
| 153 |
+
/// Destroys a scheduler policy.
|
| 154 |
+
/// </summary>
|
| 155 |
+
SchedulerPolicy::~SchedulerPolicy()
|
| 156 |
+
{
|
| 157 |
+
delete _M_pPolicyBag;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/// <summary>
|
| 161 |
+
/// Retrieve the value of the supplied policy key.
|
| 162 |
+
/// </summary>
|
| 163 |
+
/// <param name="key">
|
| 164 |
+
/// [in] The policy key.
|
| 165 |
+
/// </param>
|
| 166 |
+
/// <returns>
|
| 167 |
+
/// The policy key value for the key, if is a supported key.
|
| 168 |
+
/// </returns>
|
| 169 |
+
/// <remarks>
|
| 170 |
+
/// The function will throw "invalid_scheduler_policy_key" for any key that is not supported.
|
| 171 |
+
/// </remarks>
|
| 172 |
+
unsigned int SchedulerPolicy::GetPolicyValue(PolicyElementKey key) const
|
| 173 |
+
{
|
| 174 |
+
if (!_ValidPolicyKey(key))
|
| 175 |
+
{
|
| 176 |
+
throw invalid_scheduler_policy_key(_StringFromPolicyKey(key));
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
return _M_pPolicyBag->_M_values._M_pPolicyBag[key];
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/// <summary>
|
| 183 |
+
/// Set the value of the supplied policy key and return the old value.
|
| 184 |
+
/// </summary>
|
| 185 |
+
/// <param name="key">
|
| 186 |
+
/// [in] The policy key.
|
| 187 |
+
/// </param>
|
| 188 |
+
/// <param name="value">
|
| 189 |
+
/// [in] The value for the policy key.
|
| 190 |
+
/// </param>
|
| 191 |
+
/// <returns>
|
| 192 |
+
/// The old policy key value for the key, if is a supported key.
|
| 193 |
+
/// </returns>
|
| 194 |
+
/// <remarks>
|
| 195 |
+
/// The function will throw "invalid_scheduler_policy_key" for any key that is not supported,
|
| 196 |
+
/// and "invalid_scheduler_policy_value" for a value that is not supported for a valid key.
|
| 197 |
+
/// </remarks>
|
| 198 |
+
unsigned int SchedulerPolicy::SetPolicyValue(PolicyElementKey key, unsigned int value)
|
| 199 |
+
{
|
| 200 |
+
if (!_ValidPolicyKey(key)
|
| 201 |
+
|| key == ::Concurrency::MinConcurrency
|
| 202 |
+
|| key == ::Concurrency::MaxConcurrency)
|
| 203 |
+
{
|
| 204 |
+
throw invalid_scheduler_policy_key(_StringFromPolicyKey(key));
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
if (!_ValidPolicyValue(key, value))
|
| 208 |
+
{
|
| 209 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(key));
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
unsigned int oldValue = GetPolicyValue(key);
|
| 213 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[key] = value;
|
| 214 |
+
|
| 215 |
+
_ResolvePolicyValues();
|
| 216 |
+
return oldValue;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// <summary>
|
| 220 |
+
/// Set the value of the supplied policy key and return the old value.
|
| 221 |
+
/// </summary>
|
| 222 |
+
/// <param name="_MinConcurrency">
|
| 223 |
+
/// The value for MinConcurrency.
|
| 224 |
+
/// </param>
|
| 225 |
+
/// <param name="_MaxConcurrency">
|
| 226 |
+
/// The value for MaxConcurrency.
|
| 227 |
+
/// </param>
|
| 228 |
+
/// <remarks>
|
| 229 |
+
/// The function will throw "invalid_scheduler_policy_value" if:
|
| 230 |
+
/// _MaxConcurrency != MaxExecutionResources && _MinConcurrency > _MaxConcurrency
|
| 231 |
+
///</remarks>
|
| 232 |
+
void SchedulerPolicy::SetConcurrencyLimits(unsigned int _MinConcurrency, unsigned int _MaxConcurrency)
|
| 233 |
+
{
|
| 234 |
+
if (!_ValidPolicyValue(::Concurrency::MaxConcurrency, _MaxConcurrency))
|
| 235 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MaxConcurrency));
|
| 236 |
+
|
| 237 |
+
if (!_ValidPolicyValue(::Concurrency::MinConcurrency, _MinConcurrency))
|
| 238 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MinConcurrency));
|
| 239 |
+
|
| 240 |
+
if (!_AreConcurrencyLimitsValid(_MinConcurrency, _MaxConcurrency))
|
| 241 |
+
throw invalid_scheduler_policy_thread_specification();
|
| 242 |
+
|
| 243 |
+
if (!_ArePolicyCombinationsValid())
|
| 244 |
+
throw invalid_scheduler_policy_value();
|
| 245 |
+
|
| 246 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::MaxConcurrency] = _MaxConcurrency;
|
| 247 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::MinConcurrency] = _MinConcurrency;
|
| 248 |
+
|
| 249 |
+
_ResolvePolicyValues();
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
/// <summary>
|
| 253 |
+
/// Resolves some of the policy keys that are set to defaults, based on the characteristics of the underlying system.
|
| 254 |
+
/// </summary>
|
| 255 |
+
void SchedulerPolicy::_ResolvePolicyValues()
|
| 256 |
+
{
|
| 257 |
+
// Resolve the SchedulerKind policy key value.
|
| 258 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[::Concurrency::SchedulerKind] = ::Concurrency::ThreadScheduler;
|
| 259 |
+
|
| 260 |
+
// Resolve MinConcurrency and MaxConcurrency, if either of them are set to the special value MaxExecutionResources.
|
| 261 |
+
unsigned int coreCount = ::Concurrency::GetProcessorCount();
|
| 262 |
+
ASSERT((coreCount > 0) && (coreCount <= INT_MAX));
|
| 263 |
+
|
| 264 |
+
if (_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] == MaxExecutionResources)
|
| 265 |
+
{
|
| 266 |
+
if (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] == MaxExecutionResources)
|
| 267 |
+
{
|
| 268 |
+
// [1] Both the keys are set to MaxExecutionResources.
|
| 269 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] = _M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] = coreCount;
|
| 270 |
+
}
|
| 271 |
+
else
|
| 272 |
+
{
|
| 273 |
+
// [2] MinConcurrency is set to MaxExecutionResources.
|
| 274 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] = (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] < coreCount) ?
|
| 275 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] : coreCount;
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
else if (_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] == MaxExecutionResources)
|
| 279 |
+
{
|
| 280 |
+
// [3] MaxConcurrency is set to MaxExecutionResources.
|
| 281 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] = (_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] > coreCount) ?
|
| 282 |
+
_M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency] : coreCount;
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
ASSERT(_M_pPolicyBag->_M_values._M_pPolicyBag[MaxConcurrency] >= _M_pPolicyBag->_M_values._M_pPolicyBag[MinConcurrency]);
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
const char* SchedulerPolicy::_StringFromPolicyKey(unsigned int index)
|
| 290 |
+
{
|
| 291 |
+
if (index > ::Concurrency::MaxPolicyElementKey)
|
| 292 |
+
index = ::Concurrency::MaxPolicyElementKey;
|
| 293 |
+
|
| 294 |
+
return PolicyElementKeyStrings[index];
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
bool SchedulerPolicy::_ValidPolicyKey(PolicyElementKey key)
|
| 298 |
+
{
|
| 299 |
+
return (key >= SchedulerKind && key < MaxPolicyElementKey);
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
bool SchedulerPolicy::_ValidPolicyValue(PolicyElementKey key, unsigned int value)
|
| 303 |
+
{
|
| 304 |
+
bool valid = true;
|
| 305 |
+
|
| 306 |
+
switch (key)
|
| 307 |
+
{
|
| 308 |
+
case ::Concurrency::SchedulerKind:
|
| 309 |
+
if ( value != ::Concurrency::ThreadScheduler )
|
| 310 |
+
{
|
| 311 |
+
valid = false;
|
| 312 |
+
}
|
| 313 |
+
break;
|
| 314 |
+
case ::Concurrency::ContextPriority:
|
| 315 |
+
{
|
| 316 |
+
int priority = (int)value;
|
| 317 |
+
//
|
| 318 |
+
// The win32 api accepts values [-7, 7), 15 and -15 for threads other than the current thread.
|
| 319 |
+
// In addition, we define a special value INHERIT_THREAD_PRIORITY, whereby the internal contexts
|
| 320 |
+
// inherit the priority of the thread creating the scheduler
|
| 321 |
+
//
|
| 322 |
+
if ( !(priority >= -7 && priority < 7
|
| 323 |
+
|| priority == 15
|
| 324 |
+
|| priority == -15
|
| 325 |
+
|| priority == INHERIT_THREAD_PRIORITY))
|
| 326 |
+
{
|
| 327 |
+
valid = false;
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
break;
|
| 331 |
+
case ::Concurrency::SchedulingProtocol:
|
| 332 |
+
if ( !(value == ::Concurrency::EnhanceScheduleGroupLocality
|
| 333 |
+
|| value == ::Concurrency::EnhanceForwardProgress))
|
| 334 |
+
{
|
| 335 |
+
valid = false;
|
| 336 |
+
}
|
| 337 |
+
break;
|
| 338 |
+
case ::Concurrency::MaxConcurrency:
|
| 339 |
+
if ( !((value > 0 && value <= INT_MAX) || value == MaxExecutionResources))
|
| 340 |
+
{
|
| 341 |
+
valid = false;
|
| 342 |
+
}
|
| 343 |
+
break;
|
| 344 |
+
case ::Concurrency::MinConcurrency:
|
| 345 |
+
if ( !((value <= INT_MAX) || value == MaxExecutionResources))
|
| 346 |
+
{
|
| 347 |
+
valid = false;
|
| 348 |
+
}
|
| 349 |
+
break;
|
| 350 |
+
case ::Concurrency::LocalContextCacheSize:
|
| 351 |
+
case ::Concurrency::ContextStackSize:
|
| 352 |
+
if ( !(value <= INT_MAX))
|
| 353 |
+
{
|
| 354 |
+
valid = false;
|
| 355 |
+
}
|
| 356 |
+
break;
|
| 357 |
+
case ::Concurrency::TargetOversubscriptionFactor:
|
| 358 |
+
if ( !(value > 0 && value <= INT_MAX))
|
| 359 |
+
{
|
| 360 |
+
valid = false;
|
| 361 |
+
}
|
| 362 |
+
break;
|
| 363 |
+
|
| 364 |
+
case ::Concurrency::DynamicProgressFeedback:
|
| 365 |
+
if ( !(value == ::Concurrency::ProgressFeedbackEnabled || value == ::Concurrency::ProgressFeedbackDisabled))
|
| 366 |
+
{
|
| 367 |
+
valid = false;
|
| 368 |
+
}
|
| 369 |
+
break;
|
| 370 |
+
|
| 371 |
+
case ::Concurrency::WinRTInitialization:
|
| 372 |
+
if ( !(value == ::Concurrency::InitializeWinRTAsMTA || value == ::Concurrency::DoNotInitializeWinRT))
|
| 373 |
+
{
|
| 374 |
+
valid = false;
|
| 375 |
+
}
|
| 376 |
+
break;
|
| 377 |
+
|
| 378 |
+
case ::Concurrency::MaxPolicyElementKey:
|
| 379 |
+
default:
|
| 380 |
+
terminate();
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
return valid;
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
void SchedulerPolicy::_ValidateConcRTPolicy() const
|
| 387 |
+
{
|
| 388 |
+
unsigned int minConcurrency = GetPolicyValue(::Concurrency::MinConcurrency);
|
| 389 |
+
if (minConcurrency == 0)
|
| 390 |
+
{
|
| 391 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::MinConcurrency));
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
::Concurrency::DynamicProgressFeedbackType dynamicProgress =
|
| 395 |
+
(::Concurrency::DynamicProgressFeedbackType) GetPolicyValue(::Concurrency::DynamicProgressFeedback);
|
| 396 |
+
|
| 397 |
+
if (dynamicProgress == ProgressFeedbackDisabled)
|
| 398 |
+
{
|
| 399 |
+
throw invalid_scheduler_policy_value(_StringFromPolicyKey(::Concurrency::DynamicProgressFeedback));
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
/// <summary>
|
| 404 |
+
/// Test a policy's concurrency limits.
|
| 405 |
+
/// </summary>
|
| 406 |
+
bool SchedulerPolicy::_AreConcurrencyLimitsValid(unsigned int _MinConcurrency, unsigned int _MaxConcurrency)
|
| 407 |
+
{
|
| 408 |
+
// For concurrency limits that are != MaxExecutionResource, plug into the equation: _MinConcurrency <= _MaxConcurrency,
|
| 409 |
+
// and return false, if it does not hold.
|
| 410 |
+
|
| 411 |
+
// Validate Max
|
| 412 |
+
if ((_MaxConcurrency != MaxExecutionResources)
|
| 413 |
+
&& (_MinConcurrency != MaxExecutionResources) && (_MaxConcurrency < _MinConcurrency))
|
| 414 |
+
{
|
| 415 |
+
return false;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
return true;
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
/// <summary>
|
| 422 |
+
/// Test a policy's concurrency limits.
|
| 423 |
+
/// </summary>
|
| 424 |
+
bool SchedulerPolicy::_AreConcurrencyLimitsValid() const
|
| 425 |
+
{
|
| 426 |
+
return _AreConcurrencyLimitsValid(GetPolicyValue(::Concurrency::MinConcurrency),
|
| 427 |
+
GetPolicyValue(::Concurrency::MaxConcurrency));
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
/// <summary>
|
| 431 |
+
/// Test a policy's concurrency limits.
|
| 432 |
+
/// </summary>
|
| 433 |
+
bool SchedulerPolicy::_ArePolicyCombinationsValid() const
|
| 434 |
+
{
|
| 435 |
+
return true;
|
| 436 |
+
}
|
| 437 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.cpp
ADDED
|
@@ -0,0 +1,1237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulerProxy.cpp
|
| 9 |
+
//
|
| 10 |
+
// RM proxy for a scheduler instance
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
#pragma warning (push)
|
| 21 |
+
#pragma warning (disable : 4702)
|
| 22 |
+
/// <summary>
|
| 23 |
+
/// Constructs a scheduler proxy.
|
| 24 |
+
/// </summary>
|
| 25 |
+
SchedulerProxy::SchedulerProxy(IScheduler * pScheduler, ResourceManager * pResourceManager, const SchedulerPolicy &policy)
|
| 26 |
+
: m_pThreadProxyFactory(nullptr)
|
| 27 |
+
, m_pResourceManager(pResourceManager)
|
| 28 |
+
, m_pHillClimbing(nullptr)
|
| 29 |
+
, m_staticData{}
|
| 30 |
+
, m_queueLength(0)
|
| 31 |
+
, m_currentConcurrency(0)
|
| 32 |
+
, m_numAllocatedCores(0)
|
| 33 |
+
, m_numBorrowedCores(0)
|
| 34 |
+
, m_numFixedCores(0)
|
| 35 |
+
, m_numAssignedThreads(0)
|
| 36 |
+
, m_numExternalThreads(0)
|
| 37 |
+
, m_numExternalThreadCores(0)
|
| 38 |
+
{
|
| 39 |
+
ASSERT(pScheduler != NULL);
|
| 40 |
+
|
| 41 |
+
m_pScheduler = pScheduler;
|
| 42 |
+
|
| 43 |
+
m_maxConcurrency = policy.GetPolicyValue(::Concurrency::MaxConcurrency);
|
| 44 |
+
m_minConcurrency = policy.GetPolicyValue(::Concurrency::MinConcurrency);
|
| 45 |
+
m_targetOversubscriptionFactor = policy.GetPolicyValue(::Concurrency::TargetOversubscriptionFactor);
|
| 46 |
+
m_contextStackSize = policy.GetPolicyValue(::Concurrency::ContextStackSize);
|
| 47 |
+
m_contextPriority = policy.GetPolicyValue(::Concurrency::ContextPriority);
|
| 48 |
+
m_fDoHillClimbing = policy.GetPolicyValue(::Concurrency::DynamicProgressFeedback) == ::Concurrency::ProgressFeedbackEnabled;
|
| 49 |
+
|
| 50 |
+
if (m_contextPriority == INHERIT_THREAD_PRIORITY)
|
| 51 |
+
{
|
| 52 |
+
m_contextPriority = (char) platform::__GetThreadPriority(GetCurrentThread());
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
m_id = m_pScheduler->GetId();
|
| 56 |
+
ASSERT(m_id != -1);
|
| 57 |
+
|
| 58 |
+
unsigned int coreCount = m_pResourceManager->GetCoreCount();
|
| 59 |
+
|
| 60 |
+
m_coreCount = coreCount;
|
| 61 |
+
|
| 62 |
+
ASSERT(coreCount > 0 && coreCount <= INT_MAX);
|
| 63 |
+
ASSERT(m_maxConcurrency > 0 && m_maxConcurrency >= m_minConcurrency);
|
| 64 |
+
|
| 65 |
+
unsigned int originalTof = m_targetOversubscriptionFactor;
|
| 66 |
+
|
| 67 |
+
// Find the minimum target oversubscription factor required to satisfy MaxConcurrency with the cores available.
|
| 68 |
+
unsigned int minTof = (m_maxConcurrency + coreCount - 1)/coreCount;
|
| 69 |
+
|
| 70 |
+
if (originalTof < minTof)
|
| 71 |
+
{
|
| 72 |
+
// Adjust target oversubscription factor to ensure that we can satisfy MaxConcurrency with the cores on the system.
|
| 73 |
+
m_targetOversubscriptionFactor = minTof;
|
| 74 |
+
// The scheduler needs all the cores on the machine to satisfy max threads. Moreover we will need to oversubscribe
|
| 75 |
+
// more than the user indicated.
|
| 76 |
+
m_desiredHardwareThreads = coreCount;
|
| 77 |
+
}
|
| 78 |
+
else
|
| 79 |
+
{
|
| 80 |
+
m_desiredHardwareThreads = (m_maxConcurrency + originalTof - 1)/originalTof;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Now adjust target oversubscription factor to ensure that MaxConcurrency virtual processors are evenly distributed
|
| 84 |
+
// over the desired number of hardware threads (i.e each core gets either m_tof vprocs or m_tof - 1 vprocs). Also
|
| 85 |
+
// calculate how many of the assigned cores will get m_tof vprocs.
|
| 86 |
+
if ((m_maxConcurrency % m_desiredHardwareThreads) == 0)
|
| 87 |
+
{
|
| 88 |
+
// This is the common case. We have a simple distribution and every allocated core will get tof vprocs.
|
| 89 |
+
m_targetOversubscriptionFactor = m_maxConcurrency/m_desiredHardwareThreads;
|
| 90 |
+
m_numFullySubscribedCores = m_desiredHardwareThreads;
|
| 91 |
+
m_minimumHardwareThreads = (m_minConcurrency + m_targetOversubscriptionFactor - 1)/m_targetOversubscriptionFactor;
|
| 92 |
+
}
|
| 93 |
+
else
|
| 94 |
+
{
|
| 95 |
+
// We have an uneven distribution; some cores will get tof vprocs and some will get tof - 1.
|
| 96 |
+
ASSERT(m_targetOversubscriptionFactor > 1);
|
| 97 |
+
|
| 98 |
+
m_targetOversubscriptionFactor = (m_maxConcurrency + m_desiredHardwareThreads - 1)/m_desiredHardwareThreads;
|
| 99 |
+
m_numFullySubscribedCores = m_desiredHardwareThreads - ((m_desiredHardwareThreads * m_targetOversubscriptionFactor) - m_maxConcurrency);
|
| 100 |
+
|
| 101 |
+
// Calculate min hardware threads. We need to make sure that given the way vprocs are distributed to cores
|
| 102 |
+
// (where some cores could get tof vprocs and some could get tof - 1 vprocs), the scheduler proxy will never go below
|
| 103 |
+
// min concurrency if it is left with just the minimum number of cores (and all of those cores happen to have tof -1
|
| 104 |
+
// vprocs assigned to them).
|
| 105 |
+
if (((m_desiredHardwareThreads - m_numFullySubscribedCores) * (m_targetOversubscriptionFactor - 1)) >= m_minConcurrency)
|
| 106 |
+
{
|
| 107 |
+
m_minimumHardwareThreads = (m_minConcurrency + m_targetOversubscriptionFactor - 2)/(m_targetOversubscriptionFactor - 1);
|
| 108 |
+
}
|
| 109 |
+
else
|
| 110 |
+
{
|
| 111 |
+
m_minimumHardwareThreads = (m_desiredHardwareThreads - m_numFullySubscribedCores);
|
| 112 |
+
|
| 113 |
+
unsigned int remainingThreads = (m_minConcurrency - (m_minimumHardwareThreads * (m_targetOversubscriptionFactor - 1)));
|
| 114 |
+
ASSERT(remainingThreads < m_minConcurrency);
|
| 115 |
+
m_minimumHardwareThreads += (remainingThreads + m_targetOversubscriptionFactor - 1)/m_targetOversubscriptionFactor;
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
ASSERT(m_maxConcurrency <= m_targetOversubscriptionFactor * m_desiredHardwareThreads);
|
| 120 |
+
ASSERT(m_numFullySubscribedCores <= m_desiredHardwareThreads);
|
| 121 |
+
ASSERT(m_targetOversubscriptionFactor > 1 || m_numFullySubscribedCores == m_desiredHardwareThreads);
|
| 122 |
+
|
| 123 |
+
ASSERT(m_targetOversubscriptionFactor > 0 && m_targetOversubscriptionFactor <= INT_MAX);
|
| 124 |
+
ASSERT(m_desiredHardwareThreads > 0 && m_desiredHardwareThreads <= coreCount);
|
| 125 |
+
ASSERT(m_desiredHardwareThreads > 0 && m_minimumHardwareThreads <= m_desiredHardwareThreads);
|
| 126 |
+
|
| 127 |
+
// Hold a reference to the resource manager.
|
| 128 |
+
int ref = m_pResourceManager->Reference();
|
| 129 |
+
(ref);
|
| 130 |
+
CONCRT_COREASSERT(ref > 1);
|
| 131 |
+
|
| 132 |
+
if (m_fDoHillClimbing)
|
| 133 |
+
{
|
| 134 |
+
m_pHillClimbing = _concrt_new HillClimbing(m_id, coreCount, this);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
m_nodeCount = GetProcessorNodeCount();
|
| 138 |
+
// The allocated nodes structure is created when the first allocation is made for this scheduler proxy. We need to read global core
|
| 139 |
+
// state during this allocation, and therefore we need to perform it while holding the RM lock.
|
| 140 |
+
m_pAllocatedNodes = NULL;
|
| 141 |
+
|
| 142 |
+
m_pSortedNodeOrder = _concrt_new unsigned int[m_nodeCount];
|
| 143 |
+
for (unsigned int i = 0; i < m_nodeCount; ++i)
|
| 144 |
+
{
|
| 145 |
+
m_pSortedNodeOrder[i] = i;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
#if defined(CONCRT_TRACING)
|
| 149 |
+
m_drmInitialState = NULL;
|
| 150 |
+
#endif
|
| 151 |
+
}
|
| 152 |
+
#pragma warning (pop)
|
| 153 |
+
|
| 154 |
+
/// <summary>
|
| 155 |
+
/// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request
|
| 156 |
+
/// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request
|
| 157 |
+
/// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to
|
| 158 |
+
/// IScheduler::AddVirtualProcessors.
|
| 159 |
+
/// </summary>
|
| 160 |
+
/// <param name="doSubscribeCurrentThread">
|
| 161 |
+
/// Whether to subscribe the current thread and account for it during resource allocation.
|
| 162 |
+
/// </param>
|
| 163 |
+
/// <returns>
|
| 164 |
+
/// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise.
|
| 165 |
+
/// </returns>
|
| 166 |
+
IExecutionResource * SchedulerProxy::RequestInitialVirtualProcessors(bool doSubscribeCurrentThread)
|
| 167 |
+
{
|
| 168 |
+
return m_pResourceManager->RequestInitialVirtualProcessors(this, doSubscribeCurrentThread);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/// <summary>
|
| 172 |
+
/// Called in order to notify the resource manager that the given scheduler is shutting down. This
|
| 173 |
+
/// will cause the resource manager to immediately reclaim all resources granted to the scheduler.
|
| 174 |
+
/// </summary>
|
| 175 |
+
void SchedulerProxy::Shutdown()
|
| 176 |
+
{
|
| 177 |
+
m_pResourceManager->Shutdown(this);
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
/// <summary>
|
| 181 |
+
/// Gets a new thread proxy from the factory.
|
| 182 |
+
/// </summary>
|
| 183 |
+
IThreadProxy * SchedulerProxy::GetNewThreadProxy(IExecutionContext * pContext)
|
| 184 |
+
{
|
| 185 |
+
if (m_pThreadProxyFactory == NULL)
|
| 186 |
+
{
|
| 187 |
+
// Populate the cached pointer from the one in the RM
|
| 188 |
+
m_pThreadProxyFactory = GetResourceManager()->GetThreadProxyFactoryManager()->GetFreeThreadProxyFactory();
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *>(m_pThreadProxyFactory->RequestProxy(ContextStackSize(), ContextPriority()));
|
| 192 |
+
pProxy->AssociateExecutionContext(pContext);
|
| 193 |
+
|
| 194 |
+
return pProxy;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
/// <summary>
|
| 198 |
+
/// Ensures that a context is bound to a thread proxy. This API should *NOT* be called in the vast majority of circumstances.
|
| 199 |
+
/// The IThreadProxy::SwitchTo will perform late binding to thread proxies as necessary. There are, however, circumstances
|
| 200 |
+
/// where it is necessary to pre-bind a context to ensure that the SwitchTo operation switches to an already bound context. This
|
| 201 |
+
/// is the case on a UMS scheduling context as it cannot call allocation APIs.
|
| 202 |
+
/// </summary>
|
| 203 |
+
/// <param name="pContext">
|
| 204 |
+
/// The context to bind.
|
| 205 |
+
/// </param>
|
| 206 |
+
void SchedulerProxy::BindContext(IExecutionContext * pContext)
|
| 207 |
+
{
|
| 208 |
+
if (pContext == NULL)
|
| 209 |
+
{
|
| 210 |
+
throw std::invalid_argument("pContext");
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
// Find out if this context already has a thread proxy, if not we have to request one from the factory.
|
| 214 |
+
if (pContext->GetProxy() == NULL)
|
| 215 |
+
{
|
| 216 |
+
// Find a thread proxy from the pool that corresponds to the stack size and priority we need.
|
| 217 |
+
GetNewThreadProxy(pContext);
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
/// <summary>
|
| 222 |
+
/// Returns an **unstarted** thread proxy attached to pContext, to the thread proxy factory.
|
| 223 |
+
/// Such a thread proxy **must** be unstarted.
|
| 224 |
+
/// This API should *NOT* be called in the vast majority of circumstances.
|
| 225 |
+
/// </summary>
|
| 226 |
+
/// <param name="pContext">
|
| 227 |
+
/// The context to unbind.
|
| 228 |
+
/// </param>
|
| 229 |
+
void SchedulerProxy::UnbindContext(IExecutionContext * pContext)
|
| 230 |
+
{
|
| 231 |
+
if (pContext == NULL)
|
| 232 |
+
{
|
| 233 |
+
throw std::invalid_argument("pContext");
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
FreeThreadProxy * pProxy = static_cast<FreeThreadProxy *> (pContext->GetProxy());
|
| 237 |
+
|
| 238 |
+
ASSERT(pProxy != NULL);
|
| 239 |
+
pProxy->ReturnIdleProxy();
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
/// <summary>
|
| 243 |
+
/// This function retrieves the execution resource associated with this thread, if one exists
|
| 244 |
+
/// </summary>
|
| 245 |
+
/// <returns>
|
| 246 |
+
/// The ExecutionResource instance representing current thread in the runtime.
|
| 247 |
+
/// </returns>
|
| 248 |
+
ExecutionResource * SchedulerProxy::GetCurrentThreadExecutionResource()
|
| 249 |
+
{
|
| 250 |
+
ExecutionResource * pExecutionResource = NULL;
|
| 251 |
+
DWORD tlsSlot = GetResourceManager()->GetExecutionResourceTls();
|
| 252 |
+
void * tlsPointer = platform::__TlsGetValue(tlsSlot);
|
| 253 |
+
size_t tlsValue = (size_t) tlsPointer;
|
| 254 |
+
|
| 255 |
+
if ((tlsPointer != NULL) && ((tlsValue & TlsResourceBitMask) == TlsResourceInResource))
|
| 256 |
+
{
|
| 257 |
+
pExecutionResource = (ExecutionResource *) tlsValue;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
return pExecutionResource;
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
/// <summary>
|
| 264 |
+
/// This function retrieves the execution resource associated with this thread, if one exists,
|
| 265 |
+
/// and updates the reference count on it for better bookkeeping.
|
| 266 |
+
/// </summary>
|
| 267 |
+
/// <returns>
|
| 268 |
+
/// The ExecutionResource instance representing current thread in the runtime.
|
| 269 |
+
/// </returns>
|
| 270 |
+
ExecutionResource * SchedulerProxy::ReferenceCurrentThreadExecutionResource()
|
| 271 |
+
{
|
| 272 |
+
ExecutionResource * pExecutionResource = NULL;
|
| 273 |
+
DWORD tlsSlot = GetResourceManager()->GetExecutionResourceTls();
|
| 274 |
+
void * tlsPointer = platform::__TlsGetValue(tlsSlot);
|
| 275 |
+
|
| 276 |
+
if (tlsPointer != NULL)
|
| 277 |
+
{
|
| 278 |
+
size_t tlsValue = (size_t) tlsPointer;
|
| 279 |
+
|
| 280 |
+
if ((tlsValue & TlsResourceBitMask) == TlsResourceInResource)
|
| 281 |
+
{
|
| 282 |
+
// The current thread was previously subscribed with the RM.
|
| 283 |
+
pExecutionResource = (ExecutionResource *) tlsValue;
|
| 284 |
+
|
| 285 |
+
VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot();
|
| 286 |
+
|
| 287 |
+
// If this is a nested subscribe call then if there was a virtual processor root,
|
| 288 |
+
// it could not have been removed, because it would have been marked as "fixed".
|
| 289 |
+
ASSERT(pVPRoot == NULL || !pVPRoot->IsRootRemoved());
|
| 290 |
+
pExecutionResource->IncrementUseCounts();
|
| 291 |
+
}
|
| 292 |
+
else if ((tlsValue & TlsResourceBitMask) == TlsResourceInProxy)
|
| 293 |
+
{
|
| 294 |
+
// The current thread is a thread proxy.
|
| 295 |
+
FreeThreadProxy * pThreadProxy = (FreeThreadProxy *) (((size_t) tlsValue) & ~TlsResourceInProxy);
|
| 296 |
+
pExecutionResource = pThreadProxy->GetVirtualProcessorRoot()->GetExecutionResource();
|
| 297 |
+
VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot();
|
| 298 |
+
if (pVPRoot != NULL && pVPRoot->IsRootRemoved())
|
| 299 |
+
{
|
| 300 |
+
// The virtual processor root that this thread is running on has been removed. We have to
|
| 301 |
+
// create a new execution resource abstraction for the current thread and perform an external
|
| 302 |
+
// thread allocation for this scheduler proxy.
|
| 303 |
+
pExecutionResource = NULL;
|
| 304 |
+
}
|
| 305 |
+
else
|
| 306 |
+
{
|
| 307 |
+
pExecutionResource->IncrementUseCounts();
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
if (pExecutionResource != NULL)
|
| 313 |
+
{
|
| 314 |
+
return GetResourceForNewSubscription(pExecutionResource);
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
return pExecutionResource;
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
/// <summary>
|
| 321 |
+
/// Creates or reuses an execution resource for the thread subscription
|
| 322 |
+
/// </summary>
|
| 323 |
+
ExecutionResource * SchedulerProxy::GetResourceForNewSubscription(ExecutionResource * pParentExecutionResource)
|
| 324 |
+
{
|
| 325 |
+
ExecutionResource * pExecutionResource = NULL;
|
| 326 |
+
|
| 327 |
+
if (pParentExecutionResource->GetSchedulerProxy() != this)
|
| 328 |
+
{
|
| 329 |
+
pExecutionResource = _concrt_new ExecutionResource(this, pParentExecutionResource);
|
| 330 |
+
pExecutionResource->IncrementUseCounts();
|
| 331 |
+
}
|
| 332 |
+
else
|
| 333 |
+
{
|
| 334 |
+
pExecutionResource = pParentExecutionResource;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
return pExecutionResource;
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
/// <summary>
|
| 341 |
+
/// Registers that a call to SubscribeCurrentThread has occurred for this core, making this core immovable.
|
| 342 |
+
/// </summary>
|
| 343 |
+
void SchedulerProxy::IncrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread)
|
| 344 |
+
{
|
| 345 |
+
SchedulerCore * pCore = &m_pAllocatedNodes[nodeId].m_pCores[coreIndex];
|
| 346 |
+
if (pCore->m_numFixedThreads++ == 0)
|
| 347 |
+
{
|
| 348 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[nodeId];
|
| 349 |
+
pNode->m_numFixedCores++;
|
| 350 |
+
m_numFixedCores++;
|
| 351 |
+
if (pCore->IsBorrowed())
|
| 352 |
+
{
|
| 353 |
+
// When a core becomes fixed, we temporarily remove the borrowed flag on it, and restore it when it
|
| 354 |
+
// becomes movable again.
|
| 355 |
+
pCore->m_fPreviouslyBorrowed = true;
|
| 356 |
+
ToggleBorrowedState(pNode, coreIndex);
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
// If this core has no virtual processors on it, count it as a core exclusively dedicated to external threads.
|
| 360 |
+
if (isExternalThread && m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_numAssignedThreads == 0)
|
| 361 |
+
{
|
| 362 |
+
++m_numExternalThreadCores;
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
// Increment the external thread count on the core, which helps account for all the resources running on that core.
|
| 367 |
+
if (isExternalThread)
|
| 368 |
+
{
|
| 369 |
+
m_numExternalThreads++;
|
| 370 |
+
pCore->m_numExternalThreads++;
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
/// <summary>
|
| 375 |
+
/// Registers that a call to IExecutionResource::Release has occurred, potentially freeing this core.
|
| 376 |
+
/// </summary>
|
| 377 |
+
void SchedulerProxy::DecrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread)
|
| 378 |
+
{
|
| 379 |
+
SchedulerCore * pCore = &m_pAllocatedNodes[nodeId].m_pCores[coreIndex];
|
| 380 |
+
// Decrement external thread count on the core which helps account for all the resources running on that core.
|
| 381 |
+
if (isExternalThread)
|
| 382 |
+
{
|
| 383 |
+
ASSERT(pCore->m_numExternalThreads > 0);
|
| 384 |
+
pCore->m_numExternalThreads--;
|
| 385 |
+
m_numExternalThreads--;
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
ASSERT(pCore->m_numFixedThreads > 0);
|
| 389 |
+
if (--pCore->m_numFixedThreads == 0)
|
| 390 |
+
{
|
| 391 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[nodeId];
|
| 392 |
+
ASSERT(pCore->m_numExternalThreads == 0);
|
| 393 |
+
m_numFixedCores--;
|
| 394 |
+
pNode->m_numFixedCores--;
|
| 395 |
+
|
| 396 |
+
if (pCore->m_fPreviouslyBorrowed)
|
| 397 |
+
{
|
| 398 |
+
// If this was a borrowed core convereted to fixed due to a subscription request, we restore the state
|
| 399 |
+
// back to borrowed, here.
|
| 400 |
+
ASSERT(!pCore->IsBorrowed());
|
| 401 |
+
ToggleBorrowedState(pNode, coreIndex);
|
| 402 |
+
pCore->m_fPreviouslyBorrowed = false;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
// If this core was owned only due to an external thread being on it, then there is
|
| 406 |
+
// no more reason for it to be marked as such.
|
| 407 |
+
if (isExternalThread && m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_numAssignedThreads == 0)
|
| 408 |
+
{
|
| 409 |
+
m_numExternalThreadCores--;
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
/// <summary>
|
| 415 |
+
/// This API registers the current thread with the resource manager associating it with this scheduler proxy,
|
| 416 |
+
/// and returns an instance of IExecutionResource back to the scheduler for bookkeeping and maintenance.
|
| 417 |
+
/// </summary>
|
| 418 |
+
/// <returns>
|
| 419 |
+
/// The IExecutionResource instance representing current thread in the runtime.
|
| 420 |
+
/// </returns>
|
| 421 |
+
IExecutionResource * SchedulerProxy::SubscribeCurrentThread()
|
| 422 |
+
{
|
| 423 |
+
return m_pResourceManager->SubscribeCurrentThread(this);
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
/// <summary>
|
| 427 |
+
/// Creates a new execution resource for the external thread and registers it with the scheduler proxy.
|
| 428 |
+
/// </summary>
|
| 429 |
+
ExecutionResource * SchedulerProxy::CreateExternalThreadResource(SchedulerNode * pNode, unsigned int coreIndex)
|
| 430 |
+
{
|
| 431 |
+
ExecutionResource * pExecutionResource = _concrt_new ExecutionResource(this, pNode, coreIndex);
|
| 432 |
+
pExecutionResource->IncrementUseCounts();
|
| 433 |
+
return pExecutionResource;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
/// <summary>
|
| 437 |
+
/// Adds the execution resource to the list of subscribed threads
|
| 438 |
+
/// </summary>
|
| 439 |
+
void SchedulerProxy::AddThreadSubscription(ExecutionResource * pExecutionResource)
|
| 440 |
+
{
|
| 441 |
+
m_threadSubscriptions.AddTail(pExecutionResource);
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
/// <summary>
|
| 445 |
+
/// Removes the execution resource from the list of subscribed threads
|
| 446 |
+
/// </summary>
|
| 447 |
+
void SchedulerProxy::RemoveThreadSubscription(ExecutionResource * pExecutionResource)
|
| 448 |
+
{
|
| 449 |
+
m_threadSubscriptions.Remove(pExecutionResource);
|
| 450 |
+
delete pExecutionResource;
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
/// <summary>
|
| 454 |
+
/// Called by the RM when it is done reserving cores for the scheduler proxy. The scheduler proxy allocates virtual processors
|
| 455 |
+
/// or standalone execution resources based on the cores that were reserved for it.
|
| 456 |
+
/// </summary>
|
| 457 |
+
ExecutionResource * SchedulerProxy::GrantAllocation(unsigned int numberReserved, bool fInitialAllocation, bool fSubscribeCurrentThread)
|
| 458 |
+
{
|
| 459 |
+
ASSERT(m_numAllocatedCores == 0 || !fInitialAllocation);
|
| 460 |
+
ASSERT(m_numExternalThreads == 0 || !fInitialAllocation);
|
| 461 |
+
|
| 462 |
+
// The scheduler proxy's allocated node map contains 'numberReserved' cores that the RM has reserved in order to
|
| 463 |
+
// satisfy the proxy's request based on its request and the availability of resources. The cores are marked with
|
| 464 |
+
// ProcessorCore::Reserved, and will be converted to ProcessorCore::Allocated here.
|
| 465 |
+
|
| 466 |
+
// Note that 'numberReserved' could have the value 0, if this is an allocation for an external thread. In this case, depending
|
| 467 |
+
// on whether the scheduler has more than its minimum, we will either oversubscribe a core, or remove virtual processors
|
| 468 |
+
// assigned to a core in order to accommodate the external thread.
|
| 469 |
+
unsigned int reservationsAllocated = 0;
|
| 470 |
+
ExecutionResource * pExecutionResource = NULL;
|
| 471 |
+
|
| 472 |
+
ASSERT(!fInitialAllocation || m_minimumHardwareThreads == MinHWThreads());
|
| 473 |
+
// Calculate the number of virtual processors we will give this scheduler based on the core allocation
|
| 474 |
+
// we received. Each core will be allocated either m_tof vprocs or m_tof - 1 vprocs, based on the
|
| 475 |
+
// desired hardware threads and the value for max concurrency.
|
| 476 |
+
|
| 477 |
+
// The current thread subscription we are about to make does not contribute to MinHWThreads() at present. The external thread
|
| 478 |
+
// gets an exclusive core, if the remaining cores, allocated and reserved, can satisfy at least 1 more then the current minimum.
|
| 479 |
+
// Note that 'externalThreadCore' can be 1 even if no cores were reserved -> in this case we will have to remove vprocs from an allocated
|
| 480 |
+
// core and use it exclusively for the external thread.
|
| 481 |
+
unsigned int externalThreadCores = fSubscribeCurrentThread ? (m_numAllocatedCores + numberReserved > MinHWThreads() ? 1 : 0) : 0;
|
| 482 |
+
unsigned int vprocCores = (numberReserved > externalThreadCores) ? (numberReserved - externalThreadCores) : 0;
|
| 483 |
+
bool fRemoveVProcs = (externalThreadCores > 0 && numberReserved == 0);
|
| 484 |
+
bool fShareExternalThreadCore = (fSubscribeCurrentThread && externalThreadCores == 0);
|
| 485 |
+
|
| 486 |
+
// These variables are used if a thread subscription is part of this allocation. For a thread subscription assignment to a core,
|
| 487 |
+
// there are 3 possibilities:
|
| 488 |
+
// 1. A Reserved core exists in the current allocation map exclusive for the thread subscription.
|
| 489 |
+
// 2. The thread subscription will share a core with virtual processors.
|
| 490 |
+
// 3. An existing allocated core will be assigned to the external thread after removing all vprocs that are currently allocated to it.
|
| 491 |
+
unsigned int externalThreadUseCount = (unsigned int) -1;
|
| 492 |
+
unsigned int externalThreadCoreIndex = (unsigned int) -1;
|
| 493 |
+
SchedulerNode * pExternalThreadNode = NULL;
|
| 494 |
+
unsigned int currentNodeIndex = fSubscribeCurrentThread ? m_pResourceManager->GetCurrentNodeAndCore(NULL) : (unsigned int) -1;
|
| 495 |
+
|
| 496 |
+
ASSERT(!fRemoveVProcs || (m_numAllocatedCores > MinHWThreads()));
|
| 497 |
+
|
| 498 |
+
unsigned int vprocCount = 0;
|
| 499 |
+
if (vprocCores > 0)
|
| 500 |
+
{
|
| 501 |
+
ASSERT(m_numFullySubscribedCores > 0 && m_numFullySubscribedCores <= m_desiredHardwareThreads);
|
| 502 |
+
if (vprocCores <= m_numFullySubscribedCores)
|
| 503 |
+
{
|
| 504 |
+
vprocCount = vprocCores * m_targetOversubscriptionFactor;
|
| 505 |
+
}
|
| 506 |
+
else
|
| 507 |
+
{
|
| 508 |
+
vprocCount = (m_numFullySubscribedCores * m_targetOversubscriptionFactor) +
|
| 509 |
+
((vprocCores - m_numFullySubscribedCores) * (m_targetOversubscriptionFactor - 1));
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
ASSERT(!fInitialAllocation || (vprocCount >= m_minConcurrency && vprocCount <= m_maxConcurrency));
|
| 514 |
+
|
| 515 |
+
IVirtualProcessorRoot** vprocArray = (vprocCount > 0) ? _concrt_new IVirtualProcessorRoot *[vprocCount] : NULL;
|
| 516 |
+
unsigned int vprocIndex = 0;
|
| 517 |
+
bool externalThreadCoreFound= !fSubscribeCurrentThread;
|
| 518 |
+
|
| 519 |
+
// We may not have a core reserved for the external thread, so we should loop until the external thread is assigned to an
|
| 520 |
+
// existing core, if thread subscription is requested.
|
| 521 |
+
for (unsigned int nodeIndex = 0; (reservationsAllocated < numberReserved || !externalThreadCoreFound) &&
|
| 522 |
+
nodeIndex < m_nodeCount; ++nodeIndex)
|
| 523 |
+
{
|
| 524 |
+
// If the core is marked Reserved, we will either assign to it virtual processors, the external thread or both. Whether or not
|
| 525 |
+
// the external thread shares the core with virtual processors depends on the value of fShareExternalThreadCore.
|
| 526 |
+
|
| 527 |
+
// If we find any cores marked Allocated, it implies that this is not the initial allocation, and all we're looking to do here
|
| 528 |
+
// is assign a core to the external thread. The external thread could either share a core with vprocs or displace vprocs, depending
|
| 529 |
+
// on the value of fRemoveVProcs.
|
| 530 |
+
|
| 531 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[nodeIndex];
|
| 532 |
+
if (pNode->m_reservedCores > 0 || pNode->m_allocatedCores > 0)
|
| 533 |
+
{
|
| 534 |
+
for(unsigned int coreIndex = 0; (reservationsAllocated < numberReserved || !externalThreadCoreFound) &&
|
| 535 |
+
coreIndex < pNode->m_coreCount; ++coreIndex)
|
| 536 |
+
{
|
| 537 |
+
SchedulerCore * pCore = &pNode->m_pCores[coreIndex];
|
| 538 |
+
if (pCore->m_coreState == ProcessorCore::Reserved)
|
| 539 |
+
{
|
| 540 |
+
bool assignExternalThread = (!externalThreadCoreFound && (reservationsAllocated == numberReserved - 1 || currentNodeIndex == nodeIndex));
|
| 541 |
+
bool assignVProcs = (!assignExternalThread || externalThreadCores == 0);
|
| 542 |
+
|
| 543 |
+
ASSERT(pCore->m_numAssignedThreads == 0 && pCore->m_numFixedThreads == 0);
|
| 544 |
+
pCore->m_coreState = ProcessorCore::Allocated;
|
| 545 |
+
ASSERT(pNode->m_allocatedCores < pNode->m_coreCount);
|
| 546 |
+
++pNode->m_allocatedCores;
|
| 547 |
+
++m_numAllocatedCores;
|
| 548 |
+
|
| 549 |
+
// 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
|
| 550 |
+
// it is currently running on. If not, reaffinitize it.
|
| 551 |
+
if (assignExternalThread)
|
| 552 |
+
{
|
| 553 |
+
// The execution resource is created right before returning from the function.
|
| 554 |
+
pExternalThreadNode = pNode;
|
| 555 |
+
externalThreadCoreIndex = coreIndex;
|
| 556 |
+
externalThreadCoreFound = true;
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
if (assignVProcs)
|
| 560 |
+
{
|
| 561 |
+
ASSERT(!assignExternalThread || fShareExternalThreadCore);
|
| 562 |
+
// Create virtual processor roots in the scheduler proxy, corresponding to the node and core we're currently looking at.
|
| 563 |
+
unsigned int numVprocs = 0;
|
| 564 |
+
if (m_numFullySubscribedCores > 0)
|
| 565 |
+
{
|
| 566 |
+
numVprocs = m_targetOversubscriptionFactor;
|
| 567 |
+
// As we assign m_tof threads to a core, we decrement this value. This value is also updated in
|
| 568 |
+
// AddCore and RemoveCore. After the scheduler proxy has been given its initial allocation
|
| 569 |
+
// or resources, this variable keeps track of how many out of the remaining quota of cores the
|
| 570 |
+
// scheduler proxy could acquire (desired - allocated) would get tof threads per core if they
|
| 571 |
+
// were added to the scheduler during dynamic core migration.
|
| 572 |
+
--m_numFullySubscribedCores;
|
| 573 |
+
}
|
| 574 |
+
else
|
| 575 |
+
{
|
| 576 |
+
numVprocs = m_targetOversubscriptionFactor - 1;
|
| 577 |
+
}
|
| 578 |
+
pCore->m_numAssignedThreads += numVprocs;
|
| 579 |
+
m_numAssignedThreads += numVprocs;
|
| 580 |
+
|
| 581 |
+
while (numVprocs-- > 0)
|
| 582 |
+
{
|
| 583 |
+
_Analysis_assume_(vprocIndex < vprocCount);
|
| 584 |
+
vprocArray[vprocIndex++] = CreateVirtualProcessorRoot(pNode, coreIndex);
|
| 585 |
+
}
|
| 586 |
+
ASSERT(vprocIndex <= vprocCount);
|
| 587 |
+
}
|
| 588 |
+
++reservationsAllocated;
|
| 589 |
+
}
|
| 590 |
+
else if (pCore->m_coreState == ProcessorCore::Allocated)
|
| 591 |
+
{
|
| 592 |
+
// If we encounter allocated cores, this is a subsequent allocation for an external core. Determine if the external
|
| 593 |
+
// thread should share a core with existing vprocs and external threads, or displace some vprocs to get a core to itself.
|
| 594 |
+
|
| 595 |
+
// Walk through all the allocated cores to find the right one to either oversubscribe or displace. For over
|
| 596 |
+
// subscription find the core with the least number of vprocs + external thread assigned to it (favouring the node
|
| 597 |
+
// where the current thread is running if there is more than one such core).
|
| 598 |
+
// For displacement, we need to find an unfixed core, favouring the node where the current thread is running.
|
| 599 |
+
if (fShareExternalThreadCore)
|
| 600 |
+
{
|
| 601 |
+
ASSERT(!fRemoveVProcs && externalThreadCores == 0);
|
| 602 |
+
|
| 603 |
+
unsigned int useCount = pCore->m_numAssignedThreads + pCore->m_numExternalThreads;
|
| 604 |
+
if (useCount < externalThreadUseCount || (useCount == externalThreadUseCount && nodeIndex == currentNodeIndex))
|
| 605 |
+
{
|
| 606 |
+
externalThreadUseCount = useCount;
|
| 607 |
+
pExternalThreadNode = pNode;
|
| 608 |
+
externalThreadCoreIndex = coreIndex;
|
| 609 |
+
|
| 610 |
+
// We don't set externalThreadCoreFound here, since we want to examine all allocated cores.
|
| 611 |
+
}
|
| 612 |
+
}
|
| 613 |
+
else if (fRemoveVProcs)
|
| 614 |
+
{
|
| 615 |
+
ASSERT(externalThreadCores == 1);
|
| 616 |
+
if (!pCore->IsFixed() && (pExternalThreadNode == NULL || nodeIndex == currentNodeIndex))
|
| 617 |
+
{
|
| 618 |
+
pExternalThreadNode = pNode;
|
| 619 |
+
externalThreadCoreIndex = coreIndex;
|
| 620 |
+
if (nodeIndex == currentNodeIndex)
|
| 621 |
+
{
|
| 622 |
+
// Stop looking if we find an unfixed core on the current node.
|
| 623 |
+
externalThreadCoreFound = true;
|
| 624 |
+
}
|
| 625 |
+
}
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
else
|
| 629 |
+
{
|
| 630 |
+
ASSERT(pCore->m_coreState == ProcessorCore::Unassigned);
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
pNode->m_reservedCores = 0;
|
| 634 |
+
}
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
ASSERT(vprocIndex == vprocCount);
|
| 638 |
+
if (vprocCount > 0)
|
| 639 |
+
{
|
| 640 |
+
AddVirtualProcessorRoots(vprocArray, vprocCount);
|
| 641 |
+
delete [] vprocArray;
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
if (fSubscribeCurrentThread)
|
| 645 |
+
{
|
| 646 |
+
ASSERT(pExternalThreadNode != NULL && externalThreadCoreIndex != (unsigned int) -1);
|
| 647 |
+
if (fShareExternalThreadCore)
|
| 648 |
+
{
|
| 649 |
+
ASSERT(externalThreadCores == 0);
|
| 650 |
+
}
|
| 651 |
+
else if (fRemoveVProcs)
|
| 652 |
+
{
|
| 653 |
+
ASSERT(externalThreadCores == 1);
|
| 654 |
+
ASSERT(m_numAllocatedCores > MinHWThreads());
|
| 655 |
+
// Remove the core and replace with an external thread subscription. Note that the use count for this core
|
| 656 |
+
// stays the same, as we simply replace virtual processors with a thread subscription.
|
| 657 |
+
RemoveCore(pExternalThreadNode, externalThreadCoreIndex);
|
| 658 |
+
|
| 659 |
+
pExternalThreadNode->m_pCores[externalThreadCoreIndex].m_coreState = ProcessorCore::Allocated;
|
| 660 |
+
ASSERT(pExternalThreadNode->m_allocatedCores < pExternalThreadNode->m_coreCount);
|
| 661 |
+
++pExternalThreadNode->m_allocatedCores;
|
| 662 |
+
++m_numAllocatedCores;
|
| 663 |
+
}
|
| 664 |
+
else
|
| 665 |
+
{
|
| 666 |
+
ASSERT(externalThreadCores == 1);
|
| 667 |
+
}
|
| 668 |
+
pExecutionResource = CreateExternalThreadResource(pExternalThreadNode, externalThreadCoreIndex);
|
| 669 |
+
}
|
| 670 |
+
#if defined(CONCRT_TRACING)
|
| 671 |
+
m_numTotalCores = m_nodeCount * m_pAllocatedNodes[0].m_coreCount;
|
| 672 |
+
m_drmInitialState = _concrt_new SchedulerCoreData[m_numTotalCores];
|
| 673 |
+
memset(m_drmInitialState, 0, sizeof(SchedulerCoreData) * m_numTotalCores);
|
| 674 |
+
#endif
|
| 675 |
+
ASSERT(m_numAllocatedCores >= MinHWThreads() && m_numAllocatedCores <= DesiredHWThreads());
|
| 676 |
+
return pExecutionResource;
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
/// <summary>
|
| 680 |
+
/// Causes the resource manager to create a new virtual processor root running atop the same hardware thread as this
|
| 681 |
+
/// execution resource. Typically, this is used when a scheduler wishes to oversubscribe a particular hardware thread
|
| 682 |
+
/// for a limited amount of time.
|
| 683 |
+
/// </summary>
|
| 684 |
+
/// <param name="pExecutionResource">
|
| 685 |
+
/// The execution resource abstraction on which to oversubscribe.
|
| 686 |
+
/// </param>
|
| 687 |
+
/// <returns>
|
| 688 |
+
/// A new virtual processor root running atop the same hardware thread as this execution resource.
|
| 689 |
+
/// </returns>
|
| 690 |
+
IVirtualProcessorRoot * SchedulerProxy::CreateOversubscriber(IExecutionResource * pExecutionResource)
|
| 691 |
+
{
|
| 692 |
+
// The scheduler proxy on the virtual processor root has to match 'this'
|
| 693 |
+
VirtualProcessorRoot * pOversubscribedRoot = NULL;
|
| 694 |
+
ExecutionResource * pResource = dynamic_cast<ExecutionResource *>(pExecutionResource);
|
| 695 |
+
bool isVprocRoot = false;
|
| 696 |
+
|
| 697 |
+
// If dynamic cast failed then we must have a virtual processor root.
|
| 698 |
+
if (pResource == NULL)
|
| 699 |
+
{
|
| 700 |
+
pResource = static_cast<VirtualProcessorRoot *>(pExecutionResource)->GetExecutionResource();
|
| 701 |
+
isVprocRoot = true;
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
// Cannot verify the scheduler proxy for external threads because they can "live" on
|
| 705 |
+
// multiple schedulers at the same time (nested).
|
| 706 |
+
if (isVprocRoot && pResource->GetSchedulerProxy() != this)
|
| 707 |
+
{
|
| 708 |
+
throw std::invalid_argument("pExecutionResource");
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
// Synchronize with other concurrent calls that are adding/removing virtual processor roots.
|
| 712 |
+
{
|
| 713 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 714 |
+
// Use the scheduler proxy to clone this virtual processor root.
|
| 715 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[pResource->GetNodeId()];
|
| 716 |
+
unsigned int coreIndex = pResource->GetCoreIndex();
|
| 717 |
+
|
| 718 |
+
pOversubscribedRoot = CreateVirtualProcessorRoot(pNode, coreIndex);
|
| 719 |
+
|
| 720 |
+
// We mark these vproc roots as oversubscribed to indicate that they do not contribute
|
| 721 |
+
// towards concurrency levels bounded by the policy
|
| 722 |
+
pOversubscribedRoot->MarkAsOversubscribed();
|
| 723 |
+
pNode->m_pCores[coreIndex].m_resources.AddTail(pOversubscribedRoot->GetExecutionResource());
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
return pOversubscribedRoot;
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
/// <summary>
|
| 730 |
+
/// Creates a virtual processor root and adds it to the scheduler proxys list of roots.
|
| 731 |
+
/// </summary>
|
| 732 |
+
VirtualProcessorRoot * SchedulerProxy::CreateVirtualProcessorRoot(SchedulerNode * pNode, unsigned int coreIndex)
|
| 733 |
+
{
|
| 734 |
+
return _concrt_new FreeVirtualProcessorRoot(this, pNode, coreIndex);
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
/// <summary>
|
| 738 |
+
/// Notifies the scheduler associated with this proxy to adds the virtual processor roots provided.
|
| 739 |
+
/// Called by the RM during initial allocation and dynamic core migration.
|
| 740 |
+
/// </summary>
|
| 741 |
+
void SchedulerProxy::AddVirtualProcessorRoots(IVirtualProcessorRoot ** vprocRoots, unsigned int count)
|
| 742 |
+
{
|
| 743 |
+
// Note, that we are holding the global RM allocation lock when this API is called.
|
| 744 |
+
{
|
| 745 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 746 |
+
for (unsigned int i = 0; i < count; ++i)
|
| 747 |
+
{
|
| 748 |
+
VirtualProcessorRoot * pRoot = static_cast<VirtualProcessorRoot *>(vprocRoots[i]);
|
| 749 |
+
// Add the resources associated with the roots to the corresponding lists in the scheduler proxy.
|
| 750 |
+
unsigned int nodeId = pRoot->GetNodeId();
|
| 751 |
+
unsigned int coreIndex = pRoot->GetCoreIndex();
|
| 752 |
+
|
| 753 |
+
m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_resources.AddTail(pRoot->GetExecutionResource());
|
| 754 |
+
}
|
| 755 |
+
m_pScheduler->AddVirtualProcessors((IVirtualProcessorRoot **) vprocRoots, count);
|
| 756 |
+
|
| 757 |
+
m_currentConcurrency += count;
|
| 758 |
+
}
|
| 759 |
+
}
|
| 760 |
+
|
| 761 |
+
/// <summary>
|
| 762 |
+
/// Adds an execution resource to the list of resources that run on a particular core.
|
| 763 |
+
/// </summary>
|
| 764 |
+
void SchedulerProxy::AddExecutionResource(ExecutionResource * pExecutionResource)
|
| 765 |
+
{
|
| 766 |
+
{
|
| 767 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 768 |
+
|
| 769 |
+
// Add the resource to the corresponding list in the scheduler proxy.
|
| 770 |
+
unsigned int nodeId = pExecutionResource->GetNodeId();
|
| 771 |
+
unsigned int coreIndex = pExecutionResource->GetCoreIndex();
|
| 772 |
+
|
| 773 |
+
m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_resources.AddTail(pExecutionResource);
|
| 774 |
+
}
|
| 775 |
+
}
|
| 776 |
+
|
| 777 |
+
/// <summary>
|
| 778 |
+
/// Toggles the state on a core from borrowed to owned (and vice versa), and updates necessary counts.
|
| 779 |
+
/// </summary>
|
| 780 |
+
void SchedulerProxy::ToggleBorrowedState(SchedulerNode * pNode, unsigned int coreIndex)
|
| 781 |
+
{
|
| 782 |
+
SchedulerCore * pCore = &pNode->m_pCores[coreIndex];
|
| 783 |
+
|
| 784 |
+
if (pCore->m_fBorrowed)
|
| 785 |
+
{
|
| 786 |
+
--m_numBorrowedCores;
|
| 787 |
+
--pNode->m_numBorrowedCores;
|
| 788 |
+
pCore->m_fBorrowed = false;
|
| 789 |
+
}
|
| 790 |
+
else
|
| 791 |
+
{
|
| 792 |
+
++m_numBorrowedCores;
|
| 793 |
+
++pNode->m_numBorrowedCores;
|
| 794 |
+
pCore->m_fBorrowed = true;
|
| 795 |
+
}
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
/// <summary>
|
| 799 |
+
/// Adds an appropriate number of virtual processor roots to the scheduler associated with this proxy.
|
| 800 |
+
/// Called by the RM during core migration when the RM decides to give this scheduler an additional
|
| 801 |
+
/// core.
|
| 802 |
+
/// </summary>
|
| 803 |
+
void SchedulerProxy::AddCore(SchedulerNode * pNode, unsigned int coreIndex, bool fBorrowed)
|
| 804 |
+
{
|
| 805 |
+
// Note, that we are holding the global RM allocation lock when this API is called.
|
| 806 |
+
|
| 807 |
+
// Decide how many virtual processors to give the scheduler on this core. Note that this value is required
|
| 808 |
+
// to be either m_tof or m_tof - 1.
|
| 809 |
+
|
| 810 |
+
unsigned int numThreads = 0;
|
| 811 |
+
if (m_numFullySubscribedCores > 0)
|
| 812 |
+
{
|
| 813 |
+
numThreads = m_targetOversubscriptionFactor;
|
| 814 |
+
--m_numFullySubscribedCores;
|
| 815 |
+
}
|
| 816 |
+
else
|
| 817 |
+
{
|
| 818 |
+
numThreads = m_targetOversubscriptionFactor - 1;
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
ASSERT(numThreads > 0 && numThreads <= INT_MAX);
|
| 822 |
+
|
| 823 |
+
ASSERT(pNode->m_allocatedCores < pNode->m_coreCount);
|
| 824 |
+
++pNode->m_allocatedCores;
|
| 825 |
+
ASSERT(m_numAllocatedCores < DesiredHWThreads());
|
| 826 |
+
++m_numAllocatedCores;
|
| 827 |
+
|
| 828 |
+
SchedulerCore * pCore = &pNode->m_pCores[coreIndex];
|
| 829 |
+
|
| 830 |
+
ASSERT(pCore->m_coreState == ProcessorCore::Unassigned);
|
| 831 |
+
pCore->m_coreState = ProcessorCore::Allocated;
|
| 832 |
+
|
| 833 |
+
ASSERT(pCore->m_numAssignedThreads == 0);
|
| 834 |
+
pCore->m_numAssignedThreads = numThreads;
|
| 835 |
+
m_numAssignedThreads += pCore->m_numAssignedThreads;
|
| 836 |
+
ASSERT(m_numAssignedThreads <= m_maxConcurrency);
|
| 837 |
+
|
| 838 |
+
if (fBorrowed)
|
| 839 |
+
{
|
| 840 |
+
ASSERT(!pCore->IsBorrowed());
|
| 841 |
+
ToggleBorrowedState(pNode, coreIndex);
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
// Special case for when there is 1 vproc per core - this is likely to be the common case.
|
| 845 |
+
IVirtualProcessorRoot * pRoot;
|
| 846 |
+
IVirtualProcessorRoot ** pRootArray = (numThreads == 1) ? &pRoot : _concrt_new IVirtualProcessorRoot *[numThreads];
|
| 847 |
+
|
| 848 |
+
for (unsigned int i = 0; i < numThreads; ++i)
|
| 849 |
+
{
|
| 850 |
+
pRootArray[i] = CreateVirtualProcessorRoot(pNode, coreIndex);
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
+
AddVirtualProcessorRoots(pRootArray, numThreads);
|
| 854 |
+
|
| 855 |
+
if (pRootArray != &pRoot)
|
| 856 |
+
{
|
| 857 |
+
delete [] pRootArray;
|
| 858 |
+
}
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
/// <summary>
|
| 862 |
+
/// Notifies the scheduler associated with this proxy to remove the virtual processor roots associated
|
| 863 |
+
/// with the core provided. Called by the RM during core migration.
|
| 864 |
+
/// </summary>
|
| 865 |
+
void SchedulerProxy::RemoveCore(SchedulerNode * pNode, unsigned int coreIndex)
|
| 866 |
+
{
|
| 867 |
+
// Note, that we are holding the global RM allocation lock when this API is called.
|
| 868 |
+
ASSERT(pNode->m_allocatedCores > 0 && pNode->m_allocatedCores <= pNode->m_coreCount);
|
| 869 |
+
--pNode->m_allocatedCores;
|
| 870 |
+
ASSERT(m_numAllocatedCores > MinVprocHWThreads());
|
| 871 |
+
--m_numAllocatedCores;
|
| 872 |
+
|
| 873 |
+
SchedulerCore * pCore = &pNode->m_pCores[coreIndex];
|
| 874 |
+
|
| 875 |
+
ASSERT(pCore->m_coreState == ProcessorCore::Allocated || pCore->m_coreState == ProcessorCore::Stolen);
|
| 876 |
+
pCore->m_coreState = ProcessorCore::Unassigned;
|
| 877 |
+
|
| 878 |
+
ASSERT(pCore->m_numAssignedThreads == m_targetOversubscriptionFactor ||
|
| 879 |
+
pCore->m_numAssignedThreads == m_targetOversubscriptionFactor - 1);
|
| 880 |
+
if (pCore->m_numAssignedThreads == m_targetOversubscriptionFactor)
|
| 881 |
+
{
|
| 882 |
+
++m_numFullySubscribedCores;
|
| 883 |
+
}
|
| 884 |
+
|
| 885 |
+
m_numAssignedThreads -= pCore->m_numAssignedThreads;
|
| 886 |
+
ASSERT(m_numAssignedThreads >= m_minConcurrency && m_numAssignedThreads < m_maxConcurrency);
|
| 887 |
+
pCore->m_numAssignedThreads = 0;
|
| 888 |
+
|
| 889 |
+
if (pCore->m_fBorrowed)
|
| 890 |
+
{
|
| 891 |
+
ToggleBorrowedState(pNode, coreIndex);
|
| 892 |
+
}
|
| 893 |
+
|
| 894 |
+
pCore->m_fIdleDuringDRM = false;
|
| 895 |
+
|
| 896 |
+
ASSERT(GetNumOwnedCores() >= MinHWThreads());
|
| 897 |
+
|
| 898 |
+
// A lock is required around the iteration of nodes and the call to AddVirtualProcessors to synchronize with concurrent
|
| 899 |
+
// calls to DestroyVirtualProcessorRoot, which removes roots from the array and deletes them.
|
| 900 |
+
|
| 901 |
+
{ // begin locked region
|
| 902 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 903 |
+
ExecutionResource * pExecutionResource = pCore->m_resources.First();
|
| 904 |
+
while (pExecutionResource != NULL)
|
| 905 |
+
{
|
| 906 |
+
// Remember the next root before hand, since a IVirtualProcessorRoot::Remove call could happen inline
|
| 907 |
+
// for the root we're removing, and by the time we get back, that root could be deleted.
|
| 908 |
+
ExecutionResource * pNextExecutionResource = pCore->m_resources.Next(pExecutionResource);
|
| 909 |
+
VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot();
|
| 910 |
+
if (pVPRoot != NULL && !pVPRoot->IsRootRemoved())
|
| 911 |
+
{
|
| 912 |
+
pVPRoot->MarkRootRemoved();
|
| 913 |
+
IVirtualProcessorRoot * pIRoot = pVPRoot;
|
| 914 |
+
m_pScheduler->RemoveVirtualProcessors(&pIRoot, 1);
|
| 915 |
+
}
|
| 916 |
+
pExecutionResource = pNextExecutionResource;
|
| 917 |
+
}
|
| 918 |
+
} // end locked region
|
| 919 |
+
}
|
| 920 |
+
|
| 921 |
+
/// <summary>
|
| 922 |
+
/// Called by the RM to instruct this scheduler proxy to notify its scheduler that this core is now
|
| 923 |
+
/// externally busy or externally idle.
|
| 924 |
+
/// </summary>
|
| 925 |
+
void SchedulerProxy::SendCoreNotification(SchedulerCore * pCore, bool isBusyNotification)
|
| 926 |
+
{
|
| 927 |
+
// Avoid a memory allocation under two locks if we have less than 8 roots per core - this is expected to be
|
| 928 |
+
// the common case.
|
| 929 |
+
IVirtualProcessorRoot * pRootArray[8];
|
| 930 |
+
IVirtualProcessorRoot ** pRoots= NULL;
|
| 931 |
+
|
| 932 |
+
#pragma warning(push)
|
| 933 |
+
#pragma warning(disable: 6385 6386) // TRANSITION, VSO-1807030
|
| 934 |
+
// Note, that we are holding the global RM allocation lock when this API is called.
|
| 935 |
+
{ // begin locked region
|
| 936 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 937 |
+
unsigned int numThreadsIndex = 0;
|
| 938 |
+
|
| 939 |
+
if (pCore->m_resources.Count() > 8)
|
| 940 |
+
{
|
| 941 |
+
pRoots = _concrt_new IVirtualProcessorRoot * [pCore->m_resources.Count()];
|
| 942 |
+
}
|
| 943 |
+
else
|
| 944 |
+
{
|
| 945 |
+
pRoots = pRootArray;
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
ExecutionResource * pExecutionResource = pCore->m_resources.First();
|
| 949 |
+
while (pExecutionResource != NULL)
|
| 950 |
+
{
|
| 951 |
+
ExecutionResource * pNextExecutionResource = pCore->m_resources.Next(pExecutionResource);
|
| 952 |
+
VirtualProcessorRoot * pVPRoot = pExecutionResource->GetVirtualProcessorRoot();
|
| 953 |
+
if (pVPRoot != NULL && !pVPRoot->IsRootRemoved())
|
| 954 |
+
{
|
| 955 |
+
pRoots[numThreadsIndex++] = pVPRoot;
|
| 956 |
+
}
|
| 957 |
+
pExecutionResource = pNextExecutionResource;
|
| 958 |
+
}
|
| 959 |
+
ASSERT(numThreadsIndex <= (unsigned int) pCore->m_resources.Count());
|
| 960 |
+
|
| 961 |
+
// Now that the array is populated, send notifications for this core
|
| 962 |
+
if (isBusyNotification)
|
| 963 |
+
{
|
| 964 |
+
m_pScheduler->NotifyResourcesExternallyBusy(pRoots, numThreadsIndex);
|
| 965 |
+
}
|
| 966 |
+
else
|
| 967 |
+
{
|
| 968 |
+
m_pScheduler->NotifyResourcesExternallyIdle(pRoots, numThreadsIndex);
|
| 969 |
+
}
|
| 970 |
+
|
| 971 |
+
} // end locked region
|
| 972 |
+
#pragma warning(pop)
|
| 973 |
+
|
| 974 |
+
if (pRoots!= pRootArray)
|
| 975 |
+
{
|
| 976 |
+
delete [] pRoots;
|
| 977 |
+
}
|
| 978 |
+
}
|
| 979 |
+
/// <summary>
|
| 980 |
+
/// Removes a root from the scheduler proxy and destroys it. This API is called in response to a scheduler
|
| 981 |
+
/// informing the RM that it is done with a virtual processor root.
|
| 982 |
+
/// </summary>
|
| 983 |
+
void SchedulerProxy::DestroyVirtualProcessorRoot(VirtualProcessorRoot * pRoot)
|
| 984 |
+
{
|
| 985 |
+
// Synchronize with other concurrent calls that are adding/removing virtual processor roots.
|
| 986 |
+
{ // begin locked region
|
| 987 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 988 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[pRoot->GetNodeId()];
|
| 989 |
+
ASSERT(pNode->m_id == pRoot->GetNodeId());
|
| 990 |
+
|
| 991 |
+
// NOTE: This API is called in response to a scheduler being done with a virtual processor root.
|
| 992 |
+
// The scheduler is expected not to invoke ISchedulerProxy::Shutdown, which destroys
|
| 993 |
+
// all remaining roots in the proxy, until all individual calls for removing virtual processor
|
| 994 |
+
// roots have completed.
|
| 995 |
+
|
| 996 |
+
pNode->m_pCores[pRoot->GetCoreIndex()].m_resources.Remove(pRoot->GetExecutionResource());
|
| 997 |
+
|
| 998 |
+
if (!pRoot->IsOversubscribed())
|
| 999 |
+
{
|
| 1000 |
+
// Oversubscribed vprocs do not contribute towards concurrency level
|
| 1001 |
+
ASSERT(m_currentConcurrency > 0);
|
| 1002 |
+
--m_currentConcurrency;
|
| 1003 |
+
}
|
| 1004 |
+
|
| 1005 |
+
} // end locked region
|
| 1006 |
+
|
| 1007 |
+
pRoot->DeleteThis();
|
| 1008 |
+
}
|
| 1009 |
+
|
| 1010 |
+
/// <summary>
|
| 1011 |
+
/// Removes an execution resource from the scheduler proxy, and destroys it. This API is called in response to a scheduler
|
| 1012 |
+
/// informing the RM that it is done with an execution resource.
|
| 1013 |
+
/// </summary>
|
| 1014 |
+
void SchedulerProxy::DestroyExecutionResource(ExecutionResource * pExecutionResource)
|
| 1015 |
+
{
|
| 1016 |
+
// NOTE: This function should be called with the RM lock held.
|
| 1017 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[pExecutionResource->GetNodeId()];
|
| 1018 |
+
SchedulerCore * pCore = &pNode->m_pCores[pExecutionResource->GetCoreIndex()];
|
| 1019 |
+
ASSERT(pNode->m_id == pExecutionResource->GetNodeId());
|
| 1020 |
+
|
| 1021 |
+
// Mark this core as available to others if this was the last resource on it
|
| 1022 |
+
// If this is the last running resource on this core then mark it as available again
|
| 1023 |
+
if (pCore->m_numAssignedThreads + pCore->m_numExternalThreads == 0)
|
| 1024 |
+
{
|
| 1025 |
+
// If there are no vprocs or external threads, then core cannot be fixed
|
| 1026 |
+
ASSERT(!pCore->IsFixed());
|
| 1027 |
+
ASSERT(pNode->m_allocatedCores > 0 && pNode->m_allocatedCores <= pNode->m_coreCount);
|
| 1028 |
+
pNode->m_allocatedCores--;
|
| 1029 |
+
ASSERT(m_numAllocatedCores > MinHWThreads());
|
| 1030 |
+
pCore->m_coreState = ProcessorCore::Unassigned;
|
| 1031 |
+
m_numAllocatedCores--;
|
| 1032 |
+
ASSERT(m_numAllocatedCores <= DesiredHWThreads());
|
| 1033 |
+
m_pResourceManager->DecrementCoreUseCount(pExecutionResource->GetNodeId(), pExecutionResource->GetCoreIndex());
|
| 1034 |
+
}
|
| 1035 |
+
|
| 1036 |
+
// Synchronize with other concurrent calls that are adding/removing execution resources.
|
| 1037 |
+
{ // begin locked region
|
| 1038 |
+
_ReentrantBlockingLock::_Scoped_lock lock(m_lock);
|
| 1039 |
+
pCore->m_resources.Remove(pExecutionResource);
|
| 1040 |
+
} // end locked region
|
| 1041 |
+
|
| 1042 |
+
delete pExecutionResource;
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
/// <summary>
|
| 1046 |
+
/// Called to assist dynamic resource management in determining whether cores assigned to schedulers
|
| 1047 |
+
/// are idle. An idle core is one whose subscription level is 0.
|
| 1048 |
+
/// </summary>
|
| 1049 |
+
void SchedulerProxy::IncrementCoreSubscription(ExecutionResource * pExecutionResource)
|
| 1050 |
+
{
|
| 1051 |
+
unsigned int nodeId = pExecutionResource->GetNodeId();
|
| 1052 |
+
unsigned int coreIndex = pExecutionResource->GetCoreIndex();
|
| 1053 |
+
|
| 1054 |
+
if ((InterlockedIncrement(&m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_subscriptionLevel) == 1) &&
|
| 1055 |
+
(m_pResourceManager->GetNumSchedulersForNotifications() > (ShouldReceiveNotifications() ? 1UL : 0UL)))
|
| 1056 |
+
{
|
| 1057 |
+
// We've incremented the local subscription from 0 to 1 -> this may warrant notifications.
|
| 1058 |
+
// Note that the number of schedulers needing notifications may change right after we read it, but any
|
| 1059 |
+
// missed notifications will be sent at the next Dynamic RM Poll.
|
| 1060 |
+
|
| 1061 |
+
// We simply set the dynamic RM event here. Note -> there may not yet be a dynamic RM thread at this point.
|
| 1062 |
+
// We clearly have 2 schedulers, but it could be that the second one is just being created. In that case,
|
| 1063 |
+
// notifications will be sent when the dynamic RM starts up (right after the second scheduler has finished
|
| 1064 |
+
// receiving all its resources). We may even race with shutdown for the penultimate scheduler. If the DRM
|
| 1065 |
+
// thread wakes up and there is only one scheduler left, it will go back to waiting.
|
| 1066 |
+
m_pResourceManager->WakeupDynamicRMWorker();
|
| 1067 |
+
}
|
| 1068 |
+
}
|
| 1069 |
+
|
| 1070 |
+
/// <summary>
|
| 1071 |
+
/// Called to assist dynamic resource management in determining whether cores assigned to schedulers
|
| 1072 |
+
/// are idle. An idle core is one whose subscription level is 0.
|
| 1073 |
+
/// </summary>
|
| 1074 |
+
void SchedulerProxy::DecrementCoreSubscription(ExecutionResource * pExecutionResource)
|
| 1075 |
+
{
|
| 1076 |
+
unsigned int nodeId = pExecutionResource->GetNodeId();
|
| 1077 |
+
unsigned int coreIndex = pExecutionResource->GetCoreIndex();
|
| 1078 |
+
|
| 1079 |
+
if ((InterlockedDecrement(&m_pAllocatedNodes[nodeId].m_pCores[coreIndex].m_subscriptionLevel) == 0) &&
|
| 1080 |
+
(m_pResourceManager->GetNumSchedulersForNotifications() > (ShouldReceiveNotifications() ? 1UL : 0UL)))
|
| 1081 |
+
{
|
| 1082 |
+
// We've decremented the local subscription from 1 to 0 -> this may warrant notifications.
|
| 1083 |
+
// Note that the number of schedulers needing notifications may change right after we read it, but any
|
| 1084 |
+
// missed notifications will be sent at the next Dynamic RM Poll.
|
| 1085 |
+
|
| 1086 |
+
// We simply set the dynamic RM event here. Note -> there may not yet be a dynamic RM thread at this point.
|
| 1087 |
+
// We clearly have 2 schedulers, but it could be that the second one is just being created. In that case,
|
| 1088 |
+
// notifications will be sent when the dynamic RM starts up (right after the second scheduler has finished
|
| 1089 |
+
// receiving all its resources). We may even race with shutdown for the penultimate scheduler. If the DRM
|
| 1090 |
+
// thread wakes up and there is only one scheduler left, it will go back to waiting.
|
| 1091 |
+
m_pResourceManager->WakeupDynamicRMWorker();
|
| 1092 |
+
}
|
| 1093 |
+
}
|
| 1094 |
+
|
| 1095 |
+
/// <summary>
|
| 1096 |
+
/// Called to adjust the suggested allocation such that we do not exceed maxConcurrency.
|
| 1097 |
+
/// This routine takes into account vprocs that are marked for removal but haven't yet been
|
| 1098 |
+
/// retired by the scheduler. The suggested allocation would be decreased to account for such
|
| 1099 |
+
/// vprocs.
|
| 1100 |
+
/// </summary>
|
| 1101 |
+
unsigned int SchedulerProxy::AdjustAllocationIncrease(unsigned int suggestedAllocation) const
|
| 1102 |
+
{
|
| 1103 |
+
ASSERT(suggestedAllocation >= GetNumAllocatedCores());
|
| 1104 |
+
ASSERT(suggestedAllocation <= DesiredHWThreads());
|
| 1105 |
+
|
| 1106 |
+
// Figure out the max number of new cores we can add
|
| 1107 |
+
unsigned int newCores = 0;
|
| 1108 |
+
|
| 1109 |
+
// Since we could be not holding the scheduler proxy lock the value in m_currentConcurrency could
|
| 1110 |
+
// be changing. This is fine since a later DRM sweep will migrate appropriate number of cores.
|
| 1111 |
+
if (m_maxConcurrency > m_currentConcurrency)
|
| 1112 |
+
{
|
| 1113 |
+
unsigned int remainingConcurrency = m_maxConcurrency - m_currentConcurrency;
|
| 1114 |
+
|
| 1115 |
+
// Convert remaining concurrency to number of cores
|
| 1116 |
+
unsigned int fullySubscribedConcurrency = m_numFullySubscribedCores * m_targetOversubscriptionFactor;
|
| 1117 |
+
|
| 1118 |
+
if (fullySubscribedConcurrency >= remainingConcurrency)
|
| 1119 |
+
{
|
| 1120 |
+
newCores = remainingConcurrency / m_targetOversubscriptionFactor;
|
| 1121 |
+
}
|
| 1122 |
+
else
|
| 1123 |
+
{
|
| 1124 |
+
ASSERT(m_targetOversubscriptionFactor > 1);
|
| 1125 |
+
newCores = m_numFullySubscribedCores;
|
| 1126 |
+
newCores += ((remainingConcurrency - fullySubscribedConcurrency) / (m_targetOversubscriptionFactor - 1));
|
| 1127 |
+
}
|
| 1128 |
+
}
|
| 1129 |
+
|
| 1130 |
+
unsigned int maxAllocation = (GetNumAllocatedCores() + newCores);
|
| 1131 |
+
|
| 1132 |
+
// Cores used exclusively by external threads are included in numAllocatedCores. As a result
|
| 1133 |
+
// maxAllocation could go above desired.
|
| 1134 |
+
maxAllocation = min(maxAllocation, DesiredHWThreads());
|
| 1135 |
+
|
| 1136 |
+
#if defined(CONCRT_TRACING)
|
| 1137 |
+
if (maxAllocation < suggestedAllocation)
|
| 1138 |
+
{
|
| 1139 |
+
TRACE(CONCRT_TRACE_DYNAMIC_RM, L"Scheduler %d: Allocated: %d, Suggested: %d, Adjusted Suggested: %d",
|
| 1140 |
+
GetId(), GetNumAllocatedCores(), suggestedAllocation, maxAllocation);
|
| 1141 |
+
}
|
| 1142 |
+
#endif
|
| 1143 |
+
|
| 1144 |
+
return min(maxAllocation, suggestedAllocation);
|
| 1145 |
+
}
|
| 1146 |
+
|
| 1147 |
+
SchedulerProxy::~SchedulerProxy()
|
| 1148 |
+
{
|
| 1149 |
+
//
|
| 1150 |
+
// Clean up anything which might be used during the asynchronous delete.
|
| 1151 |
+
//
|
| 1152 |
+
m_pResourceManager->DestroyAllocatedNodeData(m_pAllocatedNodes);
|
| 1153 |
+
delete [] m_pSortedNodeOrder;
|
| 1154 |
+
|
| 1155 |
+
#if defined(CONCRT_TRACING)
|
| 1156 |
+
delete [] m_drmInitialState;
|
| 1157 |
+
#endif
|
| 1158 |
+
//
|
| 1159 |
+
// Release the reference on the Resource manager
|
| 1160 |
+
//
|
| 1161 |
+
m_pResourceManager->Release();
|
| 1162 |
+
}
|
| 1163 |
+
|
| 1164 |
+
/// <summary>
|
| 1165 |
+
/// Called to shutdown a scheduler proxy. Derived classes can override shutdown behavior based on this.
|
| 1166 |
+
/// </summary>
|
| 1167 |
+
void SchedulerProxy::FinalShutdown()
|
| 1168 |
+
{
|
| 1169 |
+
Cleanup();
|
| 1170 |
+
DeleteThis();
|
| 1171 |
+
}
|
| 1172 |
+
|
| 1173 |
+
/// <summary>
|
| 1174 |
+
/// Cleans up resources associated with the scheduler.
|
| 1175 |
+
/// </summary>
|
| 1176 |
+
void SchedulerProxy::Cleanup()
|
| 1177 |
+
{
|
| 1178 |
+
//
|
| 1179 |
+
// Delete vproc roots that exist in the allocated nodes at this time. The deletion here is a notification. It may happen asynchronously
|
| 1180 |
+
// depending on the type of scheduler proxy. The data structures maintained for the scheduler proxy cannot go away until the deferred
|
| 1181 |
+
// deletion happens.
|
| 1182 |
+
//
|
| 1183 |
+
for (unsigned int i = 0; i < m_nodeCount; ++i)
|
| 1184 |
+
{
|
| 1185 |
+
SchedulerNode * pNode = &m_pAllocatedNodes[i];
|
| 1186 |
+
|
| 1187 |
+
for (unsigned int j = 0; j < pNode->m_coreCount; ++j)
|
| 1188 |
+
{
|
| 1189 |
+
ExecutionResource * pExecutionResource = pNode->m_pCores[j].m_resources.First();
|
| 1190 |
+
|
| 1191 |
+
while (pExecutionResource != NULL)
|
| 1192 |
+
{
|
| 1193 |
+
ExecutionResource * pExecutionResourceToDelete = pExecutionResource;
|
| 1194 |
+
pExecutionResource = pNode->m_pCores[j].m_resources.Next(pExecutionResource);
|
| 1195 |
+
VirtualProcessorRoot * pVPRoot = pExecutionResourceToDelete->GetVirtualProcessorRoot();
|
| 1196 |
+
ASSERT(pVPRoot != NULL);
|
| 1197 |
+
|
| 1198 |
+
// Since the root is going away, check if it contributes to the subscription count on the core, and
|
| 1199 |
+
// fix up the count, if so.
|
| 1200 |
+
pVPRoot->ResetSubscriptionLevel();
|
| 1201 |
+
pVPRoot->DeleteThis();
|
| 1202 |
+
}
|
| 1203 |
+
}
|
| 1204 |
+
}
|
| 1205 |
+
|
| 1206 |
+
delete m_pHillClimbing;
|
| 1207 |
+
}
|
| 1208 |
+
|
| 1209 |
+
#if defined(CONCRT_TRACING)
|
| 1210 |
+
|
| 1211 |
+
/// <summary>
|
| 1212 |
+
/// Sets or clears a flag indicating that the RM needs to do an external thread allocation for this
|
| 1213 |
+
/// scheduler proxy.
|
| 1214 |
+
/// </summary>
|
| 1215 |
+
void SchedulerProxy::TraceInitialDRMState()
|
| 1216 |
+
{
|
| 1217 |
+
int traceCoreIndex = 0;
|
| 1218 |
+
for (unsigned int nodeIndex = 0; nodeIndex < m_nodeCount; ++nodeIndex)
|
| 1219 |
+
{
|
| 1220 |
+
SchedulerNode * pAllocatedNode = &m_pAllocatedNodes[nodeIndex];
|
| 1221 |
+
for (unsigned int coreIndex = 0; coreIndex < pAllocatedNode->m_coreCount; ++coreIndex)
|
| 1222 |
+
{
|
| 1223 |
+
SchedulerCore * pAllocatedCore = &pAllocatedNode->m_pCores[coreIndex];
|
| 1224 |
+
SchedulerCoreData * pCoreData = &m_drmInitialState[traceCoreIndex++];
|
| 1225 |
+
pCoreData->m_nodeIndex = (unsigned char)nodeIndex;
|
| 1226 |
+
pCoreData->m_coreIndex = (unsigned char)coreIndex;
|
| 1227 |
+
pCoreData->m_fAllocated = pAllocatedCore->m_coreState == ProcessorCore::Allocated;
|
| 1228 |
+
pCoreData->m_fFixed = pAllocatedCore->IsFixed();
|
| 1229 |
+
pCoreData->m_fBorrowed = pAllocatedCore->IsBorrowed();
|
| 1230 |
+
pCoreData->m_fIdle = pAllocatedCore->IsIdle();
|
| 1231 |
+
}
|
| 1232 |
+
}
|
| 1233 |
+
}
|
| 1234 |
+
|
| 1235 |
+
#endif
|
| 1236 |
+
} // namespace details
|
| 1237 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulerProxy.h
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
#pragma warning(push)
|
| 21 |
+
#pragma warning(disable: 4265) // non-virtual destructor in base class
|
| 22 |
+
class SchedulerProxy : public ::Concurrency::ISchedulerProxy
|
| 23 |
+
{
|
| 24 |
+
public:
|
| 25 |
+
/// <summary>
|
| 26 |
+
/// Constructs a scheduler proxy.
|
| 27 |
+
/// </summary>
|
| 28 |
+
SchedulerProxy(IScheduler * pScheduler, ResourceManager * pResourceManager, const SchedulerPolicy &policy);
|
| 29 |
+
|
| 30 |
+
/// <summary>
|
| 31 |
+
/// Called in order to notify the resource manager that the given scheduler is shutting down. This
|
| 32 |
+
/// will cause the resource manager to immediately reclaim all resources granted to the scheduler.
|
| 33 |
+
/// </summary>
|
| 34 |
+
virtual void Shutdown();
|
| 35 |
+
|
| 36 |
+
/// <summary>
|
| 37 |
+
/// Called by a scheduler in order make an initial request for an allocation of virtual processors. The request
|
| 38 |
+
/// is driven by policies within the scheduler queried via the IScheduler::GetPolicy method. If the request
|
| 39 |
+
/// can be satisfied via the rules of allocation, it is communicated to the scheduler as a call to
|
| 40 |
+
/// IScheduler::AddVirtualProcessors.
|
| 41 |
+
/// </summary>
|
| 42 |
+
/// <param name="doSubscribeCurrentThread">
|
| 43 |
+
/// Whether to subscribe the current thread and account for it during resource allocation.
|
| 44 |
+
/// </param>
|
| 45 |
+
/// <returns>
|
| 46 |
+
/// The IExecutionResource instance representing current thread if doSubscribeCurrentThread was true; NULL otherwise.
|
| 47 |
+
/// </returns>
|
| 48 |
+
virtual IExecutionResource * RequestInitialVirtualProcessors(bool doSubscribeCurrentThread);
|
| 49 |
+
|
| 50 |
+
/// <summary>
|
| 51 |
+
/// Ensures that a context is bound to a thread proxy. This API should *NOT* be called in the vast majority of circumstances.
|
| 52 |
+
/// The IThreadProxy::SwitchTo will perform late binding to thread proxies as necessary. There are, however, circumstances
|
| 53 |
+
/// where it is necessary to pre-bind a context to ensure that the SwitchTo operation switches to an already bound context. This
|
| 54 |
+
/// is the case on a UMS scheduling context as it cannot call allocation APIs.
|
| 55 |
+
/// </summary>
|
| 56 |
+
/// <param name="pContext">
|
| 57 |
+
/// The context to bind.
|
| 58 |
+
/// </param>
|
| 59 |
+
virtual void BindContext(IExecutionContext * pContext);
|
| 60 |
+
|
| 61 |
+
/// <summary>
|
| 62 |
+
/// Returns an **unstarted** thread proxy attached to pContext, to the thread proxy factory.
|
| 63 |
+
/// Such a thread proxy **must** be unstarted.
|
| 64 |
+
/// This API should *NOT* be called in the vast majority of circumstances.
|
| 65 |
+
/// </summary>
|
| 66 |
+
/// <param name="pContext">
|
| 67 |
+
/// The context to unbind.
|
| 68 |
+
/// </param>
|
| 69 |
+
virtual void UnbindContext(IExecutionContext * pContext);
|
| 70 |
+
|
| 71 |
+
/// <summary>
|
| 72 |
+
/// This API registers the current thread with the resource manager associating it with this scheduler,
|
| 73 |
+
/// and returns an instance of IExecutionResource back to the scheduler, for bookkeeping and maintenance.
|
| 74 |
+
/// </summary>
|
| 75 |
+
/// <returns>
|
| 76 |
+
/// The IExecutionResource instance representing current thread in the runtime.
|
| 77 |
+
/// </returns>
|
| 78 |
+
virtual IExecutionResource * SubscribeCurrentThread();
|
| 79 |
+
|
| 80 |
+
/// <summary>
|
| 81 |
+
/// The unique identifier of the scheduler this proxy represents.
|
| 82 |
+
/// </summary>
|
| 83 |
+
unsigned int GetId() const
|
| 84 |
+
{
|
| 85 |
+
return m_id;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/// <summary>
|
| 89 |
+
/// Causes the resource manager to create a new virtual processor root running atop the same hardware thread as this
|
| 90 |
+
/// execution resource. Typically, this is used when a scheduler wishes to oversubscribe a particular hardware thread
|
| 91 |
+
/// for a limited amount of time.
|
| 92 |
+
/// </summary>
|
| 93 |
+
/// <param name="pExecutionResource">
|
| 94 |
+
/// The execution resource abstraction on which to oversubscribe.
|
| 95 |
+
/// </param>
|
| 96 |
+
/// <returns>
|
| 97 |
+
/// A new virtual processor root running atop the same hardware thread as this execution resource.
|
| 98 |
+
/// </returns>
|
| 99 |
+
virtual IVirtualProcessorRoot * CreateOversubscriber(IExecutionResource * pExecutionResource);
|
| 100 |
+
|
| 101 |
+
/// <summary>
|
| 102 |
+
/// Getters for the various policy elements.
|
| 103 |
+
/// </summary>
|
| 104 |
+
unsigned int MaxConcurrency() const
|
| 105 |
+
{
|
| 106 |
+
return m_maxConcurrency;
|
| 107 |
+
}
|
| 108 |
+
unsigned int MinConcurrency() const
|
| 109 |
+
{
|
| 110 |
+
return m_minConcurrency;
|
| 111 |
+
}
|
| 112 |
+
unsigned int TargetOversubscriptionFactor() const
|
| 113 |
+
{
|
| 114 |
+
return m_targetOversubscriptionFactor;
|
| 115 |
+
}
|
| 116 |
+
int ContextStackSize () const
|
| 117 |
+
{
|
| 118 |
+
return m_contextStackSize;
|
| 119 |
+
}
|
| 120 |
+
int ContextPriority () const
|
| 121 |
+
{
|
| 122 |
+
return m_contextPriority;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/// <summary>
|
| 126 |
+
/// Returns the minimum number of cores that must contain vprocs for this scheduler. These cores
|
| 127 |
+
/// may contain a subscribed thread in addition to virtual processors.
|
| 128 |
+
/// </summary>
|
| 129 |
+
unsigned int MinVprocHWThreads() const
|
| 130 |
+
{
|
| 131 |
+
// Compute number of cores used for virtual processors that are fixed
|
| 132 |
+
ASSERT(m_numFixedCores >= m_numExternalThreadCores);
|
| 133 |
+
unsigned int fixedVprocCores = m_numFixedCores - m_numExternalThreadCores;
|
| 134 |
+
// Compute maximum(t1, minimum set by policy) which is minimum of virtual processor cores
|
| 135 |
+
return max(fixedVprocCores, m_minimumHardwareThreads);
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
unsigned int MinHWThreads() const
|
| 139 |
+
{
|
| 140 |
+
// The minimum needed number of hardware threads (cores) is equal to:
|
| 141 |
+
// - minimum needed vproc cores + minimum needed external thread cores
|
| 142 |
+
unsigned int minimumCores = MinVprocHWThreads() + m_numExternalThreadCores;
|
| 143 |
+
|
| 144 |
+
ASSERT(minimumCores <= m_coreCount);
|
| 145 |
+
return minimumCores;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
unsigned int DesiredHWThreads() const
|
| 149 |
+
{
|
| 150 |
+
unsigned int desiredCores = min(m_coreCount, m_desiredHardwareThreads + m_numExternalThreadCores);
|
| 151 |
+
|
| 152 |
+
ASSERT(m_numExternalThreads != 0 || desiredCores == m_desiredHardwareThreads);
|
| 153 |
+
return desiredCores;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
unsigned int ComputeMinHWThreadsWithExternalThread() const
|
| 157 |
+
{
|
| 158 |
+
unsigned int newMin = min(m_coreCount, MinHWThreads() + 1);
|
| 159 |
+
return newMin;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
unsigned int ComputeDesiredHWThreadsWithExternalThread() const
|
| 163 |
+
{
|
| 164 |
+
unsigned int newDesired = min(m_coreCount, DesiredHWThreads() + 1);
|
| 165 |
+
return newDesired;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
/// <summary>
|
| 169 |
+
/// Returns the number of external thread subscriptions
|
| 170 |
+
/// </summary>
|
| 171 |
+
unsigned int GetNumNestedThreadSubscriptions()
|
| 172 |
+
{
|
| 173 |
+
return m_threadSubscriptions.Count();
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
/// <summary>
|
| 177 |
+
/// Called to adjust the suggested allocation such that we do not exceed maxConcurrency.
|
| 178 |
+
/// This routine takes into account vprocs that are marked for removal but haven't yet been
|
| 179 |
+
/// retired by the scheduler. The suggested allocation would be decreased to account for such
|
| 180 |
+
/// vprocs.
|
| 181 |
+
/// </summary>
|
| 182 |
+
unsigned int AdjustAllocationIncrease(unsigned int suggestedAllocation) const;
|
| 183 |
+
|
| 184 |
+
/// <summary>
|
| 185 |
+
/// Returns the number of cores allocated to the proxy at any time.
|
| 186 |
+
/// </summary>
|
| 187 |
+
unsigned int GetNumAllocatedCores() const
|
| 188 |
+
{
|
| 189 |
+
return m_numAllocatedCores;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
/// <summary>
|
| 193 |
+
/// Returns the number of borrowed cores. These are cores that were oversubscribed and temporarily
|
| 194 |
+
/// assigned to this scheduler during dynamic core migration as they were found to be unused
|
| 195 |
+
/// by the other scheduler(s) they were assigned to. The reason these cores were oversubscribed
|
| 196 |
+
/// instead of migrated was that they contributed to the minimum number of cores on the other
|
| 197 |
+
/// scheduler(s) and hence couldn't be taken away.
|
| 198 |
+
/// </summary>
|
| 199 |
+
unsigned int GetNumBorrowedCores() const
|
| 200 |
+
{
|
| 201 |
+
return m_numBorrowedCores;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
/// <summary>
|
| 205 |
+
/// Returns the number of owned cores. This is the total allocated cores minus the borrowed cores.
|
| 206 |
+
/// </summary>
|
| 207 |
+
unsigned int GetNumOwnedCores() const
|
| 208 |
+
{
|
| 209 |
+
return m_numAllocatedCores - m_numBorrowedCores;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
/// <summary>
|
| 213 |
+
/// Returns the number of fixed cores - cores that have a subscribed thread on them. These cores may
|
| 214 |
+
/// also have vprocs belonging to this scheduler.
|
| 215 |
+
/// </summary>
|
| 216 |
+
unsigned int GetNumFixedCores() const
|
| 217 |
+
{
|
| 218 |
+
return m_numFixedCores;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
/// <summary>
|
| 222 |
+
/// Toggles the state on a core from borrowed to owned (and vice versa), and updates necessary counts.
|
| 223 |
+
/// </summary>
|
| 224 |
+
void ToggleBorrowedState(SchedulerNode * pNode, unsigned int coreIndex);
|
| 225 |
+
|
| 226 |
+
/// <summary>
|
| 227 |
+
/// Creates a new execution resource for the external thread and registers it with the scheduler proxy.
|
| 228 |
+
/// </summary>
|
| 229 |
+
ExecutionResource * CreateExternalThreadResource(SchedulerNode * pNode, unsigned int coreIndex);
|
| 230 |
+
|
| 231 |
+
/// <summary>
|
| 232 |
+
/// Called by the RM when it is done reserving cores for the scheduler proxy. The scheduler proxy
|
| 233 |
+
/// allocates virtual processors or standalone execution resources based on the cores that were allocated
|
| 234 |
+
/// to it.
|
| 235 |
+
/// </summary>
|
| 236 |
+
ExecutionResource * GrantAllocation(unsigned int numberReserved, bool fInitialAllocation, bool fSubscribeCurrentThread);
|
| 237 |
+
|
| 238 |
+
/// <summary>
|
| 239 |
+
/// Finds the core allocated by the RM on which a single subscribed external thread should run.
|
| 240 |
+
/// </summary>
|
| 241 |
+
ExecutionResource * GrantExternalThreadAllocation(bool doOversubscribeCore);
|
| 242 |
+
|
| 243 |
+
/// <summary>
|
| 244 |
+
/// Returns a pointer to the copy of allocated nodes that were assigned to the proxy at
|
| 245 |
+
/// creation time.
|
| 246 |
+
/// </summary>
|
| 247 |
+
SchedulerNode * GetAllocatedNodes() const
|
| 248 |
+
{
|
| 249 |
+
return m_pAllocatedNodes;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
/// <summary>
|
| 253 |
+
/// Sets the allocated nodes for the scheduler proxy to the nodes provided.
|
| 254 |
+
/// </summary>
|
| 255 |
+
void SetAllocatedNodes(SchedulerNode * pNodes)
|
| 256 |
+
{
|
| 257 |
+
ASSERT(m_pAllocatedNodes == NULL && pNodes != NULL);
|
| 258 |
+
m_pAllocatedNodes = pNodes;
|
| 259 |
+
}
|
| 260 |
+
/// <summary>
|
| 261 |
+
/// Returns a pointer to the array that holds the sorted order for nodes. This is used by the
|
| 262 |
+
/// RM to sort nodes by whatever criteria it chooses.
|
| 263 |
+
/// </summary>
|
| 264 |
+
unsigned int * GetSortedNodeOrder() const
|
| 265 |
+
{
|
| 266 |
+
return m_pSortedNodeOrder;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
/// <summary>
|
| 270 |
+
/// Returns a pointer to the scheduler associated with the scheduler proxy.
|
| 271 |
+
/// </summary>
|
| 272 |
+
IScheduler * Scheduler() const
|
| 273 |
+
{
|
| 274 |
+
return m_pScheduler;
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
/// <summary>
|
| 278 |
+
/// Returns a pointer to the resource manager associated with the scheduler proxy.
|
| 279 |
+
/// </summary>
|
| 280 |
+
ResourceManager * GetResourceManager() const
|
| 281 |
+
{
|
| 282 |
+
return m_pResourceManager;
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
/// <summary>
|
| 286 |
+
/// Returns a pointer to a data buffer that is used to store static allocation data. The data
|
| 287 |
+
/// is populated and manipulated by the RM, but stored in the scheduler proxy for convenience.
|
| 288 |
+
/// </summary>
|
| 289 |
+
StaticAllocationData * GetStaticAllocationData()
|
| 290 |
+
{
|
| 291 |
+
return &m_staticData;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
/// <summary>
|
| 295 |
+
/// Returns a pointer to a data buffer that is used to store dynamic allocation data. The data
|
| 296 |
+
/// is populated and manipulated by the RM, but stored in the scheduler proxy for convenience.
|
| 297 |
+
/// </summary>
|
| 298 |
+
DynamicAllocationData * GetDynamicAllocationData()
|
| 299 |
+
{
|
| 300 |
+
return &m_dynamicData;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
/// <summary>
|
| 304 |
+
/// Creates a virtual processor root and adds it to the scheduler proxys list of roots.
|
| 305 |
+
/// </summary>
|
| 306 |
+
virtual VirtualProcessorRoot * CreateVirtualProcessorRoot(SchedulerNode * pNode, unsigned int coreIndex);
|
| 307 |
+
|
| 308 |
+
/// <summary>
|
| 309 |
+
/// Notifies the scheduler associated with this proxy to add the virtual processor roots provided.
|
| 310 |
+
/// Called by the RM during initial allocation and dynamic core migration.
|
| 311 |
+
/// </summary>
|
| 312 |
+
void AddVirtualProcessorRoots(IVirtualProcessorRoot ** vprocRoots, unsigned int count);
|
| 313 |
+
|
| 314 |
+
/// <summary>
|
| 315 |
+
/// Adds an appropriate number of virtual processor roots to the scheduler associated with this proxy.
|
| 316 |
+
/// Called by the RM during core migration when the RM decides to give this scheduler an additional
|
| 317 |
+
/// core.
|
| 318 |
+
/// </summary>
|
| 319 |
+
void AddCore(SchedulerNode * pNode, unsigned int coreIndex, bool fBorrowed);
|
| 320 |
+
|
| 321 |
+
/// <summary>
|
| 322 |
+
/// Notifies the scheduler associated with this proxy to remove the virtual processor roots associated
|
| 323 |
+
/// with the core provided. Called by the RM during core migration.
|
| 324 |
+
/// </summary>
|
| 325 |
+
void RemoveCore(SchedulerNode * pNode, unsigned int coreIndex);
|
| 326 |
+
|
| 327 |
+
/// <summary>
|
| 328 |
+
/// Called by the RM to instruct this scheduler proxy to notify its scheduler that this core is now
|
| 329 |
+
/// externally busy or externally idle.
|
| 330 |
+
/// </summary>
|
| 331 |
+
void SendCoreNotification(SchedulerCore * pCore, bool isBusyNotification);
|
| 332 |
+
|
| 333 |
+
/// <summary>
|
| 334 |
+
/// Removes a root from the scheduler proxy and destroys it. This API is called in response to a scheduler
|
| 335 |
+
/// informing the RM that it is done with a virtual processor root.
|
| 336 |
+
/// </summary>
|
| 337 |
+
void DestroyVirtualProcessorRoot(VirtualProcessorRoot * pRoot);
|
| 338 |
+
|
| 339 |
+
/// <summary>
|
| 340 |
+
/// Removes an execution resource from the scheduler proxy and destroys it. This API is called in response to a scheduler
|
| 341 |
+
/// informing the RM that it is done with an execution resource.
|
| 342 |
+
/// </summary>
|
| 343 |
+
void DestroyExecutionResource(ExecutionResource * pExecutionResource);
|
| 344 |
+
|
| 345 |
+
/// <summary>
|
| 346 |
+
/// Returns a hardware affinity for the given node. Note that a scheduler proxy may only be assigned a subset
|
| 347 |
+
/// of cores within a node -> the mask in the affinity reflects this subset.
|
| 348 |
+
/// </summary>
|
| 349 |
+
/// <returns>
|
| 350 |
+
/// An abstraction of the hardware affinity which can be applied to Win32 objects.
|
| 351 |
+
/// </returns>
|
| 352 |
+
HardwareAffinity GetNodeAffinity(unsigned int nodeId)
|
| 353 |
+
{
|
| 354 |
+
ASSERT(nodeId < m_nodeCount);
|
| 355 |
+
ASSERT(m_pAllocatedNodes[nodeId].m_id == nodeId);
|
| 356 |
+
|
| 357 |
+
return HardwareAffinity(static_cast<USHORT>(m_pAllocatedNodes[nodeId].m_processorGroup), m_pAllocatedNodes[nodeId].m_nodeAffinity);
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
/// <summary>
|
| 361 |
+
/// Adds an execution resource to the list of resources that run on a particular core.
|
| 362 |
+
/// </summary>
|
| 363 |
+
void AddExecutionResource(ExecutionResource * pExecutionResource);
|
| 364 |
+
|
| 365 |
+
/// <summary>
|
| 366 |
+
/// Adds the execution resource to the list of subscribed threads
|
| 367 |
+
/// </summary>
|
| 368 |
+
void AddThreadSubscription(ExecutionResource * pExecutionResource);
|
| 369 |
+
|
| 370 |
+
/// <summary>
|
| 371 |
+
/// Removes the execution resource from the list of subscribed threads
|
| 372 |
+
/// </summary>
|
| 373 |
+
void RemoveThreadSubscription(ExecutionResource * pExecutionResource);
|
| 374 |
+
|
| 375 |
+
/// <summary>
|
| 376 |
+
/// Creates or reuses an execution resource for the thread subscription
|
| 377 |
+
/// </summary>
|
| 378 |
+
ExecutionResource * GetResourceForNewSubscription(ExecutionResource * pParentExecutionResource);
|
| 379 |
+
|
| 380 |
+
/// <summary>
|
| 381 |
+
/// This function retrieves the execution resource associated with this thread, if one exists,
|
| 382 |
+
/// and updates the reference count on it for better bookkeeping.
|
| 383 |
+
/// </summary>
|
| 384 |
+
/// <returns>
|
| 385 |
+
/// The ExecutionResource instance representing current thread in the runtime.
|
| 386 |
+
/// </returns>
|
| 387 |
+
ExecutionResource * ReferenceCurrentThreadExecutionResource();
|
| 388 |
+
|
| 389 |
+
/// <summary>
|
| 390 |
+
/// This function retrieves the execution resource associated with this thread, if one exists.
|
| 391 |
+
/// </summary>
|
| 392 |
+
/// <returns>
|
| 393 |
+
/// The ExecutionResource instance representing current thread in the runtime.
|
| 394 |
+
/// </returns>
|
| 395 |
+
ExecutionResource * GetCurrentThreadExecutionResource();
|
| 396 |
+
|
| 397 |
+
/// <summary>
|
| 398 |
+
/// Registers that a call to SubscribeCurrentThread has occurred for this core, making this core immovable.
|
| 399 |
+
/// </summary>
|
| 400 |
+
void IncrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread);
|
| 401 |
+
|
| 402 |
+
/// <summary>
|
| 403 |
+
/// Registers that a call to IExecutionResource::Release has occurred, potentially freeing this core.
|
| 404 |
+
/// </summary>
|
| 405 |
+
void DecrementFixedCoreCount(unsigned int nodeId, unsigned int coreIndex, bool isExternalThread);
|
| 406 |
+
|
| 407 |
+
/// <summary>
|
| 408 |
+
/// Returns the number of external threads on this scheduler proxy.
|
| 409 |
+
/// </summary>
|
| 410 |
+
unsigned int GetNumExternalThreads()
|
| 411 |
+
{
|
| 412 |
+
return m_numExternalThreads;
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/// <summary>
|
| 416 |
+
/// Decides whether this scheduler proxy should receive notifications when other
|
| 417 |
+
/// schedulers borrow its cores or return them back.
|
| 418 |
+
/// </summary>
|
| 419 |
+
bool ShouldReceiveNotifications()
|
| 420 |
+
{
|
| 421 |
+
return (m_minimumHardwareThreads == m_desiredHardwareThreads);
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
/// <summary>
|
| 425 |
+
/// A function that passes statistical information to the hill climbing instance. Based on these
|
| 426 |
+
/// statistics, hill climbing will make a recommendation on the number of resources the scheduler
|
| 427 |
+
/// should be allocated.
|
| 428 |
+
/// </summary>
|
| 429 |
+
/// <param name="currentCoreCount">
|
| 430 |
+
/// The number of resources used in this period of time.
|
| 431 |
+
/// </param>
|
| 432 |
+
/// <param name="completionRate">
|
| 433 |
+
/// The number of completed units or work in that period of time.
|
| 434 |
+
/// </param>
|
| 435 |
+
/// <param name="arrivalRate">
|
| 436 |
+
/// The number of incoming units or work in that period of time.
|
| 437 |
+
/// </param>
|
| 438 |
+
/// <param name="queueLength">
|
| 439 |
+
/// The total length of the work queue.
|
| 440 |
+
/// </param>
|
| 441 |
+
/// <returns>
|
| 442 |
+
/// The recommended allocation for the scheduler.
|
| 443 |
+
/// </returns>
|
| 444 |
+
unsigned int DoHillClimbing(unsigned int currentCoreCount, unsigned int completionRate, unsigned int arrivalRate, unsigned int queueLength)
|
| 445 |
+
{
|
| 446 |
+
return m_pHillClimbing->Update(currentCoreCount, completionRate, arrivalRate, queueLength);
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
/// <summary>
|
| 450 |
+
/// This function returns whether the scheduler has opted in to statistical rebalancing.
|
| 451 |
+
/// </summary>
|
| 452 |
+
/// <returns>
|
| 453 |
+
/// Whether hill climbing is enabled.
|
| 454 |
+
/// </returns>
|
| 455 |
+
bool IsHillClimbingEnabled()
|
| 456 |
+
{
|
| 457 |
+
return m_fDoHillClimbing;
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
/// <summary>
|
| 461 |
+
/// Gets the current length of the scheduler queue.
|
| 462 |
+
/// </summary>
|
| 463 |
+
/// <returns>
|
| 464 |
+
/// The queue length.
|
| 465 |
+
/// </returns>
|
| 466 |
+
unsigned int GetQueueLength()
|
| 467 |
+
{
|
| 468 |
+
return m_queueLength;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
/// <summary>
|
| 472 |
+
/// Sets the current length of the scheduler queue.
|
| 473 |
+
/// </summary>
|
| 474 |
+
/// <param name="queueLength">
|
| 475 |
+
/// The length to be set.
|
| 476 |
+
/// </param>
|
| 477 |
+
void SetQueueLength(unsigned int queueLength)
|
| 478 |
+
{
|
| 479 |
+
m_queueLength = queueLength;
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
/// <summary>
|
| 483 |
+
/// Gets a new thread proxy from the factory.
|
| 484 |
+
/// </summary>
|
| 485 |
+
virtual IThreadProxy * GetNewThreadProxy(IExecutionContext * pContext);
|
| 486 |
+
|
| 487 |
+
/// <summary>
|
| 488 |
+
/// Called to shutdown a scheduler proxy. Derived classes can override shutdown behavior based on this.
|
| 489 |
+
/// </summary>
|
| 490 |
+
virtual void FinalShutdown();
|
| 491 |
+
|
| 492 |
+
/// <summary>
|
| 493 |
+
/// Called to assist dynamic resource management in determining whether cores assigned to schedulers
|
| 494 |
+
/// are idle. An idle core is one whose subscription level is 0.
|
| 495 |
+
/// </summary>
|
| 496 |
+
void IncrementCoreSubscription(ExecutionResource * pExecutionResource);
|
| 497 |
+
|
| 498 |
+
/// <summary>
|
| 499 |
+
/// Called to assist dynamic resource management in determining whether cores assigned to schedulers
|
| 500 |
+
/// are idle. An idle core is one whose subscription level is 0.
|
| 501 |
+
/// </summary>
|
| 502 |
+
void DecrementCoreSubscription(ExecutionResource * pExecutionResource);
|
| 503 |
+
|
| 504 |
+
#if defined(CONCRT_TRACING)
|
| 505 |
+
/// <summary>
|
| 506 |
+
/// Captures the initial state of the scheduler map at the beginning of core migration, each cycle.
|
| 507 |
+
/// </summary>
|
| 508 |
+
void TraceInitialDRMState();
|
| 509 |
+
#endif
|
| 510 |
+
|
| 511 |
+
protected:
|
| 512 |
+
|
| 513 |
+
/// <summary>
|
| 514 |
+
/// Deletes the scheduler proxy.
|
| 515 |
+
/// </summary>
|
| 516 |
+
virtual void DeleteThis()
|
| 517 |
+
{
|
| 518 |
+
delete this;
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
/// <summary>
|
| 522 |
+
/// Cleans up resources associated with the scheduler.
|
| 523 |
+
/// </summary>
|
| 524 |
+
void Cleanup();
|
| 525 |
+
|
| 526 |
+
/// <summary>
|
| 527 |
+
/// Destructor.
|
| 528 |
+
/// </summary>
|
| 529 |
+
~SchedulerProxy();
|
| 530 |
+
|
| 531 |
+
// A cached pointer to a thread proxy factory of the appropriate type for this scheduler proxy.
|
| 532 |
+
IThreadProxyFactory * m_pThreadProxyFactory;
|
| 533 |
+
|
| 534 |
+
private:
|
| 535 |
+
template <class T, class Counter> friend class List;
|
| 536 |
+
|
| 537 |
+
#if defined(CONCRT_TRACING)
|
| 538 |
+
|
| 539 |
+
struct SchedulerCoreData
|
| 540 |
+
{
|
| 541 |
+
unsigned char m_nodeIndex;
|
| 542 |
+
unsigned char m_coreIndex;
|
| 543 |
+
bool m_fAllocated : 1;
|
| 544 |
+
bool m_fFixed : 1;
|
| 545 |
+
bool m_fBorrowed : 1;
|
| 546 |
+
bool m_fIdle : 1;
|
| 547 |
+
};
|
| 548 |
+
|
| 549 |
+
// Captures the initial global allocation during the DRM phase.
|
| 550 |
+
SchedulerCoreData * m_drmInitialState;
|
| 551 |
+
unsigned int m_numTotalCores;
|
| 552 |
+
|
| 553 |
+
#endif
|
| 554 |
+
IScheduler * m_pScheduler;
|
| 555 |
+
|
| 556 |
+
// Pointer to the resource manager instance.
|
| 557 |
+
ResourceManager * m_pResourceManager;
|
| 558 |
+
|
| 559 |
+
// Local copy of allocation map for this scheduler proxy.
|
| 560 |
+
SchedulerNode * m_pAllocatedNodes;
|
| 561 |
+
|
| 562 |
+
// Helper array used to sort nodes, used by the RM during core migration.
|
| 563 |
+
unsigned int * m_pSortedNodeOrder;
|
| 564 |
+
|
| 565 |
+
// Links for a list.
|
| 566 |
+
SchedulerProxy * m_pNext{}, * m_pPrev{};
|
| 567 |
+
|
| 568 |
+
// A lock that protects resource allocation and deallocation of roots within this proxy.
|
| 569 |
+
_ReentrantBlockingLock m_lock;
|
| 570 |
+
|
| 571 |
+
// Hill climbing instance.
|
| 572 |
+
HillClimbing * m_pHillClimbing;
|
| 573 |
+
|
| 574 |
+
// Static and dynamic allocation data is populated and manipulated by the RM, but
|
| 575 |
+
// stored in the scheduler proxy for convenience.
|
| 576 |
+
union
|
| 577 |
+
{
|
| 578 |
+
// Data used during static allocation.
|
| 579 |
+
StaticAllocationData m_staticData;
|
| 580 |
+
|
| 581 |
+
// Data used during dynamic allocation.
|
| 582 |
+
DynamicAllocationData m_dynamicData;
|
| 583 |
+
};
|
| 584 |
+
|
| 585 |
+
// Scheduler queue length.
|
| 586 |
+
unsigned int m_queueLength;
|
| 587 |
+
|
| 588 |
+
// Unique identifier.
|
| 589 |
+
unsigned int m_id;
|
| 590 |
+
|
| 591 |
+
// Variables that store policy elements.
|
| 592 |
+
unsigned int m_desiredHardwareThreads;
|
| 593 |
+
unsigned int m_minimumHardwareThreads;
|
| 594 |
+
unsigned int m_minConcurrency;
|
| 595 |
+
unsigned int m_maxConcurrency;
|
| 596 |
+
unsigned int m_targetOversubscriptionFactor;
|
| 597 |
+
int m_contextStackSize;
|
| 598 |
+
int m_contextPriority;
|
| 599 |
+
|
| 600 |
+
// Current concurrency level (number of vproc roots). This includes vproc roots
|
| 601 |
+
// that are marked for removal but has not yet been destroyed by the scheduler.
|
| 602 |
+
// Protected by the scheduler proxy lock
|
| 603 |
+
unsigned int m_currentConcurrency;
|
| 604 |
+
|
| 605 |
+
// The number of cores allocated to this scheduler proxy.
|
| 606 |
+
unsigned int m_numAllocatedCores;
|
| 607 |
+
|
| 608 |
+
// At any time this has the number of additional cores that can be allocated with m_tof threads.
|
| 609 |
+
// When this falls to 0, all remaining allocated cores will get m_tof - 1 threads, to ensure that
|
| 610 |
+
// we don't go over max concurrency threads.
|
| 611 |
+
unsigned int m_numFullySubscribedCores;
|
| 612 |
+
|
| 613 |
+
// The number of allocated cores that are borrowed. An borrowed core is a core that is assigned to
|
| 614 |
+
// one or more different schedulers, but was found to be idle. The RM temporarily assigns idle resources to
|
| 615 |
+
// schedulers that need them.
|
| 616 |
+
unsigned int m_numBorrowedCores;
|
| 617 |
+
|
| 618 |
+
// The number of cores that have a subscribed thread on them. These cores are 'fixed' in that they cannot
|
| 619 |
+
// be removed by static/dynamic allocations, as long as the subscribed thread is present on them.
|
| 620 |
+
unsigned int m_numFixedCores;
|
| 621 |
+
|
| 622 |
+
// The number of virtual processors (threads) that were added to the related scheduler via initial
|
| 623 |
+
// allocation or core migration. Does not include oversubscribed virtual processors.
|
| 624 |
+
unsigned int m_numAssignedThreads;
|
| 625 |
+
|
| 626 |
+
// The number of external threads that were added to the related scheduler via external subscription calls.
|
| 627 |
+
unsigned int m_numExternalThreads;
|
| 628 |
+
|
| 629 |
+
// The number of cores that external threads occupy exclusively.
|
| 630 |
+
unsigned int m_numExternalThreadCores;
|
| 631 |
+
|
| 632 |
+
// The number of hardware threads available on this machine.
|
| 633 |
+
unsigned int m_coreCount;
|
| 634 |
+
|
| 635 |
+
// Number of nodes in the allocated nodes array.
|
| 636 |
+
unsigned int m_nodeCount;
|
| 637 |
+
|
| 638 |
+
// List of execution resources representing subscribed threads
|
| 639 |
+
List<ExecutionResource, CollectionTypes::Count> m_threadSubscriptions;
|
| 640 |
+
|
| 641 |
+
// Used to determine whether statistical rebalancing is used for this scheduler proxy.
|
| 642 |
+
bool m_fDoHillClimbing;
|
| 643 |
+
};
|
| 644 |
+
|
| 645 |
+
#pragma warning(pop)
|
| 646 |
+
} // namespace details
|
| 647 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.cpp
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulingNode.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the SchedulingNode implementation.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
SchedulingNode::SchedulingNode(const QuickBitSet& resourceSet, DWORD numaNodeNumber, SchedulingRing *pRing)
|
| 21 |
+
: m_pRing(pRing)
|
| 22 |
+
, m_resourceSet(resourceSet)
|
| 23 |
+
, m_virtualProcessorAvailableCount(0)
|
| 24 |
+
, m_virtualProcessorsPendingThreadCreate(0)
|
| 25 |
+
, m_virtualProcessorCount(0) // needed for scheduling rings
|
| 26 |
+
, m_ramblingCount(0)
|
| 27 |
+
, m_numaNodeNumber(numaNodeNumber)
|
| 28 |
+
, m_virtualProcessors(pRing->m_pScheduler, 256, ListArray<VirtualProcessor>::DeletionThresholdInfinite)
|
| 29 |
+
{
|
| 30 |
+
m_pScheduler = m_pRing->m_pScheduler;
|
| 31 |
+
m_id = m_pRing->Id();
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
SchedulingNode::~SchedulingNode()
|
| 35 |
+
{
|
| 36 |
+
Cleanup();
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
void SchedulingNode::Cleanup()
|
| 40 |
+
{
|
| 41 |
+
//
|
| 42 |
+
// Do not clean up m_pRing here, it is done at SchedulerBase::m_rings
|
| 43 |
+
//
|
| 44 |
+
|
| 45 |
+
// Cleanup of the virtual processors does not need to explicitly happen. When
|
| 46 |
+
// the destructor of the list array is called, it will internally delete
|
| 47 |
+
// all of its elements
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/// <summary>
|
| 51 |
+
/// Creates and adds a new virtual processor in the node to associated with the root provided.
|
| 52 |
+
/// NOTE: For non-oversubscribed vprocs this API is currently will only work for initial allocation.
|
| 53 |
+
/// </summary>
|
| 54 |
+
/// <param name="pOwningRoot">
|
| 55 |
+
/// The virtual processor root to create the virtual processor with.
|
| 56 |
+
/// </param>
|
| 57 |
+
/// <param name="fOversubscribed">
|
| 58 |
+
/// True if this is an oversubscribed virtual processor.
|
| 59 |
+
/// </param>
|
| 60 |
+
/// <returns>
|
| 61 |
+
/// The newly created virtual processor.
|
| 62 |
+
/// </returns>
|
| 63 |
+
VirtualProcessor* SchedulingNode::AddVirtualProcessor(IVirtualProcessorRoot *pOwningRoot, bool fOversubscribed)
|
| 64 |
+
{
|
| 65 |
+
ContextBase *pCurrentContext = SchedulerBase::FastCurrentContext();
|
| 66 |
+
|
| 67 |
+
// Try and grab a virtual processor from the free pool before creating a new one
|
| 68 |
+
VirtualProcessor *pVirtualProcessor = m_virtualProcessors.PullFromFreePool();
|
| 69 |
+
if (pVirtualProcessor == NULL)
|
| 70 |
+
{
|
| 71 |
+
pVirtualProcessor = m_pScheduler->CreateVirtualProcessor(this, pOwningRoot);
|
| 72 |
+
}
|
| 73 |
+
else
|
| 74 |
+
{
|
| 75 |
+
pVirtualProcessor->Initialize(this, pOwningRoot);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
if (fOversubscribed)
|
| 79 |
+
{
|
| 80 |
+
ASSERT(pCurrentContext != NULL && !pCurrentContext->IsExternal());
|
| 81 |
+
InternalContextBase * pOversubscribingContext = static_cast<InternalContextBase *>(pCurrentContext);
|
| 82 |
+
|
| 83 |
+
pVirtualProcessor->m_fOversubscribed = true;
|
| 84 |
+
pVirtualProcessor->m_pOversubscribingContext = pOversubscribingContext;
|
| 85 |
+
|
| 86 |
+
// The oversubscribed vproc is fenced by adding it to the list array below.
|
| 87 |
+
pOversubscribingContext ->SetOversubscribedVProc(pVirtualProcessor);
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// We increment the total count of virtual processors on the node since the rambling logic uses this count.
|
| 91 |
+
InterlockedIncrement(&m_virtualProcessorCount);
|
| 92 |
+
m_pScheduler->IncrementActiveResourcesByMask(pVirtualProcessor->GetMaskId());
|
| 93 |
+
|
| 94 |
+
// If no virtual processors are 'available' in the scheduler, try to start this one up right away, if not, make it available,
|
| 95 |
+
// and increment the counts to indicate this. The only exception is the first virtual processor added as part of the initial
|
| 96 |
+
// set of virtual processors.
|
| 97 |
+
//
|
| 98 |
+
// @TODO: Q: Is the lack of relative atomicity between the two counts (avail / pending thread) a problem here for any real
|
| 99 |
+
// scenario?
|
| 100 |
+
if ((m_pScheduler->m_virtualProcessorAvailableCount == m_pScheduler->m_virtualProcessorsPendingThreadCreate) && (m_pScheduler->m_virtualProcessorCount > 0))
|
| 101 |
+
{
|
| 102 |
+
//
|
| 103 |
+
// The check above is not accurate, since the count may increase right after the check -> in the worst case, the virtual
|
| 104 |
+
// processor is activated when it should've been left available.
|
| 105 |
+
//
|
| 106 |
+
// We should only be activating virtual processors as they are added, if they are either oversubscribed or as a result
|
| 107 |
+
// of core migration. The initial set of virtual processors should never be activated here.
|
| 108 |
+
//
|
| 109 |
+
ASSERT(pCurrentContext == NULL || fOversubscribed);
|
| 110 |
+
|
| 111 |
+
//
|
| 112 |
+
// The vproc should be added to the list array only after it is fully initialized. If this is an oversubscribed vproc,
|
| 113 |
+
// we need to synchronize with a concurrent RemoveCore, which assumes it can party on the vproc if it is found in the list
|
| 114 |
+
// array.
|
| 115 |
+
//
|
| 116 |
+
m_virtualProcessors.Add(pVirtualProcessor);
|
| 117 |
+
|
| 118 |
+
//
|
| 119 |
+
// Activation of a virtual processor synchronizes with finalization. If the scheduler is in the middle of finalization
|
| 120 |
+
// or has already shutdown, the API will return false.
|
| 121 |
+
//
|
| 122 |
+
bool activated = m_pScheduler->VirtualProcessorActive(true);
|
| 123 |
+
|
| 124 |
+
if (activated)
|
| 125 |
+
{
|
| 126 |
+
ScheduleGroupSegmentBase * pSegment = (pCurrentContext != NULL) ?
|
| 127 |
+
pCurrentContext->GetScheduleGroupSegment() :
|
| 128 |
+
m_pRing->GetAnonymousScheduleGroupSegment();
|
| 129 |
+
pVirtualProcessor->StartupWorkerContext(pSegment);
|
| 130 |
+
}
|
| 131 |
+
else
|
| 132 |
+
{
|
| 133 |
+
//
|
| 134 |
+
// We do nothing here since the scheduler is shutting down/has shutdown. The virtual processor remains unavailable,
|
| 135 |
+
// and since we didn't increment available counts, we don't have to decrement them.
|
| 136 |
+
//
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
else
|
| 140 |
+
{
|
| 141 |
+
//
|
| 142 |
+
// The vproc should be added to the list array only after it is fully initialized. If this is an oversubscribed vproc,
|
| 143 |
+
// we need to synchronize with a concurrent RemoveVirtualProcessor, which assumes it can party on the vproc if it is
|
| 144 |
+
// found in the list array.
|
| 145 |
+
//
|
| 146 |
+
m_virtualProcessors.Add(pVirtualProcessor);
|
| 147 |
+
pVirtualProcessor->MakeAvailable(VirtualProcessor::AvailabilityInactive, false);
|
| 148 |
+
|
| 149 |
+
OMTRACE(MTRACE_EVT_MADEAVAILABLE, m_pScheduler, SchedulerBase::FastCurrentContext(), pVirtualProcessor, NULL);
|
| 150 |
+
OMTRACE(MTRACE_EVT_AVAILABLEVPROCS, m_pScheduler, SchedulerBase::FastCurrentContext(), this, m_pScheduler->m_virtualProcessorAvailableCount);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
return pVirtualProcessor;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
/// <summary>
|
| 157 |
+
/// Find the virtual processor in this node that matches the root provided.
|
| 158 |
+
/// </summary>
|
| 159 |
+
/// <param name="pRoot">
|
| 160 |
+
/// The virtual processor root to match.
|
| 161 |
+
/// </param>
|
| 162 |
+
/// <remarks>
|
| 163 |
+
/// IMPORTANT: This API is only called while removing virtual processors via IScheduler::RemoveVirtualProcessors.
|
| 164 |
+
/// If this functionality is needed at other call sites in the future, the implementation may need to be
|
| 165 |
+
/// reevaluated (see comments below).
|
| 166 |
+
/// </remarks>
|
| 167 |
+
VirtualProcessor* SchedulingNode::FindMatchingVirtualProcessor(IVirtualProcessorRoot* pRoot)
|
| 168 |
+
{
|
| 169 |
+
int arraySize = m_virtualProcessors.MaxIndex();
|
| 170 |
+
|
| 171 |
+
for (int i = 0; i < arraySize; i++)
|
| 172 |
+
{
|
| 173 |
+
VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i];
|
| 174 |
+
|
| 175 |
+
// It is ok to test the owning root here without a lock. If the owning root matches what we're looking for,
|
| 176 |
+
// we are guaranteed it will not change (by way of the virtual processor being retired and reused). This is because
|
| 177 |
+
// the call to IVirtualProcessorRoot::Remove in the virtual processor retirement code path is serialized in the RM
|
| 178 |
+
// before or after the call to IScheduler::RemoveVirtualProcessors. i.e. if we find an owning root that matches, the retirement
|
| 179 |
+
// path is unable to set it to NULL until after we're done.
|
| 180 |
+
if ((pVirtualProcessor != NULL) && (pVirtualProcessor->m_pOwningRoot == pRoot))
|
| 181 |
+
{
|
| 182 |
+
return pVirtualProcessor;
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
return NULL;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
InternalContextBase *SchedulingNode::StealLocalRunnableContext(VirtualProcessor* pSkipVirtualProcessor)
|
| 190 |
+
{
|
| 191 |
+
InternalContextBase *pContext = NULL;
|
| 192 |
+
int skipIndex, startIndex;
|
| 193 |
+
int arraySize = m_virtualProcessors.MaxIndex();
|
| 194 |
+
|
| 195 |
+
if (pSkipVirtualProcessor != NULL)
|
| 196 |
+
{
|
| 197 |
+
skipIndex = pSkipVirtualProcessor->m_listArrayIndex;
|
| 198 |
+
startIndex = 1;
|
| 199 |
+
}
|
| 200 |
+
else
|
| 201 |
+
{
|
| 202 |
+
skipIndex = 0;
|
| 203 |
+
startIndex = 0;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
for (int i = startIndex; i < arraySize; i++)
|
| 207 |
+
{
|
| 208 |
+
int index = (i + skipIndex) % arraySize;
|
| 209 |
+
VirtualProcessor *pVirtualProcessor = m_virtualProcessors[index];
|
| 210 |
+
if (pVirtualProcessor == NULL)
|
| 211 |
+
{
|
| 212 |
+
continue;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
pContext = pVirtualProcessor->m_localRunnableContexts.Steal();
|
| 216 |
+
if (pContext != NULL)
|
| 217 |
+
{
|
| 218 |
+
#if defined(_DEBUG)
|
| 219 |
+
pContext->SetDebugBits(CTX_DEBUGBIT_STOLENFROMLOCALRUNNABLECONTEXTS);
|
| 220 |
+
#endif // _DEBUG
|
| 221 |
+
|
| 222 |
+
break;
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
return pContext;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/// <summary>
|
| 229 |
+
/// Find an available virtual processor in the scheduling node. We claim ownership of the virtual
|
| 230 |
+
/// processor and return it.
|
| 231 |
+
/// </summary>
|
| 232 |
+
bool SchedulingNode::FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket,
|
| 233 |
+
location bias,
|
| 234 |
+
ULONG type)
|
| 235 |
+
{
|
| 236 |
+
if (bias._GetType() == location::_ExecutionResource)
|
| 237 |
+
{
|
| 238 |
+
VirtualProcessor *pBiasProc = FindVirtualProcessorByLocation(&bias);
|
| 239 |
+
ASSERT(!pBiasProc || pBiasProc->GetOwningNode() == this);
|
| 240 |
+
if (pBiasProc && pBiasProc->ClaimExclusiveOwnership(ticket, type))
|
| 241 |
+
return true;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// The callers of this API MUST check that that the available virtual processor count in the scheduling node
|
| 245 |
+
// is non-zero before calling the API. We avoid putting that check here since it would evaluate to false
|
| 246 |
+
// most of the time, and it saves the function call overhead on fast paths (chore push)
|
| 247 |
+
|
| 248 |
+
for (int i = 0; i < m_virtualProcessors.MaxIndex(); i++)
|
| 249 |
+
{
|
| 250 |
+
VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i];
|
| 251 |
+
|
| 252 |
+
if (pVirtualProcessor != NULL && pVirtualProcessor->ClaimExclusiveOwnership(ticket, type))
|
| 253 |
+
return true;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
return false;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
/// <summary>
|
| 260 |
+
/// Gets a location object which represents the scheduling node.
|
| 261 |
+
/// </summary>
|
| 262 |
+
location SchedulingNode::GetLocation()
|
| 263 |
+
{
|
| 264 |
+
return location(location::_SchedulingNode, m_id, m_pScheduler->Id(), this);
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
/// <summary>
|
| 268 |
+
/// Returns a virtual processor from the given location. The virtual processor must be within this node.
|
| 269 |
+
/// </summary>
|
| 270 |
+
VirtualProcessor* SchedulingNode::FindVirtualProcessorByLocation(const location* pLoc)
|
| 271 |
+
{
|
| 272 |
+
if (pLoc->_GetType() != location::_ExecutionResource)
|
| 273 |
+
return NULL;
|
| 274 |
+
|
| 275 |
+
if (m_pScheduler->IsLocationBound(pLoc))
|
| 276 |
+
return pLoc->_As<VirtualProcessor>();
|
| 277 |
+
|
| 278 |
+
//
|
| 279 |
+
// The specified location has not been specifically bound yet. Find any virtual processor which we deem appropriate for the binding
|
| 280 |
+
// to the specified execution resource id.
|
| 281 |
+
//
|
| 282 |
+
for (int i = 0; i < m_virtualProcessors.MaxIndex(); i++)
|
| 283 |
+
{
|
| 284 |
+
VirtualProcessor *pVirtualProcessor = m_virtualProcessors[i];
|
| 285 |
+
|
| 286 |
+
if (pVirtualProcessor != NULL && pVirtualProcessor->GetExecutionResourceId() == pLoc->_GetId())
|
| 287 |
+
return pVirtualProcessor;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
return NULL;
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
} // namespace details
|
| 294 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingNode.h
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulingNode.h
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the SchedulingNode declaration.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
namespace Concurrency
|
| 15 |
+
{
|
| 16 |
+
namespace details
|
| 17 |
+
{
|
| 18 |
+
/// <summary>
|
| 19 |
+
/// A scheduling node corresponds to a NUMA node or a processor package; containing one or more virtual processor groups.
|
| 20 |
+
/// </summary>
|
| 21 |
+
class SchedulingNode
|
| 22 |
+
{
|
| 23 |
+
public:
|
| 24 |
+
|
| 25 |
+
/// <summary>
|
| 26 |
+
/// Constructs a scheduling node.
|
| 27 |
+
/// </summary>
|
| 28 |
+
SchedulingNode(const QuickBitSet& resourceSet, DWORD numaNodeNumber, SchedulingRing *pRing);
|
| 29 |
+
|
| 30 |
+
/// <summary>
|
| 31 |
+
/// Destroys a scheduling node.
|
| 32 |
+
/// </summary>
|
| 33 |
+
~SchedulingNode();
|
| 34 |
+
|
| 35 |
+
/// <summary>
|
| 36 |
+
/// Creates and adds a new virtual processor in the node to associated with the root provided.
|
| 37 |
+
/// NOTE: For non-oversubscribed vprocs this API is currently will only work for initial allocation.
|
| 38 |
+
/// </summary>
|
| 39 |
+
/// <param name="pOwningRoot">
|
| 40 |
+
/// The virtual processor root to create the virtual processor with.
|
| 41 |
+
/// </param>
|
| 42 |
+
/// <param name="fOversubscribed">
|
| 43 |
+
/// True if this is an oversubscribed virtual processor.
|
| 44 |
+
/// </param>
|
| 45 |
+
/// <returns>
|
| 46 |
+
/// The newly created virtual processor.
|
| 47 |
+
/// </returns>
|
| 48 |
+
VirtualProcessor* AddVirtualProcessor(IVirtualProcessorRoot *pOwningRoot, bool fOversubscribed = false);
|
| 49 |
+
|
| 50 |
+
/// <summary>
|
| 51 |
+
/// Returns the scheduler associated with the node.
|
| 52 |
+
/// </summary>
|
| 53 |
+
SchedulerBase * GetScheduler() { return m_pScheduler; }
|
| 54 |
+
|
| 55 |
+
/// <summary>
|
| 56 |
+
/// Returns the scheduling ring associated with the node.
|
| 57 |
+
/// </summary>
|
| 58 |
+
SchedulingRing * GetSchedulingRing() { return m_pRing; }
|
| 59 |
+
|
| 60 |
+
/// <summary>
|
| 61 |
+
/// Find the virtual processor in this node that matches the root provided.
|
| 62 |
+
/// </summary>
|
| 63 |
+
/// <param name="pRoot">
|
| 64 |
+
/// The virtual processor root to match.
|
| 65 |
+
/// </param>
|
| 66 |
+
VirtualProcessor* FindMatchingVirtualProcessor(IVirtualProcessorRoot* pRoot);
|
| 67 |
+
|
| 68 |
+
/// <summary>
|
| 69 |
+
/// Returns the ID of the scheduling node.
|
| 70 |
+
/// </summary>
|
| 71 |
+
int Id() const
|
| 72 |
+
{
|
| 73 |
+
return m_id;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/// <summary>
|
| 77 |
+
/// Returns the first virtual processor in the non-cyclic range [min, max). If such is found
|
| 78 |
+
/// the virtual processor is returned and pIdx contains its index within the list array.
|
| 79 |
+
/// If not found, NULL is returned and the value in pIdx is unspecified.
|
| 80 |
+
/// </summary>
|
| 81 |
+
VirtualProcessor *FindVirtualProcessor(int min, int max, int *pIdx)
|
| 82 |
+
{
|
| 83 |
+
VirtualProcessor *pVProc = NULL;
|
| 84 |
+
int i = min;
|
| 85 |
+
for (; i < max && pVProc == NULL; ++i)
|
| 86 |
+
{
|
| 87 |
+
pVProc = m_virtualProcessors[i];
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
//
|
| 91 |
+
// The loop incremented "i" prior to the check. If found, the index is i - 1. If not, we care
|
| 92 |
+
// not what pIdx contains.
|
| 93 |
+
//
|
| 94 |
+
*pIdx = i - 1;
|
| 95 |
+
return pVProc;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
/// <summary>
|
| 99 |
+
/// Returns the first virtual processor.
|
| 100 |
+
/// </summary>
|
| 101 |
+
/// <param name="pIdx">
|
| 102 |
+
/// The iterator position of the returned virtual processor will be placed here. This can only be
|
| 103 |
+
/// utilized as the pIdx parameter or the idxStart parameter of a GetNextVirtualProcessor.
|
| 104 |
+
/// </param>
|
| 105 |
+
VirtualProcessor *GetFirstVirtualProcessor(int *pIdx)
|
| 106 |
+
{
|
| 107 |
+
return FindVirtualProcessor(0, m_virtualProcessors.MaxIndex(), pIdx);
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/// <summary>
|
| 111 |
+
/// Returns the next virtual processor in an iteration.
|
| 112 |
+
/// </summary>
|
| 113 |
+
VirtualProcessor *GetNextVirtualProcessor(int *pIdx, int idxStart = 0)
|
| 114 |
+
{
|
| 115 |
+
VirtualProcessor *pVProc = NULL;
|
| 116 |
+
|
| 117 |
+
int min = *pIdx + 1;
|
| 118 |
+
if (min > idxStart)
|
| 119 |
+
{
|
| 120 |
+
pVProc = FindVirtualProcessor(min, m_virtualProcessors.MaxIndex(), pIdx);
|
| 121 |
+
min = 0;
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
if (pVProc == NULL)
|
| 125 |
+
pVProc = FindVirtualProcessor(min, idxStart, pIdx);
|
| 126 |
+
|
| 127 |
+
return pVProc;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
/// <summary>
|
| 131 |
+
/// Returns whether a virtual processor is available.
|
| 132 |
+
/// </summary>
|
| 133 |
+
bool HasVirtualProcessorAvailable() const
|
| 134 |
+
{
|
| 135 |
+
return m_virtualProcessorAvailableCount > 0;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
/// <summary>
|
| 139 |
+
/// Returns whether a virtual processor is waiting for throttling.
|
| 140 |
+
/// </summary>
|
| 141 |
+
bool HasVirtualProcessorPendingThread() const
|
| 142 |
+
{
|
| 143 |
+
return m_virtualProcessorsPendingThreadCreate > 0;
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
/// <summary>
|
| 147 |
+
/// Returns whether a virtual processor is available to execute new work.
|
| 148 |
+
/// </summary>
|
| 149 |
+
bool HasVirtualProcessorAvailableForNewWork() const
|
| 150 |
+
{
|
| 151 |
+
//
|
| 152 |
+
// The observational race (lack of atomicity between the two reads) should not matter. If it does in some obscure
|
| 153 |
+
// case, a new atomic counter can be added.
|
| 154 |
+
//
|
| 155 |
+
return (m_virtualProcessorAvailableCount - m_virtualProcessorsPendingThreadCreate) > 0;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// <summary>
|
| 159 |
+
/// Gets a location object which represents the scheduling node.
|
| 160 |
+
/// </summary>
|
| 161 |
+
location GetLocation();
|
| 162 |
+
|
| 163 |
+
/// <summary>
|
| 164 |
+
/// Returns a virtual processor from the given location. The virtual processor must be within this node.
|
| 165 |
+
/// </summary>
|
| 166 |
+
VirtualProcessor* FindVirtualProcessorByLocation(const location* pLoc);
|
| 167 |
+
|
| 168 |
+
/// <summary>
|
| 169 |
+
/// Determines whether the scheduling node contains an execution resource with ID as specified. Note that this does NOT return
|
| 170 |
+
/// whether the said resource is available in the scheduler -- only whether the given resource ID is logically contained in the
|
| 171 |
+
/// node. The scheduler may have no virtual processor with that execution resource ID at the moment.
|
| 172 |
+
/// </summary>
|
| 173 |
+
bool ContainsResourceId(unsigned int resourceId) /*const*/
|
| 174 |
+
{
|
| 175 |
+
return m_resourceBitMap.Exists(resourceId);
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
/// <summary>
|
| 179 |
+
/// Notifies the node of a resource that is contained within it and its assigned position in all bitmasks used by all ConcRT
|
| 180 |
+
/// schedulers.
|
| 181 |
+
/// </summary>
|
| 182 |
+
void NotifyResource(unsigned int resourceId, unsigned int maskId)
|
| 183 |
+
{
|
| 184 |
+
m_resourceBitMap.Insert(resourceId, maskId);
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
/// <summary>
|
| 188 |
+
/// Returns the bitset for all resources in the node.
|
| 189 |
+
/// </summary>
|
| 190 |
+
const QuickBitSet& GetResourceSet()
|
| 191 |
+
{
|
| 192 |
+
return m_resourceSet;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
/// <summary>
|
| 196 |
+
/// Gets the NUMA node to which this scheduling node belongs.
|
| 197 |
+
/// </summary>
|
| 198 |
+
DWORD GetNumaNodeNumber() const
|
| 199 |
+
{
|
| 200 |
+
return m_numaNodeNumber;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
private:
|
| 204 |
+
friend class SchedulerBase;
|
| 205 |
+
friend class VirtualProcessor;
|
| 206 |
+
friend class InternalContextBase;
|
| 207 |
+
friend class FairScheduleGroup;
|
| 208 |
+
template <typename T> friend class ListArray;
|
| 209 |
+
|
| 210 |
+
// Owning scheduler
|
| 211 |
+
SchedulerBase *m_pScheduler;
|
| 212 |
+
|
| 213 |
+
// Owning ring
|
| 214 |
+
SchedulingRing * const m_pRing;
|
| 215 |
+
|
| 216 |
+
// The bit-set identifying execution resources within this node for quick affinity masking.
|
| 217 |
+
QuickBitSet m_resourceSet;
|
| 218 |
+
|
| 219 |
+
// Maps resource IDs contained within the node to a mask identifier
|
| 220 |
+
Hash<unsigned int, unsigned int> m_resourceBitMap;
|
| 221 |
+
|
| 222 |
+
volatile LONG m_virtualProcessorAvailableCount;
|
| 223 |
+
volatile LONG m_virtualProcessorsPendingThreadCreate;
|
| 224 |
+
|
| 225 |
+
volatile LONG m_virtualProcessorCount;
|
| 226 |
+
volatile LONG m_ramblingCount; // rambling -- searching foreign nodes for work
|
| 227 |
+
|
| 228 |
+
DWORD m_numaNodeNumber;
|
| 229 |
+
|
| 230 |
+
int m_id;
|
| 231 |
+
|
| 232 |
+
// Virtual processors owned by this node.
|
| 233 |
+
ListArray<VirtualProcessor> m_virtualProcessors;
|
| 234 |
+
|
| 235 |
+
InternalContextBase *StealLocalRunnableContext(VirtualProcessor* pSkipVirtualProcessor = NULL);
|
| 236 |
+
|
| 237 |
+
/// <summary>
|
| 238 |
+
/// Find an available virtual processor in the scheduling node.
|
| 239 |
+
/// </summary>
|
| 240 |
+
bool FoundAvailableVirtualProcessor(VirtualProcessor::ClaimTicket& ticket,
|
| 241 |
+
location bias = location(),
|
| 242 |
+
ULONG type = VirtualProcessor::AvailabilityAny);
|
| 243 |
+
|
| 244 |
+
void Cleanup();
|
| 245 |
+
|
| 246 |
+
// Prevent warning about generated assignment operator & copy constructors.
|
| 247 |
+
SchedulingNode(const SchedulingNode&);
|
| 248 |
+
void operator=(const SchedulingNode&);
|
| 249 |
+
};
|
| 250 |
+
} // namespace details
|
| 251 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.cpp
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulingRing.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the SchedulingRing implementation.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Construct a new scheduling ring.
|
| 22 |
+
/// </summary>
|
| 23 |
+
SchedulingRing::SchedulingRing(SchedulerBase *pScheduler, int id)
|
| 24 |
+
: m_pScheduler(pScheduler)
|
| 25 |
+
, m_pNode(NULL) // Will be set later explicitly by the creating scheduler
|
| 26 |
+
, m_pAnonymousSegment(NULL)
|
| 27 |
+
, m_affineSegments(pScheduler, 256, 64)
|
| 28 |
+
, m_nonAffineSegments(pScheduler, 256, 64)
|
| 29 |
+
, m_nextAffineSegment(0)
|
| 30 |
+
, m_nextNonAffineSegment(0)
|
| 31 |
+
, m_id(id)
|
| 32 |
+
, m_active(0)
|
| 33 |
+
{
|
| 34 |
+
//
|
| 35 |
+
// Create the anonymous schedule group early. UMS schedulers need somewhere to begin a search for a given node that is guaranteed
|
| 36 |
+
// to be safe. This is the only such place.
|
| 37 |
+
//
|
| 38 |
+
// Create schedule group takes a reference to the schedule group. The scheduling
|
| 39 |
+
// node maintains this reference and will release it when it disassociates from the
|
| 40 |
+
// schedule group (either in the destructor, or if the schedule group is moved to
|
| 41 |
+
// a different node due to resource management reclaiming the node).
|
| 42 |
+
//
|
| 43 |
+
location unbiased;
|
| 44 |
+
m_pAnonymousSegment = pScheduler->GetAnonymousScheduleGroup()->CreateSegment(&unbiased, this);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
SchedulingRing::~SchedulingRing()
|
| 48 |
+
{
|
| 49 |
+
ASSERT(m_pAnonymousSegment != NULL);
|
| 50 |
+
m_pAnonymousSegment = NULL;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
//
|
| 54 |
+
// Called when a schedule group's ref count is 0. remove this schedule group from the action.
|
| 55 |
+
//
|
| 56 |
+
void SchedulingRing::RemoveScheduleGroupSegment(ScheduleGroupSegmentBase *pSegment)
|
| 57 |
+
{
|
| 58 |
+
if (pSegment->GetAffinity()._Is_system())
|
| 59 |
+
m_nonAffineSegments.Remove(pSegment);
|
| 60 |
+
else
|
| 61 |
+
m_affineSegments.Remove(pSegment);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/// <summary>
|
| 65 |
+
/// Activates the ring.
|
| 66 |
+
/// </summary>
|
| 67 |
+
void SchedulingRing::Activate()
|
| 68 |
+
{
|
| 69 |
+
InterlockedExchange(&m_active, 1);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
} // namespace details
|
| 73 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SchedulingRing.h
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SchedulingRing.h
|
| 9 |
+
//
|
| 10 |
+
// Source file containing the SchedulingRing declaration.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
namespace Concurrency
|
| 15 |
+
{
|
| 16 |
+
namespace details
|
| 17 |
+
{
|
| 18 |
+
/// <summary>
|
| 19 |
+
/// A scheduling node corresponds to a NUMA node or a processor package; containing one or more virtual processor groups.
|
| 20 |
+
/// </summary>
|
| 21 |
+
class SchedulingRing
|
| 22 |
+
{
|
| 23 |
+
public:
|
| 24 |
+
SchedulingRing(SchedulerBase *pScheduler, int id);
|
| 25 |
+
|
| 26 |
+
~SchedulingRing();
|
| 27 |
+
|
| 28 |
+
int Id() const
|
| 29 |
+
{
|
| 30 |
+
return m_id;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// Create a new Schedule Group
|
| 34 |
+
ScheduleGroupBase *AllocateScheduleGroup();
|
| 35 |
+
|
| 36 |
+
// Delete a Schedule Group
|
| 37 |
+
void FreeScheduleGroup(ScheduleGroupBase *pGroup);
|
| 38 |
+
|
| 39 |
+
// Create a schedule group, add it to the list of groups
|
| 40 |
+
ScheduleGroupBase *CreateScheduleGroup();
|
| 41 |
+
|
| 42 |
+
ScheduleGroupSegmentBase *GetAnonymousScheduleGroupSegment() const
|
| 43 |
+
{
|
| 44 |
+
return m_pAnonymousSegment;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// <summary>
|
| 48 |
+
/// Returns a shared index to pseudo-round robin through affine schedule group segments within the ring.
|
| 49 |
+
/// </summary>
|
| 50 |
+
ScheduleGroupSegmentBase *GetPseudoRRAffineScheduleGroupSegment(int *pIdx)
|
| 51 |
+
{
|
| 52 |
+
int min = m_nextAffineSegment;
|
| 53 |
+
|
| 54 |
+
ScheduleGroupSegmentBase *pSegment = FindScheduleGroupSegment(min, m_affineSegments.MaxIndex(), pIdx, &m_affineSegments);
|
| 55 |
+
if (pSegment == NULL && min != 0)
|
| 56 |
+
pSegment = FindScheduleGroupSegment(0, min, pIdx, &m_affineSegments);
|
| 57 |
+
|
| 58 |
+
return pSegment;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
/// <summary>
|
| 62 |
+
/// Returns a shared index to pseudo-round robin through non-affine schedule group segments within the ring.
|
| 63 |
+
/// </summary>
|
| 64 |
+
ScheduleGroupSegmentBase *GetPseudoRRNonAffineScheduleGroupSegment(int *pIdx)
|
| 65 |
+
{
|
| 66 |
+
int min = m_nextNonAffineSegment;
|
| 67 |
+
|
| 68 |
+
ScheduleGroupSegmentBase *pSegment = FindScheduleGroupSegment(min, m_nonAffineSegments.MaxIndex(), pIdx, &m_nonAffineSegments);
|
| 69 |
+
if (pSegment == NULL && min != 0)
|
| 70 |
+
pSegment = FindScheduleGroupSegment(0, min, pIdx, &m_nonAffineSegments);
|
| 71 |
+
|
| 72 |
+
return pSegment;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Sets a shared index to pseudo-round robin through affine schedule group segments within the ring. This sets the index
|
| 77 |
+
/// to the schedule group segment *AFTER* idx in the iterator position.
|
| 78 |
+
/// </summary>
|
| 79 |
+
void SetPseudoRRAffineScheduleGroupSegmentNext(int idx)
|
| 80 |
+
{
|
| 81 |
+
m_nextAffineSegment = (idx + 1) % (m_affineSegments.MaxIndex());
|
| 82 |
+
ASSERT(m_nextAffineSegment >= 0);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
/// <summary>
|
| 86 |
+
/// Sets a shared index to pseudo-round robin through non-affine schedule group segments within the ring. This sets the index
|
| 87 |
+
/// to the schedule group segment *AFTER* idx in the iterator position.
|
| 88 |
+
/// </summary>
|
| 89 |
+
void SetPseudoRRNonAffineScheduleGroupSegmentNext(int idx)
|
| 90 |
+
{
|
| 91 |
+
m_nextNonAffineSegment = (idx + 1) % (m_nonAffineSegments.MaxIndex());
|
| 92 |
+
ASSERT(m_nextNonAffineSegment >= 0);
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/// <summary>
|
| 96 |
+
/// Returns the first affine schedule group segment within the ring.
|
| 97 |
+
/// </summary>
|
| 98 |
+
/// <param name="pIdx">
|
| 99 |
+
/// The iterator position of the returned schedule group segment will be placed here. This can only be
|
| 100 |
+
/// utilized as the pIdx parameter or the idxStart parameter of a GetNextAffineScheduleGroup.
|
| 101 |
+
/// </param>
|
| 102 |
+
ScheduleGroupSegmentBase *GetFirstAffineScheduleGroupSegment(int *pIdx)
|
| 103 |
+
{
|
| 104 |
+
return GetFirstScheduleGroupSegment(pIdx, &m_affineSegments);
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
/// <summary>
|
| 108 |
+
/// Returns the next affine schedule group segment in an iteration.
|
| 109 |
+
/// </summary>
|
| 110 |
+
ScheduleGroupSegmentBase *GetNextAffineScheduleGroupSegment(int *pIdx, int idxStart = 0)
|
| 111 |
+
{
|
| 112 |
+
return GetNextScheduleGroupSegment(pIdx, idxStart, &m_affineSegments);
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
/// <summary>
|
| 116 |
+
/// Returns the first non-affine schedule group segment within the ring.
|
| 117 |
+
/// </summary>
|
| 118 |
+
/// <param name="pIdx">
|
| 119 |
+
/// The iterator position of the returned schedule group segment will be placed here. This can only be
|
| 120 |
+
/// utilized as the pIdx parameter or the idxStart parameter of a GetNextNonAffineScheduleGroup.
|
| 121 |
+
/// </param>
|
| 122 |
+
ScheduleGroupSegmentBase *GetFirstNonAffineScheduleGroupSegment(int *pIdx)
|
| 123 |
+
{
|
| 124 |
+
return GetFirstScheduleGroupSegment(pIdx, &m_nonAffineSegments);
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/// <summary>
|
| 128 |
+
/// Returns the next non-affine schedule group segment in an iteration.
|
| 129 |
+
/// </summary>
|
| 130 |
+
ScheduleGroupSegmentBase *GetNextNonAffineScheduleGroupSegment(int *pIdx, int idxStart = 0)
|
| 131 |
+
{
|
| 132 |
+
return GetNextScheduleGroupSegment(pIdx, idxStart, &m_nonAffineSegments);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/// <summary>
|
| 136 |
+
/// Returns the node which owns this ring.
|
| 137 |
+
/// </summary>
|
| 138 |
+
SchedulingNode *GetOwningNode() const
|
| 139 |
+
{
|
| 140 |
+
return m_pNode;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/// <summary>
|
| 144 |
+
/// Returns whether this is an active ring or not.
|
| 145 |
+
/// </summary>
|
| 146 |
+
bool IsActive() const
|
| 147 |
+
{
|
| 148 |
+
return (m_active != 0);
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
/// <summary>
|
| 152 |
+
/// Activates the ring.
|
| 153 |
+
/// </summary>
|
| 154 |
+
void Activate();
|
| 155 |
+
|
| 156 |
+
private:
|
| 157 |
+
friend class SchedulerBase;
|
| 158 |
+
friend class ScheduleGroupBase;
|
| 159 |
+
friend class ScheduleGroupSegmentBase;
|
| 160 |
+
friend class FairScheduleGroup;
|
| 161 |
+
friend class CacheLocalScheduleGroup;
|
| 162 |
+
friend class SchedulingNode;
|
| 163 |
+
friend class VirtualProcessor;
|
| 164 |
+
friend class InternalContextBase;
|
| 165 |
+
friend class ThreadInternalContext;
|
| 166 |
+
|
| 167 |
+
// Owning scheduler
|
| 168 |
+
SchedulerBase *m_pScheduler;
|
| 169 |
+
|
| 170 |
+
// Owning Node
|
| 171 |
+
SchedulingNode *m_pNode;
|
| 172 |
+
|
| 173 |
+
// The anonymous schedule group - for external contexts and tasks without an explicitly specified schedule group.
|
| 174 |
+
// There is one anonymous group segment per scheduling node.
|
| 175 |
+
ScheduleGroupSegmentBase * m_pAnonymousSegment;
|
| 176 |
+
|
| 177 |
+
// Scheduler group segments owned by this ring which have explicitly specified affinity.
|
| 178 |
+
ListArray<ScheduleGroupSegmentBase> m_affineSegments;
|
| 179 |
+
|
| 180 |
+
// Scheduler groups segments owned by this ring which do not have explicitly specified affinity.
|
| 181 |
+
ListArray<ScheduleGroupSegmentBase> m_nonAffineSegments;
|
| 182 |
+
|
| 183 |
+
// Pseudo Round robin indicies.
|
| 184 |
+
int m_nextAffineSegment;
|
| 185 |
+
int m_nextNonAffineSegment;
|
| 186 |
+
|
| 187 |
+
int m_id;
|
| 188 |
+
|
| 189 |
+
// An indication as to whether the ring is active.
|
| 190 |
+
volatile LONG m_active;
|
| 191 |
+
|
| 192 |
+
// Removes the schedule group segment from the appropriate list.
|
| 193 |
+
void RemoveScheduleGroupSegment(ScheduleGroupSegmentBase* pGroup);
|
| 194 |
+
|
| 195 |
+
void SetOwningNode(SchedulingNode *pNode)
|
| 196 |
+
{
|
| 197 |
+
m_pNode = pNode;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/// <summary>
|
| 201 |
+
/// Returns the first schedule group segment in the non-cyclic range [min, max). If such is found
|
| 202 |
+
/// the schedule group segment is returned and pIdx contains its index within the list array.
|
| 203 |
+
/// If not found, NULL is returned and the value in pIdx is unspecified.
|
| 204 |
+
/// </summary>
|
| 205 |
+
ScheduleGroupSegmentBase *FindScheduleGroupSegment(int min, int max, int *pIdx, ListArray<ScheduleGroupSegmentBase> *pSegmentList)
|
| 206 |
+
{
|
| 207 |
+
ScheduleGroupSegmentBase *pSegment = NULL;
|
| 208 |
+
int i = min;
|
| 209 |
+
for (; i < max && pSegment == NULL; ++i)
|
| 210 |
+
{
|
| 211 |
+
pSegment = (*pSegmentList)[i];
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
//
|
| 215 |
+
// The loop incremented "i" prior to the check. If found, the index is i - 1. If not, we care
|
| 216 |
+
// not what pIdx contains.
|
| 217 |
+
//
|
| 218 |
+
*pIdx = i - 1;
|
| 219 |
+
return pSegment;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// <summary>
|
| 223 |
+
/// Returns the first schedule group.
|
| 224 |
+
/// </summary>
|
| 225 |
+
/// <param name="pIdx">
|
| 226 |
+
/// The iterator position of the returned schedule group will be placed here. This can only be
|
| 227 |
+
/// utilized as the pIdx parameter or the idxStart parameter of a GetNextScheduleGroup.
|
| 228 |
+
/// </param>
|
| 229 |
+
ScheduleGroupSegmentBase *GetFirstScheduleGroupSegment(int *pIdx, ListArray<ScheduleGroupSegmentBase>* pSegmentList)
|
| 230 |
+
{
|
| 231 |
+
return FindScheduleGroupSegment(0, pSegmentList->MaxIndex(), pIdx, pSegmentList);
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
/// <summary>
|
| 235 |
+
/// Returns the next schedule group in an iteration.
|
| 236 |
+
/// </summary>
|
| 237 |
+
ScheduleGroupSegmentBase *GetNextScheduleGroupSegment(int *pIdx, int idxStart, ListArray<ScheduleGroupSegmentBase>* pSegmentList)
|
| 238 |
+
{
|
| 239 |
+
ScheduleGroupSegmentBase *pSegment = NULL;
|
| 240 |
+
|
| 241 |
+
int min = *pIdx + 1;
|
| 242 |
+
if (min > idxStart)
|
| 243 |
+
{
|
| 244 |
+
pSegment = FindScheduleGroupSegment(min, pSegmentList->MaxIndex(), pIdx, pSegmentList);
|
| 245 |
+
min = 0;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
if (pSegment == NULL)
|
| 249 |
+
pSegment = FindScheduleGroupSegment(min, idxStart, pIdx, pSegmentList);
|
| 250 |
+
|
| 251 |
+
return pSegment;
|
| 252 |
+
}
|
| 253 |
+
};
|
| 254 |
+
} // namespace details
|
| 255 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.cpp
ADDED
|
@@ -0,0 +1,1659 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SearchAlgorithms.cpp
|
| 9 |
+
//
|
| 10 |
+
// Implementation file containing all scheduling algorithms.
|
| 11 |
+
//
|
| 12 |
+
// **PLEASE NOTE**:
|
| 13 |
+
//
|
| 14 |
+
// Any search algorithm in here must be fully reentrant. On UMS schedulers, the UMS primary will invoke these routines
|
| 15 |
+
// to perform a search for work.
|
| 16 |
+
//
|
| 17 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 18 |
+
|
| 19 |
+
#include "concrtinternal.h"
|
| 20 |
+
|
| 21 |
+
namespace Concurrency
|
| 22 |
+
{
|
| 23 |
+
namespace details
|
| 24 |
+
{
|
| 25 |
+
//***************************************************************************
|
| 26 |
+
//
|
| 27 |
+
// General:
|
| 28 |
+
//
|
| 29 |
+
|
| 30 |
+
/// <summary>
|
| 31 |
+
/// Constructs a work item from an internal context.
|
| 32 |
+
/// </summary>
|
| 33 |
+
WorkItem::WorkItem(InternalContextBase *pContext) :
|
| 34 |
+
m_type(WorkItemTypeContext),
|
| 35 |
+
m_pSegment(pContext->GetScheduleGroupSegment()),
|
| 36 |
+
m_pContext(pContext)
|
| 37 |
+
{
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/// <summary>
|
| 41 |
+
/// Resolves a token to an underlying work item.
|
| 42 |
+
/// </summary>
|
| 43 |
+
bool WorkItem::ResolveToken()
|
| 44 |
+
{
|
| 45 |
+
CONCRT_COREASSERT(IsToken());
|
| 46 |
+
switch(m_type)
|
| 47 |
+
{
|
| 48 |
+
case WorkItemTypeRealizedChoreToken:
|
| 49 |
+
{
|
| 50 |
+
RealizedChore *pChore = m_pSegment->GetRealizedChore();
|
| 51 |
+
if (pChore != NULL)
|
| 52 |
+
{
|
| 53 |
+
m_pRealizedChore = pChore;
|
| 54 |
+
m_type = WorkItemTypeRealizedChore;
|
| 55 |
+
}
|
| 56 |
+
break;
|
| 57 |
+
}
|
| 58 |
+
case WorkItemTypeUnrealizedChoreToken:
|
| 59 |
+
{
|
| 60 |
+
if (m_pWorkQueue == MAILBOX_LOCATION)
|
| 61 |
+
{
|
| 62 |
+
_UnrealizedChore *pChore;
|
| 63 |
+
if (!m_pSegment->m_mailedTasks.Dequeue(&pChore))
|
| 64 |
+
pChore = NULL;
|
| 65 |
+
|
| 66 |
+
if (pChore != NULL)
|
| 67 |
+
{
|
| 68 |
+
// The chore may not be from a detached workqueue, but since it is dequeued from a mailbox, we set it as detached
|
| 69 |
+
// which will add the stealing context to a list in the task collection instead of the owning contexts stealer collection.
|
| 70 |
+
pChore->_SetDetached(true);
|
| 71 |
+
m_pUnrealizedChore = pChore;
|
| 72 |
+
m_type = WorkItemTypeUnrealizedChore;
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
else
|
| 76 |
+
{
|
| 77 |
+
_UnrealizedChore *pChore = m_pWorkQueue->Steal(false);
|
| 78 |
+
if (pChore != NULL)
|
| 79 |
+
{
|
| 80 |
+
m_pUnrealizedChore = pChore;
|
| 81 |
+
m_type = WorkItemTypeUnrealizedChore;
|
| 82 |
+
}
|
| 83 |
+
break;
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
return !IsToken();
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/// <summary>
|
| 92 |
+
/// Binds the work item to a context and returns the context. This may or may not allocate a new context. Note that
|
| 93 |
+
/// act of binding which performs a context allocation will transfer a single count of work to the counter of the new
|
| 94 |
+
/// context.
|
| 95 |
+
/// </summary>
|
| 96 |
+
InternalContextBase *WorkItem::Bind()
|
| 97 |
+
{
|
| 98 |
+
if (IsToken() && !ResolveToken())
|
| 99 |
+
return NULL;
|
| 100 |
+
|
| 101 |
+
switch(m_type)
|
| 102 |
+
{
|
| 103 |
+
case WorkItemTypeUnrealizedChore:
|
| 104 |
+
m_pContext = m_pSegment->GetInternalContext(m_pUnrealizedChore, true);
|
| 105 |
+
if (m_pContext != NULL)
|
| 106 |
+
{
|
| 107 |
+
m_pContext->SaveDequeuedTask();
|
| 108 |
+
m_type = WorkItemTypeContext;
|
| 109 |
+
}
|
| 110 |
+
break;
|
| 111 |
+
case WorkItemTypeRealizedChore:
|
| 112 |
+
m_pContext = m_pSegment->GetInternalContext(m_pRealizedChore);
|
| 113 |
+
if (m_pContext != NULL)
|
| 114 |
+
{
|
| 115 |
+
m_pContext->SaveDequeuedTask();
|
| 116 |
+
m_type = WorkItemTypeContext;
|
| 117 |
+
}
|
| 118 |
+
break;
|
| 119 |
+
case WorkItemTypeContext:
|
| 120 |
+
break;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
return m_pContext;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/// <summary>
|
| 127 |
+
/// Binds the work item to the specified context (which is allocated). This will never allocate a new context.
|
| 128 |
+
/// </summary>
|
| 129 |
+
void WorkItem::BindTo(InternalContextBase *pContext)
|
| 130 |
+
{
|
| 131 |
+
switch(m_type)
|
| 132 |
+
{
|
| 133 |
+
case WorkItemTypeUnrealizedChore:
|
| 134 |
+
pContext->PrepareForUse(m_pSegment, m_pUnrealizedChore, true);
|
| 135 |
+
break;
|
| 136 |
+
case WorkItemTypeRealizedChore:
|
| 137 |
+
pContext->PrepareForUse(m_pSegment, m_pRealizedChore, false);
|
| 138 |
+
break;
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
m_pContext = pContext;
|
| 142 |
+
m_type = WorkItemTypeContext;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/// <summary>
|
| 146 |
+
/// Invokes the work item.
|
| 147 |
+
/// </summary>
|
| 148 |
+
void WorkItem::Invoke()
|
| 149 |
+
{
|
| 150 |
+
CONCRT_COREASSERT(m_type == WorkItemTypeRealizedChore || m_type == WorkItemTypeUnrealizedChore);
|
| 151 |
+
switch(m_type)
|
| 152 |
+
{
|
| 153 |
+
case WorkItemTypeUnrealizedChore:
|
| 154 |
+
m_pUnrealizedChore->_Invoke();
|
| 155 |
+
break;
|
| 156 |
+
case WorkItemTypeRealizedChore:
|
| 157 |
+
m_pRealizedChore->Invoke();
|
| 158 |
+
m_pSegment->GetGroup()->GetScheduler()->ReleaseRealizedChore(m_pRealizedChore);
|
| 159 |
+
break;
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
/// <summary>
|
| 164 |
+
/// Transfers reference counts as necessary to inline the given work item on the given context. This may
|
| 165 |
+
/// only be called on a work item that can be inlined (e.g.: an unbound one).
|
| 166 |
+
/// </summary>
|
| 167 |
+
/// <param name="pContext">
|
| 168 |
+
/// The context that is attempting to inline the work item.
|
| 169 |
+
/// </param>
|
| 170 |
+
void WorkItem::TransferReferences(InternalContextBase *pContext)
|
| 171 |
+
{
|
| 172 |
+
ASSERT(m_type == WorkItemTypeRealizedChore || m_type == WorkItemTypeUnrealizedChore);
|
| 173 |
+
|
| 174 |
+
ScheduleGroupSegmentBase *pSegment = pContext->GetScheduleGroupSegment();
|
| 175 |
+
if (m_type == WorkItemTypeRealizedChore)
|
| 176 |
+
{
|
| 177 |
+
if (pSegment->GetGroup() != m_pSegment->GetGroup())
|
| 178 |
+
{
|
| 179 |
+
pContext->SwapScheduleGroupSegment(m_pSegment, false);
|
| 180 |
+
}
|
| 181 |
+
else
|
| 182 |
+
{
|
| 183 |
+
//
|
| 184 |
+
// If newGroup is the same as the existing group, we need to release a reference since both, the context,
|
| 185 |
+
// and the realized chore, have a reference on the schedule group, and we only need to hold one reference.
|
| 186 |
+
//
|
| 187 |
+
OMTRACE(MTRACE_EVT_WORKITEMDEREFERENCE, pSegment->GetGroup(), NULL, NULL, 0);
|
| 188 |
+
pSegment->GetGroup()->InternalRelease();
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
}
|
| 192 |
+
else if (pSegment->GetGroup() != m_pSegment->GetGroup())
|
| 193 |
+
{
|
| 194 |
+
pContext->SwapScheduleGroupSegment(m_pSegment, true);
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
/// <summary>
|
| 199 |
+
/// Resets the work search context to utilize the specified algorithm at the starting iterator position.
|
| 200 |
+
/// </summary>
|
| 201 |
+
/// <param name="pVirtualProcessor">
|
| 202 |
+
/// The virtual processor binding the searching.
|
| 203 |
+
/// </param>
|
| 204 |
+
/// <param name="algorithm">
|
| 205 |
+
/// The algorithm to reset the iterator with.
|
| 206 |
+
/// </param>
|
| 207 |
+
void WorkSearchContext::Reset(VirtualProcessor *pVirtualProcessor, Algorithm algorithm)
|
| 208 |
+
{
|
| 209 |
+
m_LRCBias = 0;;
|
| 210 |
+
m_pVirtualProcessor = pVirtualProcessor;
|
| 211 |
+
m_maskId = m_pVirtualProcessor->GetMaskId();
|
| 212 |
+
m_pScheduler = pVirtualProcessor->GetOwningNode()->GetScheduler();
|
| 213 |
+
m_serviceTick = m_lastPriorityPull = platform::__GetTickCount64();
|
| 214 |
+
|
| 215 |
+
switch(algorithm)
|
| 216 |
+
{
|
| 217 |
+
case AlgorithmCacheLocal:
|
| 218 |
+
m_pSearchFn = &WorkSearchContext::SearchCacheLocal;
|
| 219 |
+
m_pSearchYieldFn = &WorkSearchContext::SearchCacheLocalYield;
|
| 220 |
+
break;
|
| 221 |
+
case AlgorithmFair:
|
| 222 |
+
m_pSearchFn = &WorkSearchContext::SearchFair;
|
| 223 |
+
m_pSearchYieldFn = &WorkSearchContext::SearchFairYield;
|
| 224 |
+
break;
|
| 225 |
+
default:
|
| 226 |
+
ASSERT(false);
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
/// <summary>
|
| 231 |
+
/// Steals a local runnable from a virtual processor within the specified node. Note that this allows a given virtual processor
|
| 232 |
+
/// to be skipped.
|
| 233 |
+
/// </summary>
|
| 234 |
+
bool WorkSearchContext::StealLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pNode, VirtualProcessor *pSkipVirtualProcessor)
|
| 235 |
+
{
|
| 236 |
+
int idx;
|
| 237 |
+
VirtualProcessor *pVProc = pNode->GetFirstVirtualProcessor(&idx);
|
| 238 |
+
while (pVProc != NULL)
|
| 239 |
+
{
|
| 240 |
+
if (pVProc != pSkipVirtualProcessor)
|
| 241 |
+
{
|
| 242 |
+
pVProc->ServiceMark(m_serviceTick);
|
| 243 |
+
InternalContextBase *pContext = pVProc->StealLocalRunnableContext();
|
| 244 |
+
if (pContext != NULL)
|
| 245 |
+
{
|
| 246 |
+
*pWorkItem = WorkItem(pContext);
|
| 247 |
+
return true;
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
pVProc = pNode->GetNextVirtualProcessor(&idx);
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
return false;
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
/// <summary>
|
| 258 |
+
/// Steals a local runnable from a virtual processor of any scheduling node other than the specified local node.
|
| 259 |
+
/// </summary>
|
| 260 |
+
bool WorkSearchContext::StealForeignLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pLocalNode)
|
| 261 |
+
{
|
| 262 |
+
int idx;
|
| 263 |
+
SchedulingNode *pNode = m_pScheduler->GetFirstSchedulingNode(&idx);
|
| 264 |
+
while (pNode != NULL)
|
| 265 |
+
{
|
| 266 |
+
if (pNode != pLocalNode)
|
| 267 |
+
{
|
| 268 |
+
if (StealLocalRunnable(pWorkItem, pNode, NULL))
|
| 269 |
+
return true;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
pNode = m_pScheduler->GetNextSchedulingNode(&idx);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
return false;
|
| 276 |
+
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
/// <summary>
|
| 280 |
+
/// Performs a pre-search for any "special" contexts (e.g.: the UMS SUT)
|
| 281 |
+
/// </summary>
|
| 282 |
+
bool WorkSearchContext::PreSearch(WorkItem *pWorkItem)
|
| 283 |
+
{
|
| 284 |
+
InternalContextBase *pContext = m_pVirtualProcessor->PreRunnableSearch();
|
| 285 |
+
if (pContext != NULL)
|
| 286 |
+
{
|
| 287 |
+
*pWorkItem = WorkItem(pContext);
|
| 288 |
+
return true;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
return false;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
/// <summary>
|
| 295 |
+
/// Gets a local runnable context from the specified virtual processor.
|
| 296 |
+
/// </summary>
|
| 297 |
+
bool WorkSearchContext::GetLocalRunnable(WorkItem *pWorkItem, VirtualProcessor *pVirtualProcessor, bool fYieldingSearch)
|
| 298 |
+
{
|
| 299 |
+
if (fYieldingSearch)
|
| 300 |
+
{
|
| 301 |
+
InternalContextBase *pContext = pVirtualProcessor->GetLocalRunnableContext();
|
| 302 |
+
if (pContext != NULL)
|
| 303 |
+
{
|
| 304 |
+
*pWorkItem = WorkItem(pContext);
|
| 305 |
+
return true;
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
else
|
| 309 |
+
{
|
| 310 |
+
BiasStageType biasStage = BiasStage();
|
| 311 |
+
if (biasStage < BiasStageSkipLRC)
|
| 312 |
+
{
|
| 313 |
+
InternalContextBase *pContext = (biasStage == BiasStageFlipLRC) ? pVirtualProcessor->StealLocalRunnableContext() : pVirtualProcessor->GetLocalRunnableContext();
|
| 314 |
+
if (pContext != NULL)
|
| 315 |
+
{
|
| 316 |
+
*pWorkItem = WorkItem(pContext);
|
| 317 |
+
LRCBias();
|
| 318 |
+
return true;
|
| 319 |
+
}
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
ResetLRCBias();
|
| 323 |
+
}
|
| 324 |
+
return false;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/// <summary>
|
| 328 |
+
/// Gets a runnable from the specified schedule group segment.
|
| 329 |
+
/// </summary>
|
| 330 |
+
/// <param name="pWorkItem">
|
| 331 |
+
/// If a work item is found, the work item will be returned here.
|
| 332 |
+
/// </param>
|
| 333 |
+
/// <param name="pSegment">
|
| 334 |
+
/// The schedule group segment in which to look for a runnable context.
|
| 335 |
+
/// </param>
|
| 336 |
+
/// <returns>
|
| 337 |
+
/// An indication of whether or not a runnable context was found in the segment.
|
| 338 |
+
/// </returns>
|
| 339 |
+
bool WorkSearchContext::GetRunnableContext(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment)
|
| 340 |
+
{
|
| 341 |
+
InternalContextBase *pContext = pSegment->GetRunnableContext();
|
| 342 |
+
if (pContext != NULL)
|
| 343 |
+
{
|
| 344 |
+
*pWorkItem = WorkItem(pContext);
|
| 345 |
+
return true;
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
return false;
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
/// <summary>
|
| 352 |
+
/// Gets a realized chore from the specified schedule group segment.
|
| 353 |
+
/// </summary>
|
| 354 |
+
/// <param name="pWorkItem">
|
| 355 |
+
/// If a work item is found, the work item will be returned here.
|
| 356 |
+
/// </param>
|
| 357 |
+
/// <param name="pSegment">
|
| 358 |
+
/// The schedule group segment in which to look for a realized chore.
|
| 359 |
+
/// </param>
|
| 360 |
+
/// <param name="fRealWork">
|
| 361 |
+
/// 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
|
| 362 |
+
/// is resolved.
|
| 363 |
+
/// </param>
|
| 364 |
+
/// <returns>
|
| 365 |
+
/// An indication of whether or not a realized chore was found in the segment.
|
| 366 |
+
/// </returns>
|
| 367 |
+
bool WorkSearchContext::GetRealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork)
|
| 368 |
+
{
|
| 369 |
+
if (fRealWork)
|
| 370 |
+
{
|
| 371 |
+
RealizedChore *pRealizedChore = pSegment->GetRealizedChore();
|
| 372 |
+
if (pRealizedChore != NULL)
|
| 373 |
+
{
|
| 374 |
+
*pWorkItem = WorkItem(pRealizedChore, pSegment);
|
| 375 |
+
return true;
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
else
|
| 379 |
+
{
|
| 380 |
+
if (pSegment->HasRealizedChores())
|
| 381 |
+
{
|
| 382 |
+
*pWorkItem = WorkItem(pSegment);
|
| 383 |
+
return true;
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
return false;
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
/// <summary>
|
| 391 |
+
/// Gets an unrealized chore from the specified schedule group segment.
|
| 392 |
+
/// </summary>
|
| 393 |
+
/// <param name="pWorkItem">
|
| 394 |
+
/// If a work item is found, the work item will be returned here.
|
| 395 |
+
/// </param>
|
| 396 |
+
/// <param name="pSegment">
|
| 397 |
+
/// The schedule group segment in which to look for an unrealized chore.
|
| 398 |
+
/// </param>
|
| 399 |
+
/// <param name="fForceStealLocalized">
|
| 400 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 401 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 402 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 403 |
+
/// </param>
|
| 404 |
+
/// <param name="fRealWork">
|
| 405 |
+
/// 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
|
| 406 |
+
/// is resolved.
|
| 407 |
+
/// </param>
|
| 408 |
+
/// <returns>
|
| 409 |
+
/// An indication of whether or not an unrealized chore was found in the segment.
|
| 410 |
+
/// </returns>
|
| 411 |
+
bool WorkSearchContext::GetUnrealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fForceStealLocalized, bool fRealWork)
|
| 412 |
+
{
|
| 413 |
+
if (fRealWork)
|
| 414 |
+
{
|
| 415 |
+
_UnrealizedChore *pUnrealizedChore = pSegment->StealUnrealizedChore(fForceStealLocalized);
|
| 416 |
+
if (pUnrealizedChore != NULL)
|
| 417 |
+
{
|
| 418 |
+
*pWorkItem = WorkItem(pUnrealizedChore, pSegment);
|
| 419 |
+
return true;
|
| 420 |
+
}
|
| 421 |
+
}
|
| 422 |
+
else
|
| 423 |
+
{
|
| 424 |
+
// 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.
|
| 425 |
+
ASSERT(!fForceStealLocalized);
|
| 426 |
+
WorkQueue *pWorkQueue = pSegment->LocateUnrealizedChores();
|
| 427 |
+
if (pWorkQueue != NULL)
|
| 428 |
+
{
|
| 429 |
+
*pWorkItem = WorkItem(pWorkQueue, pSegment);
|
| 430 |
+
return true;
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
return false;
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
/// <summary>
|
| 438 |
+
/// Performs a quick search of a particular segment.
|
| 439 |
+
/// </summary>
|
| 440 |
+
bool WorkSearchContext::QuickSearch(ScheduleGroupSegmentBase *pQCSegment,
|
| 441 |
+
WorkItem *pWorkItem,
|
| 442 |
+
bool fLastPass,
|
| 443 |
+
ULONG allowableTypes)
|
| 444 |
+
{
|
| 445 |
+
if (((allowableTypes & WorkItem::WorkItemTypeContext) && GetRunnableContext(pWorkItem, pQCSegment)) ||
|
| 446 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) &&
|
| 447 |
+
GetRealizedChore(pWorkItem, pQCSegment, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore))) ||
|
| 448 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) &&
|
| 449 |
+
GetUnrealizedChore(pWorkItem, pQCSegment, fLastPass, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore))))
|
| 450 |
+
{
|
| 451 |
+
return true;
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
return false;
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
/// <summary>
|
| 458 |
+
/// Performs a quick yielding search of a particular segment.
|
| 459 |
+
/// </summary>
|
| 460 |
+
bool WorkSearchContext::QuickSearchYield(ScheduleGroupSegmentBase *pQCSegment,
|
| 461 |
+
WorkItem *pWorkItem,
|
| 462 |
+
bool fLastPass,
|
| 463 |
+
ULONG allowableTypes)
|
| 464 |
+
{
|
| 465 |
+
if (((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) &&
|
| 466 |
+
GetUnrealizedChore(pWorkItem, pQCSegment, fLastPass, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore))) ||
|
| 467 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) &&
|
| 468 |
+
GetRealizedChore(pWorkItem, pQCSegment, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore))) ||
|
| 469 |
+
((allowableTypes & WorkItem::WorkItemTypeContext) && GetRunnableContext(pWorkItem, pQCSegment)))
|
| 470 |
+
{
|
| 471 |
+
return true;
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
return false;
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
/// <summary>
|
| 478 |
+
/// Determines if a segment should be skipped given the search parameters and the segment's affinity.
|
| 479 |
+
/// </summary>
|
| 480 |
+
/// <param name="pSegment">
|
| 481 |
+
/// The segment to query about skipping.
|
| 482 |
+
/// </param>
|
| 483 |
+
/// <param name="pSkipSegment">
|
| 484 |
+
/// A segment which should be arbitrarily skipped regardless of affinity type. This parameter can be NULL.
|
| 485 |
+
/// </param>
|
| 486 |
+
/// <param name="affinity">
|
| 487 |
+
/// The search affinity type to query for.
|
| 488 |
+
/// </param>
|
| 489 |
+
/// <param name="fLastPass">
|
| 490 |
+
/// An indication as to whether this is a last pass SFW.
|
| 491 |
+
/// </param>
|
| 492 |
+
/// <returns>
|
| 493 |
+
/// An indication as to whether pSegment should be skipped according to the pSkipSegment and affinity parameters.
|
| 494 |
+
/// </returns>
|
| 495 |
+
bool WorkSearchContext::SkipSegmentSearch(ScheduleGroupSegmentBase *pSegment, ScheduleGroupSegmentBase *pSkipSegment, SearchAffinity affinity, bool fLastPass)
|
| 496 |
+
{
|
| 497 |
+
if (pSegment == pSkipSegment)
|
| 498 |
+
{
|
| 499 |
+
return true;
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
bool fSkip = false;
|
| 503 |
+
const location& segmentAffinity = pSegment->GetAffinity();
|
| 504 |
+
|
| 505 |
+
switch(affinity)
|
| 506 |
+
{
|
| 507 |
+
case SearchNonAffine:
|
| 508 |
+
//
|
| 509 |
+
// Skip if it has any affinity and we're looking for non-affine work.
|
| 510 |
+
//
|
| 511 |
+
fSkip = !segmentAffinity._Is_system();
|
| 512 |
+
break;
|
| 513 |
+
|
| 514 |
+
case SearchAffineLocal:
|
| 515 |
+
//
|
| 516 |
+
// Skip if it has specific affinity to something that doesn't intersect with us.
|
| 517 |
+
//
|
| 518 |
+
fSkip = segmentAffinity._Is_system() || !m_pVirtualProcessor->GetLocation()._FastVPIntersects(segmentAffinity);
|
| 519 |
+
break;
|
| 520 |
+
|
| 521 |
+
case SearchAffineNotMe:
|
| 522 |
+
//
|
| 523 |
+
// Skip if it has specific affinity to us **OR** the virtual processors to which it has affinity are in the middle
|
| 524 |
+
// of search-for-work. This is an optimization to prevent us from ripping affine work out from underneath someone who
|
| 525 |
+
// will soon find it.
|
| 526 |
+
//
|
| 527 |
+
// In the last pass of SFW, we ignore this heuristic in order to avoid deadlock in required dependence cases.
|
| 528 |
+
//
|
| 529 |
+
fSkip = segmentAffinity._Is_system() ||
|
| 530 |
+
(m_pVirtualProcessor->GetLocation()._FastVPIntersects(segmentAffinity) ||
|
| 531 |
+
(m_pScheduler->HasSearchers(pSegment->GetAffinitySet()) && !fLastPass));
|
| 532 |
+
break;
|
| 533 |
+
|
| 534 |
+
default:
|
| 535 |
+
break;
|
| 536 |
+
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
return fSkip;
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
/// <summary>
|
| 543 |
+
/// Searches the schedule group to which pSegment belongs to find a runnable. The group is searched for segments according to the specified
|
| 544 |
+
/// affinity type.
|
| 545 |
+
/// </summary>
|
| 546 |
+
/// <param name="pWorkItem">
|
| 547 |
+
/// If an appropriate runnable is found, the resulting work item will be placed here.
|
| 548 |
+
/// </param>
|
| 549 |
+
/// <param name="pSegment">
|
| 550 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 551 |
+
/// </param>
|
| 552 |
+
/// <param name="fLastPass">
|
| 553 |
+
/// An indication as to whether this is a last pass SFW.
|
| 554 |
+
/// </param>
|
| 555 |
+
/// <returns>
|
| 556 |
+
/// An indication of whether a work item was found or not.
|
| 557 |
+
/// </returns>
|
| 558 |
+
bool WorkSearchContext::GetRunnableContextWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, SearchAffinity affinity, bool fLastPass)
|
| 559 |
+
{
|
| 560 |
+
ScheduleGroupBase *pGroup = pSegment->GetGroup();
|
| 561 |
+
|
| 562 |
+
//
|
| 563 |
+
// @TODO_LOC:
|
| 564 |
+
//
|
| 565 |
+
// We need to slice this differently so that we pick up "local" affine work before "non-local" affine work, etc...
|
| 566 |
+
//
|
| 567 |
+
if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetRunnableContext(pWorkItem, pSegment))
|
| 568 |
+
{
|
| 569 |
+
return true;
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine);
|
| 573 |
+
while(pCurSegment != NULL)
|
| 574 |
+
{
|
| 575 |
+
if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetRunnableContext(pWorkItem, pCurSegment))
|
| 576 |
+
{
|
| 577 |
+
return true;
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment);
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
return false;
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
/// <summary>
|
| 587 |
+
/// Searches the schedule group to which pSegment belongs to find a realized chore. The group is searched for segments according to the specified
|
| 588 |
+
/// affinity type.
|
| 589 |
+
/// </summary>
|
| 590 |
+
/// <param name="pWorkItem">
|
| 591 |
+
/// If an appropriate realized chore is found, the resulting work item will be placed here.
|
| 592 |
+
/// </param>
|
| 593 |
+
/// <param name="pSegment">
|
| 594 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 595 |
+
/// </param>
|
| 596 |
+
/// <param name="fLastPass">
|
| 597 |
+
/// An indication as to whether this is a last pass SFW.
|
| 598 |
+
/// </param>
|
| 599 |
+
/// <returns>
|
| 600 |
+
/// An indication of whether a work item was found or not.
|
| 601 |
+
/// </returns>
|
| 602 |
+
bool WorkSearchContext::GetRealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass)
|
| 603 |
+
{
|
| 604 |
+
ScheduleGroupBase *pGroup = pSegment->GetGroup();
|
| 605 |
+
|
| 606 |
+
//
|
| 607 |
+
// @TODO_LOC:
|
| 608 |
+
//
|
| 609 |
+
// We need to slice this differently so that we pick up "local" affine work before "non-local" affine work, etc...
|
| 610 |
+
//
|
| 611 |
+
if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetRealizedChore(pWorkItem, pSegment, fRealWork))
|
| 612 |
+
{
|
| 613 |
+
return true;
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine);
|
| 617 |
+
while(pCurSegment != NULL)
|
| 618 |
+
{
|
| 619 |
+
if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetRealizedChore(pWorkItem, pCurSegment, fRealWork))
|
| 620 |
+
{
|
| 621 |
+
return true;
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment);
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
return false;
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
/// <summary>
|
| 631 |
+
/// Searches the schedule group to which pSegment belongs to find an unrealized chore. The group is searched for segments according to the
|
| 632 |
+
/// specified affinity type.
|
| 633 |
+
/// </summary>
|
| 634 |
+
/// <param name="pWorkItem">
|
| 635 |
+
/// If an appropriate unrealized chore is found, the resulting work item will be placed here.
|
| 636 |
+
/// </param>
|
| 637 |
+
/// <param name="pSegment">
|
| 638 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 639 |
+
/// </param>
|
| 640 |
+
/// <param name="fLastPass">
|
| 641 |
+
/// An indication as to whether this is a last pass SFW.
|
| 642 |
+
/// </param>
|
| 643 |
+
/// <returns>
|
| 644 |
+
/// An indication of whether a work item was found or not.
|
| 645 |
+
/// </returns>
|
| 646 |
+
bool WorkSearchContext::GetUnrealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass)
|
| 647 |
+
{
|
| 648 |
+
ScheduleGroupBase *pGroup = pSegment->GetGroup();
|
| 649 |
+
|
| 650 |
+
//
|
| 651 |
+
// @TODO_LOC:
|
| 652 |
+
//
|
| 653 |
+
// 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
|
| 654 |
+
// slice out pSegment first. The second aspect requires more thought.
|
| 655 |
+
//
|
| 656 |
+
if (!SkipSegmentSearch(pSegment, NULL, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pSegment, fLastPass, fRealWork))
|
| 657 |
+
{
|
| 658 |
+
return true;
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
ScheduleGroupSegmentBase *pCurSegment = pGroup->GetFirstScheduleGroupSegment(affinity != SearchNonAffine);
|
| 662 |
+
while(pCurSegment != NULL)
|
| 663 |
+
{
|
| 664 |
+
if (!SkipSegmentSearch(pCurSegment, pSegment, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pCurSegment, fLastPass, fRealWork))
|
| 665 |
+
{
|
| 666 |
+
return true;
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
pCurSegment = pGroup->GetNextScheduleGroupSegment(pCurSegment);
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
return false;
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
//***************************************************************************
|
| 677 |
+
//
|
| 678 |
+
// Fair Searches
|
| 679 |
+
//
|
| 680 |
+
// NOTE: At present, we completely ignore affine lists because fair schedulers ignore location hints. This means you cannot "switch" scheduling
|
| 681 |
+
// to fair on a cache local scheduler should that ever come up.
|
| 682 |
+
//
|
| 683 |
+
|
| 684 |
+
/// <summary>
|
| 685 |
+
/// Performs a fair search for runnables in the specified ring.
|
| 686 |
+
/// </summary>
|
| 687 |
+
bool WorkSearchContext::SearchFair_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing)
|
| 688 |
+
{
|
| 689 |
+
int idx;
|
| 690 |
+
ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx);
|
| 691 |
+
|
| 692 |
+
int idxStart = idx;
|
| 693 |
+
|
| 694 |
+
while (pSegment != NULL)
|
| 695 |
+
{
|
| 696 |
+
InternalContextBase *pContext = pSegment->GetRunnableContext();
|
| 697 |
+
if (pContext != NULL)
|
| 698 |
+
{
|
| 699 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 700 |
+
*pWorkItem = WorkItem(pContext);
|
| 701 |
+
return true;
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart);
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
return false;
|
| 708 |
+
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
/// <summary>
|
| 712 |
+
/// Performs a fair search for realized chores in the specified ring.
|
| 713 |
+
/// </summary>
|
| 714 |
+
bool WorkSearchContext::SearchFair_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem)
|
| 715 |
+
{
|
| 716 |
+
int idx;
|
| 717 |
+
ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx);
|
| 718 |
+
|
| 719 |
+
int idxStart = idx;
|
| 720 |
+
|
| 721 |
+
while (pSegment != NULL)
|
| 722 |
+
{
|
| 723 |
+
if (fRealItem)
|
| 724 |
+
{
|
| 725 |
+
RealizedChore *pRealizedChore = pSegment->GetRealizedChore();
|
| 726 |
+
if (pRealizedChore != NULL)
|
| 727 |
+
{
|
| 728 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 729 |
+
*pWorkItem = WorkItem(pRealizedChore, pSegment);
|
| 730 |
+
return true;
|
| 731 |
+
}
|
| 732 |
+
}
|
| 733 |
+
else
|
| 734 |
+
{
|
| 735 |
+
if (pSegment->HasRealizedChores())
|
| 736 |
+
{
|
| 737 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 738 |
+
*pWorkItem = WorkItem(pSegment);
|
| 739 |
+
return true;
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart);
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
return false;
|
| 747 |
+
|
| 748 |
+
}
|
| 749 |
+
|
| 750 |
+
/// <summary>
|
| 751 |
+
/// Performs a fair search for unrealized chores in the specified ring.
|
| 752 |
+
/// </summary>
|
| 753 |
+
bool WorkSearchContext::SearchFair_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem)
|
| 754 |
+
{
|
| 755 |
+
int idx;
|
| 756 |
+
ScheduleGroupSegmentBase *pSegment = pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx);
|
| 757 |
+
|
| 758 |
+
int idxStart = idx;
|
| 759 |
+
|
| 760 |
+
while (pSegment != NULL)
|
| 761 |
+
{
|
| 762 |
+
if (fRealItem)
|
| 763 |
+
{
|
| 764 |
+
_UnrealizedChore *pUnrealizedChore = pSegment->StealUnrealizedChore();
|
| 765 |
+
if (pUnrealizedChore != NULL)
|
| 766 |
+
{
|
| 767 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 768 |
+
*pWorkItem = WorkItem(pUnrealizedChore, pSegment);
|
| 769 |
+
return true;
|
| 770 |
+
}
|
| 771 |
+
}
|
| 772 |
+
else
|
| 773 |
+
{
|
| 774 |
+
WorkQueue *pWorkQueue = pSegment->LocateUnrealizedChores();
|
| 775 |
+
if (pWorkQueue != NULL)
|
| 776 |
+
{
|
| 777 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 778 |
+
*pWorkItem = WorkItem(pWorkQueue, pSegment);
|
| 779 |
+
return true;
|
| 780 |
+
}
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
pSegment = pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart);
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
return false;
|
| 787 |
+
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
/// <summary>
|
| 791 |
+
/// Performs a fair search for work.
|
| 792 |
+
/// </summary>
|
| 793 |
+
bool WorkSearchContext::SearchFair(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool, ULONG allowableTypes)
|
| 794 |
+
{
|
| 795 |
+
bool fFound = false;
|
| 796 |
+
|
| 797 |
+
CONCRT_COREASSERT(pOriginSegment != NULL);
|
| 798 |
+
//
|
| 799 |
+
// Do any up-front searching required for special circumstances (e.g.: UMS schedulers)
|
| 800 |
+
//
|
| 801 |
+
if (PreSearch(pWorkItem))
|
| 802 |
+
return true;
|
| 803 |
+
|
| 804 |
+
//
|
| 805 |
+
// The fair search essentially round robins among scheduling rings and groups within a ring.
|
| 806 |
+
// If you consider the search space as follows:
|
| 807 |
+
//
|
| 808 |
+
// SR SR SR SR
|
| 809 |
+
// Contexts ---------------------->
|
| 810 |
+
// Realized ---------------------->
|
| 811 |
+
// Unrealized ---------------------->
|
| 812 |
+
//
|
| 813 |
+
// fair scheduling will make horizontal slices through the search space to find work.
|
| 814 |
+
//
|
| 815 |
+
// Each entry in the above matrix can be viewed as:
|
| 816 |
+
//
|
| 817 |
+
// SG -> SG -> SG -> SG
|
| 818 |
+
//
|
| 819 |
+
// However, after finding work in a particular ring, fair will move onto the next ring in round-robin fashion.
|
| 820 |
+
//
|
| 821 |
+
|
| 822 |
+
//
|
| 823 |
+
// 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.
|
| 824 |
+
//
|
| 825 |
+
SchedulingRing *pStartingRing = m_pScheduler->GetNextSchedulingRing();
|
| 826 |
+
|
| 827 |
+
if (allowableTypes & WorkItem::WorkItemTypeContext)
|
| 828 |
+
{
|
| 829 |
+
SchedulingRing *pRing = pStartingRing;
|
| 830 |
+
while (pRing != NULL)
|
| 831 |
+
{
|
| 832 |
+
fFound = SearchFair_Runnables(pWorkItem, pRing);
|
| 833 |
+
if (fFound)
|
| 834 |
+
{
|
| 835 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 836 |
+
break;
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
if (!fFound)
|
| 843 |
+
fFound = StealForeignLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode());
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore))
|
| 847 |
+
{
|
| 848 |
+
SchedulingRing *pRing = pStartingRing;
|
| 849 |
+
while (pRing != NULL)
|
| 850 |
+
{
|
| 851 |
+
fFound = SearchFair_Realized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore));
|
| 852 |
+
if (fFound)
|
| 853 |
+
{
|
| 854 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 855 |
+
break;
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 859 |
+
}
|
| 860 |
+
}
|
| 861 |
+
|
| 862 |
+
if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore))
|
| 863 |
+
{
|
| 864 |
+
SchedulingRing *pRing = pStartingRing;
|
| 865 |
+
while (pRing != NULL)
|
| 866 |
+
{
|
| 867 |
+
fFound = SearchFair_Unrealized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore));
|
| 868 |
+
if (fFound)
|
| 869 |
+
{
|
| 870 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 871 |
+
break;
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 875 |
+
}
|
| 876 |
+
}
|
| 877 |
+
|
| 878 |
+
return fFound;
|
| 879 |
+
}
|
| 880 |
+
|
| 881 |
+
/// <summary>
|
| 882 |
+
/// Performs a fair search for work in the yielding case.
|
| 883 |
+
/// </summary>
|
| 884 |
+
bool WorkSearchContext::SearchFairYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *, bool, ULONG allowableTypes)
|
| 885 |
+
{
|
| 886 |
+
//
|
| 887 |
+
// The yielding case slices identically to the regular case excepting that the search is done in a pseudo-reverse order
|
| 888 |
+
//
|
| 889 |
+
bool fFound = false;
|
| 890 |
+
|
| 891 |
+
//
|
| 892 |
+
// Do any up-front searching required for special circumstances (e.g.: UMS schedulers)
|
| 893 |
+
//
|
| 894 |
+
if (PreSearch(pWorkItem))
|
| 895 |
+
return true;
|
| 896 |
+
|
| 897 |
+
//
|
| 898 |
+
// 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.
|
| 899 |
+
//
|
| 900 |
+
SchedulingRing *pStartingRing = m_pScheduler->GetNextSchedulingRing();
|
| 901 |
+
|
| 902 |
+
if (allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore)
|
| 903 |
+
{
|
| 904 |
+
SchedulingRing *pRing = pStartingRing;
|
| 905 |
+
while (pRing != NULL)
|
| 906 |
+
{
|
| 907 |
+
fFound = SearchFair_Unrealized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore));
|
| 908 |
+
if (fFound)
|
| 909 |
+
{
|
| 910 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 911 |
+
break;
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 915 |
+
}
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
if (!fFound && (allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore))
|
| 920 |
+
{
|
| 921 |
+
SchedulingRing *pRing = pStartingRing;
|
| 922 |
+
while (pRing != NULL)
|
| 923 |
+
{
|
| 924 |
+
fFound = SearchFair_Realized(pWorkItem, pRing, !!(allowableTypes & WorkItem::WorkItemTypeRealizedChore));
|
| 925 |
+
if (fFound)
|
| 926 |
+
{
|
| 927 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 928 |
+
break;
|
| 929 |
+
}
|
| 930 |
+
|
| 931 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 932 |
+
}
|
| 933 |
+
}
|
| 934 |
+
|
| 935 |
+
if (!fFound && (allowableTypes & WorkItem::WorkItemTypeContext))
|
| 936 |
+
{
|
| 937 |
+
SchedulingRing *pRing = pStartingRing;
|
| 938 |
+
while (pRing != NULL)
|
| 939 |
+
{
|
| 940 |
+
fFound = SearchFair_Runnables(pWorkItem, pRing);
|
| 941 |
+
if (fFound)
|
| 942 |
+
{
|
| 943 |
+
m_pScheduler->SetNextSchedulingRing(pRing);
|
| 944 |
+
break;
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pStartingRing, pRing);
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
if (!fFound)
|
| 951 |
+
fFound = StealForeignLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode());
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
return fFound;
|
| 955 |
+
|
| 956 |
+
}
|
| 957 |
+
|
| 958 |
+
//***************************************************************************
|
| 959 |
+
//
|
| 960 |
+
// Cache Local Searches
|
| 961 |
+
//
|
| 962 |
+
|
| 963 |
+
/// <summary>
|
| 964 |
+
/// Searches for a runnable within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 965 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 966 |
+
/// </summary>
|
| 967 |
+
/// <param name="pWorkItem">
|
| 968 |
+
/// If a work item is found, the work item will be returned here.
|
| 969 |
+
/// </param>
|
| 970 |
+
/// <param name="pRing">
|
| 971 |
+
/// The scheduling ring to search.
|
| 972 |
+
/// </param>
|
| 973 |
+
/// <param name="pBiasSegment">
|
| 974 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 975 |
+
/// </param>
|
| 976 |
+
/// <param name="fOtherLocalLRCCheck">
|
| 977 |
+
/// Determines whether or not to check other local LRCs in this search.
|
| 978 |
+
/// </param>
|
| 979 |
+
/// <param name="affinity">
|
| 980 |
+
/// The search affinity type to query for.
|
| 981 |
+
/// </param>
|
| 982 |
+
/// <param name="allowableTypes">
|
| 983 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 984 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 985 |
+
/// </param>
|
| 986 |
+
/// <param name="fLastPass">
|
| 987 |
+
/// An indication as to whether this is a last pass SFW.
|
| 988 |
+
/// </param>
|
| 989 |
+
/// <returns>
|
| 990 |
+
/// An indication of whether a runnable was found in the bias segment, group, or the specified ring.
|
| 991 |
+
/// </returns>
|
| 992 |
+
bool WorkSearchContext::SearchCacheLocal_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 993 |
+
bool fOtherLocalLRCCheck, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass)
|
| 994 |
+
{
|
| 995 |
+
if (pBiasSegment != NULL && GetRunnableContextWithinGroup(pWorkItem, pBiasSegment, affinity, fLastPass))
|
| 996 |
+
{
|
| 997 |
+
return true;
|
| 998 |
+
}
|
| 999 |
+
|
| 1000 |
+
//
|
| 1001 |
+
// 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.
|
| 1002 |
+
// Attempt to steal a local runnable context from the current node.
|
| 1003 |
+
//
|
| 1004 |
+
if (fOtherLocalLRCCheck && StealLocalRunnable(pWorkItem, m_pVirtualProcessor->GetOwningNode(), m_pVirtualProcessor))
|
| 1005 |
+
{
|
| 1006 |
+
return true;
|
| 1007 |
+
}
|
| 1008 |
+
|
| 1009 |
+
int idx;
|
| 1010 |
+
ScheduleGroupSegmentBase *pSegment =
|
| 1011 |
+
(affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx);
|
| 1012 |
+
|
| 1013 |
+
int idxStart = idx;
|
| 1014 |
+
|
| 1015 |
+
while (pSegment != NULL)
|
| 1016 |
+
{
|
| 1017 |
+
ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId);
|
| 1018 |
+
if (pQCSegment)
|
| 1019 |
+
{
|
| 1020 |
+
if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1021 |
+
return true;
|
| 1022 |
+
}
|
| 1023 |
+
|
| 1024 |
+
//
|
| 1025 |
+
// Is this a segment we should skip:
|
| 1026 |
+
//
|
| 1027 |
+
// - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment).
|
| 1028 |
+
// - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter.
|
| 1029 |
+
//
|
| 1030 |
+
if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetRunnableContext(pWorkItem, pSegment))
|
| 1031 |
+
{
|
| 1032 |
+
if (affinity == SearchNonAffine)
|
| 1033 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 1034 |
+
else
|
| 1035 |
+
pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx);
|
| 1036 |
+
|
| 1037 |
+
return true;
|
| 1038 |
+
}
|
| 1039 |
+
|
| 1040 |
+
pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) :
|
| 1041 |
+
pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart);
|
| 1042 |
+
}
|
| 1043 |
+
|
| 1044 |
+
return false;
|
| 1045 |
+
|
| 1046 |
+
}
|
| 1047 |
+
|
| 1048 |
+
/// <summary>
|
| 1049 |
+
/// Searches for a realized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 1050 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 1051 |
+
/// </summary>
|
| 1052 |
+
/// <param name="pWorkItem">
|
| 1053 |
+
/// If a work item is found, the work item will be returned here.
|
| 1054 |
+
/// </param>
|
| 1055 |
+
/// <param name="pRing">
|
| 1056 |
+
/// The scheduling ring to search.
|
| 1057 |
+
/// </param>
|
| 1058 |
+
/// <param name="pBiasSegment">
|
| 1059 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 1060 |
+
/// </param>
|
| 1061 |
+
/// <param name="fRealWork">
|
| 1062 |
+
/// 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
|
| 1063 |
+
/// is resolved.
|
| 1064 |
+
/// </param>
|
| 1065 |
+
/// <param name="affinity">
|
| 1066 |
+
/// The search affinity type to query for.
|
| 1067 |
+
/// </param>
|
| 1068 |
+
/// <param name="allowableTypes">
|
| 1069 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 1070 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 1071 |
+
/// </param>
|
| 1072 |
+
/// <param name="fLastPass">
|
| 1073 |
+
/// An indication as to whether this is a last pass SFW.
|
| 1074 |
+
/// </param>
|
| 1075 |
+
/// <returns>
|
| 1076 |
+
/// An indication of whether a realized chore was found in the bias segment, group, or the specified ring.
|
| 1077 |
+
/// </returns>
|
| 1078 |
+
bool WorkSearchContext::SearchCacheLocal_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 1079 |
+
bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass)
|
| 1080 |
+
{
|
| 1081 |
+
bool fFound = false;
|
| 1082 |
+
|
| 1083 |
+
if (pBiasSegment != NULL && GetRealizedChoreWithinGroup(pWorkItem, pBiasSegment, fRealWork, affinity, fLastPass))
|
| 1084 |
+
{
|
| 1085 |
+
return true;
|
| 1086 |
+
}
|
| 1087 |
+
|
| 1088 |
+
int idx;
|
| 1089 |
+
ScheduleGroupSegmentBase *pSegment =
|
| 1090 |
+
(affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx);
|
| 1091 |
+
|
| 1092 |
+
int idxStart = idx;
|
| 1093 |
+
|
| 1094 |
+
while (pSegment != NULL && !fFound)
|
| 1095 |
+
{
|
| 1096 |
+
ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId);
|
| 1097 |
+
if (pQCSegment)
|
| 1098 |
+
{
|
| 1099 |
+
if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1100 |
+
return true;
|
| 1101 |
+
}
|
| 1102 |
+
|
| 1103 |
+
//
|
| 1104 |
+
// Is this a segment we should skip:
|
| 1105 |
+
//
|
| 1106 |
+
// - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment).
|
| 1107 |
+
// - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter.
|
| 1108 |
+
//
|
| 1109 |
+
if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetRealizedChore(pWorkItem, pSegment, fRealWork))
|
| 1110 |
+
{
|
| 1111 |
+
if (affinity == SearchNonAffine)
|
| 1112 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 1113 |
+
else
|
| 1114 |
+
pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx);
|
| 1115 |
+
|
| 1116 |
+
return true;
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) :
|
| 1120 |
+
pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart);
|
| 1121 |
+
}
|
| 1122 |
+
|
| 1123 |
+
return false;
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
/// <summary>
|
| 1127 |
+
/// Searches for an unrealized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 1128 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 1129 |
+
/// </summary>
|
| 1130 |
+
/// <param name="pWorkItem">
|
| 1131 |
+
/// If a work item is found, the work item will be returned here.
|
| 1132 |
+
/// </param>
|
| 1133 |
+
/// <param name="pRing">
|
| 1134 |
+
/// The scheduling ring to search.
|
| 1135 |
+
/// </param>
|
| 1136 |
+
/// <param name="pBiasSegment">
|
| 1137 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 1138 |
+
/// </param>
|
| 1139 |
+
/// <param name="fRealWork">
|
| 1140 |
+
/// 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
|
| 1141 |
+
/// is resolved.
|
| 1142 |
+
/// </param>
|
| 1143 |
+
/// <param name="affinity">
|
| 1144 |
+
/// The search affinity type to query for.
|
| 1145 |
+
/// </param>
|
| 1146 |
+
/// <param name="allowableTypes">
|
| 1147 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 1148 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 1149 |
+
/// </param>
|
| 1150 |
+
/// <param name="fLastPass">
|
| 1151 |
+
/// An indication as to whether this is a last pass SFW.
|
| 1152 |
+
/// </param>
|
| 1153 |
+
/// <returns>
|
| 1154 |
+
/// An indication of whether an unrealized chore was found in the bias segment, group, or the specified ring.
|
| 1155 |
+
/// </returns>
|
| 1156 |
+
bool WorkSearchContext::SearchCacheLocal_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 1157 |
+
bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass)
|
| 1158 |
+
{
|
| 1159 |
+
bool fFound = false;
|
| 1160 |
+
|
| 1161 |
+
if (pBiasSegment != NULL && GetUnrealizedChoreWithinGroup(pWorkItem, pBiasSegment, fRealWork, affinity, fLastPass))
|
| 1162 |
+
{
|
| 1163 |
+
return true;
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
int idx;
|
| 1167 |
+
ScheduleGroupSegmentBase *pSegment =
|
| 1168 |
+
(affinity == SearchNonAffine) ? pRing->GetPseudoRRNonAffineScheduleGroupSegment(&idx) : pRing->GetPseudoRRAffineScheduleGroupSegment(&idx);
|
| 1169 |
+
|
| 1170 |
+
int idxStart = idx;
|
| 1171 |
+
|
| 1172 |
+
while (pSegment != NULL && !fFound)
|
| 1173 |
+
{
|
| 1174 |
+
ScheduleGroupSegmentBase *pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId);
|
| 1175 |
+
if (pQCSegment)
|
| 1176 |
+
{
|
| 1177 |
+
if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1178 |
+
return true;
|
| 1179 |
+
}
|
| 1180 |
+
|
| 1181 |
+
//
|
| 1182 |
+
// Is this a segment we should skip:
|
| 1183 |
+
//
|
| 1184 |
+
// - If we are explicitly told to skip it in the search because it was checked elsewhere (pSkipSegment).
|
| 1185 |
+
// - If we are searching for affine work and it matches or doesn't match the search context affinity as dictated by the affinity parameter.
|
| 1186 |
+
//
|
| 1187 |
+
if (!SkipSegmentSearch(pSegment, pBiasSegment, affinity, fLastPass) && GetUnrealizedChore(pWorkItem, pSegment, fLastPass, fRealWork))
|
| 1188 |
+
{
|
| 1189 |
+
if (affinity == SearchNonAffine)
|
| 1190 |
+
pRing->SetPseudoRRNonAffineScheduleGroupSegmentNext(idx);
|
| 1191 |
+
else
|
| 1192 |
+
pRing->SetPseudoRRAffineScheduleGroupSegmentNext(idx);
|
| 1193 |
+
|
| 1194 |
+
return true;
|
| 1195 |
+
}
|
| 1196 |
+
|
| 1197 |
+
pSegment = (affinity == SearchNonAffine) ? pRing->GetNextNonAffineScheduleGroupSegment(&idx, idxStart) :
|
| 1198 |
+
pRing->GetNextAffineScheduleGroupSegment(&idx, idxStart);
|
| 1199 |
+
}
|
| 1200 |
+
|
| 1201 |
+
return false;
|
| 1202 |
+
}
|
| 1203 |
+
|
| 1204 |
+
/// <summary>
|
| 1205 |
+
/// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm.
|
| 1206 |
+
/// </summary>
|
| 1207 |
+
/// <param name="pWorkItem">
|
| 1208 |
+
/// If a work item is found, the work item will be returned here.
|
| 1209 |
+
/// </param>
|
| 1210 |
+
/// <param name="pOriginSegment">
|
| 1211 |
+
/// The segment to bias the search to.
|
| 1212 |
+
/// </param>
|
| 1213 |
+
/// <param name="fLastPass">
|
| 1214 |
+
/// An indication as to whether this is a last pass SFW.
|
| 1215 |
+
/// </param>
|
| 1216 |
+
/// <param name="allowableTypes">
|
| 1217 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 1218 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 1219 |
+
/// </param>
|
| 1220 |
+
/// <returns>
|
| 1221 |
+
/// An indication of whether a work item was found or not.
|
| 1222 |
+
/// </returns>
|
| 1223 |
+
bool WorkSearchContext::SearchCacheLocal(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes)
|
| 1224 |
+
{
|
| 1225 |
+
bool fFound = false;
|
| 1226 |
+
|
| 1227 |
+
if (PreSearch(pWorkItem))
|
| 1228 |
+
return true;
|
| 1229 |
+
|
| 1230 |
+
ASSERT(pOriginSegment);
|
| 1231 |
+
|
| 1232 |
+
m_serviceTick = platform::__GetTickCount64();
|
| 1233 |
+
m_pScheduler->PeriodicScan(m_serviceTick);
|
| 1234 |
+
|
| 1235 |
+
//
|
| 1236 |
+
// @TODO: This is a temporary patch until we have priority and boosts in the scheduler. Right now, search for any segment in the locked
|
| 1237 |
+
// FIFO of "priority" segments to see if we need to service someone to avoid livelock. We also periodically scan to determine whether
|
| 1238 |
+
// groups need to go into this list.
|
| 1239 |
+
//
|
| 1240 |
+
|
| 1241 |
+
if (CheckPriorityList(m_serviceTick))
|
| 1242 |
+
{
|
| 1243 |
+
if (m_pScheduler->HasPriorityObjects())
|
| 1244 |
+
{
|
| 1245 |
+
BoostedObject *pObject = m_pScheduler->GetNextPriorityObject();
|
| 1246 |
+
while (pObject != NULL)
|
| 1247 |
+
{
|
| 1248 |
+
if (pObject->IsScheduleGroupSegment())
|
| 1249 |
+
{
|
| 1250 |
+
ScheduleGroupSegmentBase *pSegment = ScheduleGroupSegmentBase::FromBoostEntry(pObject);
|
| 1251 |
+
OMTRACE(MTRACE_EVT_PRIORITYPULL, pSegment, NULL, m_pVirtualProcessor, 0);
|
| 1252 |
+
if (QuickSearch(pSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1253 |
+
{
|
| 1254 |
+
fFound = true;
|
| 1255 |
+
break;
|
| 1256 |
+
}
|
| 1257 |
+
}
|
| 1258 |
+
else if (allowableTypes & WorkItem::WorkItemTypeContext)
|
| 1259 |
+
{
|
| 1260 |
+
VirtualProcessor *pVProc = VirtualProcessor::FromBoostEntry(pObject);
|
| 1261 |
+
InternalContextBase *pContext = pVProc->StealLocalRunnableContext();
|
| 1262 |
+
if (pContext != NULL)
|
| 1263 |
+
{
|
| 1264 |
+
*pWorkItem = WorkItem(pContext);
|
| 1265 |
+
fFound = true;
|
| 1266 |
+
break;
|
| 1267 |
+
}
|
| 1268 |
+
}
|
| 1269 |
+
|
| 1270 |
+
pObject = m_pScheduler->GetNextPriorityObject();
|
| 1271 |
+
}
|
| 1272 |
+
}
|
| 1273 |
+
|
| 1274 |
+
//
|
| 1275 |
+
// If we found something in a priority segment, we need to mark the V-Proc so that it once again looks for affinitized work
|
| 1276 |
+
// the next time through SFW.
|
| 1277 |
+
//
|
| 1278 |
+
m_pVirtualProcessor->MarkGrabbedPriority();
|
| 1279 |
+
}
|
| 1280 |
+
|
| 1281 |
+
SchedulingRing *pOwningRing = m_pVirtualProcessor->GetOwningRing();
|
| 1282 |
+
|
| 1283 |
+
if (!fFound)
|
| 1284 |
+
{
|
| 1285 |
+
//
|
| 1286 |
+
// Before describing the cache local search algorithm, some definitions to aid in this are in order:
|
| 1287 |
+
//
|
| 1288 |
+
// Work:
|
| 1289 |
+
// local work -- Work within a node/ring that a given virtual processor belongs to is considered local work
|
| 1290 |
+
// foreign work -- Work within a node/ring that a given virtual processor does *NOT* belong to is considered foreign work
|
| 1291 |
+
// affine work -- Work which is placed at a location more specific than the system location is affine work
|
| 1292 |
+
// non-affine work -- Work which is placed at the system location (or no location) is considered non-affine work
|
| 1293 |
+
//
|
| 1294 |
+
// Virtual Processors:
|
| 1295 |
+
// rambling -- a given virtual processor is *rambling* when it is executing foreign work (regardless whether such work is affine to it or not)
|
| 1296 |
+
// non-affine -- a given virtual processor is *non-affine* when it is executing non-affine work (regardless whether it is rambling or not)
|
| 1297 |
+
//
|
| 1298 |
+
// Virtual processors which are rambling or are executing non-affine work are tracked by the scheduler. When such virtual processors
|
| 1299 |
+
// exist, notifications will be published whenever affine work or local work becomes available.
|
| 1300 |
+
//
|
| 1301 |
+
|
| 1302 |
+
//
|
| 1303 |
+
// Look for work in the scheduler. **IN GENERAL**, we want to find work in the following order of precedence:
|
| 1304 |
+
//
|
| 1305 |
+
// Phase 1: Affine work
|
| 1306 |
+
// Affine work in our current group (preferring local affine work)
|
| 1307 |
+
// Local affine (to us) work (in our starting (home) ring)
|
| 1308 |
+
// Foreign affine (to us) work (in foreign ring segments that match our affinity mask -- such have a segment in our ring by definition)
|
| 1309 |
+
//
|
| 1310 |
+
// - This phase may be skipped if we are executing non-affine work and have not received an affinity notification from the scheduler.
|
| 1311 |
+
// Doing so prevents SFW from making a full pass per work item if no affinity has been used.
|
| 1312 |
+
//
|
| 1313 |
+
// Phase 2: Non-affine work
|
| 1314 |
+
// Non-Affine work in our current group (preferring local work)
|
| 1315 |
+
// Local non-affine work (in our starting (home ring))
|
| 1316 |
+
// Foreign non-affine work (in foreign rings).
|
| 1317 |
+
//
|
| 1318 |
+
// - This phase may *NEVER* be skipped.
|
| 1319 |
+
//
|
| 1320 |
+
// Phase 3: Affine work (non-local)
|
| 1321 |
+
// Non-local affine (*NOT* to us) work (in foreign ring segments that do not match our affinity mask
|
| 1322 |
+
//
|
| 1323 |
+
// - 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
|
| 1324 |
+
// any scheduling API, this phase is only hit if the scheduler is completely idle. At idle, performing a pass is likely little additional
|
| 1325 |
+
// cost to any performance sensitive scenario. At present, this stage is not skipped for this reason.
|
| 1326 |
+
//
|
| 1327 |
+
// At a very high level, you can consider a cache local search to be making vertical slices through the search space as follows:
|
| 1328 |
+
//
|
| 1329 |
+
// SR SR SR SR
|
| 1330 |
+
// Contexts | | | |
|
| 1331 |
+
// Realized | | | |
|
| 1332 |
+
// Unrealized v v v v
|
| 1333 |
+
//
|
| 1334 |
+
// where each entry in this matrix is a piece of a schedule group.
|
| 1335 |
+
//
|
| 1336 |
+
// 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
|
| 1337 |
+
// (assumptions on concurrency level).
|
| 1338 |
+
//
|
| 1339 |
+
static const SearchAffinity phaseAffinities[] = { SearchAffineLocal, SearchNonAffine, SearchAffineNotMe };
|
| 1340 |
+
// { 1 , 0 , 2 };
|
| 1341 |
+
int startPhaseIndex = (!m_pVirtualProcessor->ExecutingAffine() && !m_pVirtualProcessor->CheckAffinityNotification() && !fLastPass) ? 1 : 0;
|
| 1342 |
+
int maxPhaseIndex = SIZEOF_ARRAY(phaseAffinities) - 1;
|
| 1343 |
+
|
| 1344 |
+
// 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
|
| 1345 |
+
// search algorithm. This variable is set to false at the end of the first pass through the inner loop.
|
| 1346 |
+
bool fLocalCheck = true;
|
| 1347 |
+
for(int phaseIndex = startPhaseIndex; !fFound && phaseIndex <= maxPhaseIndex; ++phaseIndex) // This loop goes through the phases in the phaseAffinity array.
|
| 1348 |
+
{
|
| 1349 |
+
SearchAffinity srchType = phaseAffinities[phaseIndex];
|
| 1350 |
+
|
| 1351 |
+
// At the outset of every pass, we bias to the originating segment/group and the current virtual processors owning ring.
|
| 1352 |
+
// Note that if we are searching for non-local affinework, we skip the owning ring (by definition, it's local).
|
| 1353 |
+
ScheduleGroupSegmentBase *pBiasSegment = pOriginSegment;
|
| 1354 |
+
SchedulingRing *pRing = pOwningRing;
|
| 1355 |
+
|
| 1356 |
+
while (pRing != NULL)
|
| 1357 |
+
{
|
| 1358 |
+
ScheduleGroupSegmentBase* pQCSegment = m_pScheduler->AcquireQuickCacheSlot(m_maskId);
|
| 1359 |
+
if (pQCSegment)
|
| 1360 |
+
{
|
| 1361 |
+
if (QuickSearch(pQCSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1362 |
+
{
|
| 1363 |
+
fFound = true;
|
| 1364 |
+
break;
|
| 1365 |
+
}
|
| 1366 |
+
}
|
| 1367 |
+
|
| 1368 |
+
if ((fLocalCheck && (allowableTypes & WorkItem::WorkItemTypeContext) &&
|
| 1369 |
+
GetLocalRunnable(pWorkItem, m_pVirtualProcessor, false)) ||
|
| 1370 |
+
|
| 1371 |
+
((allowableTypes & WorkItem::WorkItemTypeContext) &&
|
| 1372 |
+
SearchCacheLocal_Runnables(pWorkItem,
|
| 1373 |
+
pRing,
|
| 1374 |
+
pBiasSegment,
|
| 1375 |
+
fLocalCheck,
|
| 1376 |
+
srchType,
|
| 1377 |
+
allowableTypes,
|
| 1378 |
+
fLastPass)) ||
|
| 1379 |
+
|
| 1380 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) &&
|
| 1381 |
+
SearchCacheLocal_Realized(pWorkItem,
|
| 1382 |
+
pRing,
|
| 1383 |
+
pBiasSegment,
|
| 1384 |
+
!!(allowableTypes & WorkItem::WorkItemTypeRealizedChore),
|
| 1385 |
+
srchType,
|
| 1386 |
+
allowableTypes,
|
| 1387 |
+
fLastPass)) ||
|
| 1388 |
+
|
| 1389 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) &&
|
| 1390 |
+
SearchCacheLocal_Unrealized(pWorkItem,
|
| 1391 |
+
pRing,
|
| 1392 |
+
pBiasSegment,
|
| 1393 |
+
!!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore),
|
| 1394 |
+
srchType,
|
| 1395 |
+
allowableTypes,
|
| 1396 |
+
fLastPass)) ||
|
| 1397 |
+
|
| 1398 |
+
((allowableTypes & WorkItem::WorkItemTypeContext) && phaseIndex == maxPhaseIndex &&
|
| 1399 |
+
StealLocalRunnable(pWorkItem, pRing->GetOwningNode(), m_pVirtualProcessor)))
|
| 1400 |
+
{
|
| 1401 |
+
fFound = true;
|
| 1402 |
+
break;
|
| 1403 |
+
}
|
| 1404 |
+
|
| 1405 |
+
// 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
|
| 1406 |
+
// search algorithm.
|
| 1407 |
+
fLocalCheck = false;
|
| 1408 |
+
|
| 1409 |
+
// 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.
|
| 1410 |
+
pBiasSegment = NULL;
|
| 1411 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pOwningRing, pRing);
|
| 1412 |
+
|
| 1413 |
+
} // end of while (pRing != NULL) - this loop goes over all rings in the scheduler
|
| 1414 |
+
} // end of for (!fFound && phase <= maxPhase) - this loop goes through all search affinity types
|
| 1415 |
+
} // end of if (!fFound)
|
| 1416 |
+
|
| 1417 |
+
if (fFound)
|
| 1418 |
+
{
|
| 1419 |
+
ScheduleGroupSegmentBase *pSegment = pWorkItem->GetScheduleGroupSegment();
|
| 1420 |
+
SchedulingRing *pRing = pSegment->GetSchedulingRing();
|
| 1421 |
+
|
| 1422 |
+
pSegment->ServiceMark(m_serviceTick);
|
| 1423 |
+
|
| 1424 |
+
bool fAffine = false;
|
| 1425 |
+
if (!pSegment->GetAffinity()._Is_system())
|
| 1426 |
+
{
|
| 1427 |
+
location vpLoc = m_pVirtualProcessor->GetLocation();
|
| 1428 |
+
if (vpLoc._FastVPIntersects(pSegment->GetAffinity()))
|
| 1429 |
+
fAffine = true;
|
| 1430 |
+
}
|
| 1431 |
+
bool fLocal = pRing == pOwningRing;
|
| 1432 |
+
|
| 1433 |
+
m_pVirtualProcessor->UpdateWorkState(fAffine, fLocal);
|
| 1434 |
+
}
|
| 1435 |
+
|
| 1436 |
+
return fFound;
|
| 1437 |
+
}
|
| 1438 |
+
|
| 1439 |
+
/// <summary>
|
| 1440 |
+
/// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm for yielding.
|
| 1441 |
+
/// </summary>
|
| 1442 |
+
/// <param name="pWorkItem">
|
| 1443 |
+
/// If a work item is found, the work item will be returned here.
|
| 1444 |
+
/// </param>
|
| 1445 |
+
/// <param name="pOriginSegment">
|
| 1446 |
+
/// The segment to bias the search to. The need to prefer localized and prioritized work will often trump this bias.
|
| 1447 |
+
/// </param>
|
| 1448 |
+
/// <param name="fLastPass">
|
| 1449 |
+
/// An indication as to whether this is a last pass SFW.
|
| 1450 |
+
/// </param>
|
| 1451 |
+
/// <param name="allowableTypes">
|
| 1452 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 1453 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 1454 |
+
/// </param>
|
| 1455 |
+
/// <returns>
|
| 1456 |
+
/// An indication of whether a work item was found or not.
|
| 1457 |
+
/// </returns>
|
| 1458 |
+
bool WorkSearchContext::SearchCacheLocalYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes)
|
| 1459 |
+
{
|
| 1460 |
+
bool fFound = false;
|
| 1461 |
+
|
| 1462 |
+
if (PreSearch(pWorkItem))
|
| 1463 |
+
return true;
|
| 1464 |
+
|
| 1465 |
+
ASSERT(pOriginSegment);
|
| 1466 |
+
|
| 1467 |
+
m_serviceTick = platform::__GetTickCount64();
|
| 1468 |
+
m_pScheduler->PeriodicScan(m_serviceTick);
|
| 1469 |
+
|
| 1470 |
+
//
|
| 1471 |
+
// @TODO: This is a temporary patch until we have priority and boosts in the scheduler. Right now, search for any segment in the locked
|
| 1472 |
+
// FIFO of "priority" segments to see if we need to service someone to avoid livelock. We also periodically scan to determine whether
|
| 1473 |
+
// groups need to go into this list.
|
| 1474 |
+
//
|
| 1475 |
+
|
| 1476 |
+
if (CheckPriorityList(m_serviceTick))
|
| 1477 |
+
{
|
| 1478 |
+
if (m_pScheduler->HasPriorityObjects())
|
| 1479 |
+
{
|
| 1480 |
+
BoostedObject *pObject = m_pScheduler->GetNextPriorityObject();
|
| 1481 |
+
while (pObject != NULL)
|
| 1482 |
+
{
|
| 1483 |
+
if (pObject->IsScheduleGroupSegment())
|
| 1484 |
+
{
|
| 1485 |
+
ScheduleGroupSegmentBase *pSegment = ScheduleGroupSegmentBase::FromBoostEntry(pObject);
|
| 1486 |
+
OMTRACE(MTRACE_EVT_PRIORITYPULL, pSegment, NULL, m_pVirtualProcessor, 1);
|
| 1487 |
+
if (QuickSearchYield(pSegment, pWorkItem, fLastPass, allowableTypes))
|
| 1488 |
+
{
|
| 1489 |
+
fFound = true;
|
| 1490 |
+
break;
|
| 1491 |
+
}
|
| 1492 |
+
}
|
| 1493 |
+
else if (allowableTypes & WorkItem::WorkItemTypeContext)
|
| 1494 |
+
{
|
| 1495 |
+
VirtualProcessor *pVProc = VirtualProcessor::FromBoostEntry(pObject);
|
| 1496 |
+
InternalContextBase *pContext = pVProc->StealLocalRunnableContext();
|
| 1497 |
+
if (pContext != NULL)
|
| 1498 |
+
{
|
| 1499 |
+
*pWorkItem = WorkItem(pContext);
|
| 1500 |
+
fFound = true;
|
| 1501 |
+
break;
|
| 1502 |
+
}
|
| 1503 |
+
}
|
| 1504 |
+
|
| 1505 |
+
pObject = m_pScheduler->GetNextPriorityObject();
|
| 1506 |
+
}
|
| 1507 |
+
}
|
| 1508 |
+
|
| 1509 |
+
//
|
| 1510 |
+
// If we found something in a priority segment, we need to mark the V-Proc so that it once again looks for affinitized work
|
| 1511 |
+
// the next time through SFW.
|
| 1512 |
+
//
|
| 1513 |
+
m_pVirtualProcessor->MarkGrabbedPriority();
|
| 1514 |
+
}
|
| 1515 |
+
|
| 1516 |
+
SchedulingRing *pOwningRing = m_pVirtualProcessor->GetOwningRing();
|
| 1517 |
+
|
| 1518 |
+
if (!fFound)
|
| 1519 |
+
{
|
| 1520 |
+
//
|
| 1521 |
+
// Before describing the cache local search algorithm, some definitions to aid in this are in order:
|
| 1522 |
+
//
|
| 1523 |
+
// Work:
|
| 1524 |
+
// local work -- Work within a node/ring that a given virtual processor belongs to is considered local work
|
| 1525 |
+
// foreign work -- Work within a node/ring that a given virtual processor does *NOT* belong to is considered foreign work
|
| 1526 |
+
// affine work -- Work which is placed at a location more specific than the system location is affine work
|
| 1527 |
+
// non-affine work -- Work which is placed at the system location (or no location) is considered non-affine work
|
| 1528 |
+
//
|
| 1529 |
+
// Virtual Processors:
|
| 1530 |
+
// rambling -- a given virtual processor is *rambling* when it is executing foreign work (regardless whether such work is affine to it or not)
|
| 1531 |
+
// non-affine -- a given virtual processor is *non-affine* when it is executing non-affine work (regardless whether it is rambling or not)
|
| 1532 |
+
//
|
| 1533 |
+
// Virtual processors which are rambling or are executing non-affine work are tracked by the scheduler. When such virtual processors
|
| 1534 |
+
// exist, notifications will be published whenever affine work or local work
|
| 1535 |
+
//
|
| 1536 |
+
|
| 1537 |
+
//
|
| 1538 |
+
// **IN GENERAL**, we want to find work in the following order of precedence:
|
| 1539 |
+
//
|
| 1540 |
+
// Phase 1: Affine work
|
| 1541 |
+
// Affine work in our current group (preferring local affine work)
|
| 1542 |
+
// Local affine (to us) work (in our starting (home) ring)
|
| 1543 |
+
// Foreign affine (to us) work (in foreign ring segments that match our affinity mask -- such have a segment in our ring by definition)
|
| 1544 |
+
//
|
| 1545 |
+
// - This phase may be skipped if we are executing non-affine work and have not received an affinity notification from the scheduler.
|
| 1546 |
+
// Doing so prevents SFW from making a full pass per work item if no affinity has been used.
|
| 1547 |
+
//
|
| 1548 |
+
// Phase 2: Non-affine work
|
| 1549 |
+
// Non-Affine work in our current group (preferring local work)
|
| 1550 |
+
// Local non-affine work (in our starting (home ring))
|
| 1551 |
+
// Foreign non-affine work (in foreign rings).
|
| 1552 |
+
//
|
| 1553 |
+
// - This phase may *NEVER* be skipped.
|
| 1554 |
+
//
|
| 1555 |
+
// Phase 3: Affine work (non-local)
|
| 1556 |
+
// Non-local affine (*NOT* to us) work (in foreign ring segments that do not match our affinity mask
|
| 1557 |
+
//
|
| 1558 |
+
// - 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
|
| 1559 |
+
// any scheduling API, this phase is only hit if the scheduler is completely idle. At idle, performing a pass is likely little additional
|
| 1560 |
+
// cost to any performance sensitive scenario. At present, this stage is not skipped for this reason.
|
| 1561 |
+
//
|
| 1562 |
+
// At a very high level, you can consider a cache local search to be making vertical slices through the search space as follows:
|
| 1563 |
+
//
|
| 1564 |
+
// SR SR SR SR
|
| 1565 |
+
// Contexts | | | |
|
| 1566 |
+
// Realized | | | |
|
| 1567 |
+
// Unrealized v v v v
|
| 1568 |
+
//
|
| 1569 |
+
// where each entry in this matrix is a piece of a schedule group.
|
| 1570 |
+
//
|
| 1571 |
+
// 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
|
| 1572 |
+
// (assumptions on concurrency level).
|
| 1573 |
+
//
|
| 1574 |
+
static const SearchAffinity phaseAffinities[] = { SearchAffineLocal, SearchNonAffine, SearchAffineNotMe };
|
| 1575 |
+
// { 1 , 0 , 2 };
|
| 1576 |
+
int startPhaseIndex = (!m_pVirtualProcessor->ExecutingAffine() && !m_pVirtualProcessor->CheckAffinityNotification() && !fLastPass) ? 1 : 0;
|
| 1577 |
+
int maxPhaseIndex = SIZEOF_ARRAY(phaseAffinities) - 1;
|
| 1578 |
+
|
| 1579 |
+
// @TODO_LOC: We need livelock prevention by doing a priority boost on segments that haven't been serviced in "too long".
|
| 1580 |
+
|
| 1581 |
+
bool fLocalCheck = true;
|
| 1582 |
+
for (int phaseIndex = startPhaseIndex; !fFound && phaseIndex <= maxPhaseIndex; ++phaseIndex) // This loop goes through the phases in the phaseAffinity array.
|
| 1583 |
+
{
|
| 1584 |
+
SearchAffinity srchType = phaseAffinities[phaseIndex];
|
| 1585 |
+
|
| 1586 |
+
// At the outset of every pass, we bias to the originating segment/group and the current virtual processor's owning ring.
|
| 1587 |
+
// Note that if we are searching for non-local affine work, we skip the owning ring (by definition, it's local).
|
| 1588 |
+
ScheduleGroupSegmentBase *pBiasSegment = pOriginSegment;
|
| 1589 |
+
SchedulingRing *pRing = pOwningRing;
|
| 1590 |
+
|
| 1591 |
+
while (pRing != NULL)
|
| 1592 |
+
{
|
| 1593 |
+
if (((allowableTypes & WorkItem::WorkItemTypeMaskAnyUnrealizedChore) &&
|
| 1594 |
+
SearchCacheLocal_Unrealized(pWorkItem,
|
| 1595 |
+
pRing,
|
| 1596 |
+
pBiasSegment,
|
| 1597 |
+
!!(allowableTypes & WorkItem::WorkItemTypeUnrealizedChore),
|
| 1598 |
+
srchType,
|
| 1599 |
+
allowableTypes,
|
| 1600 |
+
fLastPass)) ||
|
| 1601 |
+
|
| 1602 |
+
((allowableTypes & WorkItem::WorkItemTypeMaskAnyRealizedChore) &&
|
| 1603 |
+
SearchCacheLocal_Realized(pWorkItem,
|
| 1604 |
+
pRing,
|
| 1605 |
+
pBiasSegment,
|
| 1606 |
+
!!(allowableTypes & WorkItem::WorkItemTypeRealizedChore),
|
| 1607 |
+
srchType,
|
| 1608 |
+
allowableTypes,
|
| 1609 |
+
fLastPass)) ||
|
| 1610 |
+
|
| 1611 |
+
((allowableTypes & WorkItem::WorkItemTypeContext) &&
|
| 1612 |
+
SearchCacheLocal_Runnables(pWorkItem,
|
| 1613 |
+
pRing,
|
| 1614 |
+
pBiasSegment,
|
| 1615 |
+
fLocalCheck,
|
| 1616 |
+
srchType,
|
| 1617 |
+
allowableTypes,
|
| 1618 |
+
fLastPass)) ||
|
| 1619 |
+
|
| 1620 |
+
((allowableTypes & WorkItem::WorkItemTypeContext) && phaseIndex == maxPhaseIndex &&
|
| 1621 |
+
StealLocalRunnable(pWorkItem, pRing->GetOwningNode(), m_pVirtualProcessor)) ||
|
| 1622 |
+
|
| 1623 |
+
(fLocalCheck && (allowableTypes & WorkItem::WorkItemTypeContext) &&
|
| 1624 |
+
GetLocalRunnable(pWorkItem, m_pVirtualProcessor, true)))
|
| 1625 |
+
|
| 1626 |
+
{
|
| 1627 |
+
fFound = true;
|
| 1628 |
+
break;
|
| 1629 |
+
}
|
| 1630 |
+
|
| 1631 |
+
// 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
|
| 1632 |
+
// search algorithm.
|
| 1633 |
+
fLocalCheck = false;
|
| 1634 |
+
|
| 1635 |
+
// 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.
|
| 1636 |
+
pBiasSegment = NULL;
|
| 1637 |
+
pRing = m_pScheduler->GetNextSchedulingRing(pOwningRing, pRing);
|
| 1638 |
+
|
| 1639 |
+
} // end of while (pRing != NULL) - this loop goes over all rings in the scheduler
|
| 1640 |
+
} // end of for (!fFound && phase <= maxPhase) - this loop goes through all search affinity types
|
| 1641 |
+
} // end of if (!fFound)
|
| 1642 |
+
|
| 1643 |
+
if (fFound)
|
| 1644 |
+
{
|
| 1645 |
+
ScheduleGroupSegmentBase *pSegment = pWorkItem->GetScheduleGroupSegment();
|
| 1646 |
+
SchedulingRing *pRing = pSegment->GetSchedulingRing();
|
| 1647 |
+
|
| 1648 |
+
pSegment->ServiceMark(m_serviceTick);
|
| 1649 |
+
|
| 1650 |
+
bool fAffine = pWorkItem->GetScheduleGroupSegment()->GetAffinity()._Is_system();
|
| 1651 |
+
bool fLocal = pRing == pOwningRing;
|
| 1652 |
+
|
| 1653 |
+
m_pVirtualProcessor->UpdateWorkState(fAffine, fLocal);
|
| 1654 |
+
}
|
| 1655 |
+
|
| 1656 |
+
return fFound;
|
| 1657 |
+
}
|
| 1658 |
+
}
|
| 1659 |
+
}
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SearchAlgorithms.h
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SearchAlgorithms.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing definitions for all scheduling algorithms.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
namespace Concurrency
|
| 15 |
+
{
|
| 16 |
+
namespace details
|
| 17 |
+
{
|
| 18 |
+
|
| 19 |
+
/// <summary>
|
| 20 |
+
/// Variant type representing a work item returned from a search.
|
| 21 |
+
/// </summary>
|
| 22 |
+
class WorkItem
|
| 23 |
+
{
|
| 24 |
+
public:
|
| 25 |
+
|
| 26 |
+
/// <summary>
|
| 27 |
+
/// The type of work item.
|
| 28 |
+
/// </summary>
|
| 29 |
+
enum WorkItemType
|
| 30 |
+
{
|
| 31 |
+
//
|
| 32 |
+
// Specific types:
|
| 33 |
+
//
|
| 34 |
+
|
| 35 |
+
// Empty work item
|
| 36 |
+
WorkItemTypeNone = 0x0,
|
| 37 |
+
|
| 38 |
+
// Work item is a context
|
| 39 |
+
WorkItemTypeContext = 0x1,
|
| 40 |
+
|
| 41 |
+
// Work item is a realized chore. Bind() will associate to a context if a context can be allocated
|
| 42 |
+
WorkItemTypeRealizedChore = 0x2,
|
| 43 |
+
|
| 44 |
+
// Work item is an unrealized chore. Bind() will associate to a context if a context can be allocated
|
| 45 |
+
WorkItemTypeUnrealizedChore = 0x4,
|
| 46 |
+
|
| 47 |
+
// Work item is a token to an realized chore. ResolveToken() will grab the item if it is still available.
|
| 48 |
+
WorkItemTypeRealizedChoreToken = 0x8,
|
| 49 |
+
|
| 50 |
+
// Work item is a token to an unrealized chore. ResolveToken() will grab the item if it is still available.
|
| 51 |
+
WorkItemTypeUnrealizedChoreToken = 0x10,
|
| 52 |
+
|
| 53 |
+
//
|
| 54 |
+
// General Masks:
|
| 55 |
+
//
|
| 56 |
+
|
| 57 |
+
WorkItemTypeMaskAnyRealizedChore = 0xA,
|
| 58 |
+
WorkItemTypeMaskAnyUnrealizedChore = 0x14
|
| 59 |
+
|
| 60 |
+
};
|
| 61 |
+
|
| 62 |
+
/// <summary>
|
| 63 |
+
/// Default constructor for a work item.
|
| 64 |
+
/// </summary>
|
| 65 |
+
WorkItem() :
|
| 66 |
+
m_type(WorkItemTypeNone),
|
| 67 |
+
m_pItem(NULL)
|
| 68 |
+
{
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/// <summary>
|
| 72 |
+
/// Constructs a work item from an internal context.
|
| 73 |
+
/// </summary>
|
| 74 |
+
WorkItem(InternalContextBase *pContext);
|
| 75 |
+
|
| 76 |
+
/// <summary>
|
| 77 |
+
/// Constructs a work item from a realized chore.
|
| 78 |
+
/// </summary>
|
| 79 |
+
WorkItem(RealizedChore *pRealizedChore, ScheduleGroupSegmentBase *pSegment) :
|
| 80 |
+
m_type(WorkItemTypeRealizedChore),
|
| 81 |
+
m_pSegment(pSegment),
|
| 82 |
+
m_pRealizedChore(pRealizedChore)
|
| 83 |
+
{
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
/// <summary>
|
| 87 |
+
/// Constructs a work item from an unrealized chore.
|
| 88 |
+
/// </summary>
|
| 89 |
+
WorkItem(_UnrealizedChore *pUnrealizedChore, ScheduleGroupSegmentBase *pSegment) :
|
| 90 |
+
m_type(WorkItemTypeUnrealizedChore),
|
| 91 |
+
m_pSegment(pSegment),
|
| 92 |
+
m_pUnrealizedChore(pUnrealizedChore)
|
| 93 |
+
{
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
/// <summary>
|
| 97 |
+
/// Constructs a work item from an unrealized chore token.
|
| 98 |
+
/// </summary>
|
| 99 |
+
WorkItem(WorkQueue *pWorkQueue, ScheduleGroupSegmentBase *pSegment) :
|
| 100 |
+
m_type(WorkItemTypeUnrealizedChoreToken),
|
| 101 |
+
m_pSegment(pSegment),
|
| 102 |
+
m_pWorkQueue(pWorkQueue)
|
| 103 |
+
{
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
/// <summary>
|
| 107 |
+
/// Constructs a work item from a realized chore token.
|
| 108 |
+
/// </summary>
|
| 109 |
+
WorkItem(ScheduleGroupSegmentBase *pSegment) :
|
| 110 |
+
m_type(WorkItemTypeRealizedChoreToken),
|
| 111 |
+
m_pSegment(pSegment),
|
| 112 |
+
m_pRealizedChore(nullptr)
|
| 113 |
+
{
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
/// <summary>
|
| 117 |
+
/// Transfers reference counts as necessary to inline the given work item on the given context. This may
|
| 118 |
+
/// only be called on a work item that can be inlined (e.g.: an unbound one).
|
| 119 |
+
/// </summary>
|
| 120 |
+
/// <param name="pContext">
|
| 121 |
+
/// The context that is attempting to inline the work item.
|
| 122 |
+
/// </param>
|
| 123 |
+
void TransferReferences(InternalContextBase *pContext);
|
| 124 |
+
|
| 125 |
+
/// <summary>
|
| 126 |
+
/// Resolves a token to an underlying work item.
|
| 127 |
+
/// </summary>
|
| 128 |
+
bool ResolveToken();
|
| 129 |
+
|
| 130 |
+
/// <summary>
|
| 131 |
+
/// Binds the work item to a context and returns the context. This may or may not allocate a new context. Note that
|
| 132 |
+
/// act of binding which performs a context allocation will transfer a single count of work to the counter of the new
|
| 133 |
+
/// context.
|
| 134 |
+
/// </summary>
|
| 135 |
+
InternalContextBase *Bind();
|
| 136 |
+
|
| 137 |
+
/// <summary>
|
| 138 |
+
/// Binds the work item to the specified context (which is allocated). This will never allocate a new context.
|
| 139 |
+
/// </summary>
|
| 140 |
+
void BindTo(InternalContextBase *pContext);
|
| 141 |
+
|
| 142 |
+
/// <summary>
|
| 143 |
+
/// Invokes the work item.
|
| 144 |
+
/// </summary>
|
| 145 |
+
void Invoke();
|
| 146 |
+
|
| 147 |
+
/// <summary>
|
| 148 |
+
/// Accessor for type.
|
| 149 |
+
/// </summary>
|
| 150 |
+
WorkItemType GetType() const
|
| 151 |
+
{
|
| 152 |
+
return m_type;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
/// <summary>
|
| 156 |
+
/// Returns the work item.
|
| 157 |
+
/// </summary>
|
| 158 |
+
void *GetItem() const
|
| 159 |
+
{
|
| 160 |
+
return m_pItem;
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
/// <summary>
|
| 164 |
+
/// Returns whether the work item is a context or not.
|
| 165 |
+
/// </summary>
|
| 166 |
+
bool IsContext() const
|
| 167 |
+
{
|
| 168 |
+
return (m_type == WorkItemTypeContext);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/// <summary>
|
| 172 |
+
/// Returns whether the work item is a token or not.
|
| 173 |
+
/// </summary>
|
| 174 |
+
bool IsToken() const
|
| 175 |
+
{
|
| 176 |
+
return ((m_type & (WorkItemTypeRealizedChoreToken | WorkItemTypeUnrealizedChoreToken)) != 0);
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
/// <summary>
|
| 180 |
+
/// Accessor for a context.
|
| 181 |
+
/// </summary>
|
| 182 |
+
InternalContextBase *GetContext() const
|
| 183 |
+
{
|
| 184 |
+
CONCRT_COREASSERT(m_type == WorkItemTypeContext);
|
| 185 |
+
return m_pContext;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
/// <summary>
|
| 189 |
+
/// Accessor for a realized chore.
|
| 190 |
+
/// </summary>
|
| 191 |
+
RealizedChore *GetRealizedChore() const
|
| 192 |
+
{
|
| 193 |
+
CONCRT_COREASSERT(m_type == WorkItemTypeRealizedChore);
|
| 194 |
+
return m_pRealizedChore;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
/// <summary>
|
| 198 |
+
/// Accessor for an unrealized chore.
|
| 199 |
+
/// </summary>
|
| 200 |
+
_UnrealizedChore *GetUnrealizedChore() const
|
| 201 |
+
{
|
| 202 |
+
CONCRT_COREASSERT(m_type == WorkItemTypeUnrealizedChore);
|
| 203 |
+
return m_pUnrealizedChore;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
/// <summary>
|
| 207 |
+
/// Accessor for the schedule group segment.
|
| 208 |
+
/// </summary>
|
| 209 |
+
ScheduleGroupSegmentBase *GetScheduleGroupSegment() const
|
| 210 |
+
{
|
| 211 |
+
return m_pSegment;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
/// <summary>
|
| 215 |
+
/// Accessor for the schedule group.
|
| 216 |
+
/// </summary>
|
| 217 |
+
ScheduleGroupBase *GetScheduleGroup() const;
|
| 218 |
+
|
| 219 |
+
private:
|
| 220 |
+
|
| 221 |
+
// The type of work item
|
| 222 |
+
WorkItemType m_type;
|
| 223 |
+
|
| 224 |
+
// The schedule group that the work item was found in.
|
| 225 |
+
ScheduleGroupSegmentBase *m_pSegment{};
|
| 226 |
+
|
| 227 |
+
// The work item itself
|
| 228 |
+
union
|
| 229 |
+
{
|
| 230 |
+
void *m_pItem;
|
| 231 |
+
WorkQueue *m_pWorkQueue;
|
| 232 |
+
InternalContextBase *m_pContext;
|
| 233 |
+
RealizedChore *m_pRealizedChore;
|
| 234 |
+
_UnrealizedChore *m_pUnrealizedChore;
|
| 235 |
+
};
|
| 236 |
+
|
| 237 |
+
};
|
| 238 |
+
|
| 239 |
+
/// <summary>
|
| 240 |
+
/// A class which tracks iterator state for a search-for-work. This is generic in terms of search algorithm.
|
| 241 |
+
/// </summary>
|
| 242 |
+
class WorkSearchContext
|
| 243 |
+
{
|
| 244 |
+
public:
|
| 245 |
+
|
| 246 |
+
/// <summary>
|
| 247 |
+
/// Describes the search algorithm being utilized.
|
| 248 |
+
/// </summary>
|
| 249 |
+
enum Algorithm
|
| 250 |
+
{
|
| 251 |
+
AlgorithmNotSet = 0,
|
| 252 |
+
AlgorithmCacheLocal,
|
| 253 |
+
AlgorithmFair
|
| 254 |
+
};
|
| 255 |
+
|
| 256 |
+
/// <summary>
|
| 257 |
+
/// Describes the type of affinity we are allowed to search for.
|
| 258 |
+
/// </summary>
|
| 259 |
+
enum SearchAffinity
|
| 260 |
+
{
|
| 261 |
+
// Search for non-affine work within the domain of the search.
|
| 262 |
+
SearchNonAffine,
|
| 263 |
+
|
| 264 |
+
// Search for work which is affine to the search context within the domain of the search.
|
| 265 |
+
SearchAffineLocal,
|
| 266 |
+
|
| 267 |
+
// Search for work which is affine to something OTHER than the search context within the domain of the search.
|
| 268 |
+
SearchAffineNotMe
|
| 269 |
+
};
|
| 270 |
+
|
| 271 |
+
/// <summary>
|
| 272 |
+
/// Constructs a work search context that will be reset later.
|
| 273 |
+
/// </summary>
|
| 274 |
+
WorkSearchContext() : m_pVirtualProcessor(NULL), m_pScheduler(NULL), m_pSearchFn(NULL), m_pSearchYieldFn(NULL)
|
| 275 |
+
{
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
/// <summary>
|
| 279 |
+
/// Constructs a work search context (an iterator position for a search algorithm).
|
| 280 |
+
/// </summary>
|
| 281 |
+
WorkSearchContext(VirtualProcessor *pVirtualProcessor, Algorithm algorithm)
|
| 282 |
+
{
|
| 283 |
+
Reset(pVirtualProcessor, algorithm);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/// <summary>
|
| 287 |
+
/// Resets the work search context to utilize the specified algorithm at the starting iterator position.
|
| 288 |
+
/// </summary>
|
| 289 |
+
/// <param name="pVirtualProcessor">
|
| 290 |
+
/// The virtual processor binding the searching.
|
| 291 |
+
/// </param>
|
| 292 |
+
/// <param name="algorithm">
|
| 293 |
+
/// What algorithm to reset the iterator with.
|
| 294 |
+
/// </param>
|
| 295 |
+
void Reset(VirtualProcessor *pVirtualProcessor, Algorithm algorithm);
|
| 296 |
+
|
| 297 |
+
/// <summary>
|
| 298 |
+
/// Searches from the last iterator position according to the set algorithm. This can return any type of work
|
| 299 |
+
/// item (context, realized chore, or unrealized chore)
|
| 300 |
+
/// </summary>
|
| 301 |
+
/// <param name="pWorkItem">
|
| 302 |
+
/// Upon successful return, the resulting work item is placed here along with information about what group it was found in, etc...
|
| 303 |
+
/// </param>
|
| 304 |
+
/// <param name="pOriginSegment">
|
| 305 |
+
/// The schedule group segment of the context which is performing the search.
|
| 306 |
+
/// </param>
|
| 307 |
+
/// <param name="fLastPass">
|
| 308 |
+
/// An indication as to whether this is a last pass SFW.
|
| 309 |
+
/// </param>
|
| 310 |
+
/// <param name="allowableTypes">
|
| 311 |
+
/// What type of work items are allowed to be returned.
|
| 312 |
+
/// </param>
|
| 313 |
+
/// <returns>
|
| 314 |
+
/// An indication of whether a work item was found or not.
|
| 315 |
+
/// </returns>
|
| 316 |
+
bool Search(WorkItem *pWorkItem,
|
| 317 |
+
ScheduleGroupSegmentBase *pOriginSegment,
|
| 318 |
+
bool fLastPass = false,
|
| 319 |
+
ULONG allowableTypes = WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore | WorkItem::WorkItemTypeUnrealizedChore)
|
| 320 |
+
{
|
| 321 |
+
return (this->*m_pSearchFn)(pWorkItem, pOriginSegment, fLastPass, allowableTypes);
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
/// <summary>
|
| 326 |
+
/// Searches from the last iterator position according to the set algorithm for a yield. This can return any type of
|
| 327 |
+
/// work item (context, realized chore, or unrealized chore)
|
| 328 |
+
/// </summary>
|
| 329 |
+
bool YieldingSearch(WorkItem *pWorkItem,
|
| 330 |
+
ScheduleGroupSegmentBase *pOriginSegment,
|
| 331 |
+
bool fLastPass = false,
|
| 332 |
+
ULONG allowableTypes = WorkItem::WorkItemTypeContext | WorkItem::WorkItemTypeRealizedChore)
|
| 333 |
+
{
|
| 334 |
+
return (this->*m_pSearchYieldFn)(pWorkItem, pOriginSegment, fLastPass, allowableTypes);
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
private:
|
| 338 |
+
|
| 339 |
+
// **************************************************
|
| 340 |
+
// Common:
|
| 341 |
+
//
|
| 342 |
+
|
| 343 |
+
/// <summary>
|
| 344 |
+
/// Describes where the bias towards certain lists is at within SFW.
|
| 345 |
+
/// </summary>
|
| 346 |
+
enum BiasStageType
|
| 347 |
+
{
|
| 348 |
+
BiasStageNone,
|
| 349 |
+
BiasStageFlipLRC,
|
| 350 |
+
BiasStageSkipLRC
|
| 351 |
+
};
|
| 352 |
+
|
| 353 |
+
// The virtual processor binding the search.
|
| 354 |
+
VirtualProcessor *m_pVirtualProcessor;
|
| 355 |
+
|
| 356 |
+
// The scheduler
|
| 357 |
+
SchedulerBase *m_pScheduler;
|
| 358 |
+
|
| 359 |
+
// The mask ID of the virtual processor binding the search.
|
| 360 |
+
unsigned int m_maskId{};
|
| 361 |
+
|
| 362 |
+
// How many times work has been found in the LRC since the last reset.
|
| 363 |
+
ULONG m_LRCBias{};
|
| 364 |
+
|
| 365 |
+
// The service time stamp
|
| 366 |
+
ULONGLONG m_serviceTick{};
|
| 367 |
+
|
| 368 |
+
// TRANSITION: This goes with real priority...
|
| 369 |
+
ULONGLONG m_lastPriorityPull{};
|
| 370 |
+
|
| 371 |
+
// The search function to utilize.
|
| 372 |
+
bool (WorkSearchContext::*m_pSearchFn)(WorkItem *pWorkItem,
|
| 373 |
+
ScheduleGroupSegmentBase *pOriginSegment,
|
| 374 |
+
bool fLastPass,
|
| 375 |
+
ULONG allowableTypes);
|
| 376 |
+
|
| 377 |
+
// The search function to utilize for yielding.
|
| 378 |
+
bool (WorkSearchContext::*m_pSearchYieldFn)(WorkItem *pWorkItem,
|
| 379 |
+
ScheduleGroupSegmentBase *pOriginSegment,
|
| 380 |
+
bool fLastPass,
|
| 381 |
+
ULONG allowableTypes);
|
| 382 |
+
|
| 383 |
+
//
|
| 384 |
+
// TRANSITION: This goes with real priority...
|
| 385 |
+
//
|
| 386 |
+
bool CheckPriorityList(ULONGLONG serviceTime)
|
| 387 |
+
{
|
| 388 |
+
bool fCheck = ((serviceTime - m_lastPriorityPull) > (ULONGLONG)1000);
|
| 389 |
+
if (fCheck)
|
| 390 |
+
m_lastPriorityPull = serviceTime;
|
| 391 |
+
|
| 392 |
+
return fCheck;
|
| 393 |
+
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
/// <summary>
|
| 397 |
+
/// Performs a quick search of a particular segment.
|
| 398 |
+
/// </summary>
|
| 399 |
+
bool QuickSearch(ScheduleGroupSegmentBase *pQCSegment,
|
| 400 |
+
WorkItem *pWorkItem,
|
| 401 |
+
bool fLastPass,
|
| 402 |
+
ULONG allowableTypes);
|
| 403 |
+
|
| 404 |
+
/// <summary>
|
| 405 |
+
/// Performs a quick yielding search of a particular segment.
|
| 406 |
+
/// </summary>
|
| 407 |
+
bool QuickSearchYield(ScheduleGroupSegmentBase *pQCSegment,
|
| 408 |
+
WorkItem *pWorkItem,
|
| 409 |
+
bool fLastPass,
|
| 410 |
+
ULONG allowableTypes);
|
| 411 |
+
|
| 412 |
+
/// <summary>
|
| 413 |
+
/// Performs a pre-search for any "special" contexts (e.g.: the UMS SUT)
|
| 414 |
+
/// </summary>
|
| 415 |
+
bool PreSearch(WorkItem *pWorkItem);
|
| 416 |
+
|
| 417 |
+
/// <summary>
|
| 418 |
+
/// Steals a local runnable from a virtual processor within the specified node. Note that this allows a given virtual processor
|
| 419 |
+
/// to be skipped.
|
| 420 |
+
/// </summary>
|
| 421 |
+
bool StealLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pNode, VirtualProcessor *pSkipVirtualProcessor);
|
| 422 |
+
|
| 423 |
+
/// <summary>
|
| 424 |
+
/// Steals a local runnable from a virtual processor of any scheduling node other than the specified local node.
|
| 425 |
+
/// </summary>
|
| 426 |
+
bool StealForeignLocalRunnable(WorkItem *pWorkItem, SchedulingNode *pLocalNode);
|
| 427 |
+
|
| 428 |
+
/// <summary>
|
| 429 |
+
/// Gets a local runnable context from the specified virtual processor.
|
| 430 |
+
/// </summary>
|
| 431 |
+
bool GetLocalRunnable(WorkItem *pWorkItem, VirtualProcessor *pVirtualProcessor, bool fYieldingSearch);
|
| 432 |
+
|
| 433 |
+
/// <summary>
|
| 434 |
+
/// Gets a runnable from the specified schedule group segment.
|
| 435 |
+
/// </summary>
|
| 436 |
+
/// <param name="pWorkItem">
|
| 437 |
+
/// If a work item is found, the work item will be returned here.
|
| 438 |
+
/// </param>
|
| 439 |
+
/// <param name="pSegment">
|
| 440 |
+
/// The schedule group segment in which to look for a runnable context.
|
| 441 |
+
/// </param>
|
| 442 |
+
/// <returns>
|
| 443 |
+
/// An indication of whether or not a runnable context was found in the segment.
|
| 444 |
+
/// </returns>
|
| 445 |
+
bool GetRunnableContext(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment);
|
| 446 |
+
|
| 447 |
+
/// <summary>
|
| 448 |
+
/// Gets a realized chore from the specified schedule group segment.
|
| 449 |
+
/// </summary>
|
| 450 |
+
/// <param name="pWorkItem">
|
| 451 |
+
/// If a work item is found, the work item will be returned here.
|
| 452 |
+
/// </param>
|
| 453 |
+
/// <param name="pSegment">
|
| 454 |
+
/// The schedule group segment in which to look for a realized chore.
|
| 455 |
+
/// </param>
|
| 456 |
+
/// <param name="fRealWork">
|
| 457 |
+
/// 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
|
| 458 |
+
/// is resolved.
|
| 459 |
+
/// </param>
|
| 460 |
+
/// <returns>
|
| 461 |
+
/// An indication of whether or not a realized chore was found in the segment.
|
| 462 |
+
/// </returns>
|
| 463 |
+
bool GetRealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork);
|
| 464 |
+
|
| 465 |
+
/// <summary>
|
| 466 |
+
/// Gets an unrealized chore from the specified schedule group segment.
|
| 467 |
+
/// </summary>
|
| 468 |
+
/// <param name="pWorkItem">
|
| 469 |
+
/// If a work item is found, the work item will be returned here.
|
| 470 |
+
/// </param>
|
| 471 |
+
/// <param name="pSegment">
|
| 472 |
+
/// The schedule group segment in which to look for an unrealized chore.
|
| 473 |
+
/// </param>
|
| 474 |
+
/// <param name="fForceStealLocalized">
|
| 475 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 476 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 477 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 478 |
+
/// </param>
|
| 479 |
+
/// <param name="fRealWork">
|
| 480 |
+
/// 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
|
| 481 |
+
/// is resolved.
|
| 482 |
+
/// </param>
|
| 483 |
+
/// <returns>
|
| 484 |
+
/// An indication of whether or not an unrealized chore was found in the segment.
|
| 485 |
+
/// </returns>
|
| 486 |
+
bool GetUnrealizedChore(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fForceStealLocalized, bool fRealWork);
|
| 487 |
+
|
| 488 |
+
/// <summary>
|
| 489 |
+
/// Determines if a segment should be skipped given the search parameters and the segment's affinity.
|
| 490 |
+
/// </summary>
|
| 491 |
+
/// <param name="pSegment">
|
| 492 |
+
/// The segment to query about skipping.
|
| 493 |
+
/// </param>
|
| 494 |
+
/// <param name="pSkipSegment">
|
| 495 |
+
/// A segment which should be arbitrarily skipped regardless of affinity type. This parameter can be NULL.
|
| 496 |
+
/// </param>
|
| 497 |
+
/// <param name="affinity">
|
| 498 |
+
/// The search affinity type to query for.
|
| 499 |
+
/// </param>
|
| 500 |
+
/// <param name="fLastPass">
|
| 501 |
+
/// An indication as to whether this is a last pass SFW.
|
| 502 |
+
/// </param>
|
| 503 |
+
/// <returns>
|
| 504 |
+
/// An indication as to whether pSegment should be skipped according to the pSkipSegment and affinity parameters.
|
| 505 |
+
/// </returns>
|
| 506 |
+
bool SkipSegmentSearch(ScheduleGroupSegmentBase *pSegment, ScheduleGroupSegmentBase *pSkipSegment, SearchAffinity affinity, bool fLastPass);
|
| 507 |
+
|
| 508 |
+
/// <summary>
|
| 509 |
+
/// Searches the schedule group to which pSegment belongs to find a runnable. The group is searched for segments according to the specified
|
| 510 |
+
/// affinity type.
|
| 511 |
+
/// </summary>
|
| 512 |
+
/// <param name="pWorkItem">
|
| 513 |
+
/// If an appropriate runnable is found, the resulting work item will be placed here.
|
| 514 |
+
/// </param>
|
| 515 |
+
/// <param name="pSegment">
|
| 516 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 517 |
+
/// </param>
|
| 518 |
+
/// <param name="fLastPass">
|
| 519 |
+
/// An indication as to whether this is a last pass SFW.
|
| 520 |
+
/// </param>
|
| 521 |
+
/// <returns>
|
| 522 |
+
/// An indication of whether a work item was found or not.
|
| 523 |
+
/// </returns>
|
| 524 |
+
bool GetRunnableContextWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, SearchAffinity affinity, bool fLastPass);
|
| 525 |
+
|
| 526 |
+
/// <summary>
|
| 527 |
+
/// Searches the schedule group to which pSegment belongs to find a realized chore. The group is searched for segments according to the specified
|
| 528 |
+
/// affinity type.
|
| 529 |
+
/// </summary>
|
| 530 |
+
/// <param name="pWorkItem">
|
| 531 |
+
/// If an appropriate realized chore is found, the resulting work item will be placed here.
|
| 532 |
+
/// </param>
|
| 533 |
+
/// <param name="pSegment">
|
| 534 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 535 |
+
/// </param>
|
| 536 |
+
/// <param name="fLastPass">
|
| 537 |
+
/// An indication as to whether this is a last pass SFW.
|
| 538 |
+
/// </param>
|
| 539 |
+
/// <returns>
|
| 540 |
+
/// An indication of whether a work item was found or not.
|
| 541 |
+
/// </returns>
|
| 542 |
+
bool GetRealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass);
|
| 543 |
+
|
| 544 |
+
/// <summary>
|
| 545 |
+
/// Searches the schedule group to which pSegment belongs to find an unrealized chore. The group is searched for segments according to the
|
| 546 |
+
/// specified affinity type.
|
| 547 |
+
/// </summary>
|
| 548 |
+
/// <param name="pWorkItem">
|
| 549 |
+
/// If an appropriate unrealized chore is found, the resulting work item will be placed here.
|
| 550 |
+
/// </param>
|
| 551 |
+
/// <param name="pSegment">
|
| 552 |
+
/// A segment within the group to search. This segment has bias within the group if it matches the specified affinity type.
|
| 553 |
+
/// </param>
|
| 554 |
+
/// <param name="fLastPass">
|
| 555 |
+
/// An indication as to whether this is a last pass SFW.
|
| 556 |
+
/// </param>
|
| 557 |
+
/// <returns>
|
| 558 |
+
/// An indication of whether a work item was found or not.
|
| 559 |
+
/// </returns>
|
| 560 |
+
bool GetUnrealizedChoreWithinGroup(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pSegment, bool fRealWork, SearchAffinity affinity, bool fLastPass);
|
| 561 |
+
|
| 562 |
+
/// <summary>
|
| 563 |
+
/// Called on any biased work.
|
| 564 |
+
/// </summary>
|
| 565 |
+
void LRCBias()
|
| 566 |
+
{
|
| 567 |
+
m_LRCBias++;
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
/// <summary>
|
| 571 |
+
/// Resets the local bias counter but not the ring bias counter.
|
| 572 |
+
/// </summary>
|
| 573 |
+
void ResetLRCBias()
|
| 574 |
+
{
|
| 575 |
+
m_LRCBias = 0;
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// <summary>
|
| 579 |
+
/// Returns the current stage of local bias.
|
| 580 |
+
/// </summary>
|
| 581 |
+
BiasStageType BiasStage()
|
| 582 |
+
{
|
| 583 |
+
if (m_LRCBias < 101)
|
| 584 |
+
return BiasStageNone; // (fwd) Normal --> LRC LIFO
|
| 585 |
+
else if (m_LRCBias < 127)
|
| 586 |
+
return BiasStageFlipLRC; // (fwd) Flip LRC --> LRC FIFO
|
| 587 |
+
else
|
| 588 |
+
return BiasStageSkipLRC; // (fwd) Skip LRC --> runnables
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
// **************************************************
|
| 592 |
+
// Cache Local Algorithm:
|
| 593 |
+
//
|
| 594 |
+
|
| 595 |
+
/// <summary>
|
| 596 |
+
/// Searches for a runnable within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 597 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 598 |
+
/// </summary>
|
| 599 |
+
/// <param name="pWorkItem">
|
| 600 |
+
/// If a work item is found, the work item will be returned here.
|
| 601 |
+
/// </param>
|
| 602 |
+
/// <param name="pRing">
|
| 603 |
+
/// The scheduling ring to search.
|
| 604 |
+
/// </param>
|
| 605 |
+
/// <param name="pBiasSegment">
|
| 606 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 607 |
+
/// </param>
|
| 608 |
+
/// <param name="fOtherLocalLRCCheck">
|
| 609 |
+
/// Determines whether or not to check other local LRCs in this search.
|
| 610 |
+
/// </param>
|
| 611 |
+
/// <param name="affinity">
|
| 612 |
+
/// The search affinity type to query for.
|
| 613 |
+
/// </param>
|
| 614 |
+
/// <param name="allowableTypes">
|
| 615 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 616 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 617 |
+
/// </param>
|
| 618 |
+
/// <param name="fLastPass">
|
| 619 |
+
/// An indication as to whether this is a last pass SFW.
|
| 620 |
+
/// </param>
|
| 621 |
+
/// <returns>
|
| 622 |
+
/// An indication of whether a runnable was found in the bias segment, group, or the specified ring.
|
| 623 |
+
/// </returns>
|
| 624 |
+
bool SearchCacheLocal_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 625 |
+
bool fOtherLocalLRCCheck, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass);
|
| 626 |
+
|
| 627 |
+
/// <summary>
|
| 628 |
+
/// Searches for a realized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 629 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 630 |
+
/// </summary>
|
| 631 |
+
/// <param name="pWorkItem">
|
| 632 |
+
/// If a work item is found, the work item will be returned here.
|
| 633 |
+
/// </param>
|
| 634 |
+
/// <param name="pRing">
|
| 635 |
+
/// The scheduling ring to search.
|
| 636 |
+
/// </param>
|
| 637 |
+
/// <param name="pBiasSegment">
|
| 638 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 639 |
+
/// </param>
|
| 640 |
+
/// <param name="fRealWork">
|
| 641 |
+
/// 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
|
| 642 |
+
/// is resolved.
|
| 643 |
+
/// </param>
|
| 644 |
+
/// <param name="affinity">
|
| 645 |
+
/// The search affinity type to query for.
|
| 646 |
+
/// </param>
|
| 647 |
+
/// <param name="allowableTypes">
|
| 648 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 649 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 650 |
+
/// </param>
|
| 651 |
+
/// <param name="fLastPass">
|
| 652 |
+
/// An indication as to whether this is a last pass SFW.
|
| 653 |
+
/// </param>
|
| 654 |
+
/// <returns>
|
| 655 |
+
/// An indication of whether a realized chore was found in the bias segment, group, or the specified ring.
|
| 656 |
+
/// </returns>
|
| 657 |
+
bool SearchCacheLocal_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 658 |
+
bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass);
|
| 659 |
+
|
| 660 |
+
/// <summary>
|
| 661 |
+
/// Searches for an unrealized chore within the specified ring. Before searching elsewhere, it searches the segment and group specified by
|
| 662 |
+
/// pBiasSegment according to the rules of the search and the requested affinity type.
|
| 663 |
+
/// </summary>
|
| 664 |
+
/// <param name="pWorkItem">
|
| 665 |
+
/// If a work item is found, the work item will be returned here.
|
| 666 |
+
/// </param>
|
| 667 |
+
/// <param name="pRing">
|
| 668 |
+
/// The scheduling ring to search.
|
| 669 |
+
/// </param>
|
| 670 |
+
/// <param name="pBiasSegment">
|
| 671 |
+
/// The segment to bias the search to. This segment and its corresponding group are searched first!
|
| 672 |
+
/// </param>
|
| 673 |
+
/// <param name="fRealWork">
|
| 674 |
+
/// 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
|
| 675 |
+
/// is resolved.
|
| 676 |
+
/// </param>
|
| 677 |
+
/// <param name="affinity">
|
| 678 |
+
/// The search affinity type to query for.
|
| 679 |
+
/// </param>
|
| 680 |
+
/// <param name="allowableTypes">
|
| 681 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 682 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 683 |
+
/// </param>
|
| 684 |
+
/// <param name="fLastPass">
|
| 685 |
+
/// An indication as to whether this is a last pass SFW.
|
| 686 |
+
/// </param>
|
| 687 |
+
/// <returns>
|
| 688 |
+
/// An indication of whether an unrealized chore was found in the bias segment, group, or the specified ring.
|
| 689 |
+
/// </returns>
|
| 690 |
+
bool SearchCacheLocal_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, ScheduleGroupSegmentBase *pBiasSegment,
|
| 691 |
+
bool fRealWork, SearchAffinity affinity, ULONG allowableTypes, bool fLastPass);
|
| 692 |
+
|
| 693 |
+
/// <summary>
|
| 694 |
+
/// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm.
|
| 695 |
+
/// </summary>
|
| 696 |
+
/// <param name="pWorkItem">
|
| 697 |
+
/// If a work item is found, the work item will be returned here.
|
| 698 |
+
/// </param>
|
| 699 |
+
/// <param name="pOriginSegment">
|
| 700 |
+
/// The segment to bias the search to.
|
| 701 |
+
/// </param>
|
| 702 |
+
/// <param name="fLastPass">
|
| 703 |
+
/// An indication as to whether this is a last pass SFW.
|
| 704 |
+
/// </param>
|
| 705 |
+
/// <param name="allowableTypes">
|
| 706 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 707 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 708 |
+
/// </param>
|
| 709 |
+
/// <returns>
|
| 710 |
+
/// An indication of whether a work item was found or not.
|
| 711 |
+
/// </returns>
|
| 712 |
+
bool SearchCacheLocal(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes);
|
| 713 |
+
|
| 714 |
+
/// <summary>
|
| 715 |
+
/// Searches for work within the scheduler according to the cache local (schedule group local) search algorithm for yielding.
|
| 716 |
+
/// </summary>
|
| 717 |
+
/// <param name="pWorkItem">
|
| 718 |
+
/// If a work item is found, the work item will be returned here.
|
| 719 |
+
/// </param>
|
| 720 |
+
/// <param name="pOriginSegment">
|
| 721 |
+
/// The segment to bias the search to.
|
| 722 |
+
/// </param>
|
| 723 |
+
/// <param name="fLastPass">
|
| 724 |
+
/// An indication as to whether this is a last pass SFW.
|
| 725 |
+
/// </param>
|
| 726 |
+
/// <param name="allowableTypes">
|
| 727 |
+
/// A bitmap of work-types allowed to be returned from the search. This indicates whether or not runnables, realized chores, or unrealized chores
|
| 728 |
+
/// can be returned as well as whether the actual work item or only a token should be returned.
|
| 729 |
+
/// </param>
|
| 730 |
+
/// <returns>
|
| 731 |
+
/// An indication of whether a work item was found or not.
|
| 732 |
+
/// </returns>
|
| 733 |
+
bool SearchCacheLocalYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes);
|
| 734 |
+
|
| 735 |
+
// **************************************************
|
| 736 |
+
// Fair Algorithm:
|
| 737 |
+
//
|
| 738 |
+
|
| 739 |
+
/// <summary>
|
| 740 |
+
/// Performs a fair search for runnables in the specified ring.
|
| 741 |
+
/// </summary>
|
| 742 |
+
bool SearchFair_Runnables(WorkItem *pWorkItem, SchedulingRing *pRing);
|
| 743 |
+
|
| 744 |
+
/// <summary>
|
| 745 |
+
/// Performs a fair search for realized chores in the specified ring.
|
| 746 |
+
/// </summary>
|
| 747 |
+
bool SearchFair_Realized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem);
|
| 748 |
+
|
| 749 |
+
/// <summary>
|
| 750 |
+
/// Performs a fair search for unrealized chores in the specified ring.
|
| 751 |
+
/// </summary>
|
| 752 |
+
bool SearchFair_Unrealized(WorkItem *pWorkItem, SchedulingRing *pRing, bool fRealItem);
|
| 753 |
+
|
| 754 |
+
/// <summary>
|
| 755 |
+
/// Performs a fair search for work.
|
| 756 |
+
/// </summary>
|
| 757 |
+
bool SearchFair(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes);
|
| 758 |
+
|
| 759 |
+
/// <summary>
|
| 760 |
+
/// Performs a fair search for work in the yielding case.
|
| 761 |
+
/// </summary>
|
| 762 |
+
bool SearchFairYield(WorkItem *pWorkItem, ScheduleGroupSegmentBase *pOriginSegment, bool fLastPass, ULONG allowableTypes);
|
| 763 |
+
|
| 764 |
+
};
|
| 765 |
+
|
| 766 |
+
}
|
| 767 |
+
}
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/StructuredWorkStealingQueue.h
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// StructuredWorkStealingQueue.h
|
| 9 |
+
//
|
| 10 |
+
// Header file containing the core implementation of the work stealing data structures and algorithms.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// A StructuredWorkStealingQueue is a wait-free, lock-free structure associated with a single
|
| 22 |
+
/// thread that can Push and Pop elements. Other threads can do Steal operations
|
| 23 |
+
/// on the other end of the StructuredWorkStealingQueue with little contention.
|
| 24 |
+
/// </summary>
|
| 25 |
+
template <typename T, typename LOCK=_NonReentrantLock>
|
| 26 |
+
class StructuredWorkStealingQueue
|
| 27 |
+
{
|
| 28 |
+
// A 'StructuredWorkStealingQueue' always runs its code in a single OS thread. We call this the
|
| 29 |
+
// 'bound' thread. Only the code in the Steal operation can be executed by
|
| 30 |
+
// other 'foreign' threads that try to steal work.
|
| 31 |
+
//
|
| 32 |
+
// The queue is implemented as a lock-free dequeue of arrays. The m_head and m_tail index this
|
| 33 |
+
// array. To avoid copying elements, the m_head and m_tail index the array modulo
|
| 34 |
+
// the size of the array. By making this a power of two, we can use a cheap
|
| 35 |
+
// bit-and operation to take the modulus. The "m_mask" is always equal to the
|
| 36 |
+
// size of the task array minus one (where the size is a power of two).
|
| 37 |
+
//
|
| 38 |
+
// The m_head and m_tail are volatile as they can be updated from different OS threads.
|
| 39 |
+
// The "m_head" is only updated by foreign threads as they Steal a task from
|
| 40 |
+
// this queue. By putting a lock in Steal, there is at most one foreign thread
|
| 41 |
+
// changing m_head at a time. The m_tail is only updated by the bound thread.
|
| 42 |
+
//
|
| 43 |
+
// invariants:
|
| 44 |
+
// tasks.length is a power of 2
|
| 45 |
+
// m_mask == tasks.length-1
|
| 46 |
+
// m_head is only written to by foreign threads
|
| 47 |
+
// m_tail is only written to by the bound thread
|
| 48 |
+
// At most one foreign thread can do a Steal
|
| 49 |
+
// All methods except Steal are executed from a single bound thread
|
| 50 |
+
// m_tail points to the first unused location
|
| 51 |
+
//
|
| 52 |
+
// This work stealing implementation also supports the notion of out-of-order waiting
|
| 53 |
+
// and out-of-order removal from the bound thread given that it is initialized to do so.
|
| 54 |
+
// There is additional cost to performing this.
|
| 55 |
+
//
|
| 56 |
+
|
| 57 |
+
public:
|
| 58 |
+
|
| 59 |
+
/// <summary>
|
| 60 |
+
/// Constructs a new work stealing queue
|
| 61 |
+
/// </summary>
|
| 62 |
+
StructuredWorkStealingQueue(LOCK *pLock)
|
| 63 |
+
: m_head(0),
|
| 64 |
+
m_tail(0),
|
| 65 |
+
m_pLock(pLock)
|
| 66 |
+
{
|
| 67 |
+
ASSERT(s_initialSize > 1);
|
| 68 |
+
m_mask = s_initialSize - 1;
|
| 69 |
+
m_ppTasks = _concrt_new T*[s_initialSize];
|
| 70 |
+
m_pSlots = _concrt_new typename Mailbox<T>::Slot[s_initialSize];
|
| 71 |
+
memset(m_ppTasks, 0, s_initialSize * sizeof(T*));
|
| 72 |
+
ASSERT(m_pLock != NULL);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/// <summary>
|
| 76 |
+
/// Reinitializes a workqueue to the state essentially equivalent to just after construction.
|
| 77 |
+
/// This is used when recycling a workqueue from its ListArray
|
| 78 |
+
/// </summary>
|
| 79 |
+
/// <param name="allowOutOfOrder">
|
| 80 |
+
/// Indicates whether or not the work stealing queue will allow out of order waiting on the bound thread.
|
| 81 |
+
/// Allowing this has additional cost.
|
| 82 |
+
/// </param>
|
| 83 |
+
/// <param name="initialSize">
|
| 84 |
+
/// Indicates the initially allocated size for the physical work item storage
|
| 85 |
+
/// </param>
|
| 86 |
+
void Reinitialize()
|
| 87 |
+
{
|
| 88 |
+
m_head = 0;
|
| 89 |
+
m_tail = 0;
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
//
|
| 93 |
+
// unlocked count
|
| 94 |
+
//
|
| 95 |
+
int Count() const
|
| 96 |
+
{
|
| 97 |
+
return (m_tail - m_head);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
//
|
| 101 |
+
// unlocked check
|
| 102 |
+
//
|
| 103 |
+
bool Empty() const
|
| 104 |
+
{
|
| 105 |
+
return (m_tail <= m_head);
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
//
|
| 109 |
+
// Push/Pop and Steal can be executed interleaved. In particular:
|
| 110 |
+
// 1) A steal and pop should be careful when there is just one element
|
| 111 |
+
// in the queue. This is done by first incrementing the m_head/decrementing the m_tail
|
| 112 |
+
// and than checking if it interleaved (m_head > m_tail).
|
| 113 |
+
// 2) A push and steal can interleave in the sense that a push can overwrite the
|
| 114 |
+
// value that is just stolen. To account for this, we check conservatively in
|
| 115 |
+
// the push to assume that the size is one less than it actually is.
|
| 116 |
+
|
| 117 |
+
/// <summary>
|
| 118 |
+
/// Attempts to steal the oldest element in the queue. This handles potential interleaving with both
|
| 119 |
+
/// a Pop and other Steal operations.
|
| 120 |
+
/// </summary>
|
| 121 |
+
/// <param name="fForceStealLocalized">
|
| 122 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 123 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 124 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 125 |
+
/// </param>
|
| 126 |
+
T* Steal(bool fForceStealLocalized = false)
|
| 127 |
+
{
|
| 128 |
+
typename LOCK::_Scoped_lock lock(*m_pLock);
|
| 129 |
+
return UnlockedSteal(fForceStealLocalized);
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// <summary>
|
| 133 |
+
/// Must be called under m_pLock->_Acquire/m_pLock->_TryAcquire
|
| 134 |
+
/// </summary>
|
| 135 |
+
/// <param name="fForceStealLocalized">
|
| 136 |
+
/// Whether to steal the task at the bottom end of the work stealing queue even if it is an affinitized to a location
|
| 137 |
+
/// that has active searches. This is set to true on the final SFW pass to ensure a vproc does not deactivate while there
|
| 138 |
+
/// are chores higher up in the queue that are un-affinitized and therefore inaccessible via a mailbox.
|
| 139 |
+
/// </param>
|
| 140 |
+
T* UnlockedSteal(bool fForceStealLocalized)
|
| 141 |
+
{
|
| 142 |
+
while (m_head < m_tail)
|
| 143 |
+
{
|
| 144 |
+
int h = m_head;
|
| 145 |
+
|
| 146 |
+
//
|
| 147 |
+
// Do not allow a steal from this work stealing queue if the bottom task was mailed to a location which has active searchers.
|
| 148 |
+
// This will not block finalization in any way as the last pass SFW will pull the task out of the mailbox regardless of affinity.
|
| 149 |
+
// We should be careful not to do this if the current context's virtual processor is in the affinity set of the segment.
|
| 150 |
+
// If not, there could be cases where all virtual processors deactivate, but the scheduler does not shutdown since there are chores
|
| 151 |
+
// in the queue, even if they have been dequeued via the mailbox.
|
| 152 |
+
//
|
| 153 |
+
if(IS_AFFINITIZED_TASK(m_ppTasks[h & m_mask]))
|
| 154 |
+
{
|
| 155 |
+
//
|
| 156 |
+
// Skip this workqueue if there are affine searchers and we are not one of them.
|
| 157 |
+
//
|
| 158 |
+
if (!fForceStealLocalized && m_pSlots[h & m_mask].DeferToAffineSearchers())
|
| 159 |
+
return NULL;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
T *pResult = (T*) _InterlockedExchangePointer((volatile PVOID*) &m_ppTasks[h & m_mask], (PVOID) NULL);
|
| 163 |
+
|
| 164 |
+
if (IS_AFFINITIZED_TASK(pResult))
|
| 165 |
+
{
|
| 166 |
+
pResult = STRIP_AFFINITY_INDICATOR(T, pResult);
|
| 167 |
+
|
| 168 |
+
//
|
| 169 |
+
// If the task was already executed via a mailbox dequeue, move on and try to steal again.
|
| 170 |
+
//
|
| 171 |
+
if (!m_pSlots[h & m_mask].Claim())
|
| 172 |
+
{
|
| 173 |
+
m_head = h + 1;
|
| 174 |
+
continue;
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
if (pResult != NULL)
|
| 179 |
+
m_head = h+1;
|
| 180 |
+
|
| 181 |
+
return pResult;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
return NULL;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
/// <summary>
|
| 188 |
+
/// Attempts to pop the newest element on the work stealing queue. It may return NULL if there is no such
|
| 189 |
+
/// item (either unbalanced push/pop, a chore stolen). A special constant AFFINITY_EXECUTED is returned
|
| 190 |
+
// if the item was executed via a mailbox slot.
|
| 191 |
+
/// </summary>
|
| 192 |
+
T* Pop()
|
| 193 |
+
{
|
| 194 |
+
int t = m_tail - 1;
|
| 195 |
+
m_tail = t;
|
| 196 |
+
T* pResult = (T*) _InterlockedExchangePointer((volatile PVOID*) &m_ppTasks[t & m_mask], (PVOID) NULL);
|
| 197 |
+
if (pResult == NULL)
|
| 198 |
+
m_tail = t + 1;
|
| 199 |
+
|
| 200 |
+
//
|
| 201 |
+
// If the task had an associated affinity, we must deal with the possibility that it was already executed by a virtual
|
| 202 |
+
// processor to which it was affine through a mailbox.
|
| 203 |
+
//
|
| 204 |
+
if (IS_AFFINITIZED_TASK(pResult))
|
| 205 |
+
{
|
| 206 |
+
pResult = STRIP_AFFINITY_INDICATOR(T, pResult);
|
| 207 |
+
|
| 208 |
+
//
|
| 209 |
+
// If the task was already executed via a mailbox dequeue, return an indication to the caller.
|
| 210 |
+
//
|
| 211 |
+
if (!m_pSlots[t & m_mask].Claim())
|
| 212 |
+
{
|
| 213 |
+
return (T*)AFFINITY_EXECUTED;
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
return pResult;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// <summary>
|
| 220 |
+
/// Pushes an element onto the work stealing queue.
|
| 221 |
+
/// </summary>
|
| 222 |
+
void Push(T* element, typename Mailbox<T>::Slot affinitySlot)
|
| 223 |
+
{
|
| 224 |
+
int t = m_tail;
|
| 225 |
+
|
| 226 |
+
AvoidOverflow(t);
|
| 227 |
+
|
| 228 |
+
//
|
| 229 |
+
// Careful here since we might interleave with Steal.
|
| 230 |
+
// This is no problem since we just conservatively check if there is
|
| 231 |
+
// enough space left (t < m_head + size). However, Steal might just have
|
| 232 |
+
// incremented m_head and we could potentially overwrite the old m_head
|
| 233 |
+
// entry, so we always leave at least one extra 'buffer' element and
|
| 234 |
+
// check (m_tail < m_head + size - 1). This also plays nicely with our
|
| 235 |
+
// initial m_mask of 0, where size is 2^0 == 1, but the tasks array is
|
| 236 |
+
// still null.
|
| 237 |
+
//
|
| 238 |
+
if (t < m_head + m_mask) // == t < m_head + size - 1
|
| 239 |
+
{
|
| 240 |
+
if (!affinitySlot.IsEmpty())
|
| 241 |
+
{
|
| 242 |
+
//
|
| 243 |
+
// Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent
|
| 244 |
+
// multiple execution.
|
| 245 |
+
//
|
| 246 |
+
m_pSlots[t & m_mask] = affinitySlot;
|
| 247 |
+
element = ADD_AFFINITY_INDICATOR(T, element);
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
m_ppTasks[t & m_mask] = element;
|
| 251 |
+
// Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models
|
| 252 |
+
m_tail = t + 1;
|
| 253 |
+
}
|
| 254 |
+
else
|
| 255 |
+
GrowAndPush(element, affinitySlot);
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/// <summary>
|
| 259 |
+
/// Pushes an element onto the work stealing queue.
|
| 260 |
+
/// </summary>
|
| 261 |
+
void Push(T* element)
|
| 262 |
+
{
|
| 263 |
+
int t = m_tail;
|
| 264 |
+
|
| 265 |
+
AvoidOverflow(t);
|
| 266 |
+
|
| 267 |
+
//
|
| 268 |
+
// Careful here since we might interleave with Steal.
|
| 269 |
+
// This is no problem since we just conservatively check if there is
|
| 270 |
+
// enough space left (t < m_head + size). However, Steal might just have
|
| 271 |
+
// incremented m_head and we could potentially overwrite the old m_head
|
| 272 |
+
// entry, so we always leave at least one extra 'buffer' element and
|
| 273 |
+
// check (m_tail < m_head + size - 1). This also plays nicely with our
|
| 274 |
+
// initial m_mask of 0, where size is 2^0 == 1, but the tasks array is
|
| 275 |
+
// still null.
|
| 276 |
+
//
|
| 277 |
+
if (t < m_head + m_mask) // == t < m_head + size - 1
|
| 278 |
+
{
|
| 279 |
+
m_ppTasks[t & m_mask] = element;
|
| 280 |
+
// Only increment once we have initialized the task entry. This is a volatile write and has release semantics on weaker memory models
|
| 281 |
+
m_tail = t + 1;
|
| 282 |
+
}
|
| 283 |
+
else
|
| 284 |
+
GrowAndPush(element, typename Mailbox<T>::Slot());
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
/// <summary>
|
| 288 |
+
/// Destroys a work stealing queue.
|
| 289 |
+
/// </summary>
|
| 290 |
+
~StructuredWorkStealingQueue()
|
| 291 |
+
{
|
| 292 |
+
delete [] m_ppTasks;
|
| 293 |
+
delete [] m_pSlots;
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
private:
|
| 297 |
+
|
| 298 |
+
// The m_head and m_tail are volatile as they can be updated from different OS threads.
|
| 299 |
+
// The "m_head" is only updated by foreign threads as they Steal a task from
|
| 300 |
+
// this queue. By putting a lock in Steal, there is at most one foreign thread
|
| 301 |
+
// changing m_head at a time. The m_tail is only updated by the bound thread.
|
| 302 |
+
//
|
| 303 |
+
// invariants:
|
| 304 |
+
// tasks.length is a power of 2
|
| 305 |
+
// m_mask == tasks.length-1
|
| 306 |
+
// m_head is only written to by foreign threads
|
| 307 |
+
// m_tail is only written to by the bound thread
|
| 308 |
+
// At most one foreign thread can do a Steal
|
| 309 |
+
// All methods except Steal are executed from a single bound thread
|
| 310 |
+
// m_tail points to the first unused location
|
| 311 |
+
//
|
| 312 |
+
|
| 313 |
+
static const int s_initialSize = 64; // must be a power of 2
|
| 314 |
+
|
| 315 |
+
volatile int m_head; // only updated by Steal
|
| 316 |
+
volatile int m_tail; // only updated by Push and Pop
|
| 317 |
+
|
| 318 |
+
int m_mask; // the m_mask for taking modulus
|
| 319 |
+
|
| 320 |
+
T** m_ppTasks; // the array of tasks
|
| 321 |
+
typename Mailbox<T>::Slot *m_pSlots; // the array of side-band affinity structures
|
| 322 |
+
|
| 323 |
+
LOCK *m_pLock;
|
| 324 |
+
|
| 325 |
+
// private helpers
|
| 326 |
+
|
| 327 |
+
T* LockedPop(int t)
|
| 328 |
+
{
|
| 329 |
+
typename LOCK::_Scoped_lock lock(*m_pLock);
|
| 330 |
+
T* pResult = NULL;
|
| 331 |
+
|
| 332 |
+
if (m_head <= t)
|
| 333 |
+
pResult = m_ppTasks[t & m_mask];
|
| 334 |
+
else
|
| 335 |
+
m_tail = t + 1;
|
| 336 |
+
if (m_tail <= m_head)
|
| 337 |
+
m_head = m_tail = 0;
|
| 338 |
+
|
| 339 |
+
return pResult;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
void GrowAndPush(T* element, typename Mailbox<T>::Slot affinitySlot)
|
| 343 |
+
{
|
| 344 |
+
// We're full; expand the queue by doubling its size.
|
| 345 |
+
int newLength = (m_mask + 1) << 1;
|
| 346 |
+
T** ppNewTasks = _concrt_new T*[newLength];
|
| 347 |
+
T** ppOldTasks = m_ppTasks;
|
| 348 |
+
|
| 349 |
+
typename Mailbox<T>::Slot *pNewSlots = _concrt_new typename Mailbox<T>::Slot[newLength];
|
| 350 |
+
typename Mailbox<T>::Slot *pOldSlots = m_pSlots;
|
| 351 |
+
|
| 352 |
+
{//for lock scope to exclude the delete[]
|
| 353 |
+
typename LOCK::_Scoped_lock lock(*m_pLock);
|
| 354 |
+
|
| 355 |
+
int t = m_tail;
|
| 356 |
+
int h = m_head;
|
| 357 |
+
int count = Count();
|
| 358 |
+
|
| 359 |
+
_Analysis_assume_(newLength > count); // Guaranteed because we're doubling the size.
|
| 360 |
+
|
| 361 |
+
for (int i = 0; i < count; i++)
|
| 362 |
+
{
|
| 363 |
+
ppNewTasks[i] = m_ppTasks[(i + h) & m_mask];
|
| 364 |
+
pNewSlots[i] = m_pSlots[(i + h) & m_mask];
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
memset(ppNewTasks + count, 0, (newLength - count) * sizeof(T*));
|
| 368 |
+
|
| 369 |
+
// Reset the field values.
|
| 370 |
+
m_ppTasks = ppNewTasks;
|
| 371 |
+
m_pSlots = pNewSlots;
|
| 372 |
+
m_head = 0;
|
| 373 |
+
t = count;
|
| 374 |
+
m_mask = newLength - 1;
|
| 375 |
+
|
| 376 |
+
if (!affinitySlot.IsEmpty())
|
| 377 |
+
{
|
| 378 |
+
//
|
| 379 |
+
// Flag the element as affinitized. On popping this element, the box slot must be cleared to prevent
|
| 380 |
+
// multiple execution.
|
| 381 |
+
//
|
| 382 |
+
m_pSlots[t & m_mask] = affinitySlot;
|
| 383 |
+
element = ADD_AFFINITY_INDICATOR(T, element);
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
m_ppTasks[t & m_mask] = element;
|
| 387 |
+
m_tail = t + 1;
|
| 388 |
+
}//end: lock scope
|
| 389 |
+
|
| 390 |
+
delete[] ppOldTasks;
|
| 391 |
+
delete[] pOldSlots;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
void AvoidOverflow(int& t) {
|
| 395 |
+
// Balanced calls to Steal() and Push() will increment m_head and m_tail forever.
|
| 396 |
+
// To avoid integer overflow, we need to reduce m_head and m_tail simultaneously,
|
| 397 |
+
// preserving their modulo-indexing behavior and relative distance.
|
| 398 |
+
|
| 399 |
+
if (t + m_mask == INT_MAX) { // begin: lock scope
|
| 400 |
+
typename LOCK::_Scoped_lock lock(*m_pLock);
|
| 401 |
+
|
| 402 |
+
int h = m_head;
|
| 403 |
+
const int original_distance = t - h;
|
| 404 |
+
|
| 405 |
+
h &= m_mask;
|
| 406 |
+
t = h + original_distance;
|
| 407 |
+
|
| 408 |
+
m_head = h;
|
| 409 |
+
m_tail = t;
|
| 410 |
+
} // end: lock scope
|
| 411 |
+
}
|
| 412 |
+
};
|
| 413 |
+
} // namespace details
|
| 414 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.cpp
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
/// <summary>
|
| 19 |
+
/// Allocates a block of memory of the size specified.
|
| 20 |
+
/// </summary>
|
| 21 |
+
/// <param name="numBytes">
|
| 22 |
+
/// Number of bytes to allocate.
|
| 23 |
+
/// </param>
|
| 24 |
+
/// <returns>
|
| 25 |
+
/// A pointer to newly allocated memory.
|
| 26 |
+
/// </returns>
|
| 27 |
+
_CONCRTIMP void* Alloc(size_t numBytes)
|
| 28 |
+
{
|
| 29 |
+
if (numBytes > MAXINT_PTR)
|
| 30 |
+
{
|
| 31 |
+
throw std::bad_alloc();
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
return SchedulerBase::CurrentContext()->Alloc(numBytes);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/// <summary>
|
| 38 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 39 |
+
/// </summary>
|
| 40 |
+
/// <param name="pAllocation">
|
| 41 |
+
/// A pointer to an allocation previously allocated by Alloc. If pAllocation is NULL, the API will ignore it, and return
|
| 42 |
+
/// immediately.
|
| 43 |
+
/// </param>
|
| 44 |
+
_Use_decl_annotations_
|
| 45 |
+
_CONCRTIMP void Free(void * pAllocation)
|
| 46 |
+
{
|
| 47 |
+
if (pAllocation == NULL)
|
| 48 |
+
{
|
| 49 |
+
return;
|
| 50 |
+
}
|
| 51 |
+
SchedulerBase::CurrentContext()->Free(pAllocation);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
namespace details
|
| 55 |
+
{
|
| 56 |
+
//
|
| 57 |
+
// Define static variables.
|
| 58 |
+
//
|
| 59 |
+
|
| 60 |
+
#if defined(_DEBUG)
|
| 61 |
+
|
| 62 |
+
// Debug patterns to fill allocated blocks (borrowed from dbgheap.c)
|
| 63 |
+
|
| 64 |
+
static const unsigned char _bNoMansLandFill = 0xFD; /* fill no-man's land with this */
|
| 65 |
+
static const unsigned char _bAlignLandFill = 0xED; /* fill no-man's land for aligned routines */
|
| 66 |
+
static const unsigned char _bDeadLandFill = 0xDD; /* fill free objects with this */
|
| 67 |
+
static const unsigned char _bCleanLandFill = 0xCD; /* fill new objects with this */
|
| 68 |
+
#endif
|
| 69 |
+
|
| 70 |
+
#ifdef _WIN64
|
| 71 |
+
// This supports the same number of buckets and bucket sizes as the LFH heap upto 8192 bytes, i.e., 96 buckets.
|
| 72 |
+
const int SubAllocator::s_bucketSizes[SubAllocator::s_numBuckets] = {
|
| 73 |
+
/* granularity - 16 */ 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, // sizeClass 0, blockUnits 1 - 16
|
| 74 |
+
/* granularity - 16 */ 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, 480, 496, 512, // sizeClass 0, blockUnits 17 - 32
|
| 75 |
+
/* granularity - 32 */ 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,// sizeClass 1, blockUnits 33 - 64
|
| 76 |
+
/* granularity - 64 */ 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048,// sizeClass 2, blockUnits 65 - 128
|
| 77 |
+
/* granularity - 128 */ 2176, 2304, 2432, 2560, 2688, 2816, 2944, 3072, 3200, 3328, 3456, 3584, 3712, 3840, 3968, 4096,// sizeClass 3, blockUnits 129 - 256
|
| 78 |
+
/* granularity - 256 */ 4352, 4608, 4864, 5120, 5376, 5632, 5888, 6144, 6400, 6656, 6912, 7168, 7424, 7680, 7936, 8192,// sizeClass 4, blockUnits 257 - 512
|
| 79 |
+
};
|
| 80 |
+
|
| 81 |
+
// A number such that 2 ^ GranularityShift = Granularity.
|
| 82 |
+
const int SubAllocator::GranularityShift = 4;
|
| 83 |
+
|
| 84 |
+
// The allocation size supported by the largest bucket.
|
| 85 |
+
const int SubAllocator::MaxAllocationSize = 8192;
|
| 86 |
+
|
| 87 |
+
#else
|
| 88 |
+
|
| 89 |
+
// This supports the same number of buckets and bucket sizes as the LFH heap upto 4096 bytes, i.e., 96 buckets.
|
| 90 |
+
const int SubAllocator::s_bucketSizes[SubAllocator::s_numBuckets] = {
|
| 91 |
+
/* granularity - 8 */ 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, // sizeClass 0, blockUnits 1 - 16
|
| 92 |
+
/* granularity - 8 */ 136, 144, 152, 160, 168, 176, 184, 192, 200, 208, 216, 224, 232, 240, 248, 256, // sizeClass 0, blockUnits 17 - 32
|
| 93 |
+
/* granularity - 16 */ 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, 480, 496, 512, // sizeClass 1, blockUnits 33 - 64
|
| 94 |
+
/* granularity - 32 */ 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,// sizeClass 2, blockUnits 65 - 128
|
| 95 |
+
/* granularity - 64 */ 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048,// sizeClass 3, blockUnits 129 - 256
|
| 96 |
+
/* granularity - 128 */ 2176, 2304, 2432, 2560, 2688, 2816, 2944, 3072, 3200, 3328, 3456, 3584, 3712, 3840, 3968, 4096 // sizeClass 4, blockUnits 257 - 512
|
| 97 |
+
};
|
| 98 |
+
|
| 99 |
+
// A number such that 2 ^ GranularityShift = Granularity.
|
| 100 |
+
const int SubAllocator::GranularityShift = 3;
|
| 101 |
+
|
| 102 |
+
// The allocation size supported by the largest bucket.
|
| 103 |
+
const int SubAllocator::MaxAllocationSize = 4096;
|
| 104 |
+
#endif
|
| 105 |
+
|
| 106 |
+
/// <summary>
|
| 107 |
+
/// Returns an index into the array of allocator buckets for this sub allocator. The allocation size of the
|
| 108 |
+
/// bucket is guaranteed to satisfy numBytes.
|
| 109 |
+
/// </summary>
|
| 110 |
+
/// <param name="numBytes">
|
| 111 |
+
/// The size of the allocation. This is what the user requested plus space for the ConcRT allocator header.
|
| 112 |
+
/// </param>
|
| 113 |
+
/// <returns>
|
| 114 |
+
/// An index into the array of allocator buckets such that.s_bucketSizes[returnedBucketIndex] >= numBytes
|
| 115 |
+
/// </returns>
|
| 116 |
+
int SubAllocator::GetBucketIndex(size_t numBytes)
|
| 117 |
+
{
|
| 118 |
+
static const int GranularityMask = (1 << GranularityShift) - 1;
|
| 119 |
+
|
| 120 |
+
int bucketIndex = -1;
|
| 121 |
+
size_t allocationSize = (size_t) (((ULONG_PTR)numBytes + GranularityMask) & ~((ULONG_PTR)GranularityMask));
|
| 122 |
+
|
| 123 |
+
if (allocationSize > MaxAllocationSize)
|
| 124 |
+
{
|
| 125 |
+
// We are unable to satisfy this allocation by an allocator bucket. It should be forwarded to the LFH heap.
|
| 126 |
+
return bucketIndex;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
int blockUnits = (int)(allocationSize >> GranularityShift);
|
| 130 |
+
|
| 131 |
+
// blockUnits is the number of Granularity size chunks that make up the allocationSize. A blockUnit of 1 is satisfied
|
| 132 |
+
// by allocator bucket 0. We need to find the index of the bucket that holds the minimum sized allocation that will
|
| 133 |
+
// satisfy allocationSize.
|
| 134 |
+
ASSERT(blockUnits > 0);
|
| 135 |
+
|
| 136 |
+
// Detect if the allocation will fall within buckets 0 - 31
|
| 137 |
+
if (blockUnits <= 32)
|
| 138 |
+
{
|
| 139 |
+
bucketIndex = blockUnits - 1;
|
| 140 |
+
}
|
| 141 |
+
else
|
| 142 |
+
{
|
| 143 |
+
int sizeClass = 5; // Add 1 << 5 = 32
|
| 144 |
+
|
| 145 |
+
while ((blockUnits >> sizeClass) > 0)
|
| 146 |
+
{
|
| 147 |
+
sizeClass += 1;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
sizeClass -= 5;
|
| 151 |
+
|
| 152 |
+
ASSERT(sizeClass > 0);
|
| 153 |
+
|
| 154 |
+
// Round blockUnits up to the block unit granularity of the size class.
|
| 155 |
+
int sizeClassMask = (1 << sizeClass) - 1;
|
| 156 |
+
blockUnits = (int) (((ULONG_PTR)blockUnits + sizeClassMask) & ~((ULONG_PTR)sizeClassMask));
|
| 157 |
+
|
| 158 |
+
bucketIndex = (sizeClass << 4) + (blockUnits >> sizeClass) - 1;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
ASSERT(allocationSize <= (size_t)s_bucketSizes[bucketIndex]);
|
| 162 |
+
ASSERT(bucketIndex == 0 || allocationSize > (size_t)s_bucketSizes[bucketIndex - 1]);
|
| 163 |
+
|
| 164 |
+
return bucketIndex;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/// <summary>
|
| 168 |
+
/// Allocates a block of memory of the size specified.
|
| 169 |
+
/// </summary>
|
| 170 |
+
/// <param name="numBytes">
|
| 171 |
+
/// Number of bytes to allocate.
|
| 172 |
+
/// </param>
|
| 173 |
+
/// <returns>
|
| 174 |
+
/// A pointer to newly allocated memory.
|
| 175 |
+
/// </returns>
|
| 176 |
+
void* SubAllocator::Alloc(size_t numBytes)
|
| 177 |
+
{
|
| 178 |
+
AllocationEntry* pAllocationEntry = NULL;
|
| 179 |
+
size_t allocationSize = numBytes + sizeof(AllocationEntry);
|
| 180 |
+
|
| 181 |
+
int bucketIndex = GetBucketIndex(allocationSize);
|
| 182 |
+
|
| 183 |
+
if (bucketIndex != -1)
|
| 184 |
+
{
|
| 185 |
+
ASSERT(bucketIndex < sizeof(s_bucketSizes));
|
| 186 |
+
pAllocationEntry = m_buckets[bucketIndex].Alloc();
|
| 187 |
+
|
| 188 |
+
#if defined(_DEBUG)
|
| 189 |
+
if (pAllocationEntry != NULL)
|
| 190 |
+
{
|
| 191 |
+
InitAndCheckBlockOnAlloc(pAllocationEntry, s_bucketSizes[bucketIndex]);
|
| 192 |
+
}
|
| 193 |
+
#endif
|
| 194 |
+
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
if (pAllocationEntry == NULL)
|
| 198 |
+
{
|
| 199 |
+
// We need to allocate memory from the CRT heap since either the bucket was empty,
|
| 200 |
+
// or the size is not one the allocator caches.
|
| 201 |
+
pAllocationEntry = (AllocationEntry*) _concrt_new char[bucketIndex == -1 ? allocationSize : s_bucketSizes[bucketIndex]];
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
ASSERT(pAllocationEntry != NULL);
|
| 205 |
+
pAllocationEntry->m_bucketIndex = (ULONG_PTR)Security::EncodePointer((PVOID)(intptr_t)bucketIndex);
|
| 206 |
+
|
| 207 |
+
return (void*)(pAllocationEntry + 1);
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/// <summary>
|
| 211 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 212 |
+
/// </summary>
|
| 213 |
+
/// <param name="pAllocation">
|
| 214 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 215 |
+
/// </param>
|
| 216 |
+
void SubAllocator::Free(void* pAllocation)
|
| 217 |
+
{
|
| 218 |
+
AllocationEntry* pAllocationEntry = (AllocationEntry*)pAllocation - 1;
|
| 219 |
+
// Disable data truncation warning as only lower 32-bits are needed.
|
| 220 |
+
#pragma warning(push)
|
| 221 |
+
#pragma warning(disable: 4302)
|
| 222 |
+
int bucketIndex = (int)(intptr_t)Security::DecodePointer((PVOID)pAllocationEntry->m_bucketIndex);
|
| 223 |
+
#pragma warning(pop)
|
| 224 |
+
|
| 225 |
+
ASSERT((bucketIndex == -1) || bucketIndex < sizeof(s_bucketSizes));
|
| 226 |
+
|
| 227 |
+
if ((bucketIndex == -1) || !m_buckets[bucketIndex].Free(pAllocationEntry))
|
| 228 |
+
{
|
| 229 |
+
delete [] (char*)pAllocationEntry;
|
| 230 |
+
}
|
| 231 |
+
#if defined(_DEBUG)
|
| 232 |
+
else
|
| 233 |
+
{
|
| 234 |
+
InitAndCheckBlockOnFree(pAllocationEntry, s_bucketSizes[bucketIndex]);
|
| 235 |
+
}
|
| 236 |
+
#endif
|
| 237 |
+
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
/// <summary>
|
| 241 |
+
/// A static allocation API that allocates directly from the CRT heap, and encodes the bucket id in the allocation,
|
| 242 |
+
/// based on the size of the block. This is used by callers that are unable to get access to a suballocator at
|
| 243 |
+
/// the time they are allocating memory.
|
| 244 |
+
/// </summary>
|
| 245 |
+
void* SubAllocator::StaticAlloc(size_t numBytes)
|
| 246 |
+
{
|
| 247 |
+
AllocationEntry* pAllocationEntry = NULL;
|
| 248 |
+
size_t allocationSize = numBytes + sizeof(AllocationEntry);
|
| 249 |
+
|
| 250 |
+
int bucketIndex = GetBucketIndex(allocationSize);
|
| 251 |
+
pAllocationEntry = (AllocationEntry*) _concrt_new char[bucketIndex == -1 ? allocationSize : s_bucketSizes[bucketIndex]];
|
| 252 |
+
|
| 253 |
+
ASSERT(pAllocationEntry != NULL);
|
| 254 |
+
pAllocationEntry->m_bucketIndex = (ULONG_PTR)Security::EncodePointer((PVOID)(intptr_t)bucketIndex);
|
| 255 |
+
|
| 256 |
+
return (void*)(pAllocationEntry + 1);
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
#if defined(_DEBUG)
|
| 260 |
+
/// <summary>
|
| 261 |
+
/// Initialize a block allocated from the freelist. Perform debug validation on the block to
|
| 262 |
+
/// detect user errors.
|
| 263 |
+
/// </summary>
|
| 264 |
+
bool SubAllocator::InitAndCheckBlockOnAlloc(AllocationEntry *pAllocationEntry, size_t numBytes)
|
| 265 |
+
{
|
| 266 |
+
// Validate the pointer
|
| 267 |
+
ASSERT(_CrtIsValidHeapPointer((const void *)pAllocationEntry));
|
| 268 |
+
|
| 269 |
+
unsigned char * userData = (unsigned char *)(pAllocationEntry + 1);
|
| 270 |
+
|
| 271 |
+
ASSERT(numBytes > sizeof(AllocationEntry));
|
| 272 |
+
size_t userNumBytes = numBytes - sizeof(AllocationEntry);
|
| 273 |
+
|
| 274 |
+
// Ensure that the free block has not been overwritten.
|
| 275 |
+
ASSERT(CheckBytes(userData, _bDeadLandFill, userNumBytes));
|
| 276 |
+
|
| 277 |
+
// Initialize the new block
|
| 278 |
+
memset((void *)userData, _bCleanLandFill, userNumBytes);
|
| 279 |
+
|
| 280 |
+
return true;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
/// <summary>
|
| 284 |
+
/// Initialize a block that is added to the freelist. Perform debug validation on the block to
|
| 285 |
+
/// detect user errors.
|
| 286 |
+
/// </summary>
|
| 287 |
+
bool SubAllocator::InitAndCheckBlockOnFree(AllocationEntry *pAllocationEntry, size_t numBytes)
|
| 288 |
+
{
|
| 289 |
+
// Validate the pointer.
|
| 290 |
+
ASSERT(_CrtIsValidHeapPointer((const void *)pAllocationEntry));
|
| 291 |
+
|
| 292 |
+
ASSERT(numBytes > sizeof(AllocationEntry));
|
| 293 |
+
// Initialize the free block
|
| 294 |
+
memset((void *)(pAllocationEntry + 1), _bDeadLandFill, (numBytes - sizeof(AllocationEntry)));
|
| 295 |
+
|
| 296 |
+
return true;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
/// <summary>
|
| 300 |
+
/// Helper routine that checks where the given block is filled with
|
| 301 |
+
/// the given pattern.
|
| 302 |
+
/// </summary>
|
| 303 |
+
bool SubAllocator::CheckBytes(unsigned char * pBlock, unsigned char bCheck, size_t numBytes)
|
| 304 |
+
{
|
| 305 |
+
while (numBytes--)
|
| 306 |
+
{
|
| 307 |
+
if (*pBlock++ != bCheck)
|
| 308 |
+
{
|
| 309 |
+
return false;
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
return true;
|
| 314 |
+
}
|
| 315 |
+
#endif
|
| 316 |
+
|
| 317 |
+
/// <summary>
|
| 318 |
+
/// Constructs an allocator bucket.
|
| 319 |
+
/// <summary>
|
| 320 |
+
AllocatorBucket::AllocatorBucket() : m_depth(0)
|
| 321 |
+
{
|
| 322 |
+
m_pHead = (AllocationEntry*)Security::EncodePointer(NULL);
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
/// <summary>
|
| 326 |
+
/// Returns an allocation from the bucket if it is non-empty, and NULL if it is empty.
|
| 327 |
+
/// </summary>
|
| 328 |
+
AllocationEntry* AllocatorBucket::Alloc()
|
| 329 |
+
{
|
| 330 |
+
AllocationEntry* pAllocationEntry = (AllocationEntry*)Security::DecodePointer(m_pHead);
|
| 331 |
+
|
| 332 |
+
if (pAllocationEntry != NULL)
|
| 333 |
+
{
|
| 334 |
+
ASSERT(m_depth > 0);
|
| 335 |
+
m_pHead = pAllocationEntry->m_pNext;
|
| 336 |
+
--m_depth;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
return pAllocationEntry;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
/// <summary>
|
| 343 |
+
/// Adds the block to the bucket and returns true if the maximum depth is not reached.
|
| 344 |
+
/// If the bucket is 'full', it returns false, and the caller is responsible for freeing
|
| 345 |
+
/// the block to the CRT heap.
|
| 346 |
+
/// </summary>
|
| 347 |
+
bool AllocatorBucket::Free(AllocationEntry* pAllocation)
|
| 348 |
+
{
|
| 349 |
+
if (m_depth < s_maxBucketDepth)
|
| 350 |
+
{
|
| 351 |
+
pAllocation->m_pNext = m_pHead;
|
| 352 |
+
m_pHead = (AllocationEntry*)Security::EncodePointer(pAllocation);
|
| 353 |
+
++m_depth;
|
| 354 |
+
|
| 355 |
+
ASSERT(m_depth <= s_maxBucketDepth);
|
| 356 |
+
return true;
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
return false;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
/// <summary>
|
| 363 |
+
/// Destroys an allocator bucket.
|
| 364 |
+
/// </summary>
|
| 365 |
+
AllocatorBucket::~AllocatorBucket()
|
| 366 |
+
{
|
| 367 |
+
while (m_depth != 0)
|
| 368 |
+
{
|
| 369 |
+
AllocationEntry * pAllocationEntry = (AllocationEntry*)Security::DecodePointer(m_pHead);
|
| 370 |
+
ASSERT(pAllocationEntry != NULL);
|
| 371 |
+
|
| 372 |
+
m_pHead = pAllocationEntry->m_pNext;
|
| 373 |
+
delete [] (char*)pAllocationEntry;
|
| 374 |
+
|
| 375 |
+
--m_depth;
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
} // namespace details
|
| 379 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/SubAllocator.h
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// SubAllocator.h
|
| 9 |
+
//
|
| 10 |
+
// Class definition for the ConcRT sub allocator.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#pragma once
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// Each allocation via the sub allocator has an AllocationEntry header. All we need the allocation entry
|
| 22 |
+
/// for, is to tell us the id of the bucket, which indicates the size of the allocation. However, the size
|
| 23 |
+
/// of the header is pointer size - since we want to align the user's allocation.
|
| 24 |
+
/// </summary>
|
| 25 |
+
union AllocationEntry
|
| 26 |
+
{
|
| 27 |
+
// The index to the bucket in the suballocator, that this entry belongs to.
|
| 28 |
+
ULONG_PTR m_bucketIndex;
|
| 29 |
+
|
| 30 |
+
// Pointer to the next allocation in the bucket. This is used to chain allocations in the bucket, and we
|
| 31 |
+
// do not require a lock since only one thread is guaranteed to be touching the suballocator at a time.
|
| 32 |
+
AllocationEntry* m_pNext;
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
// A bucket that stores a particular size memory block. A SubAllocator has several allocator buckets.
|
| 36 |
+
class AllocatorBucket
|
| 37 |
+
{
|
| 38 |
+
public:
|
| 39 |
+
|
| 40 |
+
/// <summary>
|
| 41 |
+
/// Constructs an allocator bucket.
|
| 42 |
+
/// <summary>
|
| 43 |
+
AllocatorBucket();
|
| 44 |
+
|
| 45 |
+
/// <summary>
|
| 46 |
+
/// Destroys an allocator bucket.
|
| 47 |
+
/// </summary>
|
| 48 |
+
~AllocatorBucket();
|
| 49 |
+
|
| 50 |
+
/// <summary>
|
| 51 |
+
/// Returns an allocation from the bucket if it is non-empty, and NULL if it is empty.
|
| 52 |
+
/// </summary>
|
| 53 |
+
AllocationEntry* Alloc();
|
| 54 |
+
|
| 55 |
+
/// <summary>
|
| 56 |
+
/// Adds the block to the bucket and returns true if the maximum depth is not reached.
|
| 57 |
+
/// If the bucket is 'full', it returns false, and the caller is responsible for freeing
|
| 58 |
+
/// the block to the CRT heap.
|
| 59 |
+
/// </summary>
|
| 60 |
+
bool Free(AllocationEntry* pAllocation);
|
| 61 |
+
|
| 62 |
+
private:
|
| 63 |
+
|
| 64 |
+
// The current depth of the bucket.
|
| 65 |
+
int m_depth;
|
| 66 |
+
|
| 67 |
+
// The head of the free block list.
|
| 68 |
+
AllocationEntry* m_pHead;
|
| 69 |
+
|
| 70 |
+
// The maximum number of allocations the sub allocator will cache per bucket.
|
| 71 |
+
static const int s_maxBucketDepth = 32;
|
| 72 |
+
};
|
| 73 |
+
|
| 74 |
+
#pragma warning(push)
|
| 75 |
+
#pragma warning(disable: 4324) // structure was padded due to alignment specifier
|
| 76 |
+
class SubAllocator
|
| 77 |
+
{
|
| 78 |
+
public:
|
| 79 |
+
|
| 80 |
+
/// <summary>
|
| 81 |
+
/// Constructs a suballocator.
|
| 82 |
+
/// </summary>
|
| 83 |
+
SubAllocator() :
|
| 84 |
+
m_fExternalAllocator(false)
|
| 85 |
+
{
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/// <summary>
|
| 89 |
+
/// Allocates a block of memory of the size specified.
|
| 90 |
+
/// </summary>
|
| 91 |
+
/// <param name="numBytes">
|
| 92 |
+
/// Number of bytes to allocate.
|
| 93 |
+
/// </param>
|
| 94 |
+
/// <returns>
|
| 95 |
+
/// A pointer to newly allocated memory.
|
| 96 |
+
/// </returns>
|
| 97 |
+
void* Alloc(size_t numBytes);
|
| 98 |
+
|
| 99 |
+
/// <summary>
|
| 100 |
+
/// Frees a block of memory previously allocated by the Alloc API.
|
| 101 |
+
/// </summary>
|
| 102 |
+
/// <param name="pAllocation">
|
| 103 |
+
/// A pointer to an allocation previously allocated by Alloc.
|
| 104 |
+
/// </param>
|
| 105 |
+
void Free(void* pAllocation);
|
| 106 |
+
|
| 107 |
+
/// <summary>
|
| 108 |
+
/// A static allocation API that allocates directly from the CRT heap, and encodes the bucket id in the allocation,
|
| 109 |
+
/// based on the size of the block. This is used by callers that are unable to get access to a suballocator at
|
| 110 |
+
/// the time they are allocating memory.
|
| 111 |
+
/// </summary>
|
| 112 |
+
static void* StaticAlloc(size_t numBytes);
|
| 113 |
+
|
| 114 |
+
/// <summary>
|
| 115 |
+
/// A static free API that frees directly to the CRT heap. This is used by callers that are unable to get access
|
| 116 |
+
/// to a suballocator at the time they are freeing memory.
|
| 117 |
+
/// </summary>
|
| 118 |
+
static void StaticFree(void* pAllocation)
|
| 119 |
+
{
|
| 120 |
+
delete [] (char*) ((AllocationEntry*)pAllocation - 1);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/// <summary>
|
| 124 |
+
/// Returns an index into the array of allocator buckets for this sub allocator. The allocation size of the
|
| 125 |
+
/// bucket is guaranteed to satisfy numBytes.
|
| 126 |
+
/// </summary>
|
| 127 |
+
/// <param name="numBytes">
|
| 128 |
+
/// The size of the allocation. This is what the user requested plus space for the ConcRT allocator header.
|
| 129 |
+
/// </param>
|
| 130 |
+
/// <returns>
|
| 131 |
+
/// An index into the array of allocator buckets such that.s_bucketSizes[returnedBucketIndex] >= numBytes
|
| 132 |
+
/// </returns>
|
| 133 |
+
static int GetBucketIndex(size_t numBytes);
|
| 134 |
+
|
| 135 |
+
/// <summary>
|
| 136 |
+
/// Every time an allocator is reused, this flag is set to denote whether it is one out of the 'fixed pool' - the set
|
| 137 |
+
/// of allocators that are used for external contexts.
|
| 138 |
+
/// </summary>
|
| 139 |
+
void SetExternalAllocatorFlag(bool flag) { m_fExternalAllocator = flag; }
|
| 140 |
+
|
| 141 |
+
/// <summary>
|
| 142 |
+
/// Returns true, if this allocator is assigned to, or was last assigned to an external context.
|
| 143 |
+
/// </summary>
|
| 144 |
+
bool IsExternalAllocator() { return m_fExternalAllocator; }
|
| 145 |
+
|
| 146 |
+
private:
|
| 147 |
+
|
| 148 |
+
// private methods
|
| 149 |
+
|
| 150 |
+
#if defined(_DEBUG)
|
| 151 |
+
|
| 152 |
+
/// <summary>
|
| 153 |
+
/// Initialize a block allocated from the freelist. Perform debug validation on the block to
|
| 154 |
+
/// detect user errors.
|
| 155 |
+
/// </summary>
|
| 156 |
+
bool InitAndCheckBlockOnAlloc(AllocationEntry *pAllocationEntry, size_t numBytes);
|
| 157 |
+
|
| 158 |
+
/// <summary>
|
| 159 |
+
/// Initialize a block that is added to the freelist. Perform debug validation on the block to
|
| 160 |
+
/// detect user errors.
|
| 161 |
+
/// </summary>
|
| 162 |
+
bool InitAndCheckBlockOnFree(AllocationEntry *pAllocationEntry, size_t numBytes);
|
| 163 |
+
|
| 164 |
+
/// <summary>
|
| 165 |
+
/// Helper routine that checks where the given block is filled with
|
| 166 |
+
/// the given pattern.
|
| 167 |
+
/// </summary>
|
| 168 |
+
bool CheckBytes(unsigned char * pBlock, unsigned char bCheck, size_t numBytes);
|
| 169 |
+
#endif
|
| 170 |
+
|
| 171 |
+
// private member variables
|
| 172 |
+
|
| 173 |
+
friend class SchedulerBase;
|
| 174 |
+
template <class T> friend class LockFreeStack;
|
| 175 |
+
|
| 176 |
+
// Entry for freelist of allocators
|
| 177 |
+
SLIST_ENTRY m_slNext{};
|
| 178 |
+
|
| 179 |
+
// The total number of buckets.
|
| 180 |
+
static const int s_numBuckets = 96;
|
| 181 |
+
|
| 182 |
+
// The array of buckets that holds memory for allocation.
|
| 183 |
+
AllocatorBucket m_buckets[s_numBuckets];
|
| 184 |
+
|
| 185 |
+
// This flag is set to true, when it this suballocator is handed to a caller that invoked GetSubAllocator with an argument
|
| 186 |
+
// of 'true'.
|
| 187 |
+
bool m_fExternalAllocator;
|
| 188 |
+
|
| 189 |
+
// An array that holds the bucket sizes.
|
| 190 |
+
static const int s_bucketSizes[s_numBuckets];
|
| 191 |
+
|
| 192 |
+
// A number such that 2 ^ GranularityShift = the minimum granularity of the allocation buckets.
|
| 193 |
+
static const int GranularityShift;
|
| 194 |
+
|
| 195 |
+
// The allocation size supported by the largest bucket.
|
| 196 |
+
static const int MaxAllocationSize;
|
| 197 |
+
};
|
| 198 |
+
#pragma warning(pop)
|
| 199 |
+
} // namespace details
|
| 200 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.cpp
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollection.h
ADDED
|
@@ -0,0 +1,241 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// TaskCollection.h
|
| 9 |
+
//
|
| 10 |
+
// Miscellaneous internal support structure definitions for a task collection
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
//
|
| 15 |
+
// The amount that we resize the task stack by per alloc.
|
| 16 |
+
//
|
| 17 |
+
#define TASK_STACK_GROWTH_SIZE 8
|
| 18 |
+
|
| 19 |
+
//
|
| 20 |
+
// The number of chores that we cap the task stack at. If after this many tasks are pushed, another is -- it cannot
|
| 21 |
+
// be inlined and will cause performance penalty for out-of-order WSQ utilization.
|
| 22 |
+
//
|
| 23 |
+
#define TASK_STACK_SIZE_CAP 1024
|
| 24 |
+
|
| 25 |
+
// **************************************************************************
|
| 26 |
+
// The phases of task collection cancellation (particularly for unstructured task collections).
|
| 27 |
+
// **************************************************************************
|
| 28 |
+
|
| 29 |
+
//
|
| 30 |
+
// The exit status mask (indicating which portion actively indicates status)
|
| 31 |
+
//
|
| 32 |
+
#define EXIT_CANCELLATION_MASK 0x3FFFFFFF
|
| 33 |
+
|
| 34 |
+
//
|
| 35 |
+
// Indicates that an exception has happened and while cancellation may proceed in due course, the end result should
|
| 36 |
+
// be a thrown exception.
|
| 37 |
+
//
|
| 38 |
+
#define EXIT_STATUS_FLAG_EXCEPTION_RAISED 0x80000000
|
| 39 |
+
|
| 40 |
+
//
|
| 41 |
+
// Indicates that the cancellation exception was thrown because cancellation was detected. The phases of cancellation are defined below.
|
| 42 |
+
//
|
| 43 |
+
#define EXIT_STATUS_FLAG_CANCELLATION_RAISED 0x40000000
|
| 44 |
+
|
| 45 |
+
//
|
| 46 |
+
// Indicates that cancel has started on the task collection.
|
| 47 |
+
//
|
| 48 |
+
#define EXIT_STATUS_START_CANCEL 0x00000001
|
| 49 |
+
|
| 50 |
+
// **************************************************************************
|
| 51 |
+
// Execution status meanings: Execution status is used for cancellation of the original task collection and its direct aliases
|
| 52 |
+
// **************************************************************************
|
| 53 |
+
|
| 54 |
+
//
|
| 55 |
+
// The task collection is in clear state -- it's not inlined, it's not canceled, etc...
|
| 56 |
+
//
|
| 57 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_CLEAR 0
|
| 58 |
+
|
| 59 |
+
//
|
| 60 |
+
// The task collection is inlined.
|
| 61 |
+
//
|
| 62 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_INLINE 1
|
| 63 |
+
|
| 64 |
+
//
|
| 65 |
+
// The task collection's cancellation for this alias was deferred because it was not inline.
|
| 66 |
+
//
|
| 67 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_CANCEL_DEFERRED 3
|
| 68 |
+
|
| 69 |
+
//
|
| 70 |
+
// The cancellation is complete on the arbitrary thread.
|
| 71 |
+
//
|
| 72 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_CANCEL_COMPLETE 4
|
| 73 |
+
|
| 74 |
+
//
|
| 75 |
+
// The task collection is inlined and about to wait for stolen chores yet the task stack has overflowed. This requires
|
| 76 |
+
// extra care during cancellation.
|
| 77 |
+
//
|
| 78 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_INLINE_WAIT_WITH_OVERFLOW_STACK 5 // 4 | TASKCOLLECTION_EXECUTION_STATUS_INLINE
|
| 79 |
+
|
| 80 |
+
//
|
| 81 |
+
// The task collection is inlined and a cancellation is in progress some arbitrary thread.
|
| 82 |
+
//
|
| 83 |
+
#define TASKCOLLECTION_EXECUTION_STATUS_INLINE_CANCEL_IN_PROGRESS 9 // 8 | TASKCOLLECTION_EXECUTION_STATUS_INLINE
|
| 84 |
+
|
| 85 |
+
// **************************************************************************
|
| 86 |
+
// Task collection flags:
|
| 87 |
+
// **************************************************************************
|
| 88 |
+
|
| 89 |
+
//
|
| 90 |
+
// This is an indirect alias.
|
| 91 |
+
//
|
| 92 |
+
#define TASKCOLLECTIONFLAG_ALIAS_IS_INDIRECT 1
|
| 93 |
+
|
| 94 |
+
//
|
| 95 |
+
// The entity involved in aliasing which views this flag is responsible for cleaning up the alias.
|
| 96 |
+
//
|
| 97 |
+
#define TASKCOLLECTIONFLAG_ALIAS_FREE_ON_VIEW 2
|
| 98 |
+
|
| 99 |
+
// **************************************************************************
|
| 100 |
+
// Related flags:
|
| 101 |
+
// **************************************************************************
|
| 102 |
+
|
| 103 |
+
//
|
| 104 |
+
// The bit indicating that this pointer is a registration rather than a token
|
| 105 |
+
//
|
| 106 |
+
#define TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION 1
|
| 107 |
+
|
| 108 |
+
// **************************************************************************
|
| 109 |
+
// Class definitions:
|
| 110 |
+
// **************************************************************************
|
| 111 |
+
|
| 112 |
+
namespace Concurrency
|
| 113 |
+
{
|
| 114 |
+
namespace details
|
| 115 |
+
{
|
| 116 |
+
/// <summary>
|
| 117 |
+
/// This class is an *INTERNAL* structure which will retain specific optimizations to keeping track
|
| 118 |
+
/// of tasks associated with an unstructured task collection.
|
| 119 |
+
/// </summary>
|
| 120 |
+
class TaskStack
|
| 121 |
+
{
|
| 122 |
+
public:
|
| 123 |
+
|
| 124 |
+
/// <summary>
|
| 125 |
+
/// Constructs a new task stack
|
| 126 |
+
/// </summary>
|
| 127 |
+
TaskStack() : m_stackSize(0), m_stackPtr(0), m_pStack(NULL), m_fOverflow(false)
|
| 128 |
+
{
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
/// <summary>
|
| 132 |
+
/// Destroys a task stack
|
| 133 |
+
/// </summary>
|
| 134 |
+
~TaskStack();
|
| 135 |
+
|
| 136 |
+
/// <summary>
|
| 137 |
+
/// Pushes an element onto the task stack. Returns a bool as to whether this could happen or not. The only
|
| 138 |
+
/// possible error here is out of memory.
|
| 139 |
+
/// </summary>
|
| 140 |
+
/// <param name="taskCookie">
|
| 141 |
+
/// The task cookie to push onto the stack
|
| 142 |
+
/// </param>
|
| 143 |
+
/// <returns>
|
| 144 |
+
/// An indication of whether the stack cap was reached.
|
| 145 |
+
/// </returns>
|
| 146 |
+
bool Push(int taskCookie);
|
| 147 |
+
|
| 148 |
+
/// <summary>
|
| 149 |
+
/// Pops an element from the task stack.
|
| 150 |
+
/// </summary>
|
| 151 |
+
/// <returns>
|
| 152 |
+
/// The element
|
| 153 |
+
/// </returns>
|
| 154 |
+
int Pop();
|
| 155 |
+
|
| 156 |
+
/// </summary>
|
| 157 |
+
/// Returns an indication of whether or not the stack is empty.
|
| 158 |
+
/// </summary>
|
| 159 |
+
bool IsEmpty() const;
|
| 160 |
+
|
| 161 |
+
/// <summary>
|
| 162 |
+
/// Clears out everything on the stack. Does *NOT* reset the overflow flag.
|
| 163 |
+
/// </summary>
|
| 164 |
+
void Clear();
|
| 165 |
+
|
| 166 |
+
/// <summary>
|
| 167 |
+
/// Resets the overflow flag.
|
| 168 |
+
/// </summary>
|
| 169 |
+
void ResetOverflow()
|
| 170 |
+
{
|
| 171 |
+
m_fOverflow = false;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
/// <summary>
|
| 175 |
+
/// An indication if the stack overflowed (was pushed beyond the cap).
|
| 176 |
+
/// </summary>
|
| 177 |
+
bool Overflow() const
|
| 178 |
+
{
|
| 179 |
+
return m_fOverflow;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
private:
|
| 183 |
+
|
| 184 |
+
int m_stackSize;
|
| 185 |
+
int m_stackPtr;
|
| 186 |
+
int *m_pStack;
|
| 187 |
+
bool m_fOverflow;
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
#define EVENT_UNSIGNALED ((void*) 0)
|
| 191 |
+
#define EVENT_SIGNALED ((void*) 1)
|
| 192 |
+
|
| 193 |
+
/// <summary>
|
| 194 |
+
/// A single fire (non-resettable) event supporting a single waiter.
|
| 195 |
+
/// </summary>
|
| 196 |
+
class StructuredEvent
|
| 197 |
+
{
|
| 198 |
+
|
| 199 |
+
public:
|
| 200 |
+
|
| 201 |
+
/// <summary>
|
| 202 |
+
/// Constructs a new structured event.
|
| 203 |
+
/// </summary>
|
| 204 |
+
StructuredEvent()
|
| 205 |
+
: m_ptr(EVENT_UNSIGNALED)
|
| 206 |
+
{
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
/// <summary>
|
| 210 |
+
/// Waits until the event is signaled (via some other context calling Set())
|
| 211 |
+
/// </summary>
|
| 212 |
+
void Wait();
|
| 213 |
+
|
| 214 |
+
/// <summary>
|
| 215 |
+
/// Set the event as signaled, and unblock any other contexts waiting on the event.
|
| 216 |
+
/// </summary>
|
| 217 |
+
void Set();
|
| 218 |
+
|
| 219 |
+
private:
|
| 220 |
+
void * volatile m_ptr;
|
| 221 |
+
};
|
| 222 |
+
|
| 223 |
+
/// <summary>
|
| 224 |
+
/// Context record for WSQ sweeps.
|
| 225 |
+
/// </summary>
|
| 226 |
+
struct SweeperContext
|
| 227 |
+
{
|
| 228 |
+
/// <summary>
|
| 229 |
+
/// Constructs a new sweeper context.
|
| 230 |
+
/// </summary>
|
| 231 |
+
SweeperContext(_TaskCollection *pTaskCollection) :
|
| 232 |
+
m_pTaskCollection(pTaskCollection),
|
| 233 |
+
m_sweptChores(0)
|
| 234 |
+
{
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
_TaskCollection *m_pTaskCollection;
|
| 238 |
+
unsigned int m_sweptChores;
|
| 239 |
+
};
|
| 240 |
+
} // namespace details
|
| 241 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/TaskCollectionBase.cpp
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// TaskCollectionBase.cpp
|
| 9 |
+
//
|
| 10 |
+
// General abstract collection of work counting / eventing implementation
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
|
| 14 |
+
#include "concrtinternal.h"
|
| 15 |
+
|
| 16 |
+
namespace Concurrency
|
| 17 |
+
{
|
| 18 |
+
namespace details
|
| 19 |
+
{
|
| 20 |
+
/// <summary>
|
| 21 |
+
/// 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
|
| 22 |
+
/// and stores it for potential transport back to the thread performing a join on a task collection.
|
| 23 |
+
/// </summary>
|
| 24 |
+
void _TaskCollectionBase::_RaisedException()
|
| 25 |
+
{
|
| 26 |
+
//
|
| 27 |
+
// Current strategy is that the first exception in is kept and rethrown. We may update this in the future.
|
| 28 |
+
//
|
| 29 |
+
void * _OldStatus = _M_pException;
|
| 30 |
+
for (;;)
|
| 31 |
+
{
|
| 32 |
+
//
|
| 33 |
+
// We always overwrite the cancel exception being here. Everything else is "more important".
|
| 34 |
+
//
|
| 35 |
+
std::exception_ptr *_pException = (std::exception_ptr *)((size_t)_OldStatus & ~_S_cancelBitsMask);
|
| 36 |
+
if (_pException != NULL && (size_t)_pException != _S_cancelException)
|
| 37 |
+
return;
|
| 38 |
+
|
| 39 |
+
//
|
| 40 |
+
// Maintain the lower bit as a cancel status flag to determine where to stop a cancellation.
|
| 41 |
+
//
|
| 42 |
+
size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask);
|
| 43 |
+
|
| 44 |
+
void * _XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, (void *) (_S_nonNull | _cancelStatus), _OldStatus);
|
| 45 |
+
if (_XchgStatus == _OldStatus)
|
| 46 |
+
break;
|
| 47 |
+
|
| 48 |
+
_OldStatus = _XchgStatus;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
//
|
| 52 |
+
// 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
|
| 53 |
+
// thread until after we "_CountUp" which comes after this.
|
| 54 |
+
//
|
| 55 |
+
void *_pExc = _concrt_new std::exception_ptr(std::current_exception());
|
| 56 |
+
_OldStatus = _M_pException;
|
| 57 |
+
for(;;)
|
| 58 |
+
{
|
| 59 |
+
size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask);
|
| 60 |
+
void *_pExcWC = (void *)((size_t)_pExc | _cancelStatus);
|
| 61 |
+
|
| 62 |
+
void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, _pExcWC, _OldStatus);
|
| 63 |
+
if (_XchgStatus == _OldStatus)
|
| 64 |
+
break;
|
| 65 |
+
|
| 66 |
+
_OldStatus = _XchgStatus;
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/// <summary>
|
| 71 |
+
/// Potentially rethrows the exception which was set with _RaisedException. The caller has responsibility to ensure that _RaisedException
|
| 72 |
+
/// was called prior to calling this and that _M_pException has progressed beyond the _S_nonNull state.
|
| 73 |
+
/// </summary>
|
| 74 |
+
void _TaskCollectionBase::_RethrowException()
|
| 75 |
+
{
|
| 76 |
+
//
|
| 77 |
+
// The cancellation exception is treated very specially within the runtime. Do not arbitrarily rethrow from here.
|
| 78 |
+
//
|
| 79 |
+
std::exception_ptr *_pException = _Exception();
|
| 80 |
+
if (_pException != NULL && (size_t)_pException != _S_cancelException)
|
| 81 |
+
{
|
| 82 |
+
std::exception_ptr _curException = *_Exception();
|
| 83 |
+
|
| 84 |
+
delete _pException;
|
| 85 |
+
_M_pException = NULL;
|
| 86 |
+
|
| 87 |
+
if ( !__uncaught_exception())
|
| 88 |
+
std::rethrow_exception(_curException);
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/// <summary>
|
| 93 |
+
/// Marks the collection for cancellation and returns whether the collection was thus marked.
|
| 94 |
+
/// </summary>
|
| 95 |
+
bool _TaskCollectionBase::_MarkCancellation()
|
| 96 |
+
{
|
| 97 |
+
void *_OldStatus = _M_pException;
|
| 98 |
+
for(;;)
|
| 99 |
+
{
|
| 100 |
+
if ((size_t)_OldStatus & _S_cancelBitsMask) // already canceled
|
| 101 |
+
return false;
|
| 102 |
+
|
| 103 |
+
void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException,
|
| 104 |
+
(void *)((size_t)_OldStatus | _S_cancelStarted),
|
| 105 |
+
_OldStatus);
|
| 106 |
+
if (_XchgStatus == _OldStatus)
|
| 107 |
+
return true;
|
| 108 |
+
|
| 109 |
+
_OldStatus = _XchgStatus;
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
/// <summary>
|
| 114 |
+
/// Finishes the cancellation state (changing from _S_cancelStarted to one of the other states). Note that only the
|
| 115 |
+
/// thread which successfully marked cancellation may call this.
|
| 116 |
+
/// </summary>
|
| 117 |
+
void _TaskCollectionBase::_FinishCancelState(size_t _NewCancelState)
|
| 118 |
+
{
|
| 119 |
+
ASSERT(_CancelState() == _S_cancelStarted);
|
| 120 |
+
ASSERT(_NewCancelState != _S_cancelNone && _NewCancelState != _S_cancelStarted);
|
| 121 |
+
|
| 122 |
+
void *_OldStatus = _M_pException;
|
| 123 |
+
for(;;)
|
| 124 |
+
{
|
| 125 |
+
void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException,
|
| 126 |
+
(void *)(((size_t)_OldStatus & ~_S_cancelBitsMask) | _NewCancelState),
|
| 127 |
+
_OldStatus);
|
| 128 |
+
|
| 129 |
+
if (_XchgStatus == _OldStatus)
|
| 130 |
+
break;
|
| 131 |
+
|
| 132 |
+
_OldStatus = _XchgStatus;
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/// <summary>
|
| 137 |
+
/// 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
|
| 138 |
+
/// and stores it for potential transport back to the thread performing a join on a chore collection. Note that every other exception
|
| 139 |
+
/// has precedence over a cancellation.
|
| 140 |
+
/// </summary>
|
| 141 |
+
void _TaskCollectionBase::_RaisedCancel()
|
| 142 |
+
{
|
| 143 |
+
void *_OldStatus = _M_pException;
|
| 144 |
+
for (;;)
|
| 145 |
+
{
|
| 146 |
+
std::exception_ptr *_pException = (std::exception_ptr *)((size_t)_OldStatus & ~_S_cancelBitsMask);
|
| 147 |
+
if (_pException != NULL)
|
| 148 |
+
return;
|
| 149 |
+
|
| 150 |
+
size_t _cancelStatus = ((size_t)_OldStatus & _S_cancelBitsMask);
|
| 151 |
+
void *pExcWC = (void *)(_S_cancelException | _cancelStatus);
|
| 152 |
+
|
| 153 |
+
void *_XchgStatus = _InterlockedCompareExchangePointer((void * volatile *) &_M_pException, pExcWC, _OldStatus);
|
| 154 |
+
if (_XchgStatus == _OldStatus)
|
| 155 |
+
break;
|
| 156 |
+
|
| 157 |
+
_OldStatus = _XchgStatus;
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
/// <summary>
|
| 162 |
+
/// Called in order to determine whether this task collection will interrupt for a pending cancellation at or above it.
|
| 163 |
+
///
|
| 164 |
+
bool _TaskCollectionBase::_WillInterruptForPendingCancel()
|
| 165 |
+
{
|
| 166 |
+
//
|
| 167 |
+
// We can only perform the interruption point if someone in the parentage chain is actually inlined. The number of times where we get here
|
| 168 |
+
// without such should be minimal.
|
| 169 |
+
//
|
| 170 |
+
// Note that structured collections do not initialize _M_pParent until they are inlined. In order to avoid excess initialization in the
|
| 171 |
+
// structured case, we key off that to determine the validity of the field. Note that this check is perfectly okay for task collections
|
| 172 |
+
// as well.
|
| 173 |
+
//
|
| 174 |
+
_TaskCollectionBase *pParent = _SafeGetParent();
|
| 175 |
+
_CancellationTokenState *pTokenState = _GetTokenState();
|
| 176 |
+
|
| 177 |
+
while (pParent != NULL)
|
| 178 |
+
{
|
| 179 |
+
//
|
| 180 |
+
// If this token is non null- it could hide cancellation from a parent task collection.
|
| 181 |
+
//
|
| 182 |
+
if (pTokenState == NULL)
|
| 183 |
+
{
|
| 184 |
+
if ((pParent->_IsStructured() && (static_cast<_StructuredTaskCollection *>(pParent))->_IsMarkedForCancellation()) ||
|
| 185 |
+
(!pParent->_IsStructured() && (static_cast<_TaskCollection *>(pParent))->_IsMarkedForAbnormalExit()))
|
| 186 |
+
return true;
|
| 187 |
+
}
|
| 188 |
+
else
|
| 189 |
+
{
|
| 190 |
+
if (pTokenState == _CancellationTokenState::_None())
|
| 191 |
+
return false;
|
| 192 |
+
else
|
| 193 |
+
return pTokenState->_IsCanceled();
|
| 194 |
+
}
|
| 195 |
+
//
|
| 196 |
+
// Grab the parent token before switching to its parent.
|
| 197 |
+
//
|
| 198 |
+
pTokenState = pParent->_GetTokenState();
|
| 199 |
+
pParent = pParent->_SafeGetParent();
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
return false;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
/// <summary>
|
| 206 |
+
/// Returns the cancellation token state associated with this task collection.
|
| 207 |
+
/// </summary>
|
| 208 |
+
_CancellationTokenState *_TaskCollectionBase::_GetTokenState(_CancellationTokenRegistration **_PRegistration)
|
| 209 |
+
{
|
| 210 |
+
_CancellationTokenState *pTokenState = _M_pTokenState;
|
| 211 |
+
_CancellationTokenRegistration *pRegistration = NULL;
|
| 212 |
+
|
| 213 |
+
if (reinterpret_cast<ULONG_PTR>(pTokenState) & TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION)
|
| 214 |
+
{
|
| 215 |
+
pRegistration = reinterpret_cast<_CancellationTokenRegistration *>(
|
| 216 |
+
reinterpret_cast<ULONG_PTR>(pTokenState) & ~TASKCOLLECTIONFLAG_POINTER_IS_REGISTRATION
|
| 217 |
+
);
|
| 218 |
+
|
| 219 |
+
if (pRegistration != NULL)
|
| 220 |
+
{
|
| 221 |
+
pTokenState = pRegistration->_GetToken();
|
| 222 |
+
}
|
| 223 |
+
else
|
| 224 |
+
{
|
| 225 |
+
pTokenState = _CancellationTokenState::_None();
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
if (_PRegistration != NULL)
|
| 229 |
+
{
|
| 230 |
+
*_PRegistration = pRegistration;
|
| 231 |
+
}
|
| 232 |
+
return pTokenState;
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
} // namespace details
|
| 236 |
+
} // namespace Concurrency
|
msvc/VC/Tools/MSVC/14.50.35717/crt/src/concrt/ThreadInternalContext.cpp
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// ==++==
|
| 2 |
+
//
|
| 3 |
+
// Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
//
|
| 5 |
+
// ==--==
|
| 6 |
+
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
|
| 7 |
+
//
|
| 8 |
+
// ThreadInternalContext.cpp
|
| 9 |
+
//
|
| 10 |
+
// Source file containing that implementation for a thread based internal execution context/stack.
|
| 11 |
+
//
|
| 12 |
+
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
| 13 |
+
#pragma once
|
| 14 |
+
|
| 15 |
+
#include "concrtinternal.h"
|
| 16 |
+
|
| 17 |
+
namespace Concurrency
|
| 18 |
+
{
|
| 19 |
+
namespace details
|
| 20 |
+
{
|
| 21 |
+
|
| 22 |
+
} // namespace details
|
| 23 |
+
} // namespace Concurrency
|