forked from ngscopeclient/scopehal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterGraphExecutor.cpp
More file actions
333 lines (280 loc) · 11.2 KB
/
Copy pathFilterGraphExecutor.cpp
File metadata and controls
333 lines (280 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/***********************************************************************************************************************
* *
* libscopehal *
* *
* Copyright (c) 2012-2025 Andrew D. Zonenberg and contributors *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of FilterGraphExecutor
@ingroup core
*/
#include "scopehal.h"
#include <shared_mutex>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
FilterGraphExecutor::FilterGraphExecutor(size_t numThreads)
: m_allWorkersComplete(true)
, m_terminating(false)
{
//Create our thread pool
for(size_t i=0; i<numThreads; i++)
m_threads.push_back(make_unique<thread>(&FilterGraphExecutor::ExecutorThread, this, i));
}
FilterGraphExecutor::~FilterGraphExecutor()
{
//Terminate worker threads
m_terminating = true;
m_workerCvar.notify_all();
for(auto& t : m_threads)
t->join();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup for a run
/**
@brief Evaluates the filter graph, blocking until execution has completed
*/
void FilterGraphExecutor::RunBlocking(const set<FlowGraphNode*>& nodes)
{
//Nothing to do if we have no nodes to run
if(nodes.empty())
return;
{
lock_guard<mutex> lock(m_perfStatsMutex);
m_currentExecutionTime.clear();
}
{
lock_guard<mutex> lock(m_mutex);
if(!m_allWorkersComplete)
LogWarning("Entering RunBlocking() but not all workers are complete from previous run\n");
m_incompleteNodes = nodes;
m_incompleteNodes.erase(nullptr); //don't crash if a null filter somehow ended up in the list
m_runnableNodes.clear();
m_allWorkersComplete = false;
Filter::ClearAnalysisCache();
}
//Wake up our workers
m_workerCvar.notify_all();
//Block until they're finished
while(true)
{
unique_lock<mutex> lock(m_completionCvarMutex);
m_completionCvar.wait(lock, [this]{return m_allWorkersComplete;});
lock_guard<mutex> lock2(m_mutex);
if(m_runnableNodes.empty())
break;
}
//Update global performance stats
{
lock_guard<mutex> lock(m_perfStatsMutex);
//For now, fixed half life exponential moving average
float halflife = 8;
float decay = 1 / pow(2, 1/halflife);
//TODO: staleness or removing of some sort for old entries?
//Add the new data
for(auto& it : m_currentExecutionTime)
m_lastExecutionTime[it.first] = (m_lastExecutionTime[it.first] * decay) + (it.second * (1-decay));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Scheduling
/**
@brief Returns the next filter available to run, blocking if none are ready.
Returns null if there are no remaining filters to evaluate.
*/
FlowGraphNode* FilterGraphExecutor::GetNextRunnableNode()
{
while(true)
{
//Check for stuff
{
lock_guard<mutex> lock(m_mutex);
//Nothing left to run? Stop
if(m_incompleteNodes.empty())
return nullptr;
//Nothing ready to run? Update the run queue
if(m_runnableNodes.empty())
UpdateRunnable();
//If there is something ready to run, grab it
if(!m_runnableNodes.empty())
{
auto f = *m_runnableNodes.begin();
m_runnableNodes.erase(f);
m_runningNodes.emplace(f);
return f;
}
}
//Still nothing to run? Block
unique_lock<mutex> lock(m_workerCvarMutex);
m_workerCvar.wait(lock);
}
}
/**
@brief Searches m_incompleteNodes for any that are unblocked, and adds them to m_runnableNodes
Assumes m_mutex is locked
*/
void FilterGraphExecutor::UpdateRunnable()
{
//Do nothing if we already have other filters marked runnable
if(!m_runnableNodes.empty())
return;
//Look for new filters that are eligible to run
for(auto f : m_incompleteNodes)
{
//If the filter is already running, nothing we can do
if(m_runningNodes.find(f) != m_runningNodes.end())
continue;
//Not actively running.
//Is it blocked by any of our incomplete filters?
bool ok = true;
for(size_t i=0; i<f->GetInputCount(); i++)
{
auto in = f->GetInput(i).m_channel;
if(m_incompleteNodes.find(in) != m_incompleteNodes.end())
{
ok = false;
break;
}
}
//Not blocked. It's runnable.
if(ok)
m_runnableNodes.emplace(f);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Main parallel execution logic
/**
@brief Thread function to handle filter graph execution
*/
void FilterGraphExecutor::ExecutorThread(FilterGraphExecutor* pThis, size_t i)
{
#ifdef __linux__
pthread_setname_np(pthread_self(), "FilterGraph");
#endif
//Make locale handling thread safe on Windows
#ifdef _WIN32
_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
Unit::SetDefaultLocale();
#endif
pThis->DoExecutorThread(i);
}
void FilterGraphExecutor::DoExecutorThread(size_t i)
{
//Create a queue and command buffer for this thread's accelerated processing
std::shared_ptr<QueueHandle> queue(g_vkQueueManager->GetComputeQueue("FilterGraphExecutor[" + to_string(i) + "].queue"));
vk::CommandPoolCreateInfo poolInfo(
vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
queue->m_family );
vk::raii::CommandPool pool(*g_vkComputeDevice, poolInfo);
vk::CommandBufferAllocateInfo bufinfo(*pool, vk::CommandBufferLevel::ePrimary, 1);
vk::raii::CommandBuffer cmdbuf(std::move(vk::raii::CommandBuffers(*g_vkComputeDevice, bufinfo).front()));
if(g_hasDebugUtils)
{
string prefix = string("FilterGraphExecutor[") + to_string(i) + "]";
string poolname = prefix + ".pool";
string bufname = prefix + ".cmdbuf";
g_vkComputeDevice->setDebugUtilsObjectNameEXT(
vk::DebugUtilsObjectNameInfoEXT(
vk::ObjectType::eCommandPool,
reinterpret_cast<uint64_t>(static_cast<VkCommandPool>(*pool)),
poolname.c_str()));
g_vkComputeDevice->setDebugUtilsObjectNameEXT(
vk::DebugUtilsObjectNameInfoEXT(
vk::ObjectType::eCommandBuffer,
reinterpret_cast<uint64_t>(static_cast<VkCommandBuffer>(*cmdbuf)),
bufname.c_str()));
}
//Main loop
while(true)
{
{
//Wait until the main thread starts a new round of execution, or the timeout elapses
//When we time out, check if we're shutting down
unique_lock<mutex> lock(m_workerCvarMutex);
m_workerCvar.wait_for(lock, chrono::milliseconds(50));
}
//If they woke us up because the context is being destroyed, we're done
if(m_terminating)
break;
//If we're already done, nothing to do
if(m_allWorkersComplete)
continue;
//Evaluate nodes as they become available, then stop when there's nothing left to do
FlowGraphNode* f;
while( (f = GetNextRunnableNode()) != nullptr)
{
shared_lock<shared_mutex> lock(g_vulkanActivityMutex);
//Make sure the filter's inputs are where we need them
auto loc = f->GetInputLocation();
if(loc != Filter::LOC_DONTCARE)
{
bool expectGpuInput = (loc == Filter::LOC_GPU);
bool expectCpuInput = (loc == Filter::LOC_CPU);
for(size_t j=0; j<f->GetInputCount(); j++)
{
auto data = f->GetInput(j).GetData();
if(data)
{
if(expectGpuInput)
data->PrepareForGpuAccess();
else if(expectCpuInput)
data->PrepareForCpuAccess();
}
}
}
//Actually execute the filter
double start = GetTime();
f->Refresh(cmdbuf, queue);
double dt = GetTime() - start;
{
lock_guard<mutex> slock(m_perfStatsMutex);
m_currentExecutionTime[f] = dt * FS_PER_SECOND;
}
//Filter execution has completed, remove it from the running list and mark as completed
lock_guard<mutex> lock2(m_mutex);
m_runningNodes.erase(f);
m_incompleteNodes.erase(f);
//Wake up all threads that might have been waiting on this filter to complete
m_workerCvar.notify_all();
}
//We have no more filters to run.
//If this was the last filter (nothing left incomplete), we're done - wake up the main thread
bool empty = false;
{
lock_guard<mutex> lock2(m_mutex);
empty = m_incompleteNodes.empty();
}
if(empty)
{
{
lock_guard<mutex> lock3(m_completionCvarMutex);
m_allWorkersComplete = true;
}
m_completionCvar.notify_all();
}
}
}