swr: [rasterizer core] refactor thread creation
[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 //////////////////////////////////////////////////////////////////////////
317 /// @brief Update client stats.
318 INLINE void UpdateClientStats(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
319 {
320 if ((pContext->pfnUpdateStats == nullptr) || (GetApiState(pDC).enableStats == false))
321 {
322 return;
323 }
324
325 DRAW_DYNAMIC_STATE& dynState = pDC->dynState;
326 SWR_STATS stats{ 0 };
327
328 // Sum up stats across all workers before sending to client.
329 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
330 {
331 stats.DepthPassCount += dynState.pStats[i].DepthPassCount;
332
333 stats.PsInvocations += dynState.pStats[i].PsInvocations;
334 stats.CsInvocations += dynState.pStats[i].CsInvocations;
335 }
336
337 pContext->pfnUpdateStats(GetPrivateState(pDC), &stats);
338 }
339
340 INLINE void ExecuteCallbacks(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
341 {
342 UpdateClientStats(pContext, pDC);
343
344 if (pDC->retireCallback.pfnCallbackFunc)
345 {
346 pDC->retireCallback.pfnCallbackFunc(pDC->retireCallback.userData,
347 pDC->retireCallback.userData2,
348 pDC->retireCallback.userData3);
349 }
350 }
351
352 // inlined-only version
353 INLINE int32_t CompleteDrawContextInl(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
354 {
355 int32_t result = InterlockedDecrement((volatile LONG*)&pDC->threadsDone);
356 SWR_ASSERT(result >= 0);
357
358 if (result == 0)
359 {
360 ExecuteCallbacks(pContext, pDC);
361
362 // Cleanup memory allocations
363 pDC->pArena->Reset(true);
364 if (!pDC->isCompute)
365 {
366 pDC->pTileMgr->initialize();
367 }
368 if (pDC->cleanupState)
369 {
370 pDC->pState->pArena->Reset(true);
371 }
372
373 _ReadWriteBarrier();
374
375 pContext->dcRing.Dequeue(); // Remove from tail
376 }
377
378 return result;
379 }
380
381 // available to other translation modules
382 int32_t CompleteDrawContext(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
383 {
384 return CompleteDrawContextInl(pContext, pDC);
385 }
386
387 INLINE bool FindFirstIncompleteDraw(SWR_CONTEXT* pContext, uint32_t& curDrawBE, uint32_t& drawEnqueued)
388 {
389 // increment our current draw id to the first incomplete draw
390 drawEnqueued = GetEnqueuedDraw(pContext);
391 while (IDComparesLess(curDrawBE, drawEnqueued))
392 {
393 DRAW_CONTEXT *pDC = &pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT];
394
395 // If its not compute and FE is not done then break out of loop.
396 if (!pDC->doneFE && !pDC->isCompute) break;
397
398 bool isWorkComplete = pDC->isCompute ?
399 pDC->pDispatch->isWorkComplete() :
400 pDC->pTileMgr->isWorkComplete();
401
402 if (isWorkComplete)
403 {
404 curDrawBE++;
405 CompleteDrawContextInl(pContext, pDC);
406 }
407 else
408 {
409 break;
410 }
411 }
412
413 // If there are no more incomplete draws then return false.
414 return IDComparesLess(curDrawBE, drawEnqueued);
415 }
416
417 //////////////////////////////////////////////////////////////////////////
418 /// @brief If there is any BE work then go work on it.
419 /// @param pContext - pointer to SWR context.
420 /// @param workerId - The unique worker ID that is assigned to this thread.
421 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
422 /// has its own curDrawBE counter and this ensures that each worker processes all the
423 /// draws in order.
424 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
425 /// own set and each time it fails to lock a macrotile, because its already locked,
426 /// then it will add that tile to the lockedTiles set. As a worker begins to work
427 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
428 /// still have work pending in a previous draw. Additionally, the lockedTiles is
429 /// hueristic that can steer a worker back to the same macrotile that it had been
430 /// working on in a previous draw.
431 /// @returns true if worker thread should shutdown
432 bool WorkOnFifoBE(
433 SWR_CONTEXT *pContext,
434 uint32_t workerId,
435 uint32_t &curDrawBE,
436 TileSet& lockedTiles,
437 uint32_t numaNode,
438 uint32_t numaMask)
439 {
440 bool bShutdown = false;
441
442 // Find the first incomplete draw that has pending work. If no such draw is found then
443 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
444 uint32_t drawEnqueued = 0;
445 if (FindFirstIncompleteDraw(pContext, curDrawBE, drawEnqueued) == false)
446 {
447 return false;
448 }
449
450 uint32_t lastRetiredDraw = pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT].drawId - 1;
451
452 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
453 lockedTiles.clear();
454
455 // Try to work on each draw in order of the available draws in flight.
456 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
457 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
458 // working on those macrotiles that are known to be complete in the prior draw to
459 // maintain order. The locked tiles provides the history to ensures this.
460 for (uint32_t i = curDrawBE; IDComparesLess(i, drawEnqueued); ++i)
461 {
462 DRAW_CONTEXT *pDC = &pContext->dcRing[i % KNOB_MAX_DRAWS_IN_FLIGHT];
463
464 if (pDC->isCompute) return false; // We don't look at compute work.
465
466 // First wait for FE to be finished with this draw. This keeps threading model simple
467 // but if there are lots of bubbles between draws then serializing FE and BE may
468 // need to be revisited.
469 if (!pDC->doneFE) return false;
470
471 // If this draw is dependent on a previous draw then we need to bail.
472 if (CheckDependency(pContext, pDC, lastRetiredDraw))
473 {
474 return false;
475 }
476
477 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
478 auto &macroTiles = pDC->pTileMgr->getDirtyTiles();
479
480 for (auto tile : macroTiles)
481 {
482 uint32_t tileID = tile->mId;
483
484 // Only work on tiles for this numa node
485 uint32_t x, y;
486 pDC->pTileMgr->getTileIndices(tileID, x, y);
487 if (((x ^ y) & numaMask) != numaNode)
488 {
489 continue;
490 }
491
492 if (!tile->getNumQueued())
493 {
494 continue;
495 }
496
497 // can only work on this draw if it's not in use by other threads
498 if (lockedTiles.find(tileID) != lockedTiles.end())
499 {
500 continue;
501 }
502
503 if (tile->tryLock())
504 {
505 BE_WORK *pWork;
506
507 AR_BEGIN(WorkerFoundWork, pDC->drawId);
508
509 uint32_t numWorkItems = tile->getNumQueued();
510 SWR_ASSERT(numWorkItems);
511
512 pWork = tile->peek();
513 SWR_ASSERT(pWork);
514 if (pWork->type == DRAW)
515 {
516 pContext->pHotTileMgr->InitializeHotTiles(pContext, pDC, workerId, tileID);
517 }
518 else if (pWork->type == SHUTDOWN)
519 {
520 bShutdown = true;
521 }
522
523 while ((pWork = tile->peek()) != nullptr)
524 {
525 pWork->pfnWork(pDC, workerId, tileID, &pWork->desc);
526 tile->dequeue();
527 }
528 AR_END(WorkerFoundWork, numWorkItems);
529
530 _ReadWriteBarrier();
531
532 pDC->pTileMgr->markTileComplete(tileID);
533
534 // Optimization: If the draw is complete and we're the last one to have worked on it then
535 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
536 if ((curDrawBE == i) && (bShutdown || pDC->pTileMgr->isWorkComplete()))
537 {
538 // We can increment the current BE and safely move to next draw since we know this draw is complete.
539 curDrawBE++;
540 CompleteDrawContextInl(pContext, pDC);
541
542 lastRetiredDraw++;
543
544 lockedTiles.clear();
545 break;
546 }
547
548 if (bShutdown)
549 {
550 break;
551 }
552 }
553 else
554 {
555 // 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.
556 lockedTiles.insert(tileID);
557 }
558 }
559 }
560
561 return bShutdown;
562 }
563
564 //////////////////////////////////////////////////////////////////////////
565 /// @brief Called when FE work is complete for this DC.
566 INLINE void CompleteDrawFE(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC)
567 {
568 _ReadWriteBarrier();
569
570 if (pContext->pfnUpdateStatsFE && GetApiState(pDC).enableStats)
571 {
572 pContext->pfnUpdateStatsFE(GetPrivateState(pDC), &pDC->dynState.statsFE);
573 }
574
575 if (pContext->pfnUpdateSoWriteOffset)
576 {
577 for (uint32_t i = 0; i < MAX_SO_BUFFERS; ++i)
578 {
579 if ((pDC->dynState.SoWriteOffsetDirty[i]) &&
580 (pDC->pState->state.soBuffer[i].soWriteEnable))
581 {
582 pContext->pfnUpdateSoWriteOffset(GetPrivateState(pDC), i, pDC->dynState.SoWriteOffset[i]);
583 }
584 }
585 }
586
587 pDC->doneFE = true;
588
589 InterlockedDecrement((volatile LONG*)&pContext->drawsOutstandingFE);
590 }
591
592 void WorkOnFifoFE(SWR_CONTEXT *pContext, uint32_t workerId, uint32_t &curDrawFE)
593 {
594 // Try to grab the next DC from the ring
595 uint32_t drawEnqueued = GetEnqueuedDraw(pContext);
596 while (IDComparesLess(curDrawFE, drawEnqueued))
597 {
598 uint32_t dcSlot = curDrawFE % KNOB_MAX_DRAWS_IN_FLIGHT;
599 DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot];
600 if (pDC->isCompute || pDC->doneFE || pDC->FeLock)
601 {
602 CompleteDrawContextInl(pContext, pDC);
603 curDrawFE++;
604 }
605 else
606 {
607 break;
608 }
609 }
610
611 uint32_t curDraw = curDrawFE;
612 while (IDComparesLess(curDraw, drawEnqueued))
613 {
614 uint32_t dcSlot = curDraw % KNOB_MAX_DRAWS_IN_FLIGHT;
615 DRAW_CONTEXT *pDC = &pContext->dcRing[dcSlot];
616
617 if (!pDC->isCompute && !pDC->FeLock)
618 {
619 uint32_t initial = InterlockedCompareExchange((volatile uint32_t*)&pDC->FeLock, 1, 0);
620 if (initial == 0)
621 {
622 // successfully grabbed the DC, now run the FE
623 pDC->FeWork.pfnWork(pContext, pDC, workerId, &pDC->FeWork.desc);
624
625 CompleteDrawFE(pContext, pDC);
626 }
627 }
628 curDraw++;
629 }
630 }
631
632 //////////////////////////////////////////////////////////////////////////
633 /// @brief If there is any compute work then go work on it.
634 /// @param pContext - pointer to SWR context.
635 /// @param workerId - The unique worker ID that is assigned to this thread.
636 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
637 /// has its own curDrawBE counter and this ensures that each worker processes all the
638 /// draws in order.
639 void WorkOnCompute(
640 SWR_CONTEXT *pContext,
641 uint32_t workerId,
642 uint32_t& curDrawBE)
643 {
644 uint32_t drawEnqueued = 0;
645 if (FindFirstIncompleteDraw(pContext, curDrawBE, drawEnqueued) == false)
646 {
647 return;
648 }
649
650 uint32_t lastRetiredDraw = pContext->dcRing[curDrawBE % KNOB_MAX_DRAWS_IN_FLIGHT].drawId - 1;
651
652 for (uint64_t i = curDrawBE; IDComparesLess(i, drawEnqueued); ++i)
653 {
654 DRAW_CONTEXT *pDC = &pContext->dcRing[i % KNOB_MAX_DRAWS_IN_FLIGHT];
655 if (pDC->isCompute == false) return;
656
657 // check dependencies
658 if (CheckDependency(pContext, pDC, lastRetiredDraw))
659 {
660 return;
661 }
662
663 SWR_ASSERT(pDC->pDispatch != nullptr);
664 DispatchQueue& queue = *pDC->pDispatch;
665
666 // Is there any work remaining?
667 if (queue.getNumQueued() > 0)
668 {
669 void* pSpillFillBuffer = nullptr;
670 uint32_t threadGroupId = 0;
671 while (queue.getWork(threadGroupId))
672 {
673 queue.dispatch(pDC, workerId, threadGroupId, pSpillFillBuffer);
674 queue.finishedWork();
675 }
676 }
677 }
678 }
679
680 template<bool IsFEThread, bool IsBEThread>
681 DWORD workerThreadMain(LPVOID pData)
682 {
683 THREAD_DATA *pThreadData = (THREAD_DATA*)pData;
684 SWR_CONTEXT *pContext = pThreadData->pContext;
685 uint32_t threadId = pThreadData->threadId;
686 uint32_t workerId = pThreadData->workerId;
687
688 bindThread(pContext, threadId, pThreadData->procGroupId, pThreadData->forceBindProcGroup);
689
690 RDTSC_INIT(threadId);
691
692 uint32_t numaNode = pThreadData->numaId;
693 uint32_t numaMask = pContext->threadPool.numaMask;
694
695 // flush denormals to 0
696 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON | _MM_DENORMALS_ZERO_ON);
697
698 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
699 // locked then we'll add it to this list so that we don't try and lock it again.
700 TileSet lockedTiles;
701
702 // each worker has the ability to work on any of the queued draws as long as certain
703 // conditions are met. the data associated
704 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
705 // has moved on to the next draw when he determines there is no more work to do. The api
706 // thread will not increment the head of the dc ring until all workers have moved past the
707 // current head.
708 // the logic to determine what to work on is:
709 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
710 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
711 // we'll need dependency tracking to force serialization on FEs. The worker will try
712 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
713 // trying until he reaches the tail.
714 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
715 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
716 // any work left by comparing the total # of binned work items and the total # of completed
717 // work items. If they are equal, then there is no more work to do for this draw, and
718 // the worker can safely increment its oldestDraw counter and move on to the next draw.
719 std::unique_lock<std::mutex> lock(pContext->WaitLock, std::defer_lock);
720
721 auto threadHasWork = [&](uint32_t curDraw) { return curDraw != pContext->dcRing.GetHead(); };
722
723 uint32_t curDrawBE = 0;
724 uint32_t curDrawFE = 0;
725
726 bool bShutdown = false;
727
728 while (true)
729 {
730 if (bShutdown && !threadHasWork(curDrawBE))
731 {
732 break;
733 }
734
735 uint32_t loop = 0;
736 while (loop++ < KNOB_WORKER_SPIN_LOOP_COUNT && !threadHasWork(curDrawBE))
737 {
738 _mm_pause();
739 }
740
741 if (!threadHasWork(curDrawBE))
742 {
743 lock.lock();
744
745 // check for thread idle condition again under lock
746 if (threadHasWork(curDrawBE))
747 {
748 lock.unlock();
749 continue;
750 }
751
752 AR_BEGIN(WorkerWaitForThreadEvent, 0);
753
754 pContext->FifosNotEmpty.wait(lock);
755 lock.unlock();
756
757 AR_END(WorkerWaitForThreadEvent, 0);
758 }
759
760 if (IsBEThread)
761 {
762 AR_BEGIN(WorkerWorkOnFifoBE, 0);
763 bShutdown |= WorkOnFifoBE(pContext, workerId, curDrawBE, lockedTiles, numaNode, numaMask);
764 AR_END(WorkerWorkOnFifoBE, 0);
765
766 WorkOnCompute(pContext, workerId, curDrawBE);
767 }
768
769 if (IsFEThread)
770 {
771 WorkOnFifoFE(pContext, workerId, curDrawFE);
772
773 if (!IsBEThread)
774 {
775 curDrawBE = curDrawFE;
776 }
777 }
778 }
779
780 return 0;
781 }
782 template<> DWORD workerThreadMain<false, false>(LPVOID) = delete;
783
784 template <bool IsFEThread, bool IsBEThread>
785 DWORD workerThreadInit(LPVOID pData)
786 {
787 #if defined(_WIN32)
788 __try
789 #endif // _WIN32
790 {
791 return workerThreadMain<IsFEThread, IsBEThread>(pData);
792 }
793
794 #if defined(_WIN32)
795 __except(EXCEPTION_CONTINUE_SEARCH)
796 {
797 }
798
799 #endif // _WIN32
800
801 return 1;
802 }
803 template<> DWORD workerThreadInit<false, false>(LPVOID pData) = delete;
804
805 //////////////////////////////////////////////////////////////////////////
806 /// @brief Creates thread pool info but doesn't launch threads.
807 /// @param pContext - pointer to context
808 /// @param pPool - pointer to thread pool object.
809 void CreateThreadPool(SWR_CONTEXT* pContext, THREAD_POOL* pPool)
810 {
811 bindThread(pContext, 0);
812
813 CPUNumaNodes nodes;
814 uint32_t numThreadsPerProcGroup = 0;
815 CalculateProcessorTopology(nodes, numThreadsPerProcGroup);
816
817 uint32_t numHWNodes = (uint32_t)nodes.size();
818 uint32_t numHWCoresPerNode = (uint32_t)nodes[0].cores.size();
819 uint32_t numHWHyperThreads = (uint32_t)nodes[0].cores[0].threadIds.size();
820
821 // Calculate num HW threads. Due to asymmetric topologies, this is not
822 // a trivial multiplication.
823 uint32_t numHWThreads = 0;
824 for (auto& node : nodes)
825 {
826 for (auto& core : node.cores)
827 {
828 numHWThreads += (uint32_t)core.threadIds.size();
829 }
830 }
831
832 uint32_t numNodes = numHWNodes;
833 uint32_t numCoresPerNode = numHWCoresPerNode;
834 uint32_t numHyperThreads = numHWHyperThreads;
835
836 if (pContext->threadInfo.MAX_NUMA_NODES)
837 {
838 numNodes = std::min(numNodes, pContext->threadInfo.MAX_NUMA_NODES);
839 }
840
841 if (pContext->threadInfo.MAX_CORES_PER_NUMA_NODE)
842 {
843 numCoresPerNode = std::min(numCoresPerNode, pContext->threadInfo.MAX_CORES_PER_NUMA_NODE);
844 }
845
846 if (pContext->threadInfo.MAX_THREADS_PER_CORE)
847 {
848 numHyperThreads = std::min(numHyperThreads, pContext->threadInfo.MAX_THREADS_PER_CORE);
849 }
850
851 #if defined(_WIN32) && !defined(_WIN64)
852 if (!pContext->threadInfo.MAX_WORKER_THREADS)
853 {
854 // Limit 32-bit windows to bindable HW threads only
855 if ((numCoresPerNode * numHWHyperThreads) > 32)
856 {
857 numCoresPerNode = 32 / numHWHyperThreads;
858 }
859 }
860 #endif
861
862 // Calculate numThreads
863 uint32_t numThreads = numNodes * numCoresPerNode * numHyperThreads;
864 numThreads = std::min(numThreads, numHWThreads);
865
866 if (pContext->threadInfo.MAX_WORKER_THREADS)
867 {
868 uint32_t maxHWThreads = numHWNodes * numHWCoresPerNode * numHWHyperThreads;
869 numThreads = std::min(pContext->threadInfo.MAX_WORKER_THREADS, maxHWThreads);
870 }
871
872 uint32_t numAPIReservedThreads = 1;
873
874
875 if (numThreads == 1)
876 {
877 // If only 1 worker threads, try to move it to an available
878 // HW thread. If that fails, use the API thread.
879 if (numCoresPerNode < numHWCoresPerNode)
880 {
881 numCoresPerNode++;
882 }
883 else if (numHyperThreads < numHWHyperThreads)
884 {
885 numHyperThreads++;
886 }
887 else if (numNodes < numHWNodes)
888 {
889 numNodes++;
890 }
891 else
892 {
893 pContext->threadInfo.SINGLE_THREADED = true;
894 }
895 }
896 else
897 {
898 // Save HW threads for the API if we can
899 if (numThreads > numAPIReservedThreads)
900 {
901 numThreads -= numAPIReservedThreads;
902 }
903 else
904 {
905 numAPIReservedThreads = 0;
906 }
907 }
908
909 if (pContext->threadInfo.SINGLE_THREADED)
910 {
911 numThreads = 1;
912 }
913
914 // Initialize DRAW_CONTEXT's per-thread stats
915 for (uint32_t dc = 0; dc < KNOB_MAX_DRAWS_IN_FLIGHT; ++dc)
916 {
917 pContext->dcRing[dc].dynState.pStats = new SWR_STATS[numThreads];
918 memset(pContext->dcRing[dc].dynState.pStats, 0, sizeof(SWR_STATS) * numThreads);
919 }
920
921 if (pContext->threadInfo.SINGLE_THREADED)
922 {
923 pContext->NumWorkerThreads = 1;
924 pContext->NumFEThreads = 1;
925 pContext->NumBEThreads = 1;
926 pPool->numThreads = 0;
927
928 return;
929 }
930
931 pPool->numThreads = numThreads;
932 pContext->NumWorkerThreads = pPool->numThreads;
933
934 pPool->pThreadData = (THREAD_DATA *)malloc(pPool->numThreads * sizeof(THREAD_DATA));
935 pPool->numaMask = 0;
936
937 pPool->pThreads = new THREAD_PTR[pPool->numThreads];
938
939 if (pContext->threadInfo.MAX_WORKER_THREADS)
940 {
941 bool bForceBindProcGroup = (numThreads > numThreadsPerProcGroup);
942 uint32_t numProcGroups = (numThreads + numThreadsPerProcGroup - 1) / numThreadsPerProcGroup;
943 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
944 // But Windows will still require binding to specific process groups
945 for (uint32_t workerId = 0; workerId < numThreads; ++workerId)
946 {
947 pPool->pThreadData[workerId].workerId = workerId;
948 pPool->pThreadData[workerId].procGroupId = workerId % numProcGroups;
949 pPool->pThreadData[workerId].threadId = 0;
950 pPool->pThreadData[workerId].numaId = 0;
951 pPool->pThreadData[workerId].coreId = 0;
952 pPool->pThreadData[workerId].htId = 0;
953 pPool->pThreadData[workerId].pContext = pContext;
954 pPool->pThreadData[workerId].forceBindProcGroup = bForceBindProcGroup;
955
956 pContext->NumBEThreads++;
957 pContext->NumFEThreads++;
958 }
959 }
960 else
961 {
962 pPool->numaMask = numNodes - 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
963
964 uint32_t workerId = 0;
965 for (uint32_t n = 0; n < numNodes; ++n)
966 {
967 auto& node = nodes[n];
968 uint32_t numCores = numCoresPerNode;
969 for (uint32_t c = 0; c < numCores; ++c)
970 {
971 if (c >= node.cores.size())
972 {
973 break;
974 }
975
976 auto& core = node.cores[c];
977 for (uint32_t t = 0; t < numHyperThreads; ++t)
978 {
979 if (t >= core.threadIds.size())
980 {
981 break;
982 }
983
984 if (numAPIReservedThreads)
985 {
986 --numAPIReservedThreads;
987 continue;
988 }
989
990 SWR_ASSERT(workerId < numThreads);
991
992 pPool->pThreadData[workerId].workerId = workerId;
993 pPool->pThreadData[workerId].procGroupId = core.procGroup;
994 pPool->pThreadData[workerId].threadId = core.threadIds[t];
995 pPool->pThreadData[workerId].numaId = n;
996 pPool->pThreadData[workerId].coreId = c;
997 pPool->pThreadData[workerId].htId = t;
998 pPool->pThreadData[workerId].pContext = pContext;
999
1000 pContext->NumBEThreads++;
1001 pContext->NumFEThreads++;
1002
1003 ++workerId;
1004 }
1005 }
1006 }
1007 SWR_ASSERT(workerId == pContext->NumWorkerThreads);
1008 }
1009 }
1010
1011 //////////////////////////////////////////////////////////////////////////
1012 /// @brief Launches worker threads in thread pool.
1013 /// @param pContext - pointer to context
1014 /// @param pPool - pointer to thread pool object.
1015 void StartThreadPool(SWR_CONTEXT* pContext, THREAD_POOL* pPool)
1016 {
1017 if (pContext->threadInfo.SINGLE_THREADED)
1018 {
1019 return;
1020 }
1021
1022 for (uint32_t workerId = 0; workerId < pContext->NumWorkerThreads; ++workerId)
1023 {
1024 pPool->pThreads[workerId] = new std::thread(workerThreadInit<true, true>, &pPool->pThreadData[workerId]);
1025 }
1026 }
1027
1028 //////////////////////////////////////////////////////////////////////////
1029 /// @brief Destroys thread pool.
1030 /// @param pContext - pointer to context
1031 /// @param pPool - pointer to thread pool object.
1032 void DestroyThreadPool(SWR_CONTEXT *pContext, THREAD_POOL *pPool)
1033 {
1034 if (!pContext->threadInfo.SINGLE_THREADED)
1035 {
1036 // Wait for all threads to finish
1037 SwrWaitForIdle(pContext);
1038
1039 // Wait for threads to finish and destroy them
1040 for (uint32_t t = 0; t < pPool->numThreads; ++t)
1041 {
1042 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1043 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1044 pPool->pThreads[t]->detach();
1045 delete(pPool->pThreads[t]);
1046 }
1047
1048 delete [] pPool->pThreads;
1049
1050 // Clean up data used by threads
1051 free(pPool->pThreadData);
1052 }
1053 }