swr: [rasterizer core] implement depth bounds test
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / context.h
1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
3 *
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:
10 *
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
13 * Software.
14 *
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
21 * IN THE SOFTWARE.
22 *
23 * @file context.h
24 *
25 * @brief Definitions for SWR_CONTEXT and DRAW_CONTEXT
26 * The SWR_CONTEXT is our global context and contains the DC ring,
27 * thread state, etc.
28 *
29 * The DRAW_CONTEXT contains all state associated with a draw operation.
30 *
31 ******************************************************************************/
32 #pragma once
33
34 #include <condition_variable>
35 #include <algorithm>
36
37 #include "core/api.h"
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"
46
47 // x.8 fixed point precision values
48 #define FIXED_POINT_SHIFT 8
49 #define FIXED_POINT_SCALE 256
50
51 // x.16 fixed point precision values
52 #define FIXED_POINT16_SHIFT 16
53 #define FIXED_POINT16_SCALE 65536
54
55 struct SWR_CONTEXT;
56 struct DRAW_CONTEXT;
57
58 struct TRI_FLAGS
59 {
60 uint32_t frontFacing : 1;
61 uint32_t yMajor : 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);
64 float pointSize;
65 uint32_t primID;
66 uint32_t renderTargetArrayIndex;
67 uint32_t viewportIndex;
68 };
69
70 //////////////////////////////////////////////////////////////////////////
71 /// SWR_TRIANGLE_DESC
72 /////////////////////////////////////////////////////////////////////////
73 struct SWR_TRIANGLE_DESC
74 {
75 float I[3];
76 float J[3];
77 float Z[3];
78 float OneOverW[3];
79 float recipDet;
80
81 float *pRecipW;
82 float *pAttribs;
83 float *pPerspAttribs;
84 float *pSamplePos;
85 float *pUserClipBuffer;
86
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;
90
91 TRI_FLAGS triFlags;
92 };
93
94 struct TRIANGLE_WORK_DESC
95 {
96 float *pTriBuffer;
97 float *pAttribs;
98 float *pUserClipBuffer;
99 uint32_t numAttribs;
100 TRI_FLAGS triFlags;
101 };
102
103 union CLEAR_FLAGS
104 {
105 struct
106 {
107 uint32_t mask : 3;
108 };
109 uint32_t bits;
110 };
111
112 struct CLEAR_DESC
113 {
114 SWR_RECT rect;
115 CLEAR_FLAGS flags;
116 float clearRTColor[4]; // RGBA_32F
117 float clearDepth; // [0..1]
118 uint8_t clearStencil;
119 };
120
121 struct DISCARD_INVALIDATE_TILES_DESC
122 {
123 uint32_t attachmentMask;
124 SWR_RECT rect;
125 SWR_TILE_STATE newTileState;
126 bool createNewTiles;
127 bool fullTilesOnly;
128 };
129
130 struct SYNC_DESC
131 {
132 PFN_CALLBACK_FUNC pfnCallbackFunc;
133 uint64_t userData;
134 uint64_t userData2;
135 uint64_t userData3;
136 };
137
138 struct STORE_TILES_DESC
139 {
140 uint32_t attachmentMask;
141 SWR_TILE_STATE postStoreTileState;
142 SWR_RECT rect;
143 };
144
145 struct COMPUTE_DESC
146 {
147 uint32_t threadGroupCountX;
148 uint32_t threadGroupCountY;
149 uint32_t threadGroupCountZ;
150 };
151
152 typedef void(*PFN_WORK_FUNC)(DRAW_CONTEXT* pDC, uint32_t workerId, uint32_t macroTile, void* pDesc);
153
154 enum WORK_TYPE
155 {
156 SYNC,
157 DRAW,
158 CLEAR,
159 DISCARDINVALIDATETILES,
160 STORETILES,
161 SHUTDOWN,
162 };
163
164 OSALIGNSIMD(struct) BE_WORK
165 {
166 WORK_TYPE type;
167 PFN_WORK_FUNC pfnWork;
168 union
169 {
170 SYNC_DESC sync;
171 TRIANGLE_WORK_DESC tri;
172 CLEAR_DESC clear;
173 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles;
174 STORE_TILES_DESC storeTiles;
175 } desc;
176 };
177
178 struct DRAW_WORK
179 {
180 DRAW_CONTEXT* pDC;
181 union
182 {
183 uint32_t numIndices; // DrawIndexed: Number of indices for draw.
184 uint32_t numVerts; // Draw: Number of verts (triangles, lines, etc)
185 };
186 union
187 {
188 const int32_t* pIB; // DrawIndexed: App supplied indices
189 uint32_t startVertex; // Draw: Starting vertex in VB to render from.
190 };
191 int32_t baseVertex;
192 uint32_t numInstances; // Number of instances
193 uint32_t startInstance; // Instance offset
194 uint32_t startPrimID; // starting primitiveID for this draw batch
195 uint32_t startVertexID; // starting VertexID for this draw batch (only needed for non-indexed draws)
196 SWR_FORMAT type; // index buffer type
197 };
198
199 typedef void(*PFN_FE_WORK_FUNC)(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC, uint32_t workerId, void* pDesc);
200 struct FE_WORK
201 {
202 WORK_TYPE type;
203 PFN_FE_WORK_FUNC pfnWork;
204 union
205 {
206 SYNC_DESC sync;
207 DRAW_WORK draw;
208 CLEAR_DESC clear;
209 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles;
210 STORE_TILES_DESC storeTiles;
211 } desc;
212 };
213
214 struct GUARDBANDS
215 {
216 float left[KNOB_NUM_VIEWPORTS_SCISSORS];
217 float right[KNOB_NUM_VIEWPORTS_SCISSORS];
218 float top[KNOB_NUM_VIEWPORTS_SCISSORS];
219 float bottom[KNOB_NUM_VIEWPORTS_SCISSORS];
220 };
221
222 struct PA_STATE;
223
224 // function signature for pipeline stages that execute after primitive assembly
225 typedef void(*PFN_PROCESS_PRIMS)(DRAW_CONTEXT *pDC, PA_STATE& pa, uint32_t workerId, simdvector prims[],
226 uint32_t primMask, simdscalari primID, simdscalari viewportIdx);
227
228 OSALIGNLINE(struct) API_STATE
229 {
230 // Vertex Buffers
231 SWR_VERTEX_BUFFER_STATE vertexBuffers[KNOB_NUM_STREAMS];
232
233 // Index Buffer
234 SWR_INDEX_BUFFER_STATE indexBuffer;
235
236 // FS - Fetch Shader State
237 PFN_FETCH_FUNC pfnFetchFunc;
238
239 // VS - Vertex Shader State
240 PFN_VERTEX_FUNC pfnVertexFunc;
241
242 // GS - Geometry Shader State
243 PFN_GS_FUNC pfnGsFunc;
244 SWR_GS_STATE gsState;
245
246 // CS - Compute Shader
247 PFN_CS_FUNC pfnCsFunc;
248 uint32_t totalThreadsInGroup;
249 uint32_t totalSpillFillSize;
250
251 // FE - Frontend State
252 SWR_FRONTEND_STATE frontendState;
253
254 // SOS - Streamout Shader State
255 PFN_SO_FUNC pfnSoFunc[MAX_SO_STREAMS];
256
257 // Streamout state
258 SWR_STREAMOUT_STATE soState;
259 mutable SWR_STREAMOUT_BUFFER soBuffer[MAX_SO_STREAMS];
260
261 // Tessellation State
262 PFN_HS_FUNC pfnHsFunc;
263 PFN_DS_FUNC pfnDsFunc;
264 SWR_TS_STATE tsState;
265
266 // Number of attributes used by the frontend (vs, so, gs)
267 uint32_t feNumAttributes;
268
269 PRIMITIVE_TOPOLOGY topology;
270 bool forceFront;
271
272 // RS - Rasterizer State
273 SWR_RASTSTATE rastState;
274 // floating point multisample offsets
275 float samplePos[SWR_MAX_NUM_MULTISAMPLES * 2];
276
277 GUARDBANDS gbState;
278
279 SWR_VIEWPORT vp[KNOB_NUM_VIEWPORTS_SCISSORS];
280 SWR_VIEWPORT_MATRICES vpMatrices;
281
282 SWR_RECT scissorRects[KNOB_NUM_VIEWPORTS_SCISSORS];
283 SWR_RECT scissorsInFixedPoint[KNOB_NUM_VIEWPORTS_SCISSORS];
284 bool scissorsTileAligned;
285
286 // Backend state
287 SWR_BACKEND_STATE backendState;
288
289 SWR_DEPTH_BOUNDS_STATE depthBoundsState;
290
291 // PS - Pixel shader state
292 SWR_PS_STATE psState;
293
294 SWR_DEPTH_STENCIL_STATE depthStencilState;
295
296 // OM - Output Merger State
297 SWR_BLEND_STATE blendState;
298 PFN_BLEND_JIT_FUNC pfnBlendFunc[SWR_NUM_RENDERTARGETS];
299
300 // Stats are incremented when this is true.
301 bool enableStats;
302
303 struct
304 {
305 uint32_t colorHottileEnable : 8;
306 uint32_t depthHottileEnable: 1;
307 uint32_t stencilHottileEnable : 1;
308 };
309
310 PFN_QUANTIZE_DEPTH pfnQuantizeDepth;
311 };
312
313 class MacroTileMgr;
314 class DispatchQueue;
315
316 struct RenderOutputBuffers
317 {
318 uint8_t* pColor[SWR_NUM_RENDERTARGETS];
319 uint8_t* pDepth;
320 uint8_t* pStencil;
321 };
322
323 // Plane equation A/B/C coeffs used to evaluate I/J barycentric coords
324 struct BarycentricCoeffs
325 {
326 simdscalar vIa;
327 simdscalar vIb;
328 simdscalar vIc;
329
330 simdscalar vJa;
331 simdscalar vJb;
332 simdscalar vJc;
333
334 simdscalar vZa;
335 simdscalar vZb;
336 simdscalar vZc;
337
338 simdscalar vRecipDet;
339
340 simdscalar vAOneOverW;
341 simdscalar vBOneOverW;
342 simdscalar vCOneOverW;
343 };
344
345 // pipeline function pointer types
346 typedef void(*PFN_BACKEND_FUNC)(DRAW_CONTEXT*, uint32_t, uint32_t, uint32_t, SWR_TRIANGLE_DESC&, RenderOutputBuffers&);
347 typedef void(*PFN_OUTPUT_MERGER)(SWR_PS_CONTEXT &, uint8_t* (&)[SWR_NUM_RENDERTARGETS], uint32_t, const SWR_BLEND_STATE*,
348 const PFN_BLEND_JIT_FUNC (&)[SWR_NUM_RENDERTARGETS], simdscalar&, simdscalar);
349 typedef void(*PFN_CALC_PIXEL_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT &);
350 typedef void(*PFN_CALC_SAMPLE_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT&);
351 typedef void(*PFN_CALC_CENTROID_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT &, const uint64_t *const, const uint32_t,
352 const simdscalar, const simdscalar);
353
354 struct BACKEND_FUNCS
355 {
356 PFN_BACKEND_FUNC pfnBackend;
357 };
358
359 // Draw State
360 struct DRAW_STATE
361 {
362 API_STATE state;
363
364 void* pPrivateState; // Its required the driver sets this up for each draw.
365
366 // pipeline function pointers, filled in by API thread when setting up the draw
367 BACKEND_FUNCS backendFuncs;
368 PFN_PROCESS_PRIMS pfnProcessPrims;
369
370 CachingArena* pArena; // This should only be used by API thread.
371 };
372
373 struct DRAW_DYNAMIC_STATE
374 {
375 void Reset(uint32_t numThreads)
376 {
377 SWR_STATS* pSavePtr = pStats;
378 memset(this, 0, sizeof(*this));
379 pStats = pSavePtr;
380 memset(pStats, 0, sizeof(SWR_STATS) * numThreads);
381 }
382 ///@todo Currently assumes only a single FE can do stream output for a draw.
383 uint32_t SoWriteOffset[4];
384 bool SoWriteOffsetDirty[4];
385
386 SWR_STATS_FE statsFE; // Only one FE thread per DC.
387 SWR_STATS* pStats;
388 };
389
390 // Draw Context
391 // The api thread sets up a draw context that exists for the life of the draw.
392 // This draw context maintains all of the state needed for the draw operation.
393 struct DRAW_CONTEXT
394 {
395 SWR_CONTEXT* pContext;
396 union
397 {
398 MacroTileMgr* pTileMgr;
399 DispatchQueue* pDispatch; // Queue for thread groups. (isCompute)
400 };
401 DRAW_STATE* pState; // Read-only state. Core should not update this outside of API thread.
402 DRAW_DYNAMIC_STATE dynState;
403
404 CachingArena* pArena;
405
406 uint32_t drawId;
407 bool dependent;
408 bool isCompute; // Is this DC a compute context?
409 bool cleanupState; // True if this is the last draw using an entry in the state ring.
410 volatile bool doneFE; // Is FE work done for this draw?
411
412 FE_WORK FeWork;
413
414 volatile OSALIGNLINE(uint32_t) FeLock;
415 volatile int32_t threadsDone;
416
417 SYNC_DESC retireCallback; // Call this func when this DC is retired.
418 };
419
420 static_assert((sizeof(DRAW_CONTEXT) & 63) == 0, "Invalid size for DRAW_CONTEXT");
421
422 INLINE const API_STATE& GetApiState(const DRAW_CONTEXT* pDC)
423 {
424 SWR_ASSERT(pDC != nullptr);
425 SWR_ASSERT(pDC->pState != nullptr);
426
427 return pDC->pState->state;
428 }
429
430 INLINE void* GetPrivateState(const DRAW_CONTEXT* pDC)
431 {
432 SWR_ASSERT(pDC != nullptr);
433 SWR_ASSERT(pDC->pState != nullptr);
434
435 return pDC->pState->pPrivateState;
436 }
437
438 class HotTileMgr;
439
440 struct SWR_CONTEXT
441 {
442 // Draw Context Ring
443 // Each draw needs its own state in order to support mulitple draws in flight across multiple threads.
444 // We maintain N draw contexts configured as a ring. The size of the ring limits the maximum number
445 // of draws that can be in flight at any given time.
446 //
447 // Description:
448 // 1. State - When an application first sets state we'll request a new draw context to use.
449 // a. If there are no available draw contexts then we'll have to wait until one becomes free.
450 // b. If one is available then set pCurDrawContext to point to it and mark it in use.
451 // c. All state calls set state on pCurDrawContext.
452 // 2. Draw - Creates submits a work item that is associated with current draw context.
453 // a. Set pPrevDrawContext = pCurDrawContext
454 // b. Set pCurDrawContext to NULL.
455 // 3. State - When an applications sets state after draw
456 // a. Same as step 1.
457 // b. State is copied from prev draw context to current.
458 RingBuffer<DRAW_CONTEXT> dcRing;
459
460 DRAW_CONTEXT *pCurDrawContext; // This points to DC entry in ring for an unsubmitted draw.
461 DRAW_CONTEXT *pPrevDrawContext; // This points to DC entry for the previous context submitted that we can copy state from.
462
463 MacroTileMgr* pMacroTileManagerArray;
464 DispatchQueue* pDispatchQueueArray;
465
466 // Draw State Ring
467 // When draw are very large (lots of primitives) then the API thread will break these up.
468 // These split draws all have identical state. So instead of storing the state directly
469 // in the Draw Context (DC) we instead store it in a Draw State (DS). This allows multiple DCs
470 // to reference a single entry in the DS ring.
471 RingBuffer<DRAW_STATE> dsRing;
472
473 uint32_t curStateId; // Current index to the next available entry in the DS ring.
474
475 uint32_t NumWorkerThreads;
476 uint32_t NumFEThreads;
477 uint32_t NumBEThreads;
478
479 THREAD_POOL threadPool; // Thread pool associated with this context
480 SWR_THREADING_INFO threadInfo;
481
482 std::condition_variable FifosNotEmpty;
483 std::mutex WaitLock;
484
485 DRIVER_TYPE driverType;
486
487 uint32_t privateStateSize;
488
489 HotTileMgr *pHotTileMgr;
490
491 // Callback functions, passed in at create context time
492 PFN_LOAD_TILE pfnLoadTile;
493 PFN_STORE_TILE pfnStoreTile;
494 PFN_CLEAR_TILE pfnClearTile;
495 PFN_UPDATE_SO_WRITE_OFFSET pfnUpdateSoWriteOffset;
496 PFN_UPDATE_STATS pfnUpdateStats;
497 PFN_UPDATE_STATS_FE pfnUpdateStatsFE;
498
499 // Global Stats
500 SWR_STATS* pStats;
501
502 // Scratch space for workers.
503 uint8_t** ppScratch;
504
505 volatile int32_t drawsOutstandingFE;
506
507 CachingAllocator cachingArenaAllocator;
508 uint32_t frameCount;
509
510 uint32_t lastFrameChecked;
511 uint64_t lastDrawChecked;
512 TileSet singleThreadLockedTiles;
513
514 // ArchRast thread contexts.
515 HANDLE* pArContext;
516 };
517
518 #define UPDATE_STAT(name, count) if (GetApiState(pDC).enableStats) { pDC->dynState.pStats[workerId].name += count; }
519 #define UPDATE_STAT_FE(name, count) if (GetApiState(pDC).enableStats) { pDC->dynState.statsFE.name += count; }
520
521 // ArchRast instrumentation framework
522 #define AR_WORKER_CTX pContext->pArContext[workerId]
523 #define AR_API_CTX pContext->pArContext[pContext->NumWorkerThreads]
524
525 #ifdef KNOB_ENABLE_AR
526 #define _AR_BEGIN(ctx, type, id) ArchRast::dispatch(ctx, ArchRast::Start(ArchRast::type, id))
527 #define _AR_END(ctx, type, count) ArchRast::dispatch(ctx, ArchRast::End(ArchRast::type, count))
528 #define _AR_EVENT(ctx, event) ArchRast::dispatch(ctx, ArchRast::event)
529 #else
530 #ifdef KNOB_ENABLE_RDTSC
531 #define _AR_BEGIN(ctx, type, id) (void)ctx; RDTSC_START(type)
532 #define _AR_END(ctx, type, id) RDTSC_STOP(type, id, 0)
533 #else
534 #define _AR_BEGIN(ctx, type, id) (void)ctx
535 #define _AR_END(ctx, type, id)
536 #endif
537 #define _AR_EVENT(ctx, event)
538 #endif
539
540 // Use these macros for api thread.
541 #define AR_API_BEGIN(type, id) _AR_BEGIN(AR_API_CTX, type, id)
542 #define AR_API_END(type, count) _AR_END(AR_API_CTX, type, count)
543 #define AR_API_EVENT(event) _AR_EVENT(AR_API_CTX, event)
544
545 // Use these macros for worker threads.
546 #define AR_BEGIN(type, id) _AR_BEGIN(AR_WORKER_CTX, type, id)
547 #define AR_END(type, count) _AR_END(AR_WORKER_CTX, type, count)
548 #define AR_EVENT(event) _AR_EVENT(AR_WORKER_CTX, event)