1 /****************************************************************************
2 * Copyright (C) 2014-2018 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__)
40 #include <sys/types.h>
41 #include <sys/sysctl.h>
44 #include "common/os.h"
49 #include "rasterizer.h"
50 #include "rdtsc_core.h"
59 uint32_t procGroup
= 0;
60 std::vector
<uint32_t> threadIds
;
66 std::vector
<Core
> cores
;
69 typedef std::vector
<NumaNode
> CPUNumaNodes
;
71 void CalculateProcessorTopology(CPUNumaNodes
& out_nodes
, uint32_t& out_numThreadsPerProcGroup
)
74 out_numThreadsPerProcGroup
= 0;
78 std::vector
<KAFFINITY
> threadMaskPerProcGroup
;
81 std::lock_guard
<std::mutex
> l(m
);
85 BOOL ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, nullptr, &bufSize
);
86 SWR_ASSERT(ret
== FALSE
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
);
88 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBufferMem
= (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX
)malloc(bufSize
);
89 SWR_ASSERT(pBufferMem
);
91 ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, pBufferMem
, &bufSize
);
92 SWR_ASSERT(ret
!= FALSE
, "Failed to get Processor Topology Information");
94 uint32_t count
= bufSize
/ pBufferMem
->Size
;
95 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBuffer
= pBufferMem
;
97 for (uint32_t i
= 0; i
< count
; ++i
)
99 SWR_ASSERT(pBuffer
->Relationship
== RelationProcessorCore
);
100 for (uint32_t g
= 0; g
< pBuffer
->Processor
.GroupCount
; ++g
)
102 auto& gmask
= pBuffer
->Processor
.GroupMask
[g
];
103 uint32_t threadId
= 0;
104 uint32_t procGroup
= gmask
.Group
;
106 Core
* pCore
= nullptr;
108 uint32_t numThreads
= (uint32_t)_mm_popcount_sizeT(gmask
.Mask
);
110 while (BitScanForwardSizeT((unsigned long*)&threadId
, gmask
.Mask
))
113 KAFFINITY threadMask
= KAFFINITY(1) << threadId
;
114 gmask
.Mask
&= ~threadMask
;
116 if (procGroup
>= threadMaskPerProcGroup
.size())
118 threadMaskPerProcGroup
.resize(procGroup
+ 1);
121 if (threadMaskPerProcGroup
[procGroup
] & threadMask
)
123 // Already seen this mask. This means that we are in 32-bit mode and
124 // have seen more than 32 HW threads for this procGroup
127 SWR_INVALID("Shouldn't get here in 64-bit mode");
132 threadMaskPerProcGroup
[procGroup
] |= (KAFFINITY(1) << threadId
);
136 PROCESSOR_NUMBER procNum
= {};
137 procNum
.Group
= WORD(procGroup
);
138 procNum
.Number
= UCHAR(threadId
);
140 ret
= GetNumaProcessorNodeEx(&procNum
, (PUSHORT
)&numaId
);
144 if (out_nodes
.size() <= numaId
)
146 out_nodes
.resize(numaId
+ 1);
148 auto& numaNode
= out_nodes
[numaId
];
149 numaNode
.numaId
= numaId
;
153 if (nullptr == pCore
)
155 numaNode
.cores
.push_back(Core());
156 pCore
= &numaNode
.cores
.back();
157 pCore
->procGroup
= procGroup
;
159 pCore
->threadIds
.push_back(threadId
);
162 out_numThreadsPerProcGroup
++;
166 pBuffer
= PtrAdd(pBuffer
, pBuffer
->Size
);
172 #elif defined(__linux__) || defined (__gnu_linux__)
174 // Parse /proc/cpuinfo to get full topology
175 std::ifstream
input("/proc/cpuinfo");
178 uint32_t procId
= uint32_t(-1);
179 uint32_t coreId
= uint32_t(-1);
180 uint32_t physId
= uint32_t(-1);
182 while (std::getline(input
, line
))
184 if (line
.find("processor") != std::string::npos
)
186 auto data_start
= line
.find(": ") + 2;
187 procId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
190 if (line
.find("core id") != std::string::npos
)
192 auto data_start
= line
.find(": ") + 2;
193 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
196 if (line
.find("physical id") != std::string::npos
)
198 auto data_start
= line
.find(": ") + 2;
199 physId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
202 if (line
.length() == 0)
204 if (physId
+ 1 > out_nodes
.size())
205 out_nodes
.resize(physId
+ 1);
206 auto& numaNode
= out_nodes
[physId
];
207 numaNode
.numaId
= physId
;
209 if (coreId
+ 1 > numaNode
.cores
.size())
210 numaNode
.cores
.resize(coreId
+ 1);
211 auto& core
= numaNode
.cores
[coreId
];
212 core
.procGroup
= coreId
;
213 core
.threadIds
.push_back(procId
);
217 out_numThreadsPerProcGroup
= 0;
218 for (auto &node
: out_nodes
)
220 for (auto &core
: node
.cores
)
222 out_numThreadsPerProcGroup
+= core
.threadIds
.size();
226 #elif defined(__APPLE__)
228 auto numProcessors
= 0;
230 auto numPhysicalIds
= 0;
233 size_t size
= sizeof(value
);
235 int result
= sysctlbyname("hw.packages", &value
, &size
, NULL
, 0);
236 SWR_ASSERT(result
== 0);
237 numPhysicalIds
= value
;
239 result
= sysctlbyname("hw.logicalcpu", &value
, &size
, NULL
, 0);
240 SWR_ASSERT(result
== 0);
241 numProcessors
= value
;
243 result
= sysctlbyname("hw.physicalcpu", &value
, &size
, NULL
, 0);
244 SWR_ASSERT(result
== 0);
247 out_nodes
.resize(numPhysicalIds
);
249 for (auto physId
= 0; physId
< numPhysicalIds
; ++physId
)
251 auto &numaNode
= out_nodes
[physId
];
254 numaNode
.cores
.resize(numCores
);
256 while (procId
< numProcessors
)
258 for (auto coreId
= 0; coreId
< numaNode
.cores
.size(); ++coreId
, ++procId
)
260 auto &core
= numaNode
.cores
[coreId
];
262 core
.procGroup
= coreId
;
263 core
.threadIds
.push_back(procId
);
268 out_numThreadsPerProcGroup
= 0;
270 for (auto &node
: out_nodes
)
272 for (auto &core
: node
.cores
)
274 out_numThreadsPerProcGroup
+= core
.threadIds
.size();
280 #error Unsupported platform
284 // Prune empty cores and numa nodes
285 for (auto node_it
= out_nodes
.begin(); node_it
!= out_nodes
.end(); )
287 // Erase empty cores (first)
288 for (auto core_it
= node_it
->cores
.begin(); core_it
!= node_it
->cores
.end(); )
290 if (core_it
->threadIds
.size() == 0)
292 core_it
= node_it
->cores
.erase(core_it
);
300 // Erase empty numa nodes (second)
301 if (node_it
->cores
.size() == 0)
303 node_it
= out_nodes
.erase(node_it
);
312 void bindThread(SWR_CONTEXT
* pContext
, uint32_t threadId
, uint32_t procGroupId
= 0, bool bindProcGroup
=false)
314 // Only bind threads when MAX_WORKER_THREADS isn't set.
315 if (pContext
->threadInfo
.SINGLE_THREADED
|| (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false))
322 GROUP_AFFINITY affinity
= {};
323 affinity
.Group
= procGroupId
;
328 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
329 SWR_INVALID("Shouldn't get here");
331 // In a 32-bit process on Windows it is impossible to bind
332 // to logical processors 32-63 within a processor group.
333 // In this case set the mask to 0 and let the system assign
334 // the processor. Hopefully it will make smart choices.
340 // If MAX_WORKER_THREADS is set, only bind to the proc group,
341 // Not the individual HW thread.
342 if (!bindProcGroup
&& !pContext
->threadInfo
.MAX_WORKER_THREADS
)
344 affinity
.Mask
= KAFFINITY(1) << threadId
;
348 affinity
.Mask
= KAFFINITY(0);
352 if (!SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr))
354 SWR_INVALID("Failed to set Thread Affinity");
357 #elif defined(__linux__) || defined(__gnu_linux__)
360 pthread_t thread
= pthread_self();
362 CPU_SET(threadId
, &cpuset
);
364 int err
= pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
367 fprintf(stderr
, "pthread_setaffinity_np failure for tid %u: %s\n", threadId
, strerror(err
));
374 uint32_t GetEnqueuedDraw(SWR_CONTEXT
*pContext
)
376 return pContext
->dcRing
.GetHead();
380 DRAW_CONTEXT
*GetDC(SWR_CONTEXT
*pContext
, uint32_t drawId
)
382 return &pContext
->dcRing
[(drawId
-1) % pContext
->MAX_DRAWS_IN_FLIGHT
];
386 bool IDComparesLess(uint32_t a
, uint32_t b
)
388 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
389 int32_t delta
= int32_t(a
- b
);
393 // returns true if dependency not met
395 bool CheckDependency(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
397 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
400 bool CheckDependencyFE(SWR_CONTEXT
*pContext
, DRAW_CONTEXT
*pDC
, uint32_t lastRetiredDraw
)
402 return pDC
->dependentFE
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
405 //////////////////////////////////////////////////////////////////////////
406 /// @brief Update client stats.
407 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
409 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStatsBE
== false))
414 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
415 OSALIGNLINE(SWR_STATS
) stats
{ 0 };
417 // Sum up stats across all workers before sending to client.
418 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
420 stats
.DepthPassCount
+= dynState
.pStats
[i
].DepthPassCount
;
422 stats
.PsInvocations
+= dynState
.pStats
[i
].PsInvocations
;
423 stats
.CsInvocations
+= dynState
.pStats
[i
].CsInvocations
;
427 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
430 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
432 UpdateClientStats(pContext
, workerId
, pDC
);
434 if (pDC
->retireCallback
.pfnCallbackFunc
)
436 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
437 pDC
->retireCallback
.userData2
,
438 pDC
->retireCallback
.userData3
);
442 // inlined-only version
443 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
445 int32_t result
= static_cast<int32_t>(InterlockedDecrement(&pDC
->threadsDone
));
446 SWR_ASSERT(result
>= 0);
448 AR_FLUSH(pDC
->drawId
);
452 ExecuteCallbacks(pContext
, workerId
, pDC
);
454 // Cleanup memory allocations
455 pDC
->pArena
->Reset(true);
458 pDC
->pTileMgr
->initialize();
460 if (pDC
->cleanupState
)
462 pDC
->pState
->pArena
->Reset(true);
467 pContext
->dcRing
.Dequeue(); // Remove from tail
473 // available to other translation modules
474 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
476 return CompleteDrawContextInl(pContext
, 0, pDC
);
479 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
, uint32_t workerId
, uint32_t& curDrawBE
, uint32_t& drawEnqueued
)
481 // increment our current draw id to the first incomplete draw
482 drawEnqueued
= GetEnqueuedDraw(pContext
);
483 while (IDComparesLess(curDrawBE
, drawEnqueued
))
485 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
];
487 // If its not compute and FE is not done then break out of loop.
488 if (!pDC
->doneFE
&& !pDC
->isCompute
) break;
490 bool isWorkComplete
= pDC
->isCompute
?
491 pDC
->pDispatch
->isWorkComplete() :
492 pDC
->pTileMgr
->isWorkComplete();
497 CompleteDrawContextInl(pContext
, workerId
, pDC
);
505 // If there are no more incomplete draws then return false.
506 return IDComparesLess(curDrawBE
, drawEnqueued
);
509 //////////////////////////////////////////////////////////////////////////
510 /// @brief If there is any BE work then go work on it.
511 /// @param pContext - pointer to SWR context.
512 /// @param workerId - The unique worker ID that is assigned to this thread.
513 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
514 /// has its own curDrawBE counter and this ensures that each worker processes all the
516 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
517 /// own set and each time it fails to lock a macrotile, because its already locked,
518 /// then it will add that tile to the lockedTiles set. As a worker begins to work
519 /// on future draws the lockedTiles ensure that it doesn't work on tiles that may
520 /// still have work pending in a previous draw. Additionally, the lockedTiles is
521 /// hueristic that can steer a worker back to the same macrotile that it had been
522 /// working on in a previous draw.
523 /// @returns true if worker thread should shutdown
525 SWR_CONTEXT
*pContext
,
528 TileSet
& lockedTiles
,
532 bool bShutdown
= false;
534 // Find the first incomplete draw that has pending work. If no such draw is found then
535 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
536 uint32_t drawEnqueued
= 0;
537 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
542 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
544 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
547 // Try to work on each draw in order of the available draws in flight.
548 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
549 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
550 // working on those macrotiles that are known to be complete in the prior draw to
551 // maintain order. The locked tiles provides the history to ensures this.
552 for (uint32_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
554 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
556 if (pDC
->isCompute
) return false; // We don't look at compute work.
558 // First wait for FE to be finished with this draw. This keeps threading model simple
559 // but if there are lots of bubbles between draws then serializing FE and BE may
560 // need to be revisited.
561 if (!pDC
->doneFE
) return false;
563 // If this draw is dependent on a previous draw then we need to bail.
564 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
569 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
570 auto ¯oTiles
= pDC
->pTileMgr
->getDirtyTiles();
572 for (auto tile
: macroTiles
)
574 uint32_t tileID
= tile
->mId
;
576 // Only work on tiles for this numa node
578 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
579 if (((x
^ y
) & numaMask
) != numaNode
)
584 if (!tile
->getNumQueued())
589 // can only work on this draw if it's not in use by other threads
590 if (lockedTiles
.find(tileID
) != lockedTiles
.end())
599 RDTSC_BEGIN(WorkerFoundWork
, pDC
->drawId
);
601 uint32_t numWorkItems
= tile
->getNumQueued();
602 SWR_ASSERT(numWorkItems
);
604 pWork
= tile
->peek();
606 if (pWork
->type
== DRAW
)
608 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, workerId
, tileID
);
610 else if (pWork
->type
== SHUTDOWN
)
615 while ((pWork
= tile
->peek()) != nullptr)
617 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
620 RDTSC_END(WorkerFoundWork
, numWorkItems
);
624 pDC
->pTileMgr
->markTileComplete(tileID
);
626 // Optimization: If the draw is complete and we're the last one to have worked on it then
627 // we can reset the locked list as we know that all previous draws before the next are guaranteed to be complete.
628 if ((curDrawBE
== i
) && (bShutdown
|| pDC
->pTileMgr
->isWorkComplete()))
630 // We can increment the current BE and safely move to next draw since we know this draw is complete.
632 CompleteDrawContextInl(pContext
, workerId
, pDC
);
647 // 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.
648 lockedTiles
.insert(tileID
);
656 //////////////////////////////////////////////////////////////////////////
657 /// @brief Called when FE work is complete for this DC.
658 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
660 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStatsFE
)
662 SWR_STATS_FE
& stats
= pDC
->dynState
.statsFE
;
664 AR_EVENT(FrontendStatsEvent(pDC
->drawId
,
665 stats
.IaVertices
, stats
.IaPrimitives
, stats
.VsInvocations
, stats
.HsInvocations
,
666 stats
.DsInvocations
, stats
.GsInvocations
, stats
.GsPrimitives
, stats
.CInvocations
, stats
.CPrimitives
,
667 stats
.SoPrimStorageNeeded
[0], stats
.SoPrimStorageNeeded
[1], stats
.SoPrimStorageNeeded
[2], stats
.SoPrimStorageNeeded
[3],
668 stats
.SoNumPrimsWritten
[0], stats
.SoNumPrimsWritten
[1], stats
.SoNumPrimsWritten
[2], stats
.SoNumPrimsWritten
[3]
670 AR_EVENT(FrontendDrawEndEvent(pDC
->drawId
));
672 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &stats
);
675 if (pContext
->pfnUpdateSoWriteOffset
)
677 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
679 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
680 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
682 pContext
->pfnUpdateSoWriteOffset(GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
687 // Ensure all streaming writes are globally visible before marking this FE done
691 InterlockedDecrement(&pContext
->drawsOutstandingFE
);
694 void WorkOnFifoFE(SWR_CONTEXT
*pContext
, uint32_t workerId
, uint32_t &curDrawFE
)
696 // Try to grab the next DC from the ring
697 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
698 while (IDComparesLess(curDrawFE
, drawEnqueued
))
700 uint32_t dcSlot
= curDrawFE
% pContext
->MAX_DRAWS_IN_FLIGHT
;
701 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
702 if (pDC
->isCompute
|| pDC
->doneFE
)
704 CompleteDrawContextInl(pContext
, workerId
, pDC
);
713 uint32_t lastRetiredFE
= curDrawFE
- 1;
714 uint32_t curDraw
= curDrawFE
;
715 while (IDComparesLess(curDraw
, drawEnqueued
))
717 uint32_t dcSlot
= curDraw
% pContext
->MAX_DRAWS_IN_FLIGHT
;
718 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[dcSlot
];
720 if (!pDC
->isCompute
&& !pDC
->FeLock
)
722 if (CheckDependencyFE(pContext
, pDC
, lastRetiredFE
))
727 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
730 // successfully grabbed the DC, now run the FE
731 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
733 CompleteDrawFE(pContext
, workerId
, pDC
);
740 //////////////////////////////////////////////////////////////////////////
741 /// @brief If there is any compute work then go work on it.
742 /// @param pContext - pointer to SWR context.
743 /// @param workerId - The unique worker ID that is assigned to this thread.
744 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker thread
745 /// has its own curDrawBE counter and this ensures that each worker processes all the
748 SWR_CONTEXT
*pContext
,
752 uint32_t drawEnqueued
= 0;
753 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
758 uint32_t lastRetiredDraw
= pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
760 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
762 DRAW_CONTEXT
*pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
763 if (pDC
->isCompute
== false) return;
765 // check dependencies
766 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
771 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
772 DispatchQueue
& queue
= *pDC
->pDispatch
;
774 // Is there any work remaining?
775 if (queue
.getNumQueued() > 0)
777 void* pSpillFillBuffer
= nullptr;
778 void* pScratchSpace
= nullptr;
779 uint32_t threadGroupId
= 0;
780 while (queue
.getWork(threadGroupId
))
782 queue
.dispatch(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
, pScratchSpace
);
783 queue
.finishedWork();
786 // Ensure all streaming writes are globally visible before moving onto the next draw
792 void BindApiThread(SWR_CONTEXT
*pContext
, uint32_t apiThreadId
)
794 if (nullptr == pContext
)
799 if (apiThreadId
>= pContext
->threadPool
.numReservedThreads
)
801 if (pContext
->threadPool
.numReservedThreads
)
803 const THREAD_DATA
&threadData
= pContext
->threadPool
.pApiThreadData
[0];
804 // Just bind to the process group used for API thread 0
805 bindThread(pContext
, 0, threadData
.procGroupId
, true);
810 const THREAD_DATA
&threadData
= pContext
->threadPool
.pApiThreadData
[apiThreadId
];
812 bindThread(pContext
, threadData
.threadId
, threadData
.procGroupId
, threadData
.forceBindProcGroup
);
815 template<bool IsFEThread
, bool IsBEThread
>
816 DWORD
workerThreadMain(LPVOID pData
)
818 THREAD_DATA
*pThreadData
= (THREAD_DATA
*)pData
;
819 SWR_CONTEXT
*pContext
= pThreadData
->pContext
;
820 uint32_t threadId
= pThreadData
->threadId
;
821 uint32_t workerId
= pThreadData
->workerId
;
823 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
827 sprintf_s(threadName
,
829 "SWRWorker_%02d_NUMA%d_Core%02d_T%d",
831 // linux pthread name limited to 16 chars (including \0)
832 "w%03d-n%d-c%03d-t%d",
834 workerId
, pThreadData
->numaId
, pThreadData
->coreId
, pThreadData
->htId
);
835 SetCurrentThreadName(threadName
);
838 RDTSC_INIT(threadId
);
840 // Only need offset numa index from base for correct masking
841 uint32_t numaNode
= pThreadData
->numaId
- pContext
->threadInfo
.BASE_NUMA_NODE
;
842 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
844 // flush denormals to 0
845 _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
847 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
848 // locked then we'll add it to this list so that we don't try and lock it again.
851 // each worker has the ability to work on any of the queued draws as long as certain
852 // conditions are met. the data associated
853 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
854 // has moved on to the next draw when he determines there is no more work to do. The api
855 // thread will not increment the head of the dc ring until all workers have moved past the
857 // the logic to determine what to work on is:
858 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
859 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
860 // we'll need dependency tracking to force serialization on FEs. The worker will try
861 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
862 // trying until he reaches the tail.
863 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
864 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
865 // any work left by comparing the total # of binned work items and the total # of completed
866 // work items. If they are equal, then there is no more work to do for this draw, and
867 // the worker can safely increment its oldestDraw counter and move on to the next draw.
868 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
, std::defer_lock
);
870 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
872 uint32_t curDrawBE
= 0;
873 uint32_t curDrawFE
= 0;
875 bool bShutdown
= false;
879 if (bShutdown
&& !threadHasWork(curDrawBE
))
885 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
890 if (!threadHasWork(curDrawBE
))
894 // check for thread idle condition again under lock
895 if (threadHasWork(curDrawBE
))
901 pContext
->FifosNotEmpty
.wait(lock
);
907 RDTSC_BEGIN(WorkerWorkOnFifoBE
, 0);
908 bShutdown
|= WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
909 RDTSC_END(WorkerWorkOnFifoBE
, 0);
911 WorkOnCompute(pContext
, workerId
, curDrawBE
);
916 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
920 curDrawBE
= curDrawFE
;
927 template<> DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
929 template <bool IsFEThread
, bool IsBEThread
>
930 DWORD
workerThreadInit(LPVOID pData
)
936 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
940 __except(EXCEPTION_CONTINUE_SEARCH
)
948 template<> DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
950 static void InitPerThreadStats(SWR_CONTEXT
* pContext
, uint32_t numThreads
)
952 // Initialize DRAW_CONTEXT's per-thread stats
953 for (uint32_t dc
= 0; dc
< pContext
->MAX_DRAWS_IN_FLIGHT
; ++dc
)
955 pContext
->dcRing
[dc
].dynState
.pStats
= (SWR_STATS
*)AlignedMalloc(sizeof(SWR_STATS
) * numThreads
, 64);
956 memset(pContext
->dcRing
[dc
].dynState
.pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
960 //////////////////////////////////////////////////////////////////////////
961 /// @brief Creates thread pool info but doesn't launch threads.
962 /// @param pContext - pointer to context
963 /// @param pPool - pointer to thread pool object.
964 void CreateThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
967 uint32_t numThreadsPerProcGroup
= 0;
968 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
970 // Assumption, for asymmetric topologies, multi-threaded cores will appear
971 // in the list before single-threaded cores. This appears to be true for
972 // Windows when the total HW threads is limited to 64.
973 uint32_t numHWNodes
= (uint32_t)nodes
.size();
974 uint32_t numHWCoresPerNode
= (uint32_t)nodes
[0].cores
.size();
975 uint32_t numHWHyperThreads
= (uint32_t)nodes
[0].cores
[0].threadIds
.size();
977 #if defined(_WIN32) && !defined(_WIN64)
978 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
980 // Limit 32-bit windows to bindable HW threads only
981 if ((numHWCoresPerNode
* numHWHyperThreads
) > 32)
983 numHWCoresPerNode
= 32 / numHWHyperThreads
;
988 // Calculate num HW threads. Due to asymmetric topologies, this is not
989 // a trivial multiplication.
990 uint32_t numHWThreads
= 0;
991 for (auto const& node
: nodes
)
993 for (auto const& core
: node
.cores
)
995 numHWThreads
+= (uint32_t)core
.threadIds
.size();
999 uint32_t numNodes
= numHWNodes
;
1000 uint32_t numCoresPerNode
= numHWCoresPerNode
;
1001 uint32_t numHyperThreads
= numHWHyperThreads
;
1003 // Calc used threads per-core
1004 if (numHyperThreads
> pContext
->threadInfo
.BASE_THREAD
)
1006 numHyperThreads
-= pContext
->threadInfo
.BASE_THREAD
;
1012 "Cannot use BASE_THREAD value: %d, maxThreads: %d, reverting BASE_THREAD to 0",
1013 pContext
->threadInfo
.BASE_THREAD
,
1015 pContext
->threadInfo
.BASE_THREAD
= 0;
1018 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
1020 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
1023 // Prune any cores that don't support the number of threads
1024 if (numHyperThreads
> 1)
1026 for (auto& node
: nodes
)
1028 uint32_t numUsableCores
= 0;
1029 for (auto& core
: node
.cores
)
1031 numUsableCores
+= (core
.threadIds
.size() >= numHyperThreads
);
1033 numCoresPerNode
= std::min(numCoresPerNode
, numUsableCores
);
1037 // Calc used cores per NUMA node
1038 if (numCoresPerNode
> pContext
->threadInfo
.BASE_CORE
)
1040 numCoresPerNode
-= pContext
->threadInfo
.BASE_CORE
;
1046 "Cannot use BASE_CORE value: %d, maxCores: %d, reverting BASE_CORE to 0",
1047 pContext
->threadInfo
.BASE_CORE
,
1049 pContext
->threadInfo
.BASE_CORE
= 0;
1052 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
1054 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
1057 // Calc used NUMA nodes
1058 if (numNodes
> pContext
->threadInfo
.BASE_NUMA_NODE
)
1060 numNodes
-= pContext
->threadInfo
.BASE_NUMA_NODE
;
1066 "Cannot use BASE_NUMA_NODE value: %d, maxNodes: %d, reverting BASE_NUMA_NODE to 0",
1067 pContext
->threadInfo
.BASE_NUMA_NODE
,
1069 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1072 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
1074 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
1077 // Calculate numThreads - at this point everything should be symmetric
1078 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
1079 SWR_REL_ASSERT(numThreads
<= numHWThreads
);
1081 uint32_t& numAPIReservedThreads
= pContext
->apiThreadInfo
.numAPIReservedThreads
;
1082 uint32_t& numAPIThreadsPerCore
= pContext
->apiThreadInfo
.numAPIThreadsPerCore
;
1083 uint32_t numRemovedThreads
= 0;
1085 if (pContext
->threadInfo
.SINGLE_THREADED
)
1087 numAPIReservedThreads
= 0;
1089 pContext
->NumWorkerThreads
= 1;
1090 pContext
->NumFEThreads
= 1;
1091 pContext
->NumBEThreads
= 1;
1092 pPool
->numThreads
= 0;
1094 else if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1096 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, numHWThreads
);
1097 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1098 pContext
->threadInfo
.BASE_CORE
= 0;
1099 pContext
->threadInfo
.BASE_THREAD
= 0;
1100 numAPIReservedThreads
= 0;
1104 if (numAPIReservedThreads
>= numThreads
)
1106 numAPIReservedThreads
= 0;
1108 else if (numAPIReservedThreads
)
1110 numAPIThreadsPerCore
= std::min(numAPIThreadsPerCore
, numHWHyperThreads
);
1112 if (0 == numAPIThreadsPerCore
)
1114 numAPIThreadsPerCore
= numHWHyperThreads
;
1117 numRemovedThreads
= numAPIReservedThreads
;
1118 if (numAPIThreadsPerCore
== 2 && numHyperThreads
== 1)
1120 // Adjust removed threads to make logic below work
1121 numRemovedThreads
= std::max(1U, (numRemovedThreads
+ numAPIThreadsPerCore
- 1) / 2);
1124 numThreads
-= numRemovedThreads
;
1128 InitPerThreadStats(pContext
, numThreads
);
1130 if (pContext
->threadInfo
.SINGLE_THREADED
)
1132 numAPIReservedThreads
= 0;
1136 if (numAPIReservedThreads
)
1138 pPool
->pApiThreadData
= new (std::nothrow
) THREAD_DATA
[numAPIReservedThreads
];
1139 SWR_ASSERT(pPool
->pApiThreadData
);
1140 if (!pPool
->pApiThreadData
)
1142 numAPIReservedThreads
= 0;
1146 memset(pPool
->pApiThreadData
, 0, sizeof(THREAD_DATA
) * numAPIReservedThreads
);
1149 pPool
->numReservedThreads
= numAPIReservedThreads
;
1151 pPool
->numThreads
= numThreads
;
1152 pContext
->NumWorkerThreads
= pPool
->numThreads
;
1154 pPool
->pThreadData
= new (std::nothrow
) THREAD_DATA
[pPool
->numThreads
];
1155 SWR_ASSERT(pPool
->pThreadData
);
1156 memset(pPool
->pThreadData
, 0, sizeof(THREAD_DATA
) * pPool
->numThreads
);
1157 pPool
->numaMask
= 0;
1159 // Allocate worker private data
1160 pPool
->pWorkerPrivateDataArray
= nullptr;
1161 if (pContext
->workerPrivateState
.perWorkerPrivateStateSize
)
1163 size_t perWorkerSize
= AlignUpPow2(pContext
->workerPrivateState
.perWorkerPrivateStateSize
, 64);
1164 size_t totalSize
= perWorkerSize
* pPool
->numThreads
;
1167 pPool
->pWorkerPrivateDataArray
= AlignedMalloc(totalSize
, 64);
1168 SWR_ASSERT(pPool
->pWorkerPrivateDataArray
);
1170 void* pWorkerData
= pPool
->pWorkerPrivateDataArray
;
1171 for (uint32_t i
= 0; i
< pPool
->numThreads
; ++i
)
1173 pPool
->pThreadData
[i
].pWorkerPrivateData
= pWorkerData
;
1174 if (pContext
->workerPrivateState
.pfnInitWorkerData
)
1176 pContext
->workerPrivateState
.pfnInitWorkerData(pWorkerData
, i
);
1178 pWorkerData
= PtrAdd(pWorkerData
, perWorkerSize
);
1183 if (pContext
->threadInfo
.SINGLE_THREADED
)
1188 pPool
->pThreads
= new (std::nothrow
) THREAD_PTR
[pPool
->numThreads
];
1189 SWR_ASSERT(pPool
->pThreads
);
1191 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1193 bool bForceBindProcGroup
= (numThreads
> numThreadsPerProcGroup
);
1194 uint32_t numProcGroups
= (numThreads
+ numThreadsPerProcGroup
- 1) / numThreadsPerProcGroup
;
1195 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
1196 // But Windows will still require binding to specific process groups
1197 for (uint32_t workerId
= 0; workerId
< numThreads
; ++workerId
)
1199 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1200 pPool
->pThreadData
[workerId
].procGroupId
= workerId
% numProcGroups
;
1201 pPool
->pThreadData
[workerId
].threadId
= 0;
1202 pPool
->pThreadData
[workerId
].numaId
= 0;
1203 pPool
->pThreadData
[workerId
].coreId
= 0;
1204 pPool
->pThreadData
[workerId
].htId
= 0;
1205 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1206 pPool
->pThreadData
[workerId
].forceBindProcGroup
= bForceBindProcGroup
;
1208 pContext
->NumBEThreads
++;
1209 pContext
->NumFEThreads
++;
1214 // numa distribution assumes workers on all nodes
1215 bool useNuma
= true;
1216 if (numCoresPerNode
* numHyperThreads
== 1)
1223 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
1227 pPool
->numaMask
= 0;
1230 uint32_t workerId
= 0;
1231 uint32_t numReservedThreads
= numAPIReservedThreads
;
1232 for (uint32_t n
= 0; n
< numNodes
; ++n
)
1234 if ((n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) >= nodes
.size())
1238 auto& node
= nodes
[n
+ pContext
->threadInfo
.BASE_NUMA_NODE
];
1239 uint32_t numCores
= numCoresPerNode
;
1240 for (uint32_t c
= 0; c
< numCores
; ++c
)
1242 if ((c
+ pContext
->threadInfo
.BASE_CORE
) >= node
.cores
.size())
1247 auto& core
= node
.cores
[c
+ pContext
->threadInfo
.BASE_CORE
];
1248 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
1250 if ((t
+ pContext
->threadInfo
.BASE_THREAD
) >= core
.threadIds
.size())
1255 if (numRemovedThreads
)
1257 --numRemovedThreads
;
1258 SWR_REL_ASSERT(numReservedThreads
);
1259 --numReservedThreads
;
1260 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1261 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1262 pPool
->pApiThreadData
[numReservedThreads
].threadId
= core
.threadIds
[t
];
1263 pPool
->pApiThreadData
[numReservedThreads
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1264 pPool
->pApiThreadData
[numReservedThreads
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1265 pPool
->pApiThreadData
[numReservedThreads
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1266 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1267 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1270 if (numAPIThreadsPerCore
> numHyperThreads
&& numReservedThreads
)
1272 --numReservedThreads
;
1273 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1274 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1275 pPool
->pApiThreadData
[numReservedThreads
].threadId
= core
.threadIds
[t
+ 1];
1276 pPool
->pApiThreadData
[numReservedThreads
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1277 pPool
->pApiThreadData
[numReservedThreads
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1278 pPool
->pApiThreadData
[numReservedThreads
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1279 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1280 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1286 SWR_ASSERT(workerId
< numThreads
);
1288 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1289 pPool
->pThreadData
[workerId
].procGroupId
= core
.procGroup
;
1290 pPool
->pThreadData
[workerId
].threadId
= core
.threadIds
[t
+ pContext
->threadInfo
.BASE_THREAD
];
1291 pPool
->pThreadData
[workerId
].numaId
= useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1292 pPool
->pThreadData
[workerId
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1293 pPool
->pThreadData
[workerId
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1294 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1295 pPool
->pThreadData
[workerId
].forceBindProcGroup
= false;
1297 pContext
->NumBEThreads
++;
1298 pContext
->NumFEThreads
++;
1304 SWR_ASSERT(workerId
== pContext
->NumWorkerThreads
);
1308 //////////////////////////////////////////////////////////////////////////
1309 /// @brief Launches worker threads in thread pool.
1310 /// @param pContext - pointer to context
1311 /// @param pPool - pointer to thread pool object.
1312 void StartThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1314 if (pContext
->threadInfo
.SINGLE_THREADED
)
1319 for (uint32_t workerId
= 0; workerId
< pContext
->NumWorkerThreads
; ++workerId
)
1321 pPool
->pThreads
[workerId
] = new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
1325 //////////////////////////////////////////////////////////////////////////
1326 /// @brief Destroys thread pool.
1327 /// @param pContext - pointer to context
1328 /// @param pPool - pointer to thread pool object.
1329 void DestroyThreadPool(SWR_CONTEXT
*pContext
, THREAD_POOL
*pPool
)
1331 // Wait for all threads to finish
1332 SwrWaitForIdle(pContext
);
1334 // Wait for threads to finish and destroy them
1335 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
1337 if (!pContext
->threadInfo
.SINGLE_THREADED
)
1339 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1340 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1341 pPool
->pThreads
[t
]->detach();
1342 delete(pPool
->pThreads
[t
]);
1345 if (pContext
->workerPrivateState
.pfnFinishWorkerData
)
1347 pContext
->workerPrivateState
.pfnFinishWorkerData(pPool
->pThreadData
[t
].pWorkerPrivateData
, t
);
1351 delete[] pPool
->pThreads
;
1353 // Clean up data used by threads
1354 delete[] pPool
->pThreadData
;
1355 delete[] pPool
->pApiThreadData
;
1357 AlignedFree(pPool
->pWorkerPrivateDataArray
);