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
);
76 static SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer
[KNOB_MAX_NUM_THREADS
];
77 DWORD bufSize
= sizeof(buffer
);
79 BOOL ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, buffer
, &bufSize
);
80 SWR_ASSERT(ret
!= FALSE
, "Failed to get Processor Topology Information");
82 uint32_t count
= bufSize
/ buffer
->Size
;
83 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBuffer
= buffer
;
85 for (uint32_t i
= 0; i
< count
; ++i
)
87 SWR_ASSERT(pBuffer
->Relationship
== RelationProcessorCore
);
88 for (uint32_t g
= 0; g
< pBuffer
->Processor
.GroupCount
; ++g
)
90 auto& gmask
= pBuffer
->Processor
.GroupMask
[g
];
91 uint32_t threadId
= 0;
92 uint32_t procGroup
= gmask
.Group
;
94 Core
* pCore
= nullptr;
96 uint32_t numThreads
= (uint32_t)_mm_popcount_sizeT(gmask
.Mask
);
98 while (BitScanForwardSizeT((unsigned long*)&threadId
, gmask
.Mask
))
101 KAFFINITY threadMask
= KAFFINITY(1) << threadId
;
102 gmask
.Mask
&= ~threadMask
;
104 if (procGroup
>= threadMaskPerProcGroup
.size())
106 threadMaskPerProcGroup
.resize(procGroup
+ 1);
109 if (threadMaskPerProcGroup
[procGroup
] & threadMask
)
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
115 SWR_ASSERT(false, "Shouldn't get here in 64-bit mode");
120 threadMaskPerProcGroup
[procGroup
] |= (KAFFINITY(1) << threadId
);
124 PROCESSOR_NUMBER procNum
= {};
125 procNum
.Group
= WORD(procGroup
);
126 procNum
.Number
= UCHAR(threadId
);
128 ret
= GetNumaProcessorNodeEx(&procNum
, (PUSHORT
)&numaId
);
132 if (out_nodes
.size() <= numaId
) out_nodes
.resize(numaId
+ 1);
133 auto& numaNode
= out_nodes
[numaId
];
137 if (nullptr == pCore
)
139 numaNode
.cores
.push_back(Core());
140 pCore
= &numaNode
.cores
.back();
141 pCore
->procGroup
= procGroup
;
143 pCore
->threadIds
.push_back(threadId
);
146 out_numThreadsPerProcGroup
++;
150 pBuffer
= PtrAdd(pBuffer
, pBuffer
->Size
);
154 #elif defined(__linux__) || defined (__gnu_linux__)
156 // Parse /proc/cpuinfo to get full topology
157 std::ifstream
input("/proc/cpuinfo");
160 uint32_t threadId
= uint32_t(-1);
161 uint32_t coreId
= uint32_t(-1);
162 uint32_t numaId
= uint32_t(-1);
164 while (std::getline(input
, line
))
166 if (line
.find("processor") != std::string::npos
)
168 if (threadId
!= uint32_t(-1))
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
];
176 core
.procGroup
= coreId
;
177 core
.threadIds
.push_back(threadId
);
179 out_numThreadsPerProcGroup
++;
182 auto data_start
= line
.find(": ") + 2;
183 threadId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
186 if (line
.find("core id") != std::string::npos
)
188 auto data_start
= line
.find(": ") + 2;
189 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
192 if (line
.find("physical id") != std::string::npos
)
194 auto data_start
= line
.find(": ") + 2;
195 numaId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
200 if (threadId
!= uint32_t(-1))
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
];
208 core
.procGroup
= coreId
;
209 core
.threadIds
.push_back(threadId
);
210 out_numThreadsPerProcGroup
++;
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
);
226 #error Unsupported platform
232 void bindThread(SWR_CONTEXT
* pContext
, uint32_t threadId
, uint32_t procGroupId
= 0, bool bindProcGroup
=false)
234 // Only bind threads when MAX_WORKER_THREADS isn't set.
235 if (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false)
242 GROUP_AFFINITY affinity
= {};
243 affinity
.Group
= procGroupId
;
248 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
249 SWR_REL_ASSERT(false, "Shouldn't get here");
251 // In a 32-bit process on Windows it is impossible to bind
252 // to logical processors 32-63 within a processor group.
253 // In this case set the mask to 0 and let the system assign
254 // the processor. Hopefully it will make smart choices.
260 // If MAX_WORKER_THREADS is set, only bind to the proc group,
261 // Not the individual HW thread.
262 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
264 affinity
.Mask
= KAFFINITY(1) << threadId
;
268 SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr);
273 pthread_t thread
= pthread_self();
275 CPU_SET(threadId
, &cpuset
);
277 pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
283 uint32_t GetEnqueuedDraw(SWR_CONTEXT
*pContext
)
285 return pContext
->dcRing
.GetHead();
289 DRAW_CONTEXT
*GetDC(SWR_CONTEXT
*pContext
, uint32_t drawId
)
291 return &pContext
->dcRing
[(drawId
-1) % KNOB_MAX_DRAWS_IN_FLIGHT
];
295 bool IDComparesLess(uint32_t a
, uint32_t b
)
297 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
298 int32_t delta
= int32_t(a
- b
);
302 // returns true if dependency not met
304 bool CheckDependency(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
306 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
309 //////////////////////////////////////////////////////////////////////////
310 /// @brief Update client stats.
311 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
313 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStats
== false))
318 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
319 SWR_STATS stats
{ 0 };
321 // Sum up stats across all workers before sending to client.
322 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
324 stats
.DepthPassCount
+= dynState
.stats
[i
].DepthPassCount
;
326 stats
.PsInvocations
+= dynState
.stats
[i
].PsInvocations
;
327 stats
.CsInvocations
+= dynState
.stats
[i
].CsInvocations
;
330 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
333 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
335 UpdateClientStats(pContext
, pDC
);
337 if (pDC
->retireCallback
.pfnCallbackFunc
)
339 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
340 pDC
->retireCallback
.userData2
,
341 pDC
->retireCallback
.userData3
);
345 // inlined-only version
346 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
348 int32_t result
= InterlockedDecrement((volatile LONG
*)&pDC
->threadsDone
);
349 SWR_ASSERT(result
>= 0);
353 ExecuteCallbacks(pContext
, pDC
);
355 // Cleanup memory allocations
356 pDC
->pArena
->Reset(true);
359 pDC
->pTileMgr
->initialize();
361 if (pDC
->cleanupState
)
363 pDC
->pState
->pArena
->Reset(true);
368 pContext
->dcRing
.Dequeue(); // Remove from tail
374 // available to other translation modules
375 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
377 return CompleteDrawContextInl(pContext
, pDC
);
380 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
, uint32_t& curDrawBE
, uint32_t& drawEnqueued
)
382 // increment our current draw id to the first incomplete draw
383 drawEnqueued
= GetEnqueuedDraw(pContext
);
384 while (IDComparesLess(curDrawBE
, drawEnqueued
))
386 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
];
388 // If its not compute and FE is not done then break out of loop.
389 if (!pDC
->doneFE
&& !pDC
->isCompute
) break;
391 bool isWorkComplete
= pDC
->isCompute
?
392 pDC
->pDispatch
->isWorkComplete() :
393 pDC
->pTileMgr
->isWorkComplete();
398 CompleteDrawContextInl(pContext
, pDC
);
406 // If there are no more incomplete draws then return false.
407 return IDComparesLess(curDrawBE
, drawEnqueued
);
410 //////////////////////////////////////////////////////////////////////////
411 /// @brief If there is any BE work then go work on it.
412 /// @param pContext - pointer to SWR context.
413 /// @param workerId - The unique worker ID that is assigned to this thread.
414 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
415 /// has its own curDrawBE counter and this ensures that each worker processes all the
417 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
418 /// own set and each time it fails to lock a macrotile, because its already locked,
419 /// then it will add that tile to the lockedTiles set. As a worker begins to work
420 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
421 /// still have work pending in a previous draw. Additionally, the lockedTiles is
422 /// hueristic that can steer a worker back to the same macrotile that it had been
423 /// working on in a previous draw.
425 SWR_CONTEXT
*pContext
,
428 TileSet
& lockedTiles
,
432 // Find the first incomplete draw that has pending work. If no such draw is found then
433 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
434 uint32_t drawEnqueued
= 0;
435 if (FindFirstIncompleteDraw(pContext
, curDrawBE
, drawEnqueued
) == false)
440 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
442 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
445 // Try to work on each draw in order of the available draws in flight.
446 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
447 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
448 // working on those macrotiles that are known to be complete in the prior draw to
449 // maintain order. The locked tiles provides the history to ensures this.
450 for (uint32_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
452 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
454 if (pDC
->isCompute
) return; // We don't look at compute work.
456 // First wait for FE to be finished with this draw. This keeps threading model simple
457 // but if there are lots of bubbles between draws then serializing FE and BE may
458 // need to be revisited.
459 if (!pDC
->doneFE
) return;
461 // If this draw is dependent on a previous draw then we need to bail.
462 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
467 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
468 auto ¯oTiles
= pDC
->pTileMgr
->getDirtyTiles();
470 for (auto tile
: macroTiles
)
472 uint32_t tileID
= tile
->mId
;
474 // Only work on tiles for this numa node
476 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
477 if (((x
^ y
) & numaMask
) != numaNode
)
482 if (!tile
->getNumQueued())
487 // can only work on this draw if it's not in use by other threads
488 if (lockedTiles
.find(tileID
) != lockedTiles
.end())
497 RDTSC_START(WorkerFoundWork
);
499 uint32_t numWorkItems
= tile
->getNumQueued();
500 SWR_ASSERT(numWorkItems
);
502 pWork
= tile
->peek();
504 if (pWork
->type
== DRAW
)
506 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, tileID
);
509 while ((pWork
= tile
->peek()) != nullptr)
511 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
514 RDTSC_STOP(WorkerFoundWork
, numWorkItems
, pDC
->drawId
);
518 pDC
->pTileMgr
->markTileComplete(tileID
);
520 // Optimization: If the draw is complete and we're the last one to have worked on it then
521 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
522 if ((curDrawBE
== i
) && pDC
->pTileMgr
->isWorkComplete())
524 // We can increment the current BE and safely move to next draw since we know this draw is complete.
526 CompleteDrawContextInl(pContext
, pDC
);
536 // 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.
537 lockedTiles
.insert(tileID
);
543 //////////////////////////////////////////////////////////////////////////
544 /// @brief Called when FE work is complete for this DC.
545 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
549 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStats
)
551 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &pDC
->dynState
.statsFE
);
554 if (pContext
->pfnUpdateSoWriteOffset
)
556 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
558 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
559 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
561 pContext
->pfnUpdateSoWriteOffset(GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
568 InterlockedDecrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
571 void WorkOnFifoFE(SWR_CONTEXT
*pContext
, uint32_t workerId
, uint32_t &curDrawFE
)
573 // Try to grab the next DC from the ring
574 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
575 while (IDComparesLess(curDrawFE
, drawEnqueued
))
577 uint32_t dcSlot
= curDrawFE
% KNOB_MAX_DRAWS_IN_FLIGHT
;
578 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
579 if (pDC
->isCompute
|| pDC
->doneFE
|| pDC
->FeLock
)
581 CompleteDrawContextInl(pContext
, pDC
);
590 uint32_t curDraw
= curDrawFE
;
591 while (IDComparesLess(curDraw
, drawEnqueued
))
593 uint32_t dcSlot
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
594 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
596 if (!pDC
->isCompute
&& !pDC
->FeLock
)
598 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
601 // successfully grabbed the DC, now run the FE
602 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
604 CompleteDrawFE(pContext
, pDC
);
611 //////////////////////////////////////////////////////////////////////////
612 /// @brief If there is any compute work then go work on it.
613 /// @param pContext - pointer to SWR context.
614 /// @param workerId - The unique worker ID that is assigned to this thread.
615 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
616 /// has its own curDrawBE counter and this ensures that each worker processes all the
619 SWR_CONTEXT
*pContext
,
623 uint32_t drawEnqueued
= 0;
624 if (FindFirstIncompleteDraw(pContext
, curDrawBE
, drawEnqueued
) == false)
629 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
631 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
633 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
634 if (pDC
->isCompute
== false) return;
636 // check dependencies
637 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
642 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
643 DispatchQueue
& queue
= *pDC
->pDispatch
;
645 // Is there any work remaining?
646 if (queue
.getNumQueued() > 0)
648 void* pSpillFillBuffer
= nullptr;
649 uint32_t threadGroupId
= 0;
650 while (queue
.getWork(threadGroupId
))
652 ProcessComputeBE(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
);
654 queue
.finishedWork();
660 template<bool IsFEThread
, bool IsBEThread
>
661 DWORD
workerThreadMain(LPVOID pData
)
663 THREAD_DATA
*pThreadData
= (THREAD_DATA
*)pData
;
664 SWR_CONTEXT
*pContext
= pThreadData
->pContext
;
665 uint32_t threadId
= pThreadData
->threadId
;
666 uint32_t workerId
= pThreadData
->workerId
;
668 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
670 RDTSC_INIT(threadId
);
672 uint32_t numaNode
= pThreadData
->numaId
;
673 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
675 // flush denormals to 0
676 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
678 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
679 // locked then we'll add it to this list so that we don't try and lock it again.
682 // each worker has the ability to work on any of the queued draws as long as certain
683 // conditions are met. the data associated
684 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
685 // has moved on to the next draw when he determines there is no more work to do. The api
686 // thread will not increment the head of the dc ring until all workers have moved past the
688 // the logic to determine what to work on is:
689 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
690 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
691 // we'll need dependency tracking to force serialization on FEs. The worker will try
692 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
693 // trying until he reaches the tail.
694 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
695 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
696 // any work left by comparing the total # of binned work items and the total # of completed
697 // work items. If they are equal, then there is no more work to do for this draw, and
698 // the worker can safely increment its oldestDraw counter and move on to the next draw.
699 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
, std::defer_lock
);
701 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
703 uint32_t curDrawBE
= 0;
704 uint32_t curDrawFE
= 0;
706 while (pContext
->threadPool
.inThreadShutdown
== false)
709 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
714 if (!threadHasWork(curDrawBE
))
718 // check for thread idle condition again under lock
719 if (threadHasWork(curDrawBE
))
725 if (pContext
->threadPool
.inThreadShutdown
)
731 RDTSC_START(WorkerWaitForThreadEvent
);
733 pContext
->FifosNotEmpty
.wait(lock
);
736 RDTSC_STOP(WorkerWaitForThreadEvent
, 0, 0);
738 if (pContext
->threadPool
.inThreadShutdown
)
746 RDTSC_START(WorkerWorkOnFifoBE
);
747 WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
748 RDTSC_STOP(WorkerWorkOnFifoBE
, 0, 0);
750 WorkOnCompute(pContext
, workerId
, curDrawBE
);
755 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
759 curDrawBE
= curDrawFE
;
766 template<> DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
768 template <bool IsFEThread
, bool IsBEThread
>
769 DWORD
workerThreadInit(LPVOID pData
)
775 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
779 __except(EXCEPTION_CONTINUE_SEARCH
)
787 template<> DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
789 void CreateThreadPool(SWR_CONTEXT
*pContext
, THREAD_POOL
*pPool
)
791 bindThread(pContext
, 0);
794 uint32_t numThreadsPerProcGroup
= 0;
795 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
797 uint32_t numHWNodes
= (uint32_t)nodes
.size();
798 uint32_t numHWCoresPerNode
= (uint32_t)nodes
[0].cores
.size();
799 uint32_t numHWHyperThreads
= (uint32_t)nodes
[0].cores
[0].threadIds
.size();
801 // Calculate num HW threads. Due to asymmetric topologies, this is not
802 // a trivial multiplication.
803 uint32_t numHWThreads
= 0;
804 for (auto& node
: nodes
)
806 for (auto& core
: node
.cores
)
808 numHWThreads
+= (uint32_t)core
.threadIds
.size();
812 uint32_t numNodes
= numHWNodes
;
813 uint32_t numCoresPerNode
= numHWCoresPerNode
;
814 uint32_t numHyperThreads
= numHWHyperThreads
;
816 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
818 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
821 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
823 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
826 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
828 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
831 #if defined(_WIN32) && !defined(_WIN64)
832 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
834 // Limit 32-bit windows to bindable HW threads only
835 if ((numCoresPerNode
* numHWHyperThreads
) > 32)
837 numCoresPerNode
= 32 / numHWHyperThreads
;
842 // Calculate numThreads
843 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
844 numThreads
= std::min(numThreads
, numHWThreads
);
846 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
848 uint32_t maxHWThreads
= numHWNodes
* numHWCoresPerNode
* numHWHyperThreads
;
849 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, maxHWThreads
);
852 if (numThreads
> KNOB_MAX_NUM_THREADS
)
854 printf("WARNING: system thread count %u exceeds max %u, "
855 "performance will be degraded\n",
856 numThreads
, KNOB_MAX_NUM_THREADS
);
859 uint32_t numAPIReservedThreads
= 1;
864 // If only 1 worker threads, try to move it to an available
865 // HW thread. If that fails, use the API thread.
866 if (numCoresPerNode
< numHWCoresPerNode
)
870 else if (numHyperThreads
< numHWHyperThreads
)
874 else if (numNodes
< numHWNodes
)
880 pPool
->numThreads
= 0;
881 SET_KNOB(SINGLE_THREADED
, true);
887 // Save HW threads for the API if we can
888 if (numThreads
> numAPIReservedThreads
)
890 numThreads
-= numAPIReservedThreads
;
894 numAPIReservedThreads
= 0;
898 pPool
->numThreads
= numThreads
;
899 pContext
->NumWorkerThreads
= pPool
->numThreads
;
901 pPool
->inThreadShutdown
= false;
902 pPool
->pThreadData
= (THREAD_DATA
*)malloc(pPool
->numThreads
* sizeof(THREAD_DATA
));
905 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
907 bool bForceBindProcGroup
= (numThreads
> numThreadsPerProcGroup
);
908 uint32_t numProcGroups
= (numThreads
+ numThreadsPerProcGroup
- 1) / numThreadsPerProcGroup
;
909 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
910 // But Windows will still require binding to specific process groups
911 for (uint32_t workerId
= 0; workerId
< numThreads
; ++workerId
)
913 pPool
->pThreadData
[workerId
].workerId
= workerId
;
914 pPool
->pThreadData
[workerId
].procGroupId
= workerId
% numProcGroups
;
915 pPool
->pThreadData
[workerId
].threadId
= 0;
916 pPool
->pThreadData
[workerId
].numaId
= 0;
917 pPool
->pThreadData
[workerId
].coreId
= 0;
918 pPool
->pThreadData
[workerId
].htId
= 0;
919 pPool
->pThreadData
[workerId
].pContext
= pContext
;
920 pPool
->pThreadData
[workerId
].forceBindProcGroup
= bForceBindProcGroup
;
921 pPool
->threads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
923 pContext
->NumBEThreads
++;
924 pContext
->NumFEThreads
++;
929 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
931 uint32_t workerId
= 0;
932 for (uint32_t n
= 0; n
< numNodes
; ++n
)
934 auto& node
= nodes
[n
];
935 uint32_t numCores
= numCoresPerNode
;
936 for (uint32_t c
= 0; c
< numCores
; ++c
)
938 if (c
>= node
.cores
.size())
943 auto& core
= node
.cores
[c
];
944 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
946 if (t
>= core
.threadIds
.size())
951 if (numAPIReservedThreads
)
953 --numAPIReservedThreads
;
957 SWR_ASSERT(workerId
< numThreads
);
959 pPool
->pThreadData
[workerId
].workerId
= workerId
;
960 pPool
->pThreadData
[workerId
].procGroupId
= core
.procGroup
;
961 pPool
->pThreadData
[workerId
].threadId
= core
.threadIds
[t
];
962 pPool
->pThreadData
[workerId
].numaId
= n
;
963 pPool
->pThreadData
[workerId
].coreId
= c
;
964 pPool
->pThreadData
[workerId
].htId
= t
;
965 pPool
->pThreadData
[workerId
].pContext
= pContext
;
967 pPool
->threads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
968 pContext
->NumBEThreads
++;
969 pContext
->NumFEThreads
++;
978 void DestroyThreadPool(SWR_CONTEXT
*pContext
, THREAD_POOL
*pPool
)
980 if (!pContext
->threadInfo
.SINGLE_THREADED
)
982 // Inform threads to finish up
983 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
984 pPool
->inThreadShutdown
= true;
986 pContext
->FifosNotEmpty
.notify_all();
989 // Wait for threads to finish and destroy them
990 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
992 pPool
->threads
[t
]->join();
993 delete(pPool
->threads
[t
]);
996 // Clean up data used by threads
997 free(pPool
->pThreadData
);