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"
58 uint32_t procGroup
= 0;
59 std::vector
<uint32_t> threadIds
;
65 std::vector
<Core
> cores
;
68 typedef std::vector
<NumaNode
> CPUNumaNodes
;
70 void CalculateProcessorTopology(CPUNumaNodes
& out_nodes
, uint32_t& out_numThreadsPerProcGroup
)
73 out_numThreadsPerProcGroup
= 0;
77 std::vector
<KAFFINITY
> threadMaskPerProcGroup
;
80 std::lock_guard
<std::mutex
> l(m
);
84 BOOL ret
= GetLogicalProcessorInformationEx(RelationProcessorCore
, nullptr, &bufSize
);
85 SWR_ASSERT(ret
== FALSE
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
);
87 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pBufferMem
=
88 (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 while (BitScanForwardSizeT((unsigned long*)&threadId
, gmask
.Mask
))
111 KAFFINITY threadMask
= KAFFINITY(1) << threadId
;
112 gmask
.Mask
&= ~threadMask
;
114 if (procGroup
>= threadMaskPerProcGroup
.size())
116 threadMaskPerProcGroup
.resize(procGroup
+ 1);
119 if (threadMaskPerProcGroup
[procGroup
] & threadMask
)
121 // Already seen this mask. This means that we are in 32-bit mode and
122 // have seen more than 32 HW threads for this procGroup
125 SWR_INVALID("Shouldn't get here in 64-bit mode");
130 threadMaskPerProcGroup
[procGroup
] |= (KAFFINITY(1) << threadId
);
134 PROCESSOR_NUMBER procNum
= {};
135 procNum
.Group
= WORD(procGroup
);
136 procNum
.Number
= UCHAR(threadId
);
138 ret
= GetNumaProcessorNodeEx(&procNum
, (PUSHORT
)&numaId
);
142 if (out_nodes
.size() <= numaId
)
144 out_nodes
.resize(numaId
+ 1);
146 auto& numaNode
= out_nodes
[numaId
];
147 numaNode
.numaId
= numaId
;
149 if (nullptr == pCore
)
151 numaNode
.cores
.push_back(Core());
152 pCore
= &numaNode
.cores
.back();
153 pCore
->procGroup
= procGroup
;
155 pCore
->threadIds
.push_back(threadId
);
158 out_numThreadsPerProcGroup
++;
162 pBuffer
= PtrAdd(pBuffer
, pBuffer
->Size
);
167 #elif defined(__linux__) || defined(__gnu_linux__)
169 // Parse /proc/cpuinfo to get full topology
170 std::ifstream
input("/proc/cpuinfo");
173 uint32_t procId
= uint32_t(-1);
174 uint32_t coreId
= uint32_t(-1);
175 uint32_t physId
= uint32_t(-1);
177 while (std::getline(input
, line
))
179 if (line
.find("processor") != std::string::npos
)
181 auto data_start
= line
.find(": ") + 2;
182 procId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
185 if (line
.find("core id") != std::string::npos
)
187 auto data_start
= line
.find(": ") + 2;
188 coreId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
191 if (line
.find("physical id") != std::string::npos
)
193 auto data_start
= line
.find(": ") + 2;
194 physId
= std::strtoul(&line
.c_str()[data_start
], &c
, 10);
197 if (line
.length() == 0)
199 if (physId
+ 1 > out_nodes
.size())
200 out_nodes
.resize(physId
+ 1);
201 auto& numaNode
= out_nodes
[physId
];
202 numaNode
.numaId
= physId
;
204 if (coreId
+ 1 > numaNode
.cores
.size())
205 numaNode
.cores
.resize(coreId
+ 1);
206 auto& core
= numaNode
.cores
[coreId
];
207 core
.procGroup
= coreId
;
208 core
.threadIds
.push_back(procId
);
212 out_numThreadsPerProcGroup
= 0;
213 for (auto& node
: out_nodes
)
215 for (auto& core
: node
.cores
)
217 out_numThreadsPerProcGroup
+= core
.threadIds
.size();
221 #elif defined(__APPLE__)
223 auto numProcessors
= 0;
225 auto numPhysicalIds
= 0;
228 size_t size
= sizeof(value
);
230 int result
= sysctlbyname("hw.packages", &value
, &size
, NULL
, 0);
231 SWR_ASSERT(result
== 0);
232 numPhysicalIds
= value
;
234 result
= sysctlbyname("hw.logicalcpu", &value
, &size
, NULL
, 0);
235 SWR_ASSERT(result
== 0);
236 numProcessors
= value
;
238 result
= sysctlbyname("hw.physicalcpu", &value
, &size
, NULL
, 0);
239 SWR_ASSERT(result
== 0);
242 out_nodes
.resize(numPhysicalIds
);
244 for (auto physId
= 0; physId
< numPhysicalIds
; ++physId
)
246 auto& numaNode
= out_nodes
[physId
];
249 numaNode
.cores
.resize(numCores
);
251 while (procId
< numProcessors
)
253 for (auto coreId
= 0; coreId
< numaNode
.cores
.size(); ++coreId
, ++procId
)
255 auto& core
= numaNode
.cores
[coreId
];
257 core
.procGroup
= coreId
;
258 core
.threadIds
.push_back(procId
);
263 out_numThreadsPerProcGroup
= 0;
265 for (auto& node
: out_nodes
)
267 for (auto& core
: node
.cores
)
269 out_numThreadsPerProcGroup
+= core
.threadIds
.size();
275 #error Unsupported platform
279 // Prune empty cores and numa nodes
280 for (auto node_it
= out_nodes
.begin(); node_it
!= out_nodes
.end();)
282 // Erase empty cores (first)
283 for (auto core_it
= node_it
->cores
.begin(); core_it
!= node_it
->cores
.end();)
285 if (core_it
->threadIds
.size() == 0)
287 core_it
= node_it
->cores
.erase(core_it
);
295 // Erase empty numa nodes (second)
296 if (node_it
->cores
.size() == 0)
298 node_it
= out_nodes
.erase(node_it
);
307 void bindThread(SWR_CONTEXT
* pContext
,
309 uint32_t procGroupId
= 0,
310 bool bindProcGroup
= false)
312 // Only bind threads when MAX_WORKER_THREADS isn't set.
313 if (pContext
->threadInfo
.SINGLE_THREADED
||
314 (pContext
->threadInfo
.MAX_WORKER_THREADS
&& bindProcGroup
== false))
321 GROUP_AFFINITY affinity
= {};
322 affinity
.Group
= procGroupId
;
327 // Hopefully we don't get here. Logic in CreateThreadPool should prevent this.
328 SWR_INVALID("Shouldn't get here");
330 // In a 32-bit process on Windows it is impossible to bind
331 // to logical processors 32-63 within a processor group.
332 // In this case set the mask to 0 and let the system assign
333 // the processor. Hopefully it will make smart choices.
339 // If MAX_WORKER_THREADS is set, only bind to the proc group,
340 // Not the individual HW thread.
341 if (!bindProcGroup
&& !pContext
->threadInfo
.MAX_WORKER_THREADS
)
343 affinity
.Mask
= KAFFINITY(1) << threadId
;
347 affinity
.Mask
= KAFFINITY(0);
351 if (!SetThreadGroupAffinity(GetCurrentThread(), &affinity
, nullptr))
353 SWR_INVALID("Failed to set Thread Affinity");
356 #elif defined(__linux__) || defined(__gnu_linux__)
359 pthread_t thread
= pthread_self();
361 CPU_SET(threadId
, &cpuset
);
363 int err
= pthread_setaffinity_np(thread
, sizeof(cpu_set_t
), &cpuset
);
366 fprintf(stderr
, "pthread_setaffinity_np failure for tid %u: %s\n", threadId
, strerror(err
));
373 uint32_t GetEnqueuedDraw(SWR_CONTEXT
* pContext
)
375 return pContext
->dcRing
.GetHead();
379 DRAW_CONTEXT
* GetDC(SWR_CONTEXT
* pContext
, uint32_t drawId
)
381 return &pContext
->dcRing
[(drawId
- 1) % pContext
->MAX_DRAWS_IN_FLIGHT
];
385 bool IDComparesLess(uint32_t a
, uint32_t b
)
387 // Use signed delta to ensure that wrap-around to 0 is correctly handled.
388 int32_t delta
= int32_t(a
- b
);
392 // returns true if dependency not met
394 bool CheckDependency(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
, uint32_t lastRetiredDraw
)
396 return pDC
->dependent
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
399 bool CheckDependencyFE(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
, uint32_t lastRetiredDraw
)
401 return pDC
->dependentFE
&& IDComparesLess(lastRetiredDraw
, pDC
->drawId
- 1);
404 //////////////////////////////////////////////////////////////////////////
405 /// @brief Update client stats.
406 INLINE
void UpdateClientStats(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
408 if ((pContext
->pfnUpdateStats
== nullptr) || (GetApiState(pDC
).enableStatsBE
== false))
413 DRAW_DYNAMIC_STATE
& dynState
= pDC
->dynState
;
414 OSALIGNLINE(SWR_STATS
) stats
{0};
416 // Sum up stats across all workers before sending to client.
417 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
419 stats
.DepthPassCount
+= dynState
.pStats
[i
].DepthPassCount
;
420 stats
.PsInvocations
+= dynState
.pStats
[i
].PsInvocations
;
421 stats
.CsInvocations
+= dynState
.pStats
[i
].CsInvocations
;
426 pContext
->pfnUpdateStats(GetPrivateState(pDC
), &stats
);
429 INLINE
void ExecuteCallbacks(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
431 UpdateClientStats(pContext
, workerId
, pDC
);
433 if (pDC
->retireCallback
.pfnCallbackFunc
)
435 pDC
->retireCallback
.pfnCallbackFunc(pDC
->retireCallback
.userData
,
436 pDC
->retireCallback
.userData2
,
437 pDC
->retireCallback
.userData3
);
439 // Callbacks to external code *could* change floating point control state
440 // Reset our optimal flags
441 SetOptimalVectorCSR();
445 // inlined-only version
446 INLINE
int32_t CompleteDrawContextInl(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
448 int32_t result
= static_cast<int32_t>(InterlockedDecrement(&pDC
->threadsDone
));
449 SWR_ASSERT(result
>= 0);
451 AR_FLUSH(pDC
->drawId
);
455 ExecuteCallbacks(pContext
, workerId
, pDC
);
458 // Cleanup memory allocations
459 pDC
->pArena
->Reset(true);
462 pDC
->pTileMgr
->initialize();
464 if (pDC
->cleanupState
)
466 pDC
->pState
->pArena
->Reset(true);
471 pContext
->dcRing
.Dequeue(); // Remove from tail
477 // available to other translation modules
478 int32_t CompleteDrawContext(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
)
480 return CompleteDrawContextInl(pContext
, 0, pDC
);
483 INLINE
bool FindFirstIncompleteDraw(SWR_CONTEXT
* pContext
,
486 uint32_t& drawEnqueued
)
488 // increment our current draw id to the first incomplete draw
489 drawEnqueued
= GetEnqueuedDraw(pContext
);
490 while (IDComparesLess(curDrawBE
, drawEnqueued
))
492 DRAW_CONTEXT
* pDC
= &pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
];
494 // If its not compute and FE is not done then break out of loop.
495 if (!pDC
->doneFE
&& !pDC
->isCompute
)
498 bool isWorkComplete
=
499 pDC
->isCompute
? pDC
->pDispatch
->isWorkComplete() : pDC
->pTileMgr
->isWorkComplete();
504 CompleteDrawContextInl(pContext
, workerId
, pDC
);
512 // If there are no more incomplete draws then return false.
513 return IDComparesLess(curDrawBE
, drawEnqueued
);
516 //////////////////////////////////////////////////////////////////////////
517 /// @brief If there is any BE work then go work on it.
518 /// @param pContext - pointer to SWR context.
519 /// @param workerId - The unique worker ID that is assigned to this thread.
520 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker
522 /// has its own curDrawBE counter and this ensures that each worker processes all
523 /// the draws in order.
524 /// @param lockedTiles - This is the set of tiles locked by other threads. Each thread maintains its
525 /// own set and each time it fails to lock a macrotile, because its already
526 /// locked, then it will add that tile to the lockedTiles set. As a worker
527 /// begins to work on future draws the lockedTiles ensure that it doesn't work
528 /// on tiles that may still have work pending in a previous draw. Additionally,
529 /// the lockedTiles is hueristic that can steer a worker back to the same
530 /// macrotile that it had been working on in a previous draw.
531 /// @returns true if worker thread should shutdown
532 bool WorkOnFifoBE(SWR_CONTEXT
* pContext
,
535 TileSet
& lockedTiles
,
539 bool bShutdown
= false;
541 // Find the first incomplete draw that has pending work. If no such draw is found then
542 // return. FindFirstIncompleteDraw is responsible for incrementing the curDrawBE.
543 uint32_t drawEnqueued
= 0;
544 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
549 uint32_t lastRetiredDraw
=
550 pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
552 // Reset our history for locked tiles. We'll have to re-learn which tiles are locked.
555 // Try to work on each draw in order of the available draws in flight.
556 // 1. If we're on curDrawBE, we can work on any macrotile that is available.
557 // 2. If we're trying to work on draws after curDrawBE, we are restricted to
558 // working on those macrotiles that are known to be complete in the prior draw to
559 // maintain order. The locked tiles provides the history to ensures this.
560 for (uint32_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
562 DRAW_CONTEXT
* pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
565 return false; // We don't look at compute work.
567 // First wait for FE to be finished with this draw. This keeps threading model simple
568 // but if there are lots of bubbles between draws then serializing FE and BE may
569 // need to be revisited.
573 // If this draw is dependent on a previous draw then we need to bail.
574 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
579 // Grab the list of all dirty macrotiles. A tile is dirty if it has work queued to it.
580 auto& macroTiles
= pDC
->pTileMgr
->getDirtyTiles();
582 for (auto tile
: macroTiles
)
584 uint32_t tileID
= tile
->mId
;
586 // Only work on tiles for this numa node
588 pDC
->pTileMgr
->getTileIndices(tileID
, x
, y
);
589 if (((x
^ y
) & numaMask
) != numaNode
)
595 if (!tile
->getNumQueued())
601 // can only work on this draw if it's not in use by other threads
602 if (lockedTiles
.get(tileID
))
612 RDTSC_BEGIN(pContext
->pBucketMgr
, WorkerFoundWork
, pDC
->drawId
);
614 uint32_t numWorkItems
= tile
->getNumQueued();
615 SWR_ASSERT(numWorkItems
);
617 pWork
= tile
->peek();
619 if (pWork
->type
== DRAW
)
621 pContext
->pHotTileMgr
->InitializeHotTiles(pContext
, pDC
, workerId
, tileID
);
623 else if (pWork
->type
== SHUTDOWN
)
628 while ((pWork
= tile
->peek()) != nullptr)
630 pWork
->pfnWork(pDC
, workerId
, tileID
, &pWork
->desc
);
633 RDTSC_END(pContext
->pBucketMgr
, WorkerFoundWork
, numWorkItems
);
637 pDC
->pTileMgr
->markTileComplete(tileID
);
639 // Optimization: If the draw is complete and we're the last one to have worked on it
640 // then we can reset the locked list as we know that all previous draws before the
641 // next are guaranteed to be complete.
642 if ((curDrawBE
== i
) && (bShutdown
|| pDC
->pTileMgr
->isWorkComplete()))
644 // We can increment the current BE and safely move to next draw since we know
645 // this draw is complete.
647 CompleteDrawContextInl(pContext
, workerId
, pDC
);
662 // This tile is already locked. So let's add it to our locked tiles set. This way we
663 // don't try locking this one again.
664 lockedTiles
.set(tileID
);
673 //////////////////////////////////////////////////////////////////////////
674 /// @brief Called when FE work is complete for this DC.
675 INLINE
void CompleteDrawFE(SWR_CONTEXT
* pContext
, uint32_t workerId
, DRAW_CONTEXT
* pDC
)
677 if (pContext
->pfnUpdateStatsFE
&& GetApiState(pDC
).enableStatsFE
)
679 SWR_STATS_FE
& stats
= pDC
->dynState
.statsFE
;
681 AR_EVENT(FrontendStatsEvent(pDC
->drawId
,
691 stats
.SoPrimStorageNeeded
[0],
692 stats
.SoPrimStorageNeeded
[1],
693 stats
.SoPrimStorageNeeded
[2],
694 stats
.SoPrimStorageNeeded
[3],
695 stats
.SoNumPrimsWritten
[0],
696 stats
.SoNumPrimsWritten
[1],
697 stats
.SoNumPrimsWritten
[2],
698 stats
.SoNumPrimsWritten
[3]));
699 AR_EVENT(FrontendDrawEndEvent(pDC
->drawId
));
701 pContext
->pfnUpdateStatsFE(GetPrivateState(pDC
), &stats
);
704 if (pContext
->pfnUpdateSoWriteOffset
)
706 for (uint32_t i
= 0; i
< MAX_SO_BUFFERS
; ++i
)
708 if ((pDC
->dynState
.SoWriteOffsetDirty
[i
]) &&
709 (pDC
->pState
->state
.soBuffer
[i
].soWriteEnable
))
711 pContext
->pfnUpdateSoWriteOffset(
712 GetPrivateState(pDC
), i
, pDC
->dynState
.SoWriteOffset
[i
]);
717 if (pContext
->pfnUpdateStreamOut
)
718 pContext
->pfnUpdateStreamOut(GetPrivateState(pDC
), pDC
->dynState
.soPrims
);
720 // Ensure all streaming writes are globally visible before marking this FE done
724 InterlockedDecrement(&pContext
->drawsOutstandingFE
);
727 void WorkOnFifoFE(SWR_CONTEXT
* pContext
, uint32_t workerId
, uint32_t& curDrawFE
)
729 // Try to grab the next DC from the ring
730 uint32_t drawEnqueued
= GetEnqueuedDraw(pContext
);
731 while (IDComparesLess(curDrawFE
, drawEnqueued
))
733 uint32_t dcSlot
= curDrawFE
% pContext
->MAX_DRAWS_IN_FLIGHT
;
734 DRAW_CONTEXT
* pDC
= &pContext
->dcRing
[dcSlot
];
735 if (pDC
->isCompute
|| pDC
->doneFE
)
737 CompleteDrawContextInl(pContext
, workerId
, pDC
);
746 uint32_t lastRetiredFE
= curDrawFE
- 1;
747 uint32_t curDraw
= curDrawFE
;
748 while (IDComparesLess(curDraw
, drawEnqueued
))
750 uint32_t dcSlot
= curDraw
% pContext
->MAX_DRAWS_IN_FLIGHT
;
751 DRAW_CONTEXT
* pDC
= &pContext
->dcRing
[dcSlot
];
753 if (!pDC
->FeLock
&& !pDC
->isCompute
)
755 if (CheckDependencyFE(pContext
, pDC
, lastRetiredFE
))
760 uint32_t initial
= InterlockedCompareExchange((volatile uint32_t*)&pDC
->FeLock
, 1, 0);
763 // successfully grabbed the DC, now run the FE
764 pDC
->FeWork
.pfnWork(pContext
, pDC
, workerId
, &pDC
->FeWork
.desc
);
766 CompleteDrawFE(pContext
, workerId
, pDC
);
782 //////////////////////////////////////////////////////////////////////////
783 /// @brief If there is any compute work then go work on it.
784 /// @param pContext - pointer to SWR context.
785 /// @param workerId - The unique worker ID that is assigned to this thread.
786 /// @param curDrawBE - This tracks the draw contexts that this thread has processed. Each worker
788 /// has its own curDrawBE counter and this ensures that each worker processes all
789 /// the draws in order.
790 void WorkOnCompute(SWR_CONTEXT
* pContext
, uint32_t workerId
, uint32_t& curDrawBE
)
792 uint32_t drawEnqueued
= 0;
793 if (FindFirstIncompleteDraw(pContext
, workerId
, curDrawBE
, drawEnqueued
) == false)
798 uint32_t lastRetiredDraw
=
799 pContext
->dcRing
[curDrawBE
% pContext
->MAX_DRAWS_IN_FLIGHT
].drawId
- 1;
801 for (uint64_t i
= curDrawBE
; IDComparesLess(i
, drawEnqueued
); ++i
)
803 DRAW_CONTEXT
* pDC
= &pContext
->dcRing
[i
% pContext
->MAX_DRAWS_IN_FLIGHT
];
804 if (pDC
->isCompute
== false)
807 // check dependencies
808 if (CheckDependency(pContext
, pDC
, lastRetiredDraw
))
813 SWR_ASSERT(pDC
->pDispatch
!= nullptr);
814 DispatchQueue
& queue
= *pDC
->pDispatch
;
816 // Is there any work remaining?
817 if (queue
.getNumQueued() > 0)
819 void* pSpillFillBuffer
= nullptr;
820 void* pScratchSpace
= nullptr;
821 uint32_t threadGroupId
= 0;
822 while (queue
.getWork(threadGroupId
))
824 queue
.dispatch(pDC
, workerId
, threadGroupId
, pSpillFillBuffer
, pScratchSpace
);
825 queue
.finishedWork();
828 // Ensure all streaming writes are globally visible before moving onto the next draw
834 void BindApiThread(SWR_CONTEXT
* pContext
, uint32_t apiThreadId
)
836 if (nullptr == pContext
)
841 if (apiThreadId
>= pContext
->threadPool
.numReservedThreads
)
843 if (pContext
->threadPool
.numReservedThreads
)
845 const THREAD_DATA
& threadData
= pContext
->threadPool
.pApiThreadData
[0];
846 // Just bind to the process group used for API thread 0
847 bindThread(pContext
, 0, threadData
.procGroupId
, true);
852 const THREAD_DATA
& threadData
= pContext
->threadPool
.pApiThreadData
[apiThreadId
];
855 pContext
, threadData
.threadId
, threadData
.procGroupId
, threadData
.forceBindProcGroup
);
858 template <bool IsFEThread
, bool IsBEThread
>
859 DWORD
workerThreadMain(LPVOID pData
)
861 THREAD_DATA
* pThreadData
= (THREAD_DATA
*)pData
;
862 SWR_CONTEXT
* pContext
= pThreadData
->pContext
;
863 uint32_t threadId
= pThreadData
->threadId
;
864 uint32_t workerId
= pThreadData
->workerId
;
866 bindThread(pContext
, threadId
, pThreadData
->procGroupId
, pThreadData
->forceBindProcGroup
);
870 sprintf_s(threadName
,
872 "SWRWorker_%02d_NUMA%d_Core%02d_T%d",
874 // linux pthread name limited to 16 chars (including \0)
875 "w%03d-n%d-c%03d-t%d",
881 SetCurrentThreadName(threadName
);
884 RDTSC_INIT(pContext
->pBucketMgr
, threadId
);
886 // Only need offset numa index from base for correct masking
887 uint32_t numaNode
= pThreadData
->numaId
- pContext
->threadInfo
.BASE_NUMA_NODE
;
888 uint32_t numaMask
= pContext
->threadPool
.numaMask
;
890 SetOptimalVectorCSR();
892 // Track tiles locked by other threads. If we try to lock a macrotile and find its already
893 // locked then we'll add it to this list so that we don't try and lock it again.
896 // each worker has the ability to work on any of the queued draws as long as certain
897 // conditions are met. the data associated
898 // with a draw is guaranteed to be active as long as a worker hasn't signaled that he
899 // has moved on to the next draw when he determines there is no more work to do. The api
900 // thread will not increment the head of the dc ring until all workers have moved past the
902 // the logic to determine what to work on is:
903 // 1- try to work on the FE any draw that is queued. For now there are no dependencies
904 // on the FE work, so any worker can grab any FE and process in parallel. Eventually
905 // we'll need dependency tracking to force serialization on FEs. The worker will try
906 // to pick an FE by atomically incrementing a counter in the swr context. he'll keep
907 // trying until he reaches the tail.
908 // 2- BE work must be done in strict order. we accomplish this today by pulling work off
909 // the oldest draw (ie the head) of the dcRing. the worker can determine if there is
910 // any work left by comparing the total # of binned work items and the total # of completed
911 // work items. If they are equal, then there is no more work to do for this draw, and
912 // the worker can safely increment its oldestDraw counter and move on to the next draw.
913 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
, std::defer_lock
);
915 auto threadHasWork
= [&](uint32_t curDraw
) { return curDraw
!= pContext
->dcRing
.GetHead(); };
917 uint32_t curDrawBE
= 0;
918 uint32_t curDrawFE
= 0;
920 bool bShutdown
= false;
924 if (bShutdown
&& !threadHasWork(curDrawBE
))
930 while (loop
++ < KNOB_WORKER_SPIN_LOOP_COUNT
&& !threadHasWork(curDrawBE
))
935 if (!threadHasWork(curDrawBE
))
939 // check for thread idle condition again under lock
940 if (threadHasWork(curDrawBE
))
946 pContext
->FifosNotEmpty
.wait(lock
);
952 RDTSC_BEGIN(pContext
->pBucketMgr
, WorkerWorkOnFifoBE
, 0);
954 WorkOnFifoBE(pContext
, workerId
, curDrawBE
, lockedTiles
, numaNode
, numaMask
);
955 RDTSC_END(pContext
->pBucketMgr
, WorkerWorkOnFifoBE
, 0);
957 WorkOnCompute(pContext
, workerId
, curDrawBE
);
962 WorkOnFifoFE(pContext
, workerId
, curDrawFE
);
966 curDrawBE
= curDrawFE
;
974 DWORD workerThreadMain
<false, false>(LPVOID
) = delete;
976 template <bool IsFEThread
, bool IsBEThread
>
977 DWORD
workerThreadInit(LPVOID pData
)
979 #if defined(_MSC_VER)
983 return workerThreadMain
<IsFEThread
, IsBEThread
>(pData
);
986 #if defined(_MSC_VER)
987 __except (EXCEPTION_CONTINUE_SEARCH
)
996 DWORD workerThreadInit
<false, false>(LPVOID pData
) = delete;
998 static void InitPerThreadStats(SWR_CONTEXT
* pContext
, uint32_t numThreads
)
1000 // Initialize DRAW_CONTEXT's per-thread stats
1001 for (uint32_t dc
= 0; dc
< pContext
->MAX_DRAWS_IN_FLIGHT
; ++dc
)
1003 pContext
->dcRing
[dc
].dynState
.pStats
=
1004 (SWR_STATS
*)AlignedMalloc(sizeof(SWR_STATS
) * numThreads
, 64);
1005 memset(pContext
->dcRing
[dc
].dynState
.pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
1009 //////////////////////////////////////////////////////////////////////////
1010 /// @brief Creates thread pool info but doesn't launch threads.
1011 /// @param pContext - pointer to context
1012 /// @param pPool - pointer to thread pool object.
1013 void CreateThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1016 uint32_t numThreadsPerProcGroup
= 0;
1017 CalculateProcessorTopology(nodes
, numThreadsPerProcGroup
);
1018 assert(numThreadsPerProcGroup
> 0);
1020 // Assumption, for asymmetric topologies, multi-threaded cores will appear
1021 // in the list before single-threaded cores. This appears to be true for
1022 // Windows when the total HW threads is limited to 64.
1023 uint32_t numHWNodes
= (uint32_t)nodes
.size();
1024 uint32_t numHWCoresPerNode
= (uint32_t)nodes
[0].cores
.size();
1025 uint32_t numHWHyperThreads
= (uint32_t)nodes
[0].cores
[0].threadIds
.size();
1027 #if defined(_WIN32) && !defined(_WIN64)
1028 if (!pContext
->threadInfo
.MAX_WORKER_THREADS
)
1030 // Limit 32-bit windows to bindable HW threads only
1031 if ((numHWCoresPerNode
* numHWHyperThreads
) > 32)
1033 numHWCoresPerNode
= 32 / numHWHyperThreads
;
1038 // Calculate num HW threads. Due to asymmetric topologies, this is not
1039 // a trivial multiplication.
1040 uint32_t numHWThreads
= 0;
1041 for (auto const& node
: nodes
)
1043 for (auto const& core
: node
.cores
)
1045 numHWThreads
+= (uint32_t)core
.threadIds
.size();
1049 uint32_t numNodes
= numHWNodes
;
1050 uint32_t numCoresPerNode
= numHWCoresPerNode
;
1051 uint32_t numHyperThreads
= numHWHyperThreads
;
1053 // Calc used threads per-core
1054 if (numHyperThreads
> pContext
->threadInfo
.BASE_THREAD
)
1056 numHyperThreads
-= pContext
->threadInfo
.BASE_THREAD
;
1061 "Cannot use BASE_THREAD value: %d, maxThreads: %d, reverting BASE_THREAD to 0",
1062 pContext
->threadInfo
.BASE_THREAD
,
1064 pContext
->threadInfo
.BASE_THREAD
= 0;
1067 if (pContext
->threadInfo
.MAX_THREADS_PER_CORE
)
1069 numHyperThreads
= std::min(numHyperThreads
, pContext
->threadInfo
.MAX_THREADS_PER_CORE
);
1072 // Prune any cores that don't support the number of threads
1073 if (numHyperThreads
> 1)
1075 for (auto& node
: nodes
)
1077 uint32_t numUsableCores
= 0;
1078 for (auto& core
: node
.cores
)
1080 numUsableCores
+= (core
.threadIds
.size() >= numHyperThreads
);
1082 numCoresPerNode
= std::min(numCoresPerNode
, numUsableCores
);
1086 // Calc used cores per NUMA node
1087 if (numCoresPerNode
> pContext
->threadInfo
.BASE_CORE
)
1089 numCoresPerNode
-= pContext
->threadInfo
.BASE_CORE
;
1094 "Cannot use BASE_CORE value: %d, maxCores: %d, reverting BASE_CORE to 0",
1095 pContext
->threadInfo
.BASE_CORE
,
1097 pContext
->threadInfo
.BASE_CORE
= 0;
1100 if (pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
)
1102 numCoresPerNode
= std::min(numCoresPerNode
, pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
);
1105 // Calc used NUMA nodes
1106 if (numNodes
> pContext
->threadInfo
.BASE_NUMA_NODE
)
1108 numNodes
-= pContext
->threadInfo
.BASE_NUMA_NODE
;
1114 "Cannot use BASE_NUMA_NODE value: %d, maxNodes: %d, reverting BASE_NUMA_NODE to 0",
1115 pContext
->threadInfo
.BASE_NUMA_NODE
,
1117 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1120 if (pContext
->threadInfo
.MAX_NUMA_NODES
)
1122 numNodes
= std::min(numNodes
, pContext
->threadInfo
.MAX_NUMA_NODES
);
1125 // Calculate numThreads - at this point everything should be symmetric
1126 uint32_t numThreads
= numNodes
* numCoresPerNode
* numHyperThreads
;
1127 SWR_REL_ASSERT(numThreads
<= numHWThreads
);
1129 uint32_t& numAPIReservedThreads
= pContext
->apiThreadInfo
.numAPIReservedThreads
;
1130 uint32_t& numAPIThreadsPerCore
= pContext
->apiThreadInfo
.numAPIThreadsPerCore
;
1131 uint32_t numRemovedThreads
= 0;
1133 if (pContext
->threadInfo
.SINGLE_THREADED
)
1135 numAPIReservedThreads
= 0;
1137 pContext
->NumWorkerThreads
= 1;
1138 pContext
->NumFEThreads
= 1;
1139 pContext
->NumBEThreads
= 1;
1140 pPool
->numThreads
= 0;
1142 else if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1144 numThreads
= std::min(pContext
->threadInfo
.MAX_WORKER_THREADS
, numHWThreads
);
1145 pContext
->threadInfo
.BASE_NUMA_NODE
= 0;
1146 pContext
->threadInfo
.BASE_CORE
= 0;
1147 pContext
->threadInfo
.BASE_THREAD
= 0;
1148 numAPIReservedThreads
= 0;
1152 if (numAPIReservedThreads
>= numThreads
)
1154 numAPIReservedThreads
= 0;
1156 else if (numAPIReservedThreads
)
1158 numAPIThreadsPerCore
= std::min(numAPIThreadsPerCore
, numHWHyperThreads
);
1160 if (0 == numAPIThreadsPerCore
)
1162 numAPIThreadsPerCore
= numHWHyperThreads
;
1165 numRemovedThreads
= numAPIReservedThreads
;
1166 if (numAPIThreadsPerCore
== 2 && numHyperThreads
== 1)
1168 // Adjust removed threads to make logic below work
1170 std::max(1U, (numRemovedThreads
+ numAPIThreadsPerCore
- 1) / 2);
1173 numThreads
-= numRemovedThreads
;
1177 InitPerThreadStats(pContext
, numThreads
);
1179 if (pContext
->threadInfo
.SINGLE_THREADED
)
1181 numAPIReservedThreads
= 0;
1185 if (numAPIReservedThreads
)
1187 pPool
->pApiThreadData
= new (std::nothrow
) THREAD_DATA
[numAPIReservedThreads
];
1188 SWR_ASSERT(pPool
->pApiThreadData
);
1189 if (!pPool
->pApiThreadData
)
1191 numAPIReservedThreads
= 0;
1195 memset(pPool
->pApiThreadData
, 0, sizeof(THREAD_DATA
) * numAPIReservedThreads
);
1198 pPool
->numReservedThreads
= numAPIReservedThreads
;
1200 pPool
->numThreads
= numThreads
;
1201 pContext
->NumWorkerThreads
= pPool
->numThreads
;
1203 pPool
->pThreadData
= new (std::nothrow
) THREAD_DATA
[pPool
->numThreads
];
1204 assert(pPool
->pThreadData
);
1205 memset(pPool
->pThreadData
, 0, sizeof(THREAD_DATA
) * pPool
->numThreads
);
1206 pPool
->numaMask
= 0;
1208 // Allocate worker private data
1209 pPool
->pWorkerPrivateDataArray
= nullptr;
1210 if (pContext
->workerPrivateState
.perWorkerPrivateStateSize
== 0)
1212 pContext
->workerPrivateState
.perWorkerPrivateStateSize
= sizeof(SWR_WORKER_DATA
);
1213 pContext
->workerPrivateState
.pfnInitWorkerData
= nullptr;
1214 pContext
->workerPrivateState
.pfnFinishWorkerData
= nullptr;
1217 // initialize contents of SWR_WORKER_DATA
1218 size_t perWorkerSize
=
1219 AlignUpPow2(pContext
->workerPrivateState
.perWorkerPrivateStateSize
, 64);
1220 size_t totalSize
= perWorkerSize
* pPool
->numThreads
;
1223 pPool
->pWorkerPrivateDataArray
= AlignedMalloc(totalSize
, 64);
1224 SWR_ASSERT(pPool
->pWorkerPrivateDataArray
);
1226 void* pWorkerData
= pPool
->pWorkerPrivateDataArray
;
1227 for (uint32_t i
= 0; i
< pPool
->numThreads
; ++i
)
1229 pPool
->pThreadData
[i
].pWorkerPrivateData
= pWorkerData
;
1230 if (pContext
->workerPrivateState
.pfnInitWorkerData
)
1232 pContext
->workerPrivateState
.pfnInitWorkerData(pContext
, pWorkerData
, i
);
1234 pWorkerData
= PtrAdd(pWorkerData
, perWorkerSize
);
1238 if (pContext
->threadInfo
.SINGLE_THREADED
)
1243 pPool
->pThreads
= new (std::nothrow
) THREAD_PTR
[pPool
->numThreads
];
1244 assert(pPool
->pThreads
);
1246 if (pContext
->threadInfo
.MAX_WORKER_THREADS
)
1248 bool bForceBindProcGroup
= (numThreads
> numThreadsPerProcGroup
);
1249 uint32_t numProcGroups
= (numThreads
+ numThreadsPerProcGroup
- 1) / numThreadsPerProcGroup
;
1250 // When MAX_WORKER_THREADS is set we don't bother to bind to specific HW threads
1251 // But Windows will still require binding to specific process groups
1252 for (uint32_t workerId
= 0; workerId
< numThreads
; ++workerId
)
1254 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1255 pPool
->pThreadData
[workerId
].procGroupId
= workerId
% numProcGroups
;
1256 pPool
->pThreadData
[workerId
].threadId
= 0;
1257 pPool
->pThreadData
[workerId
].numaId
= 0;
1258 pPool
->pThreadData
[workerId
].coreId
= 0;
1259 pPool
->pThreadData
[workerId
].htId
= 0;
1260 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1261 pPool
->pThreadData
[workerId
].forceBindProcGroup
= bForceBindProcGroup
;
1263 pContext
->NumBEThreads
++;
1264 pContext
->NumFEThreads
++;
1269 // numa distribution assumes workers on all nodes
1270 bool useNuma
= true;
1271 if (numCoresPerNode
* numHyperThreads
== 1)
1278 pPool
->numaMask
= numNodes
- 1; // Only works for 2**n numa nodes (1, 2, 4, etc.)
1282 pPool
->numaMask
= 0;
1285 uint32_t workerId
= 0;
1286 uint32_t numReservedThreads
= numAPIReservedThreads
;
1287 for (uint32_t n
= 0; n
< numNodes
; ++n
)
1289 if ((n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) >= nodes
.size())
1293 auto& node
= nodes
[n
+ pContext
->threadInfo
.BASE_NUMA_NODE
];
1294 uint32_t numCores
= numCoresPerNode
;
1295 for (uint32_t c
= 0; c
< numCores
; ++c
)
1297 if ((c
+ pContext
->threadInfo
.BASE_CORE
) >= node
.cores
.size())
1302 auto& core
= node
.cores
[c
+ pContext
->threadInfo
.BASE_CORE
];
1303 for (uint32_t t
= 0; t
< numHyperThreads
; ++t
)
1305 if ((t
+ pContext
->threadInfo
.BASE_THREAD
) >= core
.threadIds
.size())
1310 if (numRemovedThreads
)
1312 --numRemovedThreads
;
1313 assert(numReservedThreads
);
1314 --numReservedThreads
;
1315 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1316 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1317 pPool
->pApiThreadData
[numReservedThreads
].threadId
= core
.threadIds
[t
];
1318 pPool
->pApiThreadData
[numReservedThreads
].numaId
=
1319 useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1320 pPool
->pApiThreadData
[numReservedThreads
].coreId
=
1321 c
+ pContext
->threadInfo
.BASE_CORE
;
1322 pPool
->pApiThreadData
[numReservedThreads
].htId
=
1323 t
+ pContext
->threadInfo
.BASE_THREAD
;
1324 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1325 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1327 if (numAPIThreadsPerCore
> numHyperThreads
&& numReservedThreads
)
1329 --numReservedThreads
;
1330 pPool
->pApiThreadData
[numReservedThreads
].workerId
= 0xFFFFFFFFU
;
1331 pPool
->pApiThreadData
[numReservedThreads
].procGroupId
= core
.procGroup
;
1332 pPool
->pApiThreadData
[numReservedThreads
].threadId
=
1333 core
.threadIds
[t
+ 1];
1334 pPool
->pApiThreadData
[numReservedThreads
].numaId
=
1335 useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1336 pPool
->pApiThreadData
[numReservedThreads
].coreId
=
1337 c
+ pContext
->threadInfo
.BASE_CORE
;
1338 pPool
->pApiThreadData
[numReservedThreads
].htId
=
1339 t
+ pContext
->threadInfo
.BASE_THREAD
;
1340 pPool
->pApiThreadData
[numReservedThreads
].pContext
= pContext
;
1341 pPool
->pApiThreadData
[numReservedThreads
].forceBindProcGroup
= false;
1347 SWR_ASSERT(workerId
< numThreads
);
1349 pPool
->pThreadData
[workerId
].workerId
= workerId
;
1350 pPool
->pThreadData
[workerId
].procGroupId
= core
.procGroup
;
1351 pPool
->pThreadData
[workerId
].threadId
=
1352 core
.threadIds
[t
+ pContext
->threadInfo
.BASE_THREAD
];
1353 pPool
->pThreadData
[workerId
].numaId
=
1354 useNuma
? (n
+ pContext
->threadInfo
.BASE_NUMA_NODE
) : 0;
1355 pPool
->pThreadData
[workerId
].coreId
= c
+ pContext
->threadInfo
.BASE_CORE
;
1356 pPool
->pThreadData
[workerId
].htId
= t
+ pContext
->threadInfo
.BASE_THREAD
;
1357 pPool
->pThreadData
[workerId
].pContext
= pContext
;
1358 pPool
->pThreadData
[workerId
].forceBindProcGroup
= false;
1360 pContext
->NumBEThreads
++;
1361 pContext
->NumFEThreads
++;
1367 SWR_ASSERT(workerId
== pContext
->NumWorkerThreads
);
1371 //////////////////////////////////////////////////////////////////////////
1372 /// @brief Launches worker threads in thread pool.
1373 /// @param pContext - pointer to context
1374 /// @param pPool - pointer to thread pool object.
1375 void StartThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1377 if (pContext
->threadInfo
.SINGLE_THREADED
)
1382 for (uint32_t workerId
= 0; workerId
< pContext
->NumWorkerThreads
; ++workerId
)
1384 pPool
->pThreads
[workerId
] =
1385 new std::thread(workerThreadInit
<true, true>, &pPool
->pThreadData
[workerId
]);
1389 //////////////////////////////////////////////////////////////////////////
1390 /// @brief Destroys thread pool.
1391 /// @param pContext - pointer to context
1392 /// @param pPool - pointer to thread pool object.
1393 void DestroyThreadPool(SWR_CONTEXT
* pContext
, THREAD_POOL
* pPool
)
1395 // Wait for all threads to finish
1396 SwrWaitForIdle(pContext
);
1398 // Wait for threads to finish and destroy them
1399 for (uint32_t t
= 0; t
< pPool
->numThreads
; ++t
)
1401 if (!pContext
->threadInfo
.SINGLE_THREADED
)
1403 // Detach from thread. Cannot join() due to possibility (in Windows) of code
1404 // in some DLLMain(THREAD_DETATCH case) blocking the thread until after this returns.
1405 pPool
->pThreads
[t
]->detach();
1406 delete (pPool
->pThreads
[t
]);
1409 if (pContext
->workerPrivateState
.pfnFinishWorkerData
)
1411 pContext
->workerPrivateState
.pfnFinishWorkerData(
1412 pContext
, pPool
->pThreadData
[t
].pWorkerPrivateData
, t
);
1416 delete[] pPool
->pThreads
;
1418 // Clean up data used by threads
1419 delete[] pPool
->pThreadData
;
1420 delete[] pPool
->pApiThreadData
;
1422 AlignedFree(pPool
->pWorkerPrivateDataArray
);