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