swr: don't claim to allow setting layer/viewport from VS
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / threads.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 ****************************************************************************/
23
24 #include <stdio.h>
25 #include <thread>
26 #include <algorithm>
27 #include <float.h>
28 #include <vector>
29 #include <utility>
30 #include <fstream>
31 #include <string>
32
33 #if defined(__linux__) || defined(__gnu_linux__)
34 #include <pthread.h>
35 #include <sched.h>
36 #include <unistd.h>
37 #endif
38
39 #include "common/os.h"
40 #include "context.h"
41 #include "frontend.h"
42 #include "backend.h"
43 #include "rasterizer.h"
44 #include "rdtsc_core.h"
45 #include "tilemgr.h"
46
47
48
49
50 // ThreadId
51 struct Core
52 {
53 uint32_t procGroup = 0;
54 std::vector<uint32_t> threadIds;
55 };
56
57 struct NumaNode
58 {
59 std::vector<Core> cores;
60 };
61
62 typedef std::vector<NumaNode> CPUNumaNodes;
63
64 void CalculateProcessorTopology(CPUNumaNodes& out_nodes, uint32_t& out_numThreadsPerProcGroup)
65 {
66 out_nodes.clear();
67 out_numThreadsPerProcGroup = 0;
68
69 #if defined(_WIN32)
70
71 std::vector<KAFFINITY> threadMaskPerProcGroup;
72
73 static std::mutex m;
74 std::lock_guard<std::mutex> l(m);
75
76 DWORD bufSize = 0;
77
78 BOOL ret = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bufSize);
79 SWR_ASSERT(ret == FALSE && GetLastError() == ERROR_INSUFFICIENT_BUFFER);
80
81 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBufferMem = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)malloc(bufSize);
82 SWR_ASSERT(pBufferMem);
83
84 ret = GetLogicalProcessorInformationEx(RelationProcessorCore, pBufferMem, &bufSize);
85 SWR_ASSERT(ret != FALSE, "Failed to get Processor Topology Information");
86
87 uint32_t count = bufSize / pBufferMem->Size;
88 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBuffer = pBufferMem;
89
90 for (uint32_t i = 0; i < count; ++i)
91 {
92 SWR_ASSERT(pBuffer->Relationship == RelationProcessorCore);
93 for (uint32_t g = 0; g < pBuffer->Processor.GroupCount; ++g)
94 {
95 auto& gmask = pBuffer->Processor.GroupMask[g];
96 uint32_t threadId = 0;
97 uint32_t procGroup = gmask.Group;
98
99 Core* pCore = nullptr;
100
101 uint32_t numThreads = (uint32_t)_mm_popcount_sizeT(gmask.Mask);
102
103 while (BitScanForwardSizeT((unsigned long*)&threadId, gmask.Mask))
104 {
105 // clear mask
106 KAFFINITY threadMask = KAFFINITY(1) << threadId;
107 gmask.Mask &= ~threadMask;
108
109 if (procGroup >= threadMaskPerProcGroup.size())
110 {
111 threadMaskPerProcGroup.resize(procGroup + 1);
112 }
113
114 if (threadMaskPerProcGroup[procGroup] & threadMask)
115 {
116 // Already seen this mask. This means that we are in 32-bit mode and
117 // have seen more than 32 HW threads for this procGroup
118 // Don't use it
119 #if defined(_WIN64)
120 SWR_ASSERT(false, "Shouldn't get here in 64-bit mode");
121 #endif
122 continue;
123 }
124
125 threadMaskPerProcGroup[procGroup] |= (KAFFINITY(1) << threadId);
126
127 // Find Numa Node
128 uint32_t numaId = 0;
129 PROCESSOR_NUMBER procNum = {};
130 procNum.Group = WORD(procGroup);
131 procNum.Number = UCHAR(threadId);
132
133 ret = GetNumaProcessorNodeEx(&procNum, (PUSHORT)&numaId);
134 SWR_ASSERT(ret);
135
136 // Store data
137 if (out_nodes.size() <= numaId) out_nodes.resize(numaId + 1);
138 auto& numaNode = out_nodes[numaId];
139
140 uint32_t coreId = 0;
141
142 if (nullptr == pCore)
143 {
144 numaNode.cores.push_back(Core());
145 pCore = &numaNode.cores.back();
146 pCore->procGroup = procGroup;
147 }
148 pCore->threadIds.push_back(threadId);
149 if (procGroup == 0)
150 {
151 out_numThreadsPerProcGroup++;
152 }
153 }
154 }
155 pBuffer = PtrAdd(pBuffer, pBuffer->Size);
156 }
157
158 free(pBufferMem);
159
160
161 #elif defined(__linux__) || defined (__gnu_linux__)
162
163 // Parse /proc/cpuinfo to get full topology
164 std::ifstream input("/proc/cpuinfo");
165 std::string line;
166 char* c;
167 uint32_t threadId = uint32_t(-1);
168 uint32_t coreId = uint32_t(-1);
169 uint32_t numaId = uint32_t(-1);
170
171 while (std::getline(input, line))
172 {
173 if (line.find("processor") != std::string::npos)
174 {
175 if (threadId != uint32_t(-1))
176 {
177 // Save information.
178 if (out_nodes.size() <= numaId) out_nodes.resize(numaId + 1);
179 auto& numaNode = out_nodes[numaId];
180 if (numaNode.cores.size() <= coreId) numaNode.cores.resize(coreId + 1);
181 auto& core = numaNode.cores[coreId];
182
183 core.procGroup = coreId;
184 core.threadIds.push_back(threadId);
185
186 out_numThreadsPerProcGroup++;
187 }
188
189 auto data_start = line.find(": ") + 2;
190 threadId = std::strtoul(&line.c_str()[data_start], &c, 10);
191 continue;
192 }
193 if (line.find("core id") != std::string::npos)
194 {
195 auto data_start = line.find(": ") + 2;
196 coreId = std::strtoul(&line.c_str()[data_start], &c, 10);
197 continue;
198 }
199 if (line.find("physical id") != std::string::npos)
200 {
201 auto data_start = line.find(": ") + 2;
202 numaId = std::strtoul(&line.c_str()[data_start], &c, 10);
203 continue;
204 }
205 }
206
207 if (threadId != uint32_t(-1))
208 {
209 // Save information.
210 if (out_nodes.size() <= numaId) out_nodes.resize(numaId + 1);
211 auto& numaNode = out_nodes[numaId];
212 if (numaNode.cores.size() <= coreId) numaNode.cores.resize(coreId + 1);
213 auto& core = numaNode.cores[coreId];
214
215 core.procGroup = coreId;
216 core.threadIds.push_back(threadId);
217 out_numThreadsPerProcGroup++;
218 }
219
220 for (uint32_t node = 0; node < out_nodes.size(); node++) {
221 auto& numaNode = out_nodes[node];
222 auto it = numaNode.cores.begin();
223 for ( ; it != numaNode.cores.end(); ) {
224 if (it->threadIds.size() == 0)
225 numaNode.cores.erase(it);
226 else
227 ++it;
228 }
229 }
230
231 #else
232
233 #error Unsupported platform
234
235 #endif
236 }
237
238
239 void bindThread(SWR_CONTEXT* pContext, uint32_t threadId, uint32_t procGroupId = 0, bool bindProcGroup=false)
240 {
241 // Only bind threads when MAX_WORKER_THREADS isn't set.
242 if (pContext->threadInfo.MAX_WORKER_THREADS && bindProcGroup == false)
243 {
244 return;
245 }
246
247 #if defined(_WIN32)
248
249 GROUP_AFFINITY affinity = {};
250 affinity.Group = procGroupId;
251
252 #if !defined(_WIN64)
253 if (threadId >= 32)
254 {
255 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
256 SWR_REL_ASSERT(false, "Shouldn't get here");
257
258 // In a 32-bit process on Windows it is impossible to bind
259 // to logical processors 32-63 within a processor group.
260 // In this case set the mask to 0 and let the system assign
261 // the processor. Hopefully it will make smart choices.
262 affinity.Mask = 0;
263 }
264 else
265 #endif
266 {
267 // If MAX_WORKER_THREADS is set, only bind to the proc group,
268 // Not the individual HW thread.
269 if (!pContext->threadInfo.MAX_WORKER_THREADS)
270 {
271 affinity.Mask = KAFFINITY(1) << threadId;
272 }
273 }
274
275 SetThreadGroupAffinity(GetCurrentThread(), &affinity, nullptr);
276
277 #else
278
279 cpu_set_t cpuset;
280 pthread_t thread = pthread_self();
281 CPU_ZERO(&cpuset);
282 CPU_SET(threadId, &cpuset);
283
284 pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
285
286 #endif
287 }
288
289 INLINE
290 uint32_t GetEnqueuedDraw(SWR_CONTEXT *pContext)
291 {
292 return pContext->dcRing.GetHead();
293 }
294
295 INLINE
296 DRAW_CONTEXT *GetDC(SWR_CONTEXT *pContext, uint32_t drawId)
297 {
298 return &pContext->dcRing[(drawId-1) % KNOB_MAX_DRAWS_IN_FLIGHT];
299 }
300
301 INLINE
302 bool IDComparesLess(uint32_t a, uint32_t b)
303 {
304 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
305 int32_t delta = int32_t(a - b);
306 return (delta < 0);
307 }
308
309 // returns true if dependency not met
310 INLINE
311 bool CheckDependency(SWR_CONTEXT *pContext, DRAW_CONTEXT *pDC, uint32_t lastRetiredDraw)
312 {
313 return pDC->dependent && IDComparesLess(lastRetiredDraw, pDC->drawId - 1);
314 }
315
316 bool CheckDependencyFE(SWR_CONTEXT *pContext, DRAW_CONTEXT *pDC, uint32_t lastRetiredDraw)
317 {
318 return pDC->dependentFE && IDComparesLess(lastRetiredDraw, pDC->drawId - 1);
319 }
320
321 //////////////////////////////////////////////////////////////////////////
322 /// @brief Update client stats.
323 INLINE void UpdateClientStats(SWR_CONTEXT* pContext, uint32_t workerId, DRAW_CONTEXT* pDC)
324 {
325 if ((pContext->pfnUpdateStats == nullptr) || (GetApiState(pDC).enableStatsBE == false))
326 {
327 return;
328 }
329
330 DRAW_DYNAMIC_STATE& dynState = pDC->dynState;
331 SWR_STATS stats{ 0 };
332
333 // Sum up stats across all workers before sending to client.
334 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
335 {
336 stats.DepthPassCount += dynState.pStats[i].DepthPassCount;
337
338 stats.PsInvocations += dynState.pStats[i].PsInvocations;
339 stats.CsInvocations += dynState.pStats[i].CsInvocations;
340 }
341
342
343 pContext->pfnUpdateStats(GetPrivateState(pDC), &stats);
344 }
345
346 INLINE void ExecuteCallbacks(SWR_CONTEXT* pContext, uint32_t workerId, DRAW_CONTEXT* pDC)
347 {
348 UpdateClientStats(pContext, workerId, pDC);
349
350 if (pDC->retireCallback.pfnCallbackFunc)
351 {
352 pDC->retireCallback.pfnCallbackFunc(pDC->retireCallback.userData,
353 pDC->retireCallback.userData2,
354 pDC->retireCallback.userData3);
355 }
356 }
357
358 // inlined-only version
359 INLINE int32_t CompleteDrawContextInl(SWR_CONTEXT* pContext, uint32_t workerId, DRAW_CONTEXT* pDC)
360 {
361 int32_t result = InterlockedDecrement((volatile LONG*)&pDC->threadsDone);
362 SWR_ASSERT(result >= 0);
363
364 if (result == 0)
365 {
366 ExecuteCallbacks(pContext, workerId, pDC);
367
368 // Cleanup memory allocations
369 pDC->pArena->Reset(true);
370 if (!pDC->isCompute)
371 {
372 pDC->pTileMgr->initialize();
373 }
374 if (pDC->cleanupState)
375 {
376 pDC->pState->pArena->Reset(true);
377 }
378
379 _ReadWriteBarrier();
380
381 pContext->dcRing.Dequeue(); // Remove from tail
382 }
383
384 return result;
385 }
386
387 // available to other translation modules
388 int32_t CompleteDrawContext(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
389 {
390 return CompleteDrawContextInl(pContext, 0, pDC);
391 }
392
393 INLINE bool FindFirstIncompleteDraw(SWR_CONTEXT* pContext, uint32_t workerId, uint32_t& curDrawBE, uint32_t& drawEnqueued)
394 {
395 // increment our current draw id to the first incomplete draw
396 drawEnqueued = GetEnqueuedDraw(pContext);
397 while (IDComparesLess(curDrawBE, drawEnqueued))
398 {
399 DRAW_CONTEXT *pDC = &pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT];
400
401 // If its not compute and FE is not done then break out of loop.
402 if (!pDC->doneFE && !pDC->isCompute) break;
403
404 bool isWorkComplete = pDC->isCompute ?
405 pDC->pDispatch->isWorkComplete() :
406 pDC->pTileMgr->isWorkComplete();
407
408 if (isWorkComplete)
409 {
410 curDrawBE++;
411 CompleteDrawContextInl(pContext, workerId, pDC);
412 }
413 else
414 {
415 break;
416 }
417 }
418
419 // If there are no more incomplete draws then return false.
420 return IDComparesLess(curDrawBE, drawEnqueued);
421 }
422
423 //////////////////////////////////////////////////////////////////////////
424 /// @brief If there is any BE work then go work on it.
425 /// @param pContext - pointer to SWR context.
426 /// @param workerId - The unique worker ID that is assigned to this thread.
427 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
428 /// has its own curDrawBE counter and this ensures that each worker processes all the
429 /// draws in order.
430 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
431 /// own set and each time it fails to lock a macrotile, because its already locked,
432 /// then it will add that tile to the lockedTiles set. As a worker begins to work
433 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
434 /// still have work pending in a previous draw. Additionally, the lockedTiles is
435 /// hueristic that can steer a worker back to the same macrotile that it had been
436 /// working on in a previous draw.
437 /// @returns true if worker thread should shutdown
438 bool WorkOnFifoBE(
439 SWR_CONTEXT *pContext,
440 uint32_t workerId,
441 uint32_t &curDrawBE,
442 TileSet& lockedTiles,
443 uint32_t numaNode,
444 uint32_t numaMask)
445 {
446 bool bShutdown = false;
447
448 // Find the first incomplete draw that has pending work. If no such draw is found then
449 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
450 uint32_t drawEnqueued = 0;
451 if (FindFirstIncompleteDraw(pContext, workerId, curDrawBE, drawEnqueued) == false)
452 {
453 return false;
454 }
455
456 uint32_t lastRetiredDraw = pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT].drawId - 1;
457
458 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
459 lockedTiles.clear();
460
461 // Try to work on each draw in order of the available draws in flight.
462 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
463 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
464 // working on those macrotiles that are known to be complete in the prior draw to
465 // maintain order. The locked tiles provides the history to ensures this.
466 for (uint32_t i = curDrawBE; IDComparesLess(i, drawEnqueued); ++i)
467 {
468 DRAW_CONTEXT *pDC = &pContext->dcRing[i % KNOB_MAX_DRAWS_IN_FLIGHT];
469
470 if (pDC->isCompute) return false; // We don't look at compute work.
471
472 // First wait for FE to be finished with this draw. This keeps threading model simple
473 // but if there are lots of bubbles between draws then serializing FE and BE may
474 // need to be revisited.
475 if (!pDC->doneFE) return false;
476
477 // If this draw is dependent on a previous draw then we need to bail.
478 if (CheckDependency(pContext, pDC, lastRetiredDraw))
479 {
480 return false;
481 }
482
483 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
484 auto &macroTiles = pDC->pTileMgr->getDirtyTiles();
485
486 for (auto tile : macroTiles)
487 {
488 uint32_t tileID = tile->mId;
489
490 // Only work on tiles for this numa node
491 uint32_t x, y;
492 pDC->pTileMgr->getTileIndices(tileID, x, y);
493 if (((x ^ y) & numaMask) != numaNode)
494 {
495 continue;
496 }
497
498 if (!tile->getNumQueued())
499 {
500 continue;
501 }
502
503 // can only work on this draw if it's not in use by other threads
504 if (lockedTiles.find(tileID) != lockedTiles.end())
505 {
506 continue;
507 }
508
509 if (tile->tryLock())
510 {
511 BE_WORK *pWork;
512
513 AR_BEGIN(WorkerFoundWork, pDC->drawId);
514
515 uint32_t numWorkItems = tile->getNumQueued();
516 SWR_ASSERT(numWorkItems);
517
518 pWork = tile->peek();
519 SWR_ASSERT(pWork);
520 if (pWork->type == DRAW)
521 {
522 pContext->pHotTileMgr->InitializeHotTiles(pContext, pDC, workerId, tileID);
523 }
524 else if (pWork->type == SHUTDOWN)
525 {
526 bShutdown = true;
527 }
528
529 while ((pWork = tile->peek()) != nullptr)
530 {
531 pWork->pfnWork(pDC, workerId, tileID, &pWork->desc);
532 tile->dequeue();
533 }
534 AR_END(WorkerFoundWork, numWorkItems);
535
536 _ReadWriteBarrier();
537
538 pDC->pTileMgr->markTileComplete(tileID);
539
540 // Optimization: If the draw is complete and we're the last one to have worked on it then
541 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
542 if ((curDrawBE == i) && (bShutdown || pDC->pTileMgr->isWorkComplete()))
543 {
544 // We can increment the current BE and safely move to next draw since we know this draw is complete.
545 curDrawBE++;
546 CompleteDrawContextInl(pContext, workerId, pDC);
547
548 lastRetiredDraw++;
549
550 lockedTiles.clear();
551 break;
552 }
553
554 if (bShutdown)
555 {
556 break;
557 }
558 }
559 else
560 {
561 // This tile is already locked. So let's add it to our locked tiles set. This way we don't try locking this one again.
562 lockedTiles.insert(tileID);
563 }
564 }
565 }
566
567 return bShutdown;
568 }
569
570 //////////////////////////////////////////////////////////////////////////
571 /// @brief Called when FE work is complete for this DC.
572 INLINE void CompleteDrawFE(SWR_CONTEXT* pContext, uint32_t workerId, DRAW_CONTEXT* pDC)
573 {
574 if (pContext->pfnUpdateStatsFE && GetApiState(pDC).enableStatsFE)
575 {
576 SWR_STATS_FE& stats = pDC->dynState.statsFE;
577
578 AR_EVENT(FrontendStatsEvent(pDC->drawId,
579 stats.IaVertices, stats.IaPrimitives, stats.VsInvocations, stats.HsInvocations,
580 stats.DsInvocations, stats.GsInvocations, stats.GsPrimitives, stats.CInvocations, stats.CPrimitives,
581 stats.SoPrimStorageNeeded[0], stats.SoPrimStorageNeeded[1], stats.SoPrimStorageNeeded[2], stats.SoPrimStorageNeeded[3],
582 stats.SoNumPrimsWritten[0], stats.SoNumPrimsWritten[1], stats.SoNumPrimsWritten[2], stats.SoNumPrimsWritten[3]
583 ));
584 AR_EVENT(FrontendDrawEndEvent(pDC->drawId));
585
586 pContext->pfnUpdateStatsFE(GetPrivateState(pDC), &stats);
587 }
588
589 if (pContext->pfnUpdateSoWriteOffset)
590 {
591 for (uint32_t i = 0; i < MAX_SO_BUFFERS; ++i)
592 {
593 if ((pDC->dynState.SoWriteOffsetDirty[i]) &&
594 (pDC->pState->state.soBuffer[i].soWriteEnable))
595 {
596 pContext->pfnUpdateSoWriteOffset(GetPrivateState(pDC), i, pDC->dynState.SoWriteOffset[i]);
597 }
598 }
599 }
600
601 // Ensure all streaming writes are globally visible before marking this FE done
602 _mm_mfence();
603 pDC->doneFE = true;
604
605 InterlockedDecrement((volatile LONG*)&pContext->drawsOutstandingFE);
606 }
607
608 void WorkOnFifoFE(SWR_CONTEXT *pContext, uint32_t workerId, uint32_t &curDrawFE)
609 {
610 // Try to grab the next DC from the ring
611 uint32_t drawEnqueued = GetEnqueuedDraw(pContext);
612 while (IDComparesLess(curDrawFE, drawEnqueued))
613 {
614 uint32_t dcSlot = curDrawFE % KNOB_MAX_DRAWS_IN_FLIGHT;
615 DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot];
616 if (pDC->isCompute || pDC->doneFE)
617 {
618 CompleteDrawContextInl(pContext, workerId, pDC);
619 curDrawFE++;
620 }
621 else
622 {
623 break;
624 }
625 }
626
627 uint32_t lastRetiredFE = curDrawFE - 1;
628 uint32_t curDraw = curDrawFE;
629 while (IDComparesLess(curDraw, drawEnqueued))
630 {
631 uint32_t dcSlot = curDraw % KNOB_MAX_DRAWS_IN_FLIGHT;
632 DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot];
633
634 if (!pDC->isCompute && !pDC->FeLock)
635 {
636 if (CheckDependencyFE(pContext, pDC, lastRetiredFE))
637 {
638 return;
639 }
640
641 uint32_t initial = InterlockedCompareExchange((volatile uint32_t*)&pDC->FeLock, 1, 0);
642 if (initial == 0)
643 {
644 // successfully grabbed the DC, now run the FE
645 pDC->FeWork.pfnWork(pContext, pDC, workerId, &pDC->FeWork.desc);
646
647 CompleteDrawFE(pContext, workerId, pDC);
648 }
649 }
650 curDraw++;
651 }
652 }
653
654 //////////////////////////////////////////////////////////////////////////
655 /// @brief If there is any compute work then go work on it.
656 /// @param pContext - pointer to SWR context.
657 /// @param workerId - The unique worker ID that is assigned to this thread.
658 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
659 /// has its own curDrawBE counter and this ensures that each worker processes all the
660 /// draws in order.
661 void WorkOnCompute(
662 SWR_CONTEXT *pContext,
663 uint32_t workerId,
664 uint32_t& curDrawBE)
665 {
666 uint32_t drawEnqueued = 0;
667 if (FindFirstIncompleteDraw(pContext, workerId, curDrawBE, drawEnqueued) == false)
668 {
669 return;
670 }
671
672 uint32_t lastRetiredDraw = pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT].drawId - 1;
673
674 for (uint64_t i = curDrawBE; IDComparesLess(i, drawEnqueued); ++i)
675 {
676 DRAW_CONTEXT *pDC = &pContext->dcRing[i % KNOB_MAX_DRAWS_IN_FLIGHT];
677 if (pDC->isCompute == false) return;
678
679 // check dependencies
680 if (CheckDependency(pContext, pDC, lastRetiredDraw))
681 {
682 return;
683 }
684
685 SWR_ASSERT(pDC->pDispatch != nullptr);
686 DispatchQueue& queue = *pDC->pDispatch;
687
688 // Is there any work remaining?
689 if (queue.getNumQueued() > 0)
690 {
691 void* pSpillFillBuffer = nullptr;
692 uint32_t threadGroupId = 0;
693 while (queue.getWork(threadGroupId))
694 {
695 queue.dispatch(pDC, workerId, threadGroupId, pSpillFillBuffer);
696 queue.finishedWork();
697 }
698
699 // Ensure all streaming writes are globally visible before moving onto the next draw
700 _mm_mfence();
701 }
702 }
703 }
704
705 template<bool IsFEThread, bool IsBEThread>
706 DWORD workerThreadMain(LPVOID pData)
707 {
708 THREAD_DATA *pThreadData = (THREAD_DATA*)pData;
709 SWR_CONTEXT *pContext = pThreadData->pContext;
710 uint32_t threadId = pThreadData->threadId;
711 uint32_t workerId = pThreadData->workerId;
712
713 bindThread(pContext, threadId, pThreadData->procGroupId, pThreadData->forceBindProcGroup);
714
715 RDTSC_INIT(threadId);
716
717 uint32_t numaNode = pThreadData->numaId;
718 uint32_t numaMask = pContext->threadPool.numaMask;
719
720 // flush denormals to 0
721 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON | _MM_DENORMALS_ZERO_ON);
722
723 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
724 // locked then we'll add it to this list so that we don't try and lock it again.
725 TileSet lockedTiles;
726
727 // each worker has the ability to work on any of the queued draws as long as certain
728 // conditions are met. the data associated
729 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
730 // has moved on to the next draw when he determines there is no more work to do. The api
731 // thread will not increment the head of the dc ring until all workers have moved past the
732 // current head.
733 // the logic to determine what to work on is:
734 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
735 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
736 // we'll need dependency tracking to force serialization on FEs. The worker will try
737 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
738 // trying until he reaches the tail.
739 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
740 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
741 // any work left by comparing the total # of binned work items and the total # of completed
742 // work items. If they are equal, then there is no more work to do for this draw, and
743 // the worker can safely increment its oldestDraw counter and move on to the next draw.
744 std::unique_lock<std::mutex> lock(pContext->WaitLock, std::defer_lock);
745
746 auto threadHasWork = [&](uint32_t curDraw) { return curDraw != pContext->dcRing.GetHead(); };
747
748 uint32_t curDrawBE = 0;
749 uint32_t curDrawFE = 0;
750
751 bool bShutdown = false;
752
753 while (true)
754 {
755 if (bShutdown && !threadHasWork(curDrawBE))
756 {
757 break;
758 }
759
760 uint32_t loop = 0;
761 while (loop++ < KNOB_WORKER_SPIN_LOOP_COUNT && !threadHasWork(curDrawBE))
762 {
763 _mm_pause();
764 }
765
766 if (!threadHasWork(curDrawBE))
767 {
768 lock.lock();
769
770 // check for thread idle condition again under lock
771 if (threadHasWork(curDrawBE))
772 {
773 lock.unlock();
774 continue;
775 }
776
777 pContext->FifosNotEmpty.wait(lock);
778 lock.unlock();
779 }
780
781 if (IsBEThread)
782 {
783 AR_BEGIN(WorkerWorkOnFifoBE, 0);
784 bShutdown |= WorkOnFifoBE(pContext, workerId, curDrawBE, lockedTiles, numaNode, numaMask);
785 AR_END(WorkerWorkOnFifoBE, 0);
786
787 WorkOnCompute(pContext, workerId, curDrawBE);
788 }
789
790 if (IsFEThread)
791 {
792 WorkOnFifoFE(pContext, workerId, curDrawFE);
793
794 if (!IsBEThread)
795 {
796 curDrawBE = curDrawFE;
797 }
798 }
799 }
800
801 return 0;
802 }
803 template<> DWORD workerThreadMain<false, false>(LPVOID) = delete;
804
805 template <bool IsFEThread, bool IsBEThread>
806 DWORD workerThreadInit(LPVOID pData)
807 {
808 #if defined(_WIN32)
809 __try
810 #endif // _WIN32
811 {
812 return workerThreadMain<IsFEThread, IsBEThread>(pData);
813 }
814
815 #if defined(_WIN32)
816 __except(EXCEPTION_CONTINUE_SEARCH)
817 {
818 }
819
820 #endif // _WIN32
821
822 return 1;
823 }
824 template<> DWORD workerThreadInit<false, false>(LPVOID pData) = delete;
825
826 //////////////////////////////////////////////////////////////////////////
827 /// @brief Creates thread pool info but doesn't launch threads.
828 /// @param pContext - pointer to context
829 /// @param pPool - pointer to thread pool object.
830 void CreateThreadPool(SWR_CONTEXT* pContext, THREAD_POOL* pPool)
831 {
832 bindThread(pContext, 0);
833
834 CPUNumaNodes nodes;
835 uint32_t numThreadsPerProcGroup = 0;
836 CalculateProcessorTopology(nodes, numThreadsPerProcGroup);
837
838 uint32_t numHWNodes = (uint32_t)nodes.size();
839 uint32_t numHWCoresPerNode = (uint32_t)nodes[0].cores.size();
840 uint32_t numHWHyperThreads = (uint32_t)nodes[0].cores[0].threadIds.size();
841
842 // Calculate num HW threads. Due to asymmetric topologies, this is not
843 // a trivial multiplication.
844 uint32_t numHWThreads = 0;
845 for (auto& node : nodes)
846 {
847 for (auto& core : node.cores)
848 {
849 numHWThreads += (uint32_t)core.threadIds.size();
850 }
851 }
852
853 uint32_t numNodes = numHWNodes;
854 uint32_t numCoresPerNode = numHWCoresPerNode;
855 uint32_t numHyperThreads = numHWHyperThreads;
856
857 if (pContext->threadInfo.MAX_NUMA_NODES)
858 {
859 numNodes = std::min(numNodes, pContext->threadInfo.MAX_NUMA_NODES);
860 }
861
862 if (pContext->threadInfo.MAX_CORES_PER_NUMA_NODE)
863 {
864 numCoresPerNode = std::min(numCoresPerNode, pContext->threadInfo.MAX_CORES_PER_NUMA_NODE);
865 }
866
867 if (pContext->threadInfo.MAX_THREADS_PER_CORE)
868 {
869 numHyperThreads = std::min(numHyperThreads, pContext->threadInfo.MAX_THREADS_PER_CORE);
870 }
871
872 #if defined(_WIN32) && !defined(_WIN64)
873 if (!pContext->threadInfo.MAX_WORKER_THREADS)
874 {
875 // Limit 32-bit windows to bindable HW threads only
876 if ((numCoresPerNode * numHWHyperThreads) > 32)
877 {
878 numCoresPerNode = 32 / numHWHyperThreads;
879 }
880 }
881 #endif
882
883 // Calculate numThreads
884 uint32_t numThreads = numNodes * numCoresPerNode * numHyperThreads;
885 numThreads = std::min(numThreads, numHWThreads);
886
887 if (pContext->threadInfo.MAX_WORKER_THREADS)
888 {
889 uint32_t maxHWThreads = numHWNodes * numHWCoresPerNode * numHWHyperThreads;
890 numThreads = std::min(pContext->threadInfo.MAX_WORKER_THREADS, maxHWThreads);
891 }
892
893 uint32_t numAPIReservedThreads = 1;
894
895
896 if (numThreads == 1)
897 {
898 // If only 1 worker threads, try to move it to an available
899 // HW thread. If that fails, use the API thread.
900 if (numCoresPerNode < numHWCoresPerNode)
901 {
902 numCoresPerNode++;
903 }
904 else if (numHyperThreads < numHWHyperThreads)
905 {
906 numHyperThreads++;
907 }
908 else if (numNodes < numHWNodes)
909 {
910 numNodes++;
911 }
912 else
913 {
914 pContext->threadInfo.SINGLE_THREADED = true;
915 }
916 }
917 else
918 {
919 // Save HW threads for the API if we can
920 if (numThreads > numAPIReservedThreads)
921 {
922 numThreads -= numAPIReservedThreads;
923 }
924 else
925 {
926 numAPIReservedThreads = 0;
927 }
928 }
929
930 if (pContext->threadInfo.SINGLE_THREADED)
931 {
932 numThreads = 1;
933 }
934
935 // Initialize DRAW_CONTEXT's per-thread stats
936 for (uint32_t dc = 0; dc < KNOB_MAX_DRAWS_IN_FLIGHT; ++dc)
937 {
938 pContext->dcRing[dc].dynState.pStats = new SWR_STATS[numThreads];
939 memset(pContext->dcRing[dc].dynState.pStats, 0, sizeof(SWR_STATS) * numThreads);
940 }
941
942 if (pContext->threadInfo.SINGLE_THREADED)
943 {
944 pContext->NumWorkerThreads = 1;
945 pContext->NumFEThreads = 1;
946 pContext->NumBEThreads = 1;
947 pPool->numThreads = 0;
948
949 return;
950 }
951
952 pPool->numThreads = numThreads;
953 pContext->NumWorkerThreads = pPool->numThreads;
954
955 pPool->pThreadData = (THREAD_DATA *)malloc(pPool->numThreads * sizeof(THREAD_DATA));
956 pPool->numaMask = 0;
957
958 pPool->pThreads = new THREAD_PTR[pPool->numThreads];
959
960 if (pContext->threadInfo.MAX_WORKER_THREADS)
961 {
962 bool bForceBindProcGroup = (numThreads > numThreadsPerProcGroup);
963 uint32_t numProcGroups = (numThreads + numThreadsPerProcGroup - 1) / numThreadsPerProcGroup;
964 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
965 // But Windows will still require binding to specific process groups
966 for (uint32_t workerId = 0; workerId < numThreads; ++workerId)
967 {
968 pPool->pThreadData[workerId].workerId = workerId;
969 pPool->pThreadData[workerId].procGroupId = workerId % numProcGroups;
970 pPool->pThreadData[workerId].threadId = 0;
971 pPool->pThreadData[workerId].numaId = 0;
972 pPool->pThreadData[workerId].coreId = 0;
973 pPool->pThreadData[workerId].htId = 0;
974 pPool->pThreadData[workerId].pContext = pContext;
975 pPool->pThreadData[workerId].forceBindProcGroup = bForceBindProcGroup;
976
977 pContext->NumBEThreads++;
978 pContext->NumFEThreads++;
979 }
980 }
981 else
982 {
983 pPool->numaMask = numNodes - 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
984
985 uint32_t workerId = 0;
986 for (uint32_t n = 0; n < numNodes; ++n)
987 {
988 auto& node = nodes[n];
989 uint32_t numCores = numCoresPerNode;
990 for (uint32_t c = 0; c < numCores; ++c)
991 {
992 if (c >= node.cores.size())
993 {
994 break;
995 }
996
997 auto& core = node.cores[c];
998 for (uint32_t t = 0; t < numHyperThreads; ++t)
999 {
1000 if (t >= core.threadIds.size())
1001 {
1002 break;
1003 }
1004
1005 if (numAPIReservedThreads)
1006 {
1007 --numAPIReservedThreads;
1008 continue;
1009 }
1010
1011 SWR_ASSERT(workerId < numThreads);
1012
1013 pPool->pThreadData[workerId].workerId = workerId;
1014 pPool->pThreadData[workerId].procGroupId = core.procGroup;
1015 pPool->pThreadData[workerId].threadId = core.threadIds[t];
1016 pPool->pThreadData[workerId].numaId = n;
1017 pPool->pThreadData[workerId].coreId = c;
1018 pPool->pThreadData[workerId].htId = t;
1019 pPool->pThreadData[workerId].pContext = pContext;
1020
1021 pContext->NumBEThreads++;
1022 pContext->NumFEThreads++;
1023
1024 ++workerId;
1025 }
1026 }
1027 }
1028 SWR_ASSERT(workerId == pContext->NumWorkerThreads);
1029 }
1030 }
1031
1032 //////////////////////////////////////////////////////////////////////////
1033 /// @brief Launches worker threads in thread pool.
1034 /// @param pContext - pointer to context
1035 /// @param pPool - pointer to thread pool object.
1036 void StartThreadPool(SWR_CONTEXT* pContext, THREAD_POOL* pPool)
1037 {
1038 if (pContext->threadInfo.SINGLE_THREADED)
1039 {
1040 return;
1041 }
1042
1043 for (uint32_t workerId = 0; workerId < pContext->NumWorkerThreads; ++workerId)
1044 {
1045 pPool->pThreads[workerId] = new std::thread(workerThreadInit<true, true>, &pPool->pThreadData[workerId]);
1046 }
1047 }
1048
1049 //////////////////////////////////////////////////////////////////////////
1050 /// @brief Destroys thread pool.
1051 /// @param pContext - pointer to context
1052 /// @param pPool - pointer to thread pool object.
1053 void DestroyThreadPool(SWR_CONTEXT *pContext, THREAD_POOL *pPool)
1054 {
1055 if (!pContext->threadInfo.SINGLE_THREADED)
1056 {
1057 // Wait for all threads to finish
1058 SwrWaitForIdle(pContext);
1059
1060 // Wait for threads to finish and destroy them
1061 for (uint32_t t = 0; t < pPool->numThreads; ++t)
1062 {
1063 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1064 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1065 pPool->pThreads[t]->detach();
1066 delete(pPool->pThreads[t]);
1067 }
1068
1069 delete [] pPool->pThreads;
1070
1071 // Clean up data used by threads
1072 free(pPool->pThreadData);
1073 }
1074 }