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