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__)
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
;
59 std::vector
<Core
> cores
;
62 typedef std::vector
<NumaNode
> CPUNumaNodes
;
64 void CalculateProcessorTopology(CPUNumaNodes
& out_nodes
, uint32_t& out_numThreadsPerProcGroup
)
67 out_numThreadsPerProcGroup
= 0;
71 std::vector
<KAFFINITY
> threadMaskPerProcGroup
;
74 std::lock_guard
<std::mutex
> l(m
);
78 BOOL ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, nullptr, &bufSize
);
79 SWR_ASSERT(ret
== FALSE
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
);
81 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBufferMem
= (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX
)malloc(bufSize
);
82 SWR_ASSERT(pBufferMem
);
84 ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, pBufferMem
, &bufSize
);
85 SWR_ASSERT(ret
!= FALSE
, "Failed to get Processor Topology Information");
87 uint32_t count
= bufSize
/ pBufferMem
->Size
;
88 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBuffer
= pBufferMem
;
90 for (uint32_t i
= 0; i
< count
; ++i
)
92 SWR_ASSERT(pBuffer
->Relationship
== RelationProcessorCore
);
93 for (uint32_t g
= 0; g
< pBuffer
->Processor
.GroupCount
; ++g
)
95 auto& gmask
= pBuffer
->Processor
.GroupMask
[g
];
96 uint32_t threadId
= 0;
97 uint32_t procGroup
= gmask
.Group
;
99 Core
* pCore
= nullptr;
101 uint32_t numThreads
= (uint32_t)_mm_popcount_sizeT(gmask
.Mask
);
103 while (BitScanForwardSizeT((unsigned long*)&threadId
, gmask
.Mask
))
106 KAFFINITY threadMask
= KAFFINITY(1) << threadId
;
107 gmask
.Mask
&= ~threadMask
;
109 if (procGroup
>= threadMaskPerProcGroup
.size())
111 threadMaskPerProcGroup
.resize(procGroup
+ 1);
114 if (threadMaskPerProcGroup
[procGroup
] & threadMask
)
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
120 SWR_ASSERT(false, "Shouldn't get here in 64-bit mode");
125 threadMaskPerProcGroup
[procGroup
] |= (KAFFINITY(1) << threadId
);
129 PROCESSOR_NUMBER procNum
= {};
130 procNum
.Group
= WORD(procGroup
);
131 procNum
.Number
= UCHAR(threadId
);
133 ret
= GetNumaProcessorNodeEx(&procNum
, (PUSHORT
)&numaId
);
137 if (out_nodes
.size() <= numaId
) out_nodes
.resize(numaId
+ 1);
138 auto& numaNode
= out_nodes
[numaId
];
142 if (nullptr == pCore
)
144 numaNode
.cores
.push_back(Core());
145 pCore
= &numaNode
.cores
.back();
146 pCore
->procGroup
= procGroup
;
148 pCore
->threadIds
.push_back(threadId
);
151 out_numThreadsPerProcGroup
++;
155 pBuffer
= PtrAdd(pBuffer
, pBuffer
->Size
);
161 #elif defined(__linux__) || defined (__gnu_linux__)
163 // Parse /proc/cpuinfo to get full topology
164 std::ifstream
input("/proc/cpuinfo");
167 uint32_t threadId
= uint32_t(-1);
168 uint32_t coreId
= uint32_t(-1);
169 uint32_t numaId
= uint32_t(-1);
171 while (std::getline(input
, line
))
173 if (line
.find("processor") != std::string::npos
)
175 if (threadId
!= uint32_t(-1))
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
];
183 core
.procGroup
= coreId
;
184 core
.threadIds
.push_back(threadId
);
186 out_numThreadsPerProcGroup
++;
189 auto data_start
= line
.find(": ") + 2;
190 threadId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
193 if (line
.find("core id") != std::string::npos
)
195 auto data_start
= line
.find(": ") + 2;
196 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
199 if (line
.find("physical id") != std::string::npos
)
201 auto data_start
= line
.find(": ") + 2;
202 numaId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
207 if (threadId
!= uint32_t(-1))
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
];
215 core
.procGroup
= coreId
;
216 core
.threadIds
.push_back(threadId
);
217 out_numThreadsPerProcGroup
++;
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
);
233 #error Unsupported platform
239 void bindThread(SWR_CONTEXT
* pContext
, uint32_t threadId
, uint32_t procGroupId
= 0, bool bindProcGroup
=false)
241 // Only bind threads when MAX_WORKER_THREADS isn't set.
242 if (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false)
249 GROUP_AFFINITY affinity
= {};
250 affinity
.Group
= procGroupId
;
255 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
256 SWR_REL_ASSERT(false, "Shouldn't get here");
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.
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
)
271 affinity
.Mask
= KAFFINITY(1) << threadId
;
275 SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr);
280 pthread_t thread
= pthread_self();
282 CPU_SET(threadId
, &cpuset
);
284 pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
290 uint32_t GetEnqueuedDraw(SWR_CONTEXT
*pContext
)
292 return pContext
->dcRing
.GetHead();
296 DRAW_CONTEXT
*GetDC(SWR_CONTEXT
*pContext
, uint32_t drawId
)
298 return &pContext
->dcRing
[(drawId
-1) % KNOB_MAX_DRAWS_IN_FLIGHT
];
302 bool IDComparesLess(uint32_t a
, uint32_t b
)
304 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
305 int32_t delta
= int32_t(a
- b
);
309 // returns true if dependency not met
311 bool CheckDependency(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
313 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
316 //////////////////////////////////////////////////////////////////////////
317 /// @brief Update client stats.
318 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
320 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStats
== false))
325 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
326 SWR_STATS stats
{ 0 };
328 // Sum up stats across all workers before sending to client.
329 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
331 stats
.DepthPassCount
+= dynState
.pStats
[i
].DepthPassCount
;
333 stats
.PsInvocations
+= dynState
.pStats
[i
].PsInvocations
;
334 stats
.CsInvocations
+= dynState
.pStats
[i
].CsInvocations
;
337 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
340 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
342 UpdateClientStats(pContext
, pDC
);
344 if (pDC
->retireCallback
.pfnCallbackFunc
)
346 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
347 pDC
->retireCallback
.userData2
,
348 pDC
->retireCallback
.userData3
);
352 // inlined-only version
353 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
355 int32_t result
= InterlockedDecrement((volatile LONG
*)&pDC
->threadsDone
);
356 SWR_ASSERT(result
>= 0);
360 ExecuteCallbacks(pContext
, pDC
);
362 // Cleanup memory allocations
363 pDC
->pArena
->Reset(true);
366 pDC
->pTileMgr
->initialize();
368 if (pDC
->cleanupState
)
370 pDC
->pState
->pArena
->Reset(true);
375 pContext
->dcRing
.Dequeue(); // Remove from tail
381 // available to other translation modules
382 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
384 return CompleteDrawContextInl(pContext
, pDC
);
387 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
, uint32_t& curDrawBE
, uint32_t& drawEnqueued
)
389 // increment our current draw id to the first incomplete draw
390 drawEnqueued
= GetEnqueuedDraw(pContext
);
391 while (IDComparesLess(curDrawBE
, drawEnqueued
))
393 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
];
395 // If its not compute and FE is not done then break out of loop.
396 if (!pDC
->doneFE
&& !pDC
->isCompute
) break;
398 bool isWorkComplete
= pDC
->isCompute
?
399 pDC
->pDispatch
->isWorkComplete() :
400 pDC
->pTileMgr
->isWorkComplete();
405 CompleteDrawContextInl(pContext
, pDC
);
413 // If there are no more incomplete draws then return false.
414 return IDComparesLess(curDrawBE
, drawEnqueued
);
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
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
433 SWR_CONTEXT
*pContext
,
436 TileSet
& lockedTiles
,
440 bool bShutdown
= false;
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)
450 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
452 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
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
)
462 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
464 if (pDC
->isCompute
) return false; // We don't look at compute work.
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;
471 // If this draw is dependent on a previous draw then we need to bail.
472 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
477 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
478 auto ¯oTiles
= pDC
->pTileMgr
->getDirtyTiles();
480 for (auto tile
: macroTiles
)
482 uint32_t tileID
= tile
->mId
;
484 // Only work on tiles for this numa node
486 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
487 if (((x
^ y
) & numaMask
) != numaNode
)
492 if (!tile
->getNumQueued())
497 // can only work on this draw if it's not in use by other threads
498 if (lockedTiles
.find(tileID
) != lockedTiles
.end())
507 AR_BEGIN(WorkerFoundWork
, pDC
->drawId
);
509 uint32_t numWorkItems
= tile
->getNumQueued();
510 SWR_ASSERT(numWorkItems
);
512 pWork
= tile
->peek();
514 if (pWork
->type
== DRAW
)
516 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, workerId
, tileID
);
518 else if (pWork
->type
== SHUTDOWN
)
523 while ((pWork
= tile
->peek()) != nullptr)
525 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
528 AR_END(WorkerFoundWork
, numWorkItems
);
532 pDC
->pTileMgr
->markTileComplete(tileID
);
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()))
538 // We can increment the current BE and safely move to next draw since we know this draw is complete.
540 CompleteDrawContextInl(pContext
, pDC
);
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
);
564 //////////////////////////////////////////////////////////////////////////
565 /// @brief Called when FE work is complete for this DC.
566 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
570 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStats
)
572 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &pDC
->dynState
.statsFE
);
575 if (pContext
->pfnUpdateSoWriteOffset
)
577 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
579 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
580 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
582 pContext
->pfnUpdateSoWriteOffset(GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
589 InterlockedDecrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
592 void WorkOnFifoFE(SWR_CONTEXT
*pContext
, uint32_t workerId
, uint32_t &curDrawFE
)
594 // Try to grab the next DC from the ring
595 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
596 while (IDComparesLess(curDrawFE
, drawEnqueued
))
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
)
602 CompleteDrawContextInl(pContext
, pDC
);
611 uint32_t curDraw
= curDrawFE
;
612 while (IDComparesLess(curDraw
, drawEnqueued
))
614 uint32_t dcSlot
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
615 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
617 if (!pDC
->isCompute
&& !pDC
->FeLock
)
619 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
622 // successfully grabbed the DC, now run the FE
623 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
625 CompleteDrawFE(pContext
, pDC
);
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
640 SWR_CONTEXT
*pContext
,
644 uint32_t drawEnqueued
= 0;
645 if (FindFirstIncompleteDraw(pContext
, curDrawBE
, drawEnqueued
) == false)
650 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
652 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
654 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
655 if (pDC
->isCompute
== false) return;
657 // check dependencies
658 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
663 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
664 DispatchQueue
& queue
= *pDC
->pDispatch
;
666 // Is there any work remaining?
667 if (queue
.getNumQueued() > 0)
669 void* pSpillFillBuffer
= nullptr;
670 uint32_t threadGroupId
= 0;
671 while (queue
.getWork(threadGroupId
))
673 queue
.dispatch(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
);
674 queue
.finishedWork();
680 template<bool IsFEThread
, bool IsBEThread
>
681 DWORD
workerThreadMain(LPVOID pData
)
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
;
688 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
690 RDTSC_INIT(threadId
);
692 uint32_t numaNode
= pThreadData
->numaId
;
693 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
695 // flush denormals to 0
696 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
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.
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
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
);
721 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
723 uint32_t curDrawBE
= 0;
724 uint32_t curDrawFE
= 0;
726 bool bShutdown
= false;
730 if (bShutdown
&& !threadHasWork(curDrawBE
))
736 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
741 if (!threadHasWork(curDrawBE
))
745 // check for thread idle condition again under lock
746 if (threadHasWork(curDrawBE
))
752 AR_BEGIN(WorkerWaitForThreadEvent
, 0);
754 pContext
->FifosNotEmpty
.wait(lock
);
757 AR_END(WorkerWaitForThreadEvent
, 0);
762 AR_BEGIN(WorkerWorkOnFifoBE
, 0);
763 bShutdown
|= WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
764 AR_END(WorkerWorkOnFifoBE
, 0);
766 WorkOnCompute(pContext
, workerId
, curDrawBE
);
771 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
775 curDrawBE
= curDrawFE
;
782 template<> DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
784 template <bool IsFEThread
, bool IsBEThread
>
785 DWORD
workerThreadInit(LPVOID pData
)
791 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
795 __except(EXCEPTION_CONTINUE_SEARCH
)
803 template<> DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
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
)
811 bindThread(pContext
, 0);
814 uint32_t numThreadsPerProcGroup
= 0;
815 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
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();
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
)
826 for (auto& core
: node
.cores
)
828 numHWThreads
+= (uint32_t)core
.threadIds
.size();
832 uint32_t numNodes
= numHWNodes
;
833 uint32_t numCoresPerNode
= numHWCoresPerNode
;
834 uint32_t numHyperThreads
= numHWHyperThreads
;
836 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
838 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
841 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
843 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
846 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
848 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
851 #if defined(_WIN32) && !defined(_WIN64)
852 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
854 // Limit 32-bit windows to bindable HW threads only
855 if ((numCoresPerNode
* numHWHyperThreads
) > 32)
857 numCoresPerNode
= 32 / numHWHyperThreads
;
862 // Calculate numThreads
863 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
864 numThreads
= std::min(numThreads
, numHWThreads
);
866 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
868 uint32_t maxHWThreads
= numHWNodes
* numHWCoresPerNode
* numHWHyperThreads
;
869 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, maxHWThreads
);
872 uint32_t numAPIReservedThreads
= 1;
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
)
883 else if (numHyperThreads
< numHWHyperThreads
)
887 else if (numNodes
< numHWNodes
)
893 pContext
->threadInfo
.SINGLE_THREADED
= true;
898 // Save HW threads for the API if we can
899 if (numThreads
> numAPIReservedThreads
)
901 numThreads
-= numAPIReservedThreads
;
905 numAPIReservedThreads
= 0;
909 if (pContext
->threadInfo
.SINGLE_THREADED
)
914 // Initialize DRAW_CONTEXT's per-thread stats
915 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
917 pContext
->dcRing
[dc
].dynState
.pStats
= new SWR_STATS
[numThreads
];
918 memset(pContext
->dcRing
[dc
].dynState
.pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
921 if (pContext
->threadInfo
.SINGLE_THREADED
)
923 pContext
->NumWorkerThreads
= 1;
924 pContext
->NumFEThreads
= 1;
925 pContext
->NumBEThreads
= 1;
926 pPool
->numThreads
= 0;
931 pPool
->numThreads
= numThreads
;
932 pContext
->NumWorkerThreads
= pPool
->numThreads
;
934 pPool
->pThreadData
= (THREAD_DATA
*)malloc(pPool
->numThreads
* sizeof(THREAD_DATA
));
937 pPool
->pThreads
= new THREAD_PTR
[pPool
->numThreads
];
939 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
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
)
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
;
956 pContext
->NumBEThreads
++;
957 pContext
->NumFEThreads
++;
962 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
964 uint32_t workerId
= 0;
965 for (uint32_t n
= 0; n
< numNodes
; ++n
)
967 auto& node
= nodes
[n
];
968 uint32_t numCores
= numCoresPerNode
;
969 for (uint32_t c
= 0; c
< numCores
; ++c
)
971 if (c
>= node
.cores
.size())
976 auto& core
= node
.cores
[c
];
977 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
979 if (t
>= core
.threadIds
.size())
984 if (numAPIReservedThreads
)
986 --numAPIReservedThreads
;
990 SWR_ASSERT(workerId
< numThreads
);
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
;
1000 pContext
->NumBEThreads
++;
1001 pContext
->NumFEThreads
++;
1007 SWR_ASSERT(workerId
== pContext
->NumWorkerThreads
);
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
)
1017 if (pContext
->threadInfo
.SINGLE_THREADED
)
1022 for (uint32_t workerId
= 0; workerId
< pContext
->NumWorkerThreads
; ++workerId
)
1024 pPool
->pThreads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
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
)
1034 if (!pContext
->threadInfo
.SINGLE_THREADED
)
1036 // Wait for all threads to finish
1037 SwrWaitForIdle(pContext
);
1039 // Wait for threads to finish and destroy them
1040 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
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
]);
1048 delete [] pPool
->pThreads
;
1050 // Clean up data used by threads
1051 free(pPool
->pThreadData
);