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
25 * @brief Definitions for SWR_CONTEXT and DRAW_CONTEXT
26 * The SWR_CONTEXT is our global context and contains the DC ring,
29 * The DRAW_CONTEXT contains all state associated with a draw operation.
31 ******************************************************************************/
34 #include <condition_variable>
38 #include "core/utils.h"
39 #include "core/arena.h"
40 #include "core/fifo.hpp"
41 #include "core/knobs.h"
42 #include "common/simdintrin.h"
43 #include "core/threads.h"
44 #include "ringbuffer.h"
45 #include "archrast/archrast.h"
47 // x.8 fixed point precision values
48 #define FIXED_POINT_SHIFT 8
49 #define FIXED_POINT_SCALE 256
51 // x.16 fixed point precision values
52 #define FIXED_POINT16_SHIFT 16
53 #define FIXED_POINT16_SCALE 65536
60 uint32_t frontFacing
: 1;
62 uint32_t coverageMask
: (SIMD_TILE_X_DIM
* SIMD_TILE_Y_DIM
);
63 uint32_t reserved
: 32 - 1 - 1 - (SIMD_TILE_X_DIM
* SIMD_TILE_Y_DIM
);
66 uint32_t renderTargetArrayIndex
;
67 uint32_t viewportIndex
;
70 //////////////////////////////////////////////////////////////////////////
72 /////////////////////////////////////////////////////////////////////////
73 struct SWR_TRIANGLE_DESC
85 float *pUserClipBuffer
;
87 uint64_t coverageMask
[SWR_MAX_NUM_MULTISAMPLES
];
88 uint64_t innerCoverageMask
; // Conservative rasterization inner coverage: marked covered if entire pixel is covered
89 uint64_t anyCoveredSamples
;
94 struct TRIANGLE_WORK_DESC
98 float *pUserClipBuffer
;
106 uint32_t attachmentMask
;
107 uint32_t renderTargetArrayIndex
;
108 float clearRTColor
[4]; // RGBA_32F
109 float clearDepth
; // [0..1]
110 uint8_t clearStencil
;
113 struct DISCARD_INVALIDATE_TILES_DESC
115 uint32_t attachmentMask
;
117 SWR_TILE_STATE newTileState
;
124 PFN_CALLBACK_FUNC pfnCallbackFunc
;
130 struct STORE_TILES_DESC
132 uint32_t attachmentMask
;
133 SWR_TILE_STATE postStoreTileState
;
139 uint32_t threadGroupCountX
;
140 uint32_t threadGroupCountY
;
141 uint32_t threadGroupCountZ
;
144 typedef void(*PFN_WORK_FUNC
)(DRAW_CONTEXT
* pDC
, uint32_t workerId
, uint32_t macroTile
, void* pDesc
);
151 DISCARDINVALIDATETILES
,
156 OSALIGNSIMD(struct) BE_WORK
159 PFN_WORK_FUNC pfnWork
;
163 TRIANGLE_WORK_DESC tri
;
165 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles
;
166 STORE_TILES_DESC storeTiles
;
175 uint32_t numIndices
; // DrawIndexed: Number of indices for draw.
176 uint32_t numVerts
; // Draw: Number of verts (triangles, lines, etc)
180 const int32_t* pIB
; // DrawIndexed: App supplied indices
181 uint32_t startVertex
; // Draw: Starting vertex in VB to render from.
184 uint32_t numInstances
; // Number of instances
185 uint32_t startInstance
; // Instance offset
186 uint32_t startPrimID
; // starting primitiveID for this draw batch
187 uint32_t startVertexID
; // starting VertexID for this draw batch (only needed for non-indexed draws)
188 SWR_FORMAT type
; // index buffer type
191 typedef void(*PFN_FE_WORK_FUNC
)(SWR_CONTEXT
* pContext
, DRAW_CONTEXT
* pDC
, uint32_t workerId
, void* pDesc
);
195 PFN_FE_WORK_FUNC pfnWork
;
201 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles
;
202 STORE_TILES_DESC storeTiles
;
208 float left
[KNOB_NUM_VIEWPORTS_SCISSORS
];
209 float right
[KNOB_NUM_VIEWPORTS_SCISSORS
];
210 float top
[KNOB_NUM_VIEWPORTS_SCISSORS
];
211 float bottom
[KNOB_NUM_VIEWPORTS_SCISSORS
];
216 // function signature for pipeline stages that execute after primitive assembly
217 typedef void(*PFN_PROCESS_PRIMS
)(DRAW_CONTEXT
*pDC
, PA_STATE
& pa
, uint32_t workerId
, simdvector prims
[],
218 uint32_t primMask
, simdscalari primID
, simdscalari viewportIdx
);
220 #if ENABLE_AVX512_SIMD16
221 // function signature for pipeline stages that execute after primitive assembly
222 typedef void(SIMDAPI
*PFN_PROCESS_PRIMS_SIMD16
)(DRAW_CONTEXT
*pDC
, PA_STATE
& pa
, uint32_t workerId
, simd16vector prims
[],
223 uint32_t primMask
, simd16scalari primID
, simd16scalari viewportIdx
);
226 OSALIGNLINE(struct) API_STATE
229 SWR_VERTEX_BUFFER_STATE vertexBuffers
[KNOB_NUM_STREAMS
];
232 SWR_INDEX_BUFFER_STATE indexBuffer
;
234 // FS - Fetch Shader State
235 PFN_FETCH_FUNC pfnFetchFunc
;
237 // VS - Vertex Shader State
238 PFN_VERTEX_FUNC pfnVertexFunc
;
240 // GS - Geometry Shader State
241 PFN_GS_FUNC pfnGsFunc
;
242 SWR_GS_STATE gsState
;
244 // CS - Compute Shader
245 PFN_CS_FUNC pfnCsFunc
;
246 uint32_t totalThreadsInGroup
;
247 uint32_t totalSpillFillSize
;
248 uint32_t scratchSpaceSize
;
249 uint32_t scratchSpaceNumInstances
;
251 // FE - Frontend State
252 SWR_FRONTEND_STATE frontendState
;
254 // SOS - Streamout Shader State
255 PFN_SO_FUNC pfnSoFunc
[MAX_SO_STREAMS
];
258 SWR_STREAMOUT_STATE soState
;
259 mutable SWR_STREAMOUT_BUFFER soBuffer
[MAX_SO_STREAMS
];
261 // Tessellation State
262 PFN_HS_FUNC pfnHsFunc
;
263 PFN_DS_FUNC pfnDsFunc
;
264 SWR_TS_STATE tsState
;
266 // Number of attributes used by the frontend (vs, so, gs)
267 uint32_t feNumAttributes
;
269 PRIMITIVE_TOPOLOGY topology
;
272 // RS - Rasterizer State
273 SWR_RASTSTATE rastState
;
274 // floating point multisample offsets
275 float samplePos
[SWR_MAX_NUM_MULTISAMPLES
* 2];
279 SWR_VIEWPORT vp
[KNOB_NUM_VIEWPORTS_SCISSORS
];
280 SWR_VIEWPORT_MATRICES vpMatrices
;
282 SWR_RECT scissorRects
[KNOB_NUM_VIEWPORTS_SCISSORS
];
283 SWR_RECT scissorsInFixedPoint
[KNOB_NUM_VIEWPORTS_SCISSORS
];
284 bool scissorsTileAligned
;
287 SWR_BACKEND_STATE backendState
;
289 SWR_DEPTH_BOUNDS_STATE depthBoundsState
;
291 // PS - Pixel shader state
292 SWR_PS_STATE psState
;
294 SWR_DEPTH_STENCIL_STATE depthStencilState
;
296 // OM - Output Merger State
297 SWR_BLEND_STATE blendState
;
298 PFN_BLEND_JIT_FUNC pfnBlendFunc
[SWR_NUM_RENDERTARGETS
];
302 uint32_t enableStatsFE
: 1; // Enable frontend pipeline stats
303 uint32_t enableStatsBE
: 1; // Enable backend pipeline stats
304 uint32_t colorHottileEnable
: 8; // Bitmask of enabled color hottiles
305 uint32_t depthHottileEnable
: 1; // Enable depth buffer hottile
306 uint32_t stencilHottileEnable
: 1; // Enable stencil buffer hottile
309 PFN_QUANTIZE_DEPTH pfnQuantizeDepth
;
315 struct RenderOutputBuffers
317 uint8_t* pColor
[SWR_NUM_RENDERTARGETS
];
322 // Plane equation A/B/C coeffs used to evaluate I/J barycentric coords
323 struct BarycentricCoeffs
337 simdscalar vRecipDet
;
339 simdscalar vAOneOverW
;
340 simdscalar vBOneOverW
;
341 simdscalar vCOneOverW
;
344 // pipeline function pointer types
345 typedef void(*PFN_BACKEND_FUNC
)(DRAW_CONTEXT
*, uint32_t, uint32_t, uint32_t, SWR_TRIANGLE_DESC
&, RenderOutputBuffers
&);
346 typedef void(*PFN_OUTPUT_MERGER
)(SWR_PS_CONTEXT
&, uint8_t* (&)[SWR_NUM_RENDERTARGETS
], uint32_t, const SWR_BLEND_STATE
*,
347 const PFN_BLEND_JIT_FUNC (&)[SWR_NUM_RENDERTARGETS
], simdscalar
&, simdscalar
);
348 typedef void(*PFN_CALC_PIXEL_BARYCENTRICS
)(const BarycentricCoeffs
&, SWR_PS_CONTEXT
&);
349 typedef void(*PFN_CALC_SAMPLE_BARYCENTRICS
)(const BarycentricCoeffs
&, SWR_PS_CONTEXT
&);
350 typedef void(*PFN_CALC_CENTROID_BARYCENTRICS
)(const BarycentricCoeffs
&, SWR_PS_CONTEXT
&, const uint64_t *const, const uint32_t,
351 const simdscalar
, const simdscalar
);
355 PFN_BACKEND_FUNC pfnBackend
;
363 void* pPrivateState
; // Its required the driver sets this up for each draw.
365 // pipeline function pointers, filled in by API thread when setting up the draw
366 BACKEND_FUNCS backendFuncs
;
367 PFN_PROCESS_PRIMS pfnProcessPrims
;
368 #if USE_SIMD16_FRONTEND
369 PFN_PROCESS_PRIMS_SIMD16 pfnProcessPrims_simd16
;
372 CachingArena
* pArena
; // This should only be used by API thread.
375 struct DRAW_DYNAMIC_STATE
377 void Reset(uint32_t numThreads
)
379 SWR_STATS
* pSavePtr
= pStats
;
380 memset(this, 0, sizeof(*this));
382 memset(pStats
, 0, sizeof(SWR_STATS
) * numThreads
);
384 ///@todo Currently assumes only a single FE can do stream output for a draw.
385 uint32_t SoWriteOffset
[4];
386 bool SoWriteOffsetDirty
[4];
388 SWR_STATS_FE statsFE
; // Only one FE thread per DC.
393 // The api thread sets up a draw context that exists for the life of the draw.
394 // This draw context maintains all of the state needed for the draw operation.
397 SWR_CONTEXT
* pContext
;
400 MacroTileMgr
* pTileMgr
;
401 DispatchQueue
* pDispatch
; // Queue for thread groups. (isCompute)
403 DRAW_STATE
* pState
; // Read-only state. Core should not update this outside of API thread.
404 DRAW_DYNAMIC_STATE dynState
;
406 CachingArena
* pArena
;
409 bool dependentFE
; // Frontend work is dependent on all previous FE
410 bool dependent
; // Backend work is dependent on all previous BE
411 bool isCompute
; // Is this DC a compute context?
412 bool cleanupState
; // True if this is the last draw using an entry in the state ring.
413 volatile bool doneFE
; // Is FE work done for this draw?
417 volatile OSALIGNLINE(uint32_t) FeLock
;
418 volatile int32_t threadsDone
;
420 SYNC_DESC retireCallback
; // Call this func when this DC is retired.
423 static_assert((sizeof(DRAW_CONTEXT
) & 63) == 0, "Invalid size for DRAW_CONTEXT");
425 INLINE
const API_STATE
& GetApiState(const DRAW_CONTEXT
* pDC
)
427 SWR_ASSERT(pDC
!= nullptr);
428 SWR_ASSERT(pDC
->pState
!= nullptr);
430 return pDC
->pState
->state
;
433 INLINE
void* GetPrivateState(const DRAW_CONTEXT
* pDC
)
435 SWR_ASSERT(pDC
!= nullptr);
436 SWR_ASSERT(pDC
->pState
!= nullptr);
438 return pDC
->pState
->pPrivateState
;
446 // Each draw needs its own state in order to support mulitple draws in flight across multiple threads.
447 // We maintain N draw contexts configured as a ring. The size of the ring limits the maximum number
448 // of draws that can be in flight at any given time.
451 // 1. State - When an application first sets state we'll request a new draw context to use.
452 // a. If there are no available draw contexts then we'll have to wait until one becomes free.
453 // b. If one is available then set pCurDrawContext to point to it and mark it in use.
454 // c. All state calls set state on pCurDrawContext.
455 // 2. Draw - Creates submits a work item that is associated with current draw context.
456 // a. Set pPrevDrawContext = pCurDrawContext
457 // b. Set pCurDrawContext to NULL.
458 // 3. State - When an applications sets state after draw
459 // a. Same as step 1.
460 // b. State is copied from prev draw context to current.
461 RingBuffer
<DRAW_CONTEXT
> dcRing
;
463 DRAW_CONTEXT
*pCurDrawContext
; // This points to DC entry in ring for an unsubmitted draw.
464 DRAW_CONTEXT
*pPrevDrawContext
; // This points to DC entry for the previous context submitted that we can copy state from.
466 MacroTileMgr
* pMacroTileManagerArray
;
467 DispatchQueue
* pDispatchQueueArray
;
470 // When draw are very large (lots of primitives) then the API thread will break these up.
471 // These split draws all have identical state. So instead of storing the state directly
472 // in the Draw Context (DC) we instead store it in a Draw State (DS). This allows multiple DCs
473 // to reference a single entry in the DS ring.
474 RingBuffer
<DRAW_STATE
> dsRing
;
476 uint32_t curStateId
; // Current index to the next available entry in the DS ring.
478 uint32_t NumWorkerThreads
;
479 uint32_t NumFEThreads
;
480 uint32_t NumBEThreads
;
482 THREAD_POOL threadPool
; // Thread pool associated with this context
483 SWR_THREADING_INFO threadInfo
;
485 std::condition_variable FifosNotEmpty
;
488 uint32_t privateStateSize
;
490 HotTileMgr
*pHotTileMgr
;
492 // Callback functions, passed in at create context time
493 PFN_LOAD_TILE pfnLoadTile
;
494 PFN_STORE_TILE pfnStoreTile
;
495 PFN_CLEAR_TILE pfnClearTile
;
496 PFN_UPDATE_SO_WRITE_OFFSET pfnUpdateSoWriteOffset
;
497 PFN_UPDATE_STATS pfnUpdateStats
;
498 PFN_UPDATE_STATS_FE pfnUpdateStatsFE
;
504 // Scratch space for workers.
507 volatile int32_t drawsOutstandingFE
;
509 CachingAllocator cachingArenaAllocator
;
512 uint32_t lastFrameChecked
;
513 uint64_t lastDrawChecked
;
514 TileSet singleThreadLockedTiles
;
516 // ArchRast thread contexts.
520 #define UPDATE_STAT_BE(name, count) if (GetApiState(pDC).enableStatsBE) { pDC->dynState.pStats[workerId].name += count; }
521 #define UPDATE_STAT_FE(name, count) if (GetApiState(pDC).enableStatsFE) { pDC->dynState.statsFE.name += count; }
523 // ArchRast instrumentation framework
524 #define AR_WORKER_CTX pContext->pArContext[workerId]
525 #define AR_API_CTX pContext->pArContext[pContext->NumWorkerThreads]
527 #ifdef KNOB_ENABLE_AR
528 #define _AR_BEGIN(ctx, type, id) ArchRast::Dispatch(ctx, ArchRast::Start(ArchRast::type, id))
529 #define _AR_END(ctx, type, count) ArchRast::Dispatch(ctx, ArchRast::End(ArchRast::type, count))
530 #define _AR_EVENT(ctx, event) ArchRast::Dispatch(ctx, ArchRast::event)
531 #define _AR_FLUSH(ctx, id) ArchRast::FlushDraw(ctx, id)
533 #ifdef KNOB_ENABLE_RDTSC
534 #define _AR_BEGIN(ctx, type, id) (void)ctx; RDTSC_START(type)
535 #define _AR_END(ctx, type, id) RDTSC_STOP(type, id, 0)
537 #define _AR_BEGIN(ctx, type, id) (void)ctx
538 #define _AR_END(ctx, type, id)
540 #define _AR_EVENT(ctx, event)
541 #define _AR_FLUSH(ctx, id)
544 // Use these macros for api thread.
545 #define AR_API_BEGIN(type, id) _AR_BEGIN(AR_API_CTX, type, id)
546 #define AR_API_END(type, count) _AR_END(AR_API_CTX, type, count)
547 #define AR_API_EVENT(event) _AR_EVENT(AR_API_CTX, event)
549 // Use these macros for worker threads.
550 #define AR_BEGIN(type, id) _AR_BEGIN(AR_WORKER_CTX, type, id)
551 #define AR_END(type, count) _AR_END(AR_WORKER_CTX, type, count)
552 #define AR_EVENT(event) _AR_EVENT(AR_WORKER_CTX, event)
553 #define AR_FLUSH(id) _AR_FLUSH(AR_WORKER_CTX, id)