1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
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:
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
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
22 ****************************************************************************/
33 #if defined(__linux__) || defined(__gnu_linux__) || defined(__APPLE__)
39 #include "common/os.h"
43 #include "rasterizer.h"
44 #include "rdtsc_core.h"
53 uint32_t procGroup
= 0;
54 std::vector
<uint32_t> threadIds
;
60 std::vector
<Core
> cores
;
63 typedef std::vector
<NumaNode
> CPUNumaNodes
;
65 void CalculateProcessorTopology(CPUNumaNodes
& out_nodes
, uint32_t& out_numThreadsPerProcGroup
)
68 out_numThreadsPerProcGroup
= 0;
72 std::vector
<KAFFINITY
> threadMaskPerProcGroup
;
75 std::lock_guard
<std::mutex
> l(m
);
79 BOOL ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, nullptr, &bufSize
);
80 SWR_ASSERT(ret
== FALSE
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
);
82 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBufferMem
= (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX
)malloc(bufSize
);
83 SWR_ASSERT(pBufferMem
);
85 ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, pBufferMem
, &bufSize
);
86 SWR_ASSERT(ret
!= FALSE
, "Failed to get Processor Topology Information");
88 uint32_t count
= bufSize
/ pBufferMem
->Size
;
89 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBuffer
= pBufferMem
;
91 for (uint32_t i
= 0; i
< count
; ++i
)
93 SWR_ASSERT(pBuffer
->Relationship
== RelationProcessorCore
);
94 for (uint32_t g
= 0; g
< pBuffer
->Processor
.GroupCount
; ++g
)
96 auto& gmask
= pBuffer
->Processor
.GroupMask
[g
];
97 uint32_t threadId
= 0;
98 uint32_t procGroup
= gmask
.Group
;
100 Core
* pCore
= nullptr;
102 uint32_t numThreads
= (uint32_t)_mm_popcount_sizeT(gmask
.Mask
);
104 while (BitScanForwardSizeT((unsigned long*)&threadId
, gmask
.Mask
))
107 KAFFINITY threadMask
= KAFFINITY(1) << threadId
;
108 gmask
.Mask
&= ~threadMask
;
110 if (procGroup
>= threadMaskPerProcGroup
.size())
112 threadMaskPerProcGroup
.resize(procGroup
+ 1);
115 if (threadMaskPerProcGroup
[procGroup
] & threadMask
)
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
121 SWR_INVALID("Shouldn't get here in 64-bit mode");
126 threadMaskPerProcGroup
[procGroup
] |= (KAFFINITY(1) << threadId
);
130 PROCESSOR_NUMBER procNum
= {};
131 procNum
.Group
= WORD(procGroup
);
132 procNum
.Number
= UCHAR(threadId
);
134 ret
= GetNumaProcessorNodeEx(&procNum
, (PUSHORT
)&numaId
);
138 if (out_nodes
.size() <= numaId
)
140 out_nodes
.resize(numaId
+ 1);
142 auto& numaNode
= out_nodes
[numaId
];
143 numaNode
.numaId
= numaId
;
147 if (nullptr == pCore
)
149 numaNode
.cores
.push_back(Core());
150 pCore
= &numaNode
.cores
.back();
151 pCore
->procGroup
= procGroup
;
153 pCore
->threadIds
.push_back(threadId
);
156 out_numThreadsPerProcGroup
++;
160 pBuffer
= PtrAdd(pBuffer
, pBuffer
->Size
);
166 #elif defined(__linux__) || defined (__gnu_linux__)
168 // Parse /proc/cpuinfo to get full topology
169 std::ifstream
input("/proc/cpuinfo");
172 uint32_t procId
= uint32_t(-1);
173 uint32_t coreId
= uint32_t(-1);
174 uint32_t physId
= uint32_t(-1);
176 while (std::getline(input
, line
))
178 if (line
.find("processor") != std::string::npos
)
180 auto data_start
= line
.find(": ") + 2;
181 procId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
184 if (line
.find("core id") != std::string::npos
)
186 auto data_start
= line
.find(": ") + 2;
187 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
190 if (line
.find("physical id") != std::string::npos
)
192 auto data_start
= line
.find(": ") + 2;
193 physId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
196 if (line
.length() == 0)
198 if (physId
+ 1 > out_nodes
.size())
199 out_nodes
.resize(physId
+ 1);
200 auto& numaNode
= out_nodes
[physId
];
201 numaNode
.numaId
= physId
;
203 if (coreId
+ 1 > numaNode
.cores
.size())
204 numaNode
.cores
.resize(coreId
+ 1);
205 auto& core
= numaNode
.cores
[coreId
];
206 core
.procGroup
= coreId
;
207 core
.threadIds
.push_back(procId
);
211 out_numThreadsPerProcGroup
= 0;
212 for (auto &node
: out_nodes
)
214 for (auto &core
: node
.cores
)
216 out_numThreadsPerProcGroup
+= core
.threadIds
.size();
220 #elif defined(__APPLE__)
224 #error Unsupported platform
228 // Prune empty cores and numa nodes
229 for (auto node_it
= out_nodes
.begin(); node_it
!= out_nodes
.end(); )
231 // Erase empty cores (first)
232 for (auto core_it
= node_it
->cores
.begin(); core_it
!= node_it
->cores
.end(); )
234 if (core_it
->threadIds
.size() == 0)
236 core_it
= node_it
->cores
.erase(core_it
);
244 // Erase empty numa nodes (second)
245 if (node_it
->cores
.size() == 0)
247 node_it
= out_nodes
.erase(node_it
);
257 void bindThread(SWR_CONTEXT
* pContext
, uint32_t threadId
, uint32_t procGroupId
= 0, bool bindProcGroup
=false)
259 // Only bind threads when MAX_WORKER_THREADS isn't set.
260 if (pContext
->threadInfo
.SINGLE_THREADED
|| (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false))
267 GROUP_AFFINITY affinity
= {};
268 affinity
.Group
= procGroupId
;
273 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
274 SWR_INVALID("Shouldn't get here");
276 // In a 32-bit process on Windows it is impossible to bind
277 // to logical processors 32-63 within a processor group.
278 // In this case set the mask to 0 and let the system assign
279 // the processor. Hopefully it will make smart choices.
285 // If MAX_WORKER_THREADS is set, only bind to the proc group,
286 // Not the individual HW thread.
287 if (!bindProcGroup
&& !pContext
->threadInfo
.MAX_WORKER_THREADS
)
289 affinity
.Mask
= KAFFINITY(1) << threadId
;
293 affinity
.Mask
= KAFFINITY(0);
297 if (!SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr))
299 SWR_INVALID("Failed to set Thread Affinity");
302 #elif defined(__linux__) || defined(__gnu_linux__)
305 pthread_t thread
= pthread_self();
307 CPU_SET(threadId
, &cpuset
);
309 int err
= pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
312 fprintf(stderr
, "pthread_setaffinity_np failure for tid %u: %s\n", threadId
, strerror(err
));
319 uint32_t GetEnqueuedDraw(SWR_CONTEXT
*pContext
)
321 return pContext
->dcRing
.GetHead();
325 DRAW_CONTEXT
*GetDC(SWR_CONTEXT
*pContext
, uint32_t drawId
)
327 return &pContext
->dcRing
[(drawId
-1) % pContext
->MAX_DRAWS_IN_FLIGHT
];
331 bool IDComparesLess(uint32_t a
, uint32_t b
)
333 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
334 int32_t delta
= int32_t(a
- b
);
338 // returns true if dependency not met
340 bool CheckDependency(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
342 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
345 bool CheckDependencyFE(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
347 return pDC
->dependentFE
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
350 //////////////////////////////////////////////////////////////////////////
351 /// @brief Update client stats.
352 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
354 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStatsBE
== false))
359 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
360 OSALIGNLINE(SWR_STATS
) stats
{ 0 };
362 // Sum up stats across all workers before sending to client.
363 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
365 stats
.DepthPassCount
+= dynState
.pStats
[i
].DepthPassCount
;
367 stats
.PsInvocations
+= dynState
.pStats
[i
].PsInvocations
;
368 stats
.CsInvocations
+= dynState
.pStats
[i
].CsInvocations
;
372 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
375 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
377 UpdateClientStats(pContext
, workerId
, pDC
);
379 if (pDC
->retireCallback
.pfnCallbackFunc
)
381 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
382 pDC
->retireCallback
.userData2
,
383 pDC
->retireCallback
.userData3
);
387 // inlined-only version
388 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
390 int32_t result
= static_cast<int32_t>(InterlockedDecrement(&pDC
->threadsDone
));
391 SWR_ASSERT(result
>= 0);
393 AR_FLUSH(pDC
->drawId
);
397 ExecuteCallbacks(pContext
, workerId
, pDC
);
399 // Cleanup memory allocations
400 pDC
->pArena
->Reset(true);
403 pDC
->pTileMgr
->initialize();
405 if (pDC
->cleanupState
)
407 pDC
->pState
->pArena
->Reset(true);
412 pContext
->dcRing
.Dequeue(); // Remove from tail
418 // available to other translation modules
419 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
421 return CompleteDrawContextInl(pContext
, 0, pDC
);
424 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
, uint32_t workerId
, uint32_t& curDrawBE
, uint32_t& drawEnqueued
)
426 // increment our current draw id to the first incomplete draw
427 drawEnqueued
= GetEnqueuedDraw(pContext
);
428 while (IDComparesLess(curDrawBE
, drawEnqueued
))
430 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
];
432 // If its not compute and FE is not done then break out of loop.
433 if (!pDC
->doneFE
&& !pDC
->isCompute
) break;
435 bool isWorkComplete
= pDC
->isCompute
?
436 pDC
->pDispatch
->isWorkComplete() :
437 pDC
->pTileMgr
->isWorkComplete();
442 CompleteDrawContextInl(pContext
, workerId
, pDC
);
450 // If there are no more incomplete draws then return false.
451 return IDComparesLess(curDrawBE
, drawEnqueued
);
454 //////////////////////////////////////////////////////////////////////////
455 /// @brief If there is any BE work then go work on it.
456 /// @param pContext - pointer to SWR context.
457 /// @param workerId - The unique worker ID that is assigned to this thread.
458 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
459 /// has its own curDrawBE counter and this ensures that each worker processes all the
461 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
462 /// own set and each time it fails to lock a macrotile, because its already locked,
463 /// then it will add that tile to the lockedTiles set. As a worker begins to work
464 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
465 /// still have work pending in a previous draw. Additionally, the lockedTiles is
466 /// hueristic that can steer a worker back to the same macrotile that it had been
467 /// working on in a previous draw.
468 /// @returns true if worker thread should shutdown
470 SWR_CONTEXT
*pContext
,
473 TileSet
& lockedTiles
,
477 bool bShutdown
= false;
479 // Find the first incomplete draw that has pending work. If no such draw is found then
480 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
481 uint32_t drawEnqueued
= 0;
482 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
487 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
489 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
492 // Try to work on each draw in order of the available draws in flight.
493 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
494 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
495 // working on those macrotiles that are known to be complete in the prior draw to
496 // maintain order. The locked tiles provides the history to ensures this.
497 for (uint32_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
499 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
501 if (pDC
->isCompute
) return false; // We don't look at compute work.
503 // First wait for FE to be finished with this draw. This keeps threading model simple
504 // but if there are lots of bubbles between draws then serializing FE and BE may
505 // need to be revisited.
506 if (!pDC
->doneFE
) return false;
508 // If this draw is dependent on a previous draw then we need to bail.
509 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
514 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
515 auto ¯oTiles
= pDC
->pTileMgr
->getDirtyTiles();
517 for (auto tile
: macroTiles
)
519 uint32_t tileID
= tile
->mId
;
521 // Only work on tiles for this numa node
523 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
524 if (((x
^ y
) & numaMask
) != numaNode
)
529 if (!tile
->getNumQueued())
534 // can only work on this draw if it's not in use by other threads
535 if (lockedTiles
.find(tileID
) != lockedTiles
.end())
544 RDTSC_BEGIN(WorkerFoundWork
, pDC
->drawId
);
546 uint32_t numWorkItems
= tile
->getNumQueued();
547 SWR_ASSERT(numWorkItems
);
549 pWork
= tile
->peek();
551 if (pWork
->type
== DRAW
)
553 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, workerId
, tileID
);
555 else if (pWork
->type
== SHUTDOWN
)
560 while ((pWork
= tile
->peek()) != nullptr)
562 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
565 RDTSC_END(WorkerFoundWork
, numWorkItems
);
569 pDC
->pTileMgr
->markTileComplete(tileID
);
571 // Optimization: If the draw is complete and we're the last one to have worked on it then
572 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
573 if ((curDrawBE
== i
) && (bShutdown
|| pDC
->pTileMgr
->isWorkComplete()))
575 // We can increment the current BE and safely move to next draw since we know this draw is complete.
577 CompleteDrawContextInl(pContext
, workerId
, pDC
);
592 // 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.
593 lockedTiles
.insert(tileID
);
601 //////////////////////////////////////////////////////////////////////////
602 /// @brief Called when FE work is complete for this DC.
603 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
605 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStatsFE
)
607 SWR_STATS_FE
& stats
= pDC
->dynState
.statsFE
;
609 AR_EVENT(FrontendStatsEvent(pDC
->drawId
,
610 stats
.IaVertices
, stats
.IaPrimitives
, stats
.VsInvocations
, stats
.HsInvocations
,
611 stats
.DsInvocations
, stats
.GsInvocations
, stats
.GsPrimitives
, stats
.CInvocations
, stats
.CPrimitives
,
612 stats
.SoPrimStorageNeeded
[0], stats
.SoPrimStorageNeeded
[1], stats
.SoPrimStorageNeeded
[2], stats
.SoPrimStorageNeeded
[3],
613 stats
.SoNumPrimsWritten
[0], stats
.SoNumPrimsWritten
[1], stats
.SoNumPrimsWritten
[2], stats
.SoNumPrimsWritten
[3]
615 AR_EVENT(FrontendDrawEndEvent(pDC
->drawId
));
617 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &stats
);
620 if (pContext
->pfnUpdateSoWriteOffset
)
622 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
624 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
625 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
627 pContext
->pfnUpdateSoWriteOffset(GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
632 // Ensure all streaming writes are globally visible before marking this FE done
636 InterlockedDecrement(&pContext
->drawsOutstandingFE
);
639 void WorkOnFifoFE(SWR_CONTEXT
*pContext
, uint32_t workerId
, uint32_t &curDrawFE
)
641 // Try to grab the next DC from the ring
642 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
643 while (IDComparesLess(curDrawFE
, drawEnqueued
))
645 uint32_t dcSlot
= curDrawFE
% pContext
->MAX_DRAWS_IN_FLIGHT
;
646 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
647 if (pDC
->isCompute
|| pDC
->doneFE
)
649 CompleteDrawContextInl(pContext
, workerId
, pDC
);
658 uint32_t lastRetiredFE
= curDrawFE
- 1;
659 uint32_t curDraw
= curDrawFE
;
660 while (IDComparesLess(curDraw
, drawEnqueued
))
662 uint32_t dcSlot
= curDraw
% pContext
->MAX_DRAWS_IN_FLIGHT
;
663 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
665 if (!pDC
->isCompute
&& !pDC
->FeLock
)
667 if (CheckDependencyFE(pContext
, pDC
, lastRetiredFE
))
672 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
675 // successfully grabbed the DC, now run the FE
676 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
678 CompleteDrawFE(pContext
, workerId
, pDC
);
685 //////////////////////////////////////////////////////////////////////////
686 /// @brief If there is any compute work then go work on it.
687 /// @param pContext - pointer to SWR context.
688 /// @param workerId - The unique worker ID that is assigned to this thread.
689 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
690 /// has its own curDrawBE counter and this ensures that each worker processes all the
693 SWR_CONTEXT
*pContext
,
697 uint32_t drawEnqueued
= 0;
698 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
703 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
705 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
707 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
708 if (pDC
->isCompute
== false) return;
710 // check dependencies
711 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
716 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
717 DispatchQueue
& queue
= *pDC
->pDispatch
;
719 // Is there any work remaining?
720 if (queue
.getNumQueued() > 0)
722 void* pSpillFillBuffer
= nullptr;
723 void* pScratchSpace
= nullptr;
724 uint32_t threadGroupId
= 0;
725 while (queue
.getWork(threadGroupId
))
727 queue
.dispatch(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
, pScratchSpace
);
728 queue
.finishedWork();
731 // Ensure all streaming writes are globally visible before moving onto the next draw
737 void BindApiThread(SWR_CONTEXT
*pContext
, uint32_t apiThreadId
)
739 if (nullptr == pContext
)
744 if (apiThreadId
>= pContext
->threadPool
.numReservedThreads
)
746 if (pContext
->threadPool
.numReservedThreads
)
748 const THREAD_DATA
&threadData
= pContext
->threadPool
.pApiThreadData
[0];
749 // Just bind to the process group used for API thread 0
750 bindThread(pContext
, 0, threadData
.procGroupId
, true);
755 const THREAD_DATA
&threadData
= pContext
->threadPool
.pApiThreadData
[apiThreadId
];
757 bindThread(pContext
, threadData
.threadId
, threadData
.procGroupId
, threadData
.forceBindProcGroup
);
760 template<bool IsFEThread
, bool IsBEThread
>
761 DWORD
workerThreadMain(LPVOID pData
)
763 THREAD_DATA
*pThreadData
= (THREAD_DATA
*)pData
;
764 SWR_CONTEXT
*pContext
= pThreadData
->pContext
;
765 uint32_t threadId
= pThreadData
->threadId
;
766 uint32_t workerId
= pThreadData
->workerId
;
768 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
772 sprintf_s(threadName
,
774 "SWRWorker_%02d_NUMA%d_Core%02d_T%d",
776 // linux pthread name limited to 16 chars (including \0)
777 "w%03d-n%d-c%03d-t%d",
779 workerId
, pThreadData
->numaId
, pThreadData
->coreId
, pThreadData
->htId
);
780 SetCurrentThreadName(threadName
);
783 RDTSC_INIT(threadId
);
785 // Only need offset numa index from base for correct masking
786 uint32_t numaNode
= pThreadData
->numaId
- pContext
->threadInfo
.BASE_NUMA_NODE
;
787 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
789 // flush denormals to 0
790 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
792 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
793 // locked then we'll add it to this list so that we don't try and lock it again.
796 // each worker has the ability to work on any of the queued draws as long as certain
797 // conditions are met. the data associated
798 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
799 // has moved on to the next draw when he determines there is no more work to do. The api
800 // thread will not increment the head of the dc ring until all workers have moved past the
802 // the logic to determine what to work on is:
803 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
804 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
805 // we'll need dependency tracking to force serialization on FEs. The worker will try
806 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
807 // trying until he reaches the tail.
808 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
809 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
810 // any work left by comparing the total # of binned work items and the total # of completed
811 // work items. If they are equal, then there is no more work to do for this draw, and
812 // the worker can safely increment its oldestDraw counter and move on to the next draw.
813 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
, std::defer_lock
);
815 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
817 uint32_t curDrawBE
= 0;
818 uint32_t curDrawFE
= 0;
820 bool bShutdown
= false;
824 if (bShutdown
&& !threadHasWork(curDrawBE
))
830 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
835 if (!threadHasWork(curDrawBE
))
839 // check for thread idle condition again under lock
840 if (threadHasWork(curDrawBE
))
846 pContext
->FifosNotEmpty
.wait(lock
);
852 RDTSC_BEGIN(WorkerWorkOnFifoBE
, 0);
853 bShutdown
|= WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
854 RDTSC_END(WorkerWorkOnFifoBE
, 0);
856 WorkOnCompute(pContext
, workerId
, curDrawBE
);
861 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
865 curDrawBE
= curDrawFE
;
872 template<> DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
874 template <bool IsFEThread
, bool IsBEThread
>
875 DWORD
workerThreadInit(LPVOID pData
)
881 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
885 __except(EXCEPTION_CONTINUE_SEARCH
)
893 template<> DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
895 static void InitPerThreadStats(SWR_CONTEXT
* pContext
, uint32_t numThreads
)
897 // Initialize DRAW_CONTEXT's per-thread stats
898 for (uint32_t dc
= 0; dc
< pContext
->MAX_DRAWS_IN_FLIGHT
; ++dc
)
900 pContext
->dcRing
[dc
].dynState
.pStats
= (SWR_STATS
*)AlignedMalloc(sizeof(SWR_STATS
) * numThreads
, 64);
901 memset(pContext
->dcRing
[dc
].dynState
.pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
905 //////////////////////////////////////////////////////////////////////////
906 /// @brief Creates thread pool info but doesn't launch threads.
907 /// @param pContext - pointer to context
908 /// @param pPool - pointer to thread pool object.
909 void CreateThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
912 uint32_t numThreadsPerProcGroup
= 0;
913 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
915 // Assumption, for asymmetric topologies, multi-threaded cores will appear
916 // in the list before single-threaded cores. This appears to be true for
917 // Windows when the total HW threads is limited to 64.
918 uint32_t numHWNodes
= (uint32_t)nodes
.size();
919 uint32_t numHWCoresPerNode
= (uint32_t)nodes
[0].cores
.size();
920 uint32_t numHWHyperThreads
= (uint32_t)nodes
[0].cores
[0].threadIds
.size();
922 #if defined(_WIN32) && !defined(_WIN64)
923 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
925 // Limit 32-bit windows to bindable HW threads only
926 if ((numHWCoresPerNode
* numHWHyperThreads
) > 32)
928 numHWCoresPerNode
= 32 / numHWHyperThreads
;
933 // Calculate num HW threads. Due to asymmetric topologies, this is not
934 // a trivial multiplication.
935 uint32_t numHWThreads
= 0;
936 for (auto const& node
: nodes
)
938 for (auto const& core
: node
.cores
)
940 numHWThreads
+= (uint32_t)core
.threadIds
.size();
944 uint32_t numNodes
= numHWNodes
;
945 uint32_t numCoresPerNode
= numHWCoresPerNode
;
946 uint32_t numHyperThreads
= numHWHyperThreads
;
948 // Calc used threads per-core
949 if (numHyperThreads
> pContext
->threadInfo
.BASE_THREAD
)
951 numHyperThreads
-= pContext
->threadInfo
.BASE_THREAD
;
957 "Cannot use BASE_THREAD value: %d, maxThreads: %d, reverting BASE_THREAD to 0",
958 pContext
->threadInfo
.BASE_THREAD
,
960 pContext
->threadInfo
.BASE_THREAD
= 0;
963 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
965 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
968 // Prune any cores that don't support the number of threads
969 if (numHyperThreads
> 1)
971 for (auto& node
: nodes
)
973 uint32_t numUsableCores
= 0;
974 for (auto& core
: node
.cores
)
976 numUsableCores
+= (core
.threadIds
.size() >= numHyperThreads
);
978 numCoresPerNode
= std::min(numCoresPerNode
, numUsableCores
);
982 // Calc used cores per NUMA node
983 if (numCoresPerNode
> pContext
->threadInfo
.BASE_CORE
)
985 numCoresPerNode
-= pContext
->threadInfo
.BASE_CORE
;
991 "Cannot use BASE_CORE value: %d, maxCores: %d, reverting BASE_CORE to 0",
992 pContext
->threadInfo
.BASE_CORE
,
994 pContext
->threadInfo
.BASE_CORE
= 0;
997 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
999 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
1002 // Calc used NUMA nodes
1003 if (numNodes
> pContext
->threadInfo
.BASE_NUMA_NODE
)
1005 numNodes
-= pContext
->threadInfo
.BASE_NUMA_NODE
;
1011 "Cannot use BASE_NUMA_NODE value: %d, maxNodes: %d, reverting BASE_NUMA_NODE to 0",
1012 pContext
->threadInfo
.BASE_NUMA_NODE
,
1014 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1017 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
1019 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
1022 // Calculate numThreads - at this point everything should be symmetric
1023 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
1024 SWR_REL_ASSERT(numThreads
<= numHWThreads
);
1026 uint32_t& numAPIReservedThreads
= pContext
->apiThreadInfo
.numAPIReservedThreads
;
1027 uint32_t& numAPIThreadsPerCore
= pContext
->apiThreadInfo
.numAPIThreadsPerCore
;
1028 uint32_t numRemovedThreads
= 0;
1030 if (pContext
->threadInfo
.SINGLE_THREADED
)
1032 numAPIReservedThreads
= 0;
1034 pContext
->NumWorkerThreads
= 1;
1035 pContext
->NumFEThreads
= 1;
1036 pContext
->NumBEThreads
= 1;
1037 pPool
->numThreads
= 0;
1039 else if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1041 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, numHWThreads
);
1042 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1043 pContext
->threadInfo
.BASE_CORE
= 0;
1044 pContext
->threadInfo
.BASE_THREAD
= 0;
1045 numAPIReservedThreads
= 0;
1049 if (numAPIReservedThreads
>= numThreads
)
1051 numAPIReservedThreads
= 0;
1053 else if (numAPIReservedThreads
)
1055 numAPIThreadsPerCore
= std::min(numAPIThreadsPerCore
, numHWHyperThreads
);
1057 if (0 == numAPIThreadsPerCore
)
1059 numAPIThreadsPerCore
= numHWHyperThreads
;
1062 numRemovedThreads
= numAPIReservedThreads
;
1063 if (numAPIThreadsPerCore
== 2 && numHyperThreads
== 1)
1065 // Adjust removed threads to make logic below work
1066 numRemovedThreads
= std::max(1U, (numRemovedThreads
+ numAPIThreadsPerCore
- 1) / 2);
1069 numThreads
-= numRemovedThreads
;
1073 InitPerThreadStats(pContext
, numThreads
);
1075 if (pContext
->threadInfo
.SINGLE_THREADED
)
1080 if (numAPIReservedThreads
)
1082 pPool
->pApiThreadData
= new (std::nothrow
) THREAD_DATA
[numAPIReservedThreads
];
1083 SWR_ASSERT(pPool
->pApiThreadData
);
1084 if (!pPool
->pApiThreadData
)
1086 numAPIReservedThreads
= 0;
1089 pPool
->numReservedThreads
= numAPIReservedThreads
;
1091 pPool
->numThreads
= numThreads
;
1092 pContext
->NumWorkerThreads
= pPool
->numThreads
;
1094 pPool
->pThreadData
= new (std::nothrow
) THREAD_DATA
[pPool
->numThreads
];
1095 SWR_ASSERT(pPool
->pThreadData
);
1096 pPool
->numaMask
= 0;
1099 pPool
->pThreads
= new (std::nothrow
) THREAD_PTR
[pPool
->numThreads
];
1100 SWR_ASSERT(pPool
->pThreads
);
1102 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1104 bool bForceBindProcGroup
= (numThreads
> numThreadsPerProcGroup
);
1105 uint32_t numProcGroups
= (numThreads
+ numThreadsPerProcGroup
- 1) / numThreadsPerProcGroup
;
1106 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
1107 // But Windows will still require binding to specific process groups
1108 for (uint32_t workerId
= 0; workerId
< numThreads
; ++workerId
)
1110 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1111 pPool
->pThreadData
[workerId
].procGroupId
= workerId
% numProcGroups
;
1112 pPool
->pThreadData
[workerId
].threadId
= 0;
1113 pPool
->pThreadData
[workerId
].numaId
= 0;
1114 pPool
->pThreadData
[workerId
].coreId
= 0;
1115 pPool
->pThreadData
[workerId
].htId
= 0;
1116 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1117 pPool
->pThreadData
[workerId
].forceBindProcGroup
= bForceBindProcGroup
;
1119 pContext
->NumBEThreads
++;
1120 pContext
->NumFEThreads
++;
1125 // numa distribution assumes workers on all nodes
1126 bool useNuma
= true;
1127 if (numCoresPerNode
* numHyperThreads
== 1)
1134 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
1138 pPool
->numaMask
= 0;
1141 uint32_t workerId
= 0;
1142 uint32_t numReservedThreads
= numAPIReservedThreads
;
1143 for (uint32_t n
= 0; n
< numNodes
; ++n
)
1145 if ((n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) >= nodes
.size())
1149 auto& node
= nodes
[n
+ pContext
->threadInfo
.BASE_NUMA_NODE
];
1150 uint32_t numCores
= numCoresPerNode
;
1151 for (uint32_t c
= 0; c
< numCores
; ++c
)
1153 if ((c
+ pContext
->threadInfo
.BASE_CORE
) >= node
.cores
.size())
1158 auto& core
= node
.cores
[c
+ pContext
->threadInfo
.BASE_CORE
];
1159 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
1161 if ((t
+ pContext
->threadInfo
.BASE_THREAD
) >= core
.threadIds
.size())
1166 if (numRemovedThreads
)
1168 --numRemovedThreads
;
1169 SWR_REL_ASSERT(numReservedThreads
);
1170 --numReservedThreads
;
1171 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1172 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1173 pPool
->pApiThreadData
[numReservedThreads
].threadId
= core
.threadIds
[t
];
1174 pPool
->pApiThreadData
[numReservedThreads
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1175 pPool
->pApiThreadData
[numReservedThreads
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1176 pPool
->pApiThreadData
[numReservedThreads
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1177 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1178 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1181 if (numAPIThreadsPerCore
> numHyperThreads
&& numReservedThreads
)
1183 --numReservedThreads
;
1184 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1185 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1186 pPool
->pApiThreadData
[numReservedThreads
].threadId
= core
.threadIds
[t
+ 1];
1187 pPool
->pApiThreadData
[numReservedThreads
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1188 pPool
->pApiThreadData
[numReservedThreads
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1189 pPool
->pApiThreadData
[numReservedThreads
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1190 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1191 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1197 SWR_ASSERT(workerId
< numThreads
);
1199 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1200 pPool
->pThreadData
[workerId
].procGroupId
= core
.procGroup
;
1201 pPool
->pThreadData
[workerId
].threadId
= core
.threadIds
[t
+ pContext
->threadInfo
.BASE_THREAD
];
1202 pPool
->pThreadData
[workerId
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1203 pPool
->pThreadData
[workerId
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1204 pPool
->pThreadData
[workerId
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1205 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1206 pPool
->pThreadData
[workerId
].forceBindProcGroup
= false;
1208 pContext
->NumBEThreads
++;
1209 pContext
->NumFEThreads
++;
1215 SWR_ASSERT(workerId
== pContext
->NumWorkerThreads
);
1219 //////////////////////////////////////////////////////////////////////////
1220 /// @brief Launches worker threads in thread pool.
1221 /// @param pContext - pointer to context
1222 /// @param pPool - pointer to thread pool object.
1223 void StartThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1225 if (pContext
->threadInfo
.SINGLE_THREADED
)
1230 for (uint32_t workerId
= 0; workerId
< pContext
->NumWorkerThreads
; ++workerId
)
1232 pPool
->pThreads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
1236 //////////////////////////////////////////////////////////////////////////
1237 /// @brief Destroys thread pool.
1238 /// @param pContext - pointer to context
1239 /// @param pPool - pointer to thread pool object.
1240 void DestroyThreadPool(SWR_CONTEXT
*pContext
, THREAD_POOL
*pPool
)
1242 if (!pContext
->threadInfo
.SINGLE_THREADED
)
1244 // Wait for all threads to finish
1245 SwrWaitForIdle(pContext
);
1247 // Wait for threads to finish and destroy them
1248 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
1250 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1251 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1252 pPool
->pThreads
[t
]->detach();
1253 delete(pPool
->pThreads
[t
]);
1256 delete[] pPool
->pThreads
;
1258 // Clean up data used by threads
1259 delete[] pPool
->pThreadData
;
1260 delete[] pPool
->pApiThreadData
;