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