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
;
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_ASSERT(false, "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 threadId
= uint32_t(-1);
173 uint32_t coreId
= uint32_t(-1);
174 uint32_t numaId
= uint32_t(-1);
176 while (std::getline(input
, line
))
178 if (line
.find("processor") != std::string::npos
)
180 if (threadId
!= uint32_t(-1))
183 if (out_nodes
.size() <= numaId
)
185 out_nodes
.resize(numaId
+ 1);
188 auto& numaNode
= out_nodes
[numaId
];
189 if (numaNode
.cores
.size() <= coreId
)
191 numaNode
.cores
.resize(coreId
+ 1);
194 auto& core
= numaNode
.cores
[coreId
];
195 core
.procGroup
= coreId
;
196 core
.threadIds
.push_back(threadId
);
198 out_numThreadsPerProcGroup
++;
201 auto data_start
= line
.find(": ") + 2;
202 threadId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
205 if (line
.find("core id") != std::string::npos
)
207 auto data_start
= line
.find(": ") + 2;
208 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
211 if (line
.find("physical id") != std::string::npos
)
213 auto data_start
= line
.find(": ") + 2;
214 numaId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
219 if (threadId
!= uint32_t(-1))
222 if (out_nodes
.size() <= numaId
)
224 out_nodes
.resize(numaId
+ 1);
226 auto& numaNode
= out_nodes
[numaId
];
227 numaNode
.numaId
= numaId
;
228 if (numaNode
.cores
.size() <= coreId
)
230 numaNode
.cores
.resize(coreId
+ 1);
232 auto& core
= numaNode
.cores
[coreId
];
234 core
.procGroup
= coreId
;
235 core
.threadIds
.push_back(threadId
);
236 out_numThreadsPerProcGroup
++;
241 #error Unsupported platform
245 // Prune empty cores and numa nodes
246 for (auto node_it
= out_nodes
.begin(); node_it
!= out_nodes
.end(); )
248 // Erase empty cores (first)
249 for (auto core_it
= node_it
->cores
.begin(); core_it
!= node_it
->cores
.end(); )
251 if (core_it
->threadIds
.size() == 0)
253 core_it
= node_it
->cores
.erase(core_it
);
261 // Erase empty numa nodes (second)
262 if (node_it
->cores
.size() == 0)
264 node_it
= out_nodes
.erase(node_it
);
274 void bindThread(SWR_CONTEXT
* pContext
, uint32_t threadId
, uint32_t procGroupId
= 0, bool bindProcGroup
=false)
276 // Only bind threads when MAX_WORKER_THREADS isn't set.
277 if (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false)
284 GROUP_AFFINITY affinity
= {};
285 affinity
.Group
= procGroupId
;
290 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
291 SWR_REL_ASSERT(false, "Shouldn't get here");
293 // In a 32-bit process on Windows it is impossible to bind
294 // to logical processors 32-63 within a processor group.
295 // In this case set the mask to 0 and let the system assign
296 // the processor. Hopefully it will make smart choices.
302 // If MAX_WORKER_THREADS is set, only bind to the proc group,
303 // Not the individual HW thread.
304 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
306 affinity
.Mask
= KAFFINITY(1) << threadId
;
310 SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr);
315 pthread_t thread
= pthread_self();
317 CPU_SET(threadId
, &cpuset
);
319 pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
325 uint32_t GetEnqueuedDraw(SWR_CONTEXT
*pContext
)
327 return pContext
->dcRing
.GetHead();
331 DRAW_CONTEXT
*GetDC(SWR_CONTEXT
*pContext
, uint32_t drawId
)
333 return &pContext
->dcRing
[(drawId
-1) % KNOB_MAX_DRAWS_IN_FLIGHT
];
337 bool IDComparesLess(uint32_t a
, uint32_t b
)
339 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
340 int32_t delta
= int32_t(a
- b
);
344 // returns true if dependency not met
346 bool CheckDependency(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
348 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
351 bool CheckDependencyFE(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
353 return pDC
->dependentFE
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
356 //////////////////////////////////////////////////////////////////////////
357 /// @brief Update client stats.
358 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
360 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStatsBE
== false))
365 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
366 SWR_STATS stats
{ 0 };
368 // Sum up stats across all workers before sending to client.
369 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
371 stats
.DepthPassCount
+= dynState
.pStats
[i
].DepthPassCount
;
373 stats
.PsInvocations
+= dynState
.pStats
[i
].PsInvocations
;
374 stats
.CsInvocations
+= dynState
.pStats
[i
].CsInvocations
;
378 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
381 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
383 UpdateClientStats(pContext
, workerId
, pDC
);
385 if (pDC
->retireCallback
.pfnCallbackFunc
)
387 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
388 pDC
->retireCallback
.userData2
,
389 pDC
->retireCallback
.userData3
);
393 // inlined-only version
394 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
396 int32_t result
= InterlockedDecrement((volatile LONG
*)&pDC
->threadsDone
);
397 SWR_ASSERT(result
>= 0);
401 ExecuteCallbacks(pContext
, workerId
, pDC
);
403 // Cleanup memory allocations
404 pDC
->pArena
->Reset(true);
407 pDC
->pTileMgr
->initialize();
409 if (pDC
->cleanupState
)
411 pDC
->pState
->pArena
->Reset(true);
416 pContext
->dcRing
.Dequeue(); // Remove from tail
422 // available to other translation modules
423 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
425 return CompleteDrawContextInl(pContext
, 0, pDC
);
428 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
, uint32_t workerId
, uint32_t& curDrawBE
, uint32_t& drawEnqueued
)
430 // increment our current draw id to the first incomplete draw
431 drawEnqueued
= GetEnqueuedDraw(pContext
);
432 while (IDComparesLess(curDrawBE
, drawEnqueued
))
434 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
];
436 // If its not compute and FE is not done then break out of loop.
437 if (!pDC
->doneFE
&& !pDC
->isCompute
) break;
439 bool isWorkComplete
= pDC
->isCompute
?
440 pDC
->pDispatch
->isWorkComplete() :
441 pDC
->pTileMgr
->isWorkComplete();
446 CompleteDrawContextInl(pContext
, workerId
, pDC
);
454 // If there are no more incomplete draws then return false.
455 return IDComparesLess(curDrawBE
, drawEnqueued
);
458 //////////////////////////////////////////////////////////////////////////
459 /// @brief If there is any BE work then go work on it.
460 /// @param pContext - pointer to SWR context.
461 /// @param workerId - The unique worker ID that is assigned to this thread.
462 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
463 /// has its own curDrawBE counter and this ensures that each worker processes all the
465 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
466 /// own set and each time it fails to lock a macrotile, because its already locked,
467 /// then it will add that tile to the lockedTiles set. As a worker begins to work
468 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
469 /// still have work pending in a previous draw. Additionally, the lockedTiles is
470 /// hueristic that can steer a worker back to the same macrotile that it had been
471 /// working on in a previous draw.
472 /// @returns true if worker thread should shutdown
474 SWR_CONTEXT
*pContext
,
477 TileSet
& lockedTiles
,
481 bool bShutdown
= false;
483 // Find the first incomplete draw that has pending work. If no such draw is found then
484 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
485 uint32_t drawEnqueued
= 0;
486 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
491 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
493 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
496 // Try to work on each draw in order of the available draws in flight.
497 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
498 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
499 // working on those macrotiles that are known to be complete in the prior draw to
500 // maintain order. The locked tiles provides the history to ensures this.
501 for (uint32_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
503 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
505 if (pDC
->isCompute
) return false; // We don't look at compute work.
507 // First wait for FE to be finished with this draw. This keeps threading model simple
508 // but if there are lots of bubbles between draws then serializing FE and BE may
509 // need to be revisited.
510 if (!pDC
->doneFE
) return false;
512 // If this draw is dependent on a previous draw then we need to bail.
513 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
518 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
519 auto ¯oTiles
= pDC
->pTileMgr
->getDirtyTiles();
521 for (auto tile
: macroTiles
)
523 uint32_t tileID
= tile
->mId
;
525 // Only work on tiles for this numa node
527 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
528 if (((x
^ y
) & numaMask
) != numaNode
)
533 if (!tile
->getNumQueued())
538 // can only work on this draw if it's not in use by other threads
539 if (lockedTiles
.find(tileID
) != lockedTiles
.end())
548 AR_BEGIN(WorkerFoundWork
, pDC
->drawId
);
550 uint32_t numWorkItems
= tile
->getNumQueued();
551 SWR_ASSERT(numWorkItems
);
553 pWork
= tile
->peek();
555 if (pWork
->type
== DRAW
)
557 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, workerId
, tileID
);
559 else if (pWork
->type
== SHUTDOWN
)
564 while ((pWork
= tile
->peek()) != nullptr)
566 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
569 AR_END(WorkerFoundWork
, numWorkItems
);
573 pDC
->pTileMgr
->markTileComplete(tileID
);
575 // Optimization: If the draw is complete and we're the last one to have worked on it then
576 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
577 if ((curDrawBE
== i
) && (bShutdown
|| pDC
->pTileMgr
->isWorkComplete()))
579 // We can increment the current BE and safely move to next draw since we know this draw is complete.
581 CompleteDrawContextInl(pContext
, workerId
, pDC
);
596 // 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.
597 lockedTiles
.insert(tileID
);
605 //////////////////////////////////////////////////////////////////////////
606 /// @brief Called when FE work is complete for this DC.
607 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
609 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStatsFE
)
611 SWR_STATS_FE
& stats
= pDC
->dynState
.statsFE
;
613 AR_EVENT(FrontendStatsEvent(pDC
->drawId
,
614 stats
.IaVertices
, stats
.IaPrimitives
, stats
.VsInvocations
, stats
.HsInvocations
,
615 stats
.DsInvocations
, stats
.GsInvocations
, stats
.GsPrimitives
, stats
.CInvocations
, stats
.CPrimitives
,
616 stats
.SoPrimStorageNeeded
[0], stats
.SoPrimStorageNeeded
[1], stats
.SoPrimStorageNeeded
[2], stats
.SoPrimStorageNeeded
[3],
617 stats
.SoNumPrimsWritten
[0], stats
.SoNumPrimsWritten
[1], stats
.SoNumPrimsWritten
[2], stats
.SoNumPrimsWritten
[3]
619 AR_EVENT(FrontendDrawEndEvent(pDC
->drawId
));
621 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &stats
);
624 if (pContext
->pfnUpdateSoWriteOffset
)
626 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
628 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
629 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
631 pContext
->pfnUpdateSoWriteOffset(GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
636 // Ensure all streaming writes are globally visible before marking this FE done
640 InterlockedDecrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
643 void WorkOnFifoFE(SWR_CONTEXT
*pContext
, uint32_t workerId
, uint32_t &curDrawFE
)
645 // Try to grab the next DC from the ring
646 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
647 while (IDComparesLess(curDrawFE
, drawEnqueued
))
649 uint32_t dcSlot
= curDrawFE
% KNOB_MAX_DRAWS_IN_FLIGHT
;
650 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
651 if (pDC
->isCompute
|| pDC
->doneFE
)
653 CompleteDrawContextInl(pContext
, workerId
, pDC
);
662 uint32_t lastRetiredFE
= curDrawFE
- 1;
663 uint32_t curDraw
= curDrawFE
;
664 while (IDComparesLess(curDraw
, drawEnqueued
))
666 uint32_t dcSlot
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
667 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
669 if (!pDC
->isCompute
&& !pDC
->FeLock
)
671 if (CheckDependencyFE(pContext
, pDC
, lastRetiredFE
))
676 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
679 // successfully grabbed the DC, now run the FE
680 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
682 CompleteDrawFE(pContext
, workerId
, pDC
);
689 //////////////////////////////////////////////////////////////////////////
690 /// @brief If there is any compute work then go work on it.
691 /// @param pContext - pointer to SWR context.
692 /// @param workerId - The unique worker ID that is assigned to this thread.
693 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
694 /// has its own curDrawBE counter and this ensures that each worker processes all the
697 SWR_CONTEXT
*pContext
,
701 uint32_t drawEnqueued
= 0;
702 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
707 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% KNOB_MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
709 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
711 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% KNOB_MAX_DRAWS_IN_FLIGHT
];
712 if (pDC
->isCompute
== false) return;
714 // check dependencies
715 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
720 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
721 DispatchQueue
& queue
= *pDC
->pDispatch
;
723 // Is there any work remaining?
724 if (queue
.getNumQueued() > 0)
726 void* pSpillFillBuffer
= nullptr;
727 uint32_t threadGroupId
= 0;
728 while (queue
.getWork(threadGroupId
))
730 queue
.dispatch(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
);
731 queue
.finishedWork();
734 // Ensure all streaming writes are globally visible before moving onto the next draw
740 template<bool IsFEThread
, bool IsBEThread
>
741 DWORD
workerThreadMain(LPVOID pData
)
743 THREAD_DATA
*pThreadData
= (THREAD_DATA
*)pData
;
744 SWR_CONTEXT
*pContext
= pThreadData
->pContext
;
745 uint32_t threadId
= pThreadData
->threadId
;
746 uint32_t workerId
= pThreadData
->workerId
;
748 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
750 RDTSC_INIT(threadId
);
752 uint32_t numaNode
= pThreadData
->numaId
;
753 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
755 // flush denormals to 0
756 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
758 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
759 // locked then we'll add it to this list so that we don't try and lock it again.
762 // each worker has the ability to work on any of the queued draws as long as certain
763 // conditions are met. the data associated
764 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
765 // has moved on to the next draw when he determines there is no more work to do. The api
766 // thread will not increment the head of the dc ring until all workers have moved past the
768 // the logic to determine what to work on is:
769 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
770 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
771 // we'll need dependency tracking to force serialization on FEs. The worker will try
772 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
773 // trying until he reaches the tail.
774 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
775 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
776 // any work left by comparing the total # of binned work items and the total # of completed
777 // work items. If they are equal, then there is no more work to do for this draw, and
778 // the worker can safely increment its oldestDraw counter and move on to the next draw.
779 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
, std::defer_lock
);
781 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
783 uint32_t curDrawBE
= 0;
784 uint32_t curDrawFE
= 0;
786 bool bShutdown
= false;
790 if (bShutdown
&& !threadHasWork(curDrawBE
))
796 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
801 if (!threadHasWork(curDrawBE
))
805 // check for thread idle condition again under lock
806 if (threadHasWork(curDrawBE
))
812 pContext
->FifosNotEmpty
.wait(lock
);
818 AR_BEGIN(WorkerWorkOnFifoBE
, 0);
819 bShutdown
|= WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
820 AR_END(WorkerWorkOnFifoBE
, 0);
822 WorkOnCompute(pContext
, workerId
, curDrawBE
);
827 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
831 curDrawBE
= curDrawFE
;
838 template<> DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
840 template <bool IsFEThread
, bool IsBEThread
>
841 DWORD
workerThreadInit(LPVOID pData
)
847 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
851 __except(EXCEPTION_CONTINUE_SEARCH
)
859 template<> DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
861 //////////////////////////////////////////////////////////////////////////
862 /// @brief Creates thread pool info but doesn't launch threads.
863 /// @param pContext - pointer to context
864 /// @param pPool - pointer to thread pool object.
865 void CreateThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
867 bindThread(pContext
, 0);
870 uint32_t numThreadsPerProcGroup
= 0;
871 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
873 uint32_t numHWNodes
= (uint32_t)nodes
.size();
874 uint32_t numHWCoresPerNode
= (uint32_t)nodes
[0].cores
.size();
875 uint32_t numHWHyperThreads
= (uint32_t)nodes
[0].cores
[0].threadIds
.size();
877 // Calculate num HW threads. Due to asymmetric topologies, this is not
878 // a trivial multiplication.
879 uint32_t numHWThreads
= 0;
880 for (auto& node
: nodes
)
882 for (auto& core
: node
.cores
)
884 numHWThreads
+= (uint32_t)core
.threadIds
.size();
888 uint32_t numNodes
= numHWNodes
;
889 uint32_t numCoresPerNode
= numHWCoresPerNode
;
890 uint32_t numHyperThreads
= numHWHyperThreads
;
892 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
894 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
897 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
899 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
902 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
904 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
907 #if defined(_WIN32) && !defined(_WIN64)
908 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
910 // Limit 32-bit windows to bindable HW threads only
911 if ((numCoresPerNode
* numHWHyperThreads
) > 32)
913 numCoresPerNode
= 32 / numHWHyperThreads
;
918 // Calculate numThreads
919 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
920 numThreads
= std::min(numThreads
, numHWThreads
);
922 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
924 uint32_t maxHWThreads
= numHWNodes
* numHWCoresPerNode
* numHWHyperThreads
;
925 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, maxHWThreads
);
928 uint32_t numAPIReservedThreads
= 1;
933 // If only 1 worker threads, try to move it to an available
934 // HW thread. If that fails, use the API thread.
935 if (numCoresPerNode
< numHWCoresPerNode
)
939 else if (numHyperThreads
< numHWHyperThreads
)
943 else if (numNodes
< numHWNodes
)
949 pContext
->threadInfo
.SINGLE_THREADED
= true;
954 // Save HW threads for the API if we can
955 if (numThreads
> numAPIReservedThreads
)
957 numThreads
-= numAPIReservedThreads
;
961 numAPIReservedThreads
= 0;
965 if (pContext
->threadInfo
.SINGLE_THREADED
)
970 // Initialize DRAW_CONTEXT's per-thread stats
971 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
973 pContext
->dcRing
[dc
].dynState
.pStats
= new SWR_STATS
[numThreads
];
974 memset(pContext
->dcRing
[dc
].dynState
.pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
977 if (pContext
->threadInfo
.SINGLE_THREADED
)
979 pContext
->NumWorkerThreads
= 1;
980 pContext
->NumFEThreads
= 1;
981 pContext
->NumBEThreads
= 1;
982 pPool
->numThreads
= 0;
987 pPool
->numThreads
= numThreads
;
988 pContext
->NumWorkerThreads
= pPool
->numThreads
;
990 pPool
->pThreadData
= (THREAD_DATA
*)malloc(pPool
->numThreads
* sizeof(THREAD_DATA
));
993 pPool
->pThreads
= new THREAD_PTR
[pPool
->numThreads
];
995 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
997 bool bForceBindProcGroup
= (numThreads
> numThreadsPerProcGroup
);
998 uint32_t numProcGroups
= (numThreads
+ numThreadsPerProcGroup
- 1) / numThreadsPerProcGroup
;
999 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
1000 // But Windows will still require binding to specific process groups
1001 for (uint32_t workerId
= 0; workerId
< numThreads
; ++workerId
)
1003 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1004 pPool
->pThreadData
[workerId
].procGroupId
= workerId
% numProcGroups
;
1005 pPool
->pThreadData
[workerId
].threadId
= 0;
1006 pPool
->pThreadData
[workerId
].numaId
= 0;
1007 pPool
->pThreadData
[workerId
].coreId
= 0;
1008 pPool
->pThreadData
[workerId
].htId
= 0;
1009 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1010 pPool
->pThreadData
[workerId
].forceBindProcGroup
= bForceBindProcGroup
;
1012 pContext
->NumBEThreads
++;
1013 pContext
->NumFEThreads
++;
1018 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
1020 uint32_t workerId
= 0;
1021 for (uint32_t n
= 0; n
< numNodes
; ++n
)
1023 auto& node
= nodes
[n
];
1024 uint32_t numCores
= numCoresPerNode
;
1025 for (uint32_t c
= 0; c
< numCores
; ++c
)
1027 if (c
>= node
.cores
.size())
1032 auto& core
= node
.cores
[c
];
1033 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
1035 if (t
>= core
.threadIds
.size())
1040 if (numAPIReservedThreads
)
1042 --numAPIReservedThreads
;
1046 SWR_ASSERT(workerId
< numThreads
);
1048 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1049 pPool
->pThreadData
[workerId
].procGroupId
= core
.procGroup
;
1050 pPool
->pThreadData
[workerId
].threadId
= core
.threadIds
[t
];
1051 pPool
->pThreadData
[workerId
].numaId
= node
.numaId
;
1052 pPool
->pThreadData
[workerId
].coreId
= c
;
1053 pPool
->pThreadData
[workerId
].htId
= t
;
1054 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1056 pContext
->NumBEThreads
++;
1057 pContext
->NumFEThreads
++;
1063 SWR_ASSERT(workerId
== pContext
->NumWorkerThreads
);
1067 //////////////////////////////////////////////////////////////////////////
1068 /// @brief Launches worker threads in thread pool.
1069 /// @param pContext - pointer to context
1070 /// @param pPool - pointer to thread pool object.
1071 void StartThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1073 if (pContext
->threadInfo
.SINGLE_THREADED
)
1078 for (uint32_t workerId
= 0; workerId
< pContext
->NumWorkerThreads
; ++workerId
)
1080 pPool
->pThreads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
1084 //////////////////////////////////////////////////////////////////////////
1085 /// @brief Destroys thread pool.
1086 /// @param pContext - pointer to context
1087 /// @param pPool - pointer to thread pool object.
1088 void DestroyThreadPool(SWR_CONTEXT
*pContext
, THREAD_POOL
*pPool
)
1090 if (!pContext
->threadInfo
.SINGLE_THREADED
)
1092 // Wait for all threads to finish
1093 SwrWaitForIdle(pContext
);
1095 // Wait for threads to finish and destroy them
1096 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
1098 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1099 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1100 pPool
->pThreads
[t
]->detach();
1101 delete(pPool
->pThreads
[t
]);
1104 delete [] pPool
->pThreads
;
1106 // Clean up data used by threads
1107 free(pPool
->pThreadData
);