1 /*
2  * Copyright (C) 2012 Rob Clark <robclark@freedesktop.org>
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 FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  *
23  * Authors:
24  *    Rob Clark <robclark@freedesktop.org>
25  */
26 
27 #ifndef FREEDRENO_CONTEXT_H_
28 #define FREEDRENO_CONTEXT_H_
29 
30 #include "pipe/p_context.h"
31 #include "indices/u_primconvert.h"
32 #include "util/u_blitter.h"
33 #include "util/libsync.h"
34 #include "util/list.h"
35 #include "util/slab.h"
36 #include "util/u_string.h"
37 
38 #include "freedreno_batch.h"
39 #include "freedreno_screen.h"
40 #include "freedreno_gmem.h"
41 #include "freedreno_util.h"
42 
43 #define BORDER_COLOR_UPLOAD_SIZE (2 * PIPE_MAX_SAMPLERS * BORDERCOLOR_SIZE)
44 
45 struct fd_vertex_stateobj;
46 
47 struct fd_texture_stateobj {
48 	struct pipe_sampler_view *textures[PIPE_MAX_SAMPLERS];
49 	unsigned num_textures;
50 	unsigned valid_textures;
51 	struct pipe_sampler_state *samplers[PIPE_MAX_SAMPLERS];
52 	unsigned num_samplers;
53 	unsigned valid_samplers;
54 	/* number of samples per sampler, 2 bits per sampler: */
55 	uint32_t samples;
56 };
57 
58 struct fd_program_stateobj {
59 	void *vs, *hs, *ds, *gs, *fs;
60 };
61 
62 struct fd_constbuf_stateobj {
63 	struct pipe_constant_buffer cb[PIPE_MAX_CONSTANT_BUFFERS];
64 	uint32_t enabled_mask;
65 };
66 
67 struct fd_shaderbuf_stateobj {
68 	struct pipe_shader_buffer sb[PIPE_MAX_SHADER_BUFFERS];
69 	uint32_t enabled_mask;
70 	uint32_t writable_mask;
71 };
72 
73 struct fd_shaderimg_stateobj {
74 	struct pipe_image_view si[PIPE_MAX_SHADER_IMAGES];
75 	uint32_t enabled_mask;
76 };
77 
78 struct fd_vertexbuf_stateobj {
79 	struct pipe_vertex_buffer vb[PIPE_MAX_ATTRIBS];
80 	unsigned count;
81 	uint32_t enabled_mask;
82 };
83 
84 struct fd_vertex_stateobj {
85 	struct pipe_vertex_element pipe[PIPE_MAX_ATTRIBS];
86 	unsigned num_elements;
87 };
88 
89 struct fd_streamout_stateobj {
90 	struct pipe_stream_output_target *targets[PIPE_MAX_SO_BUFFERS];
91 	/* Bitmask of stream that should be reset. */
92 	unsigned reset;
93 
94 	unsigned num_targets;
95 	/* Track offset from vtxcnt for streamout data.  This counter
96 	 * is just incremented by # of vertices on each draw until
97 	 * reset or new streamout buffer bound.
98 	 *
99 	 * When we eventually have GS, the CPU won't actually know the
100 	 * number of vertices per draw, so I think we'll have to do
101 	 * something more clever.
102 	 */
103 	unsigned offsets[PIPE_MAX_SO_BUFFERS];
104 };
105 
106 #define MAX_GLOBAL_BUFFERS 16
107 struct fd_global_bindings_stateobj {
108 	struct pipe_resource *buf[MAX_GLOBAL_BUFFERS];
109 	uint32_t enabled_mask;
110 };
111 
112 /* group together the vertex and vertexbuf state.. for ease of passing
113  * around, and because various internal operations (gmem<->mem, etc)
114  * need their own vertex state:
115  */
116 struct fd_vertex_state {
117 	struct fd_vertex_stateobj *vtx;
118 	struct fd_vertexbuf_stateobj vertexbuf;
119 };
120 
121 /* global 3d pipeline dirty state: */
122 enum fd_dirty_3d_state {
123 	FD_DIRTY_BLEND       = BIT(0),
124 	FD_DIRTY_RASTERIZER  = BIT(1),
125 	FD_DIRTY_ZSA         = BIT(2),
126 	FD_DIRTY_BLEND_COLOR = BIT(3),
127 	FD_DIRTY_STENCIL_REF = BIT(4),
128 	FD_DIRTY_SAMPLE_MASK = BIT(5),
129 	FD_DIRTY_FRAMEBUFFER = BIT(6),
130 	FD_DIRTY_STIPPLE     = BIT(7),
131 	FD_DIRTY_VIEWPORT    = BIT(8),
132 	FD_DIRTY_VTXSTATE    = BIT(9),
133 	FD_DIRTY_VTXBUF      = BIT(10),
134 	FD_DIRTY_MIN_SAMPLES = BIT(11),
135 	FD_DIRTY_SCISSOR     = BIT(12),
136 	FD_DIRTY_STREAMOUT   = BIT(13),
137 	FD_DIRTY_UCP         = BIT(14),
138 	FD_DIRTY_BLEND_DUAL  = BIT(15),
139 
140 	/* These are a bit redundent with fd_dirty_shader_state, and possibly
141 	 * should be removed.  (But OTOH kinda convenient in some places)
142 	 */
143 	FD_DIRTY_PROG        = BIT(16),
144 	FD_DIRTY_CONST       = BIT(17),
145 	FD_DIRTY_TEX         = BIT(18),
146 	FD_DIRTY_IMAGE       = BIT(19),
147 	FD_DIRTY_SSBO        = BIT(20),
148 
149 	/* only used by a2xx.. possibly can be removed.. */
150 	FD_DIRTY_TEXSTATE    = BIT(21),
151 
152 	/* fine grained state changes, for cases where state is not orthogonal
153 	 * from hw perspective:
154 	 */
155 	FD_DIRTY_RASTERIZER_DISCARD = BIT(24),
156 };
157 
158 /* per shader-stage dirty state: */
159 enum fd_dirty_shader_state {
160 	FD_DIRTY_SHADER_PROG  = BIT(0),
161 	FD_DIRTY_SHADER_CONST = BIT(1),
162 	FD_DIRTY_SHADER_TEX   = BIT(2),
163 	FD_DIRTY_SHADER_SSBO  = BIT(3),
164 	FD_DIRTY_SHADER_IMAGE = BIT(4),
165 };
166 
167 struct fd_context {
168 	struct pipe_context base;
169 
170 	struct list_head node;   /* node in screen->context_list */
171 
172 	/* We currently need to serialize emitting GMEM batches, because of
173 	 * VSC state access in the context.
174 	 *
175 	 * In practice this lock should not be contended, since pipe_context
176 	 * use should be single threaded.  But it is needed to protect the
177 	 * case, with batch reordering where a ctxB batch triggers flushing
178 	 * a ctxA batch
179 	 */
180 	mtx_t gmem_lock;
181 
182 	struct fd_device *dev;
183 	struct fd_screen *screen;
184 	struct fd_pipe *pipe;
185 
186 	struct blitter_context *blitter;
187 	void *clear_rs_state[2];
188 	struct primconvert_context *primconvert;
189 
190 	/* slab for pipe_transfer allocations: */
191 	struct slab_child_pool transfer_pool;
192 
193 	/**
194 	 * query related state:
195 	 */
196 	/*@{*/
197 	/* slabs for fd_hw_sample and fd_hw_sample_period allocations: */
198 	struct slab_mempool sample_pool;
199 	struct slab_mempool sample_period_pool;
200 
201 	/* sample-providers for hw queries: */
202 	const struct fd_hw_sample_provider *hw_sample_providers[MAX_HW_SAMPLE_PROVIDERS];
203 
204 	/* list of active queries: */
205 	struct list_head hw_active_queries;
206 
207 	/* sample-providers for accumulating hw queries: */
208 	const struct fd_acc_sample_provider *acc_sample_providers[MAX_HW_SAMPLE_PROVIDERS];
209 
210 	/* list of active accumulating queries: */
211 	struct list_head acc_active_queries;
212 	/*@}*/
213 
214 	/* Whether we need to walk the acc_active_queries next fd_set_stage() to
215 	 * update active queries (even if stage doesn't change).
216 	 */
217 	bool update_active_queries;
218 
219 	/* Current state of pctx->set_active_query_state() (i.e. "should drawing
220 	 * be counted against non-perfcounter queries")
221 	 */
222 	bool active_queries;
223 
224 	/* table with PIPE_PRIM_MAX entries mapping PIPE_PRIM_x to
225 	 * DI_PT_x value to use for draw initiator.  There are some
226 	 * slight differences between generation:
227 	 */
228 	const uint8_t *primtypes;
229 	uint32_t primtype_mask;
230 
231 	/* shaders used by clear, and gmem->mem blits: */
232 	struct fd_program_stateobj solid_prog; // TODO move to screen?
233 
234 	/* shaders used by mem->gmem blits: */
235 	struct fd_program_stateobj blit_prog[MAX_RENDER_TARGETS]; // TODO move to screen?
236 	struct fd_program_stateobj blit_z, blit_zs;
237 
238 	/* Stats/counters:
239 	 */
240 	struct {
241 		uint64_t prims_emitted;
242 		uint64_t prims_generated;
243 		uint64_t draw_calls;
244 		uint64_t batch_total, batch_sysmem, batch_gmem, batch_nondraw, batch_restore;
245 		uint64_t staging_uploads, shadow_uploads;
246 		uint64_t vs_regs, hs_regs, ds_regs, gs_regs, fs_regs;
247 	} stats;
248 
249 	/* Current batch.. the rule here is that you can deref ctx->batch
250 	 * in codepaths from pipe_context entrypoints.  But not in code-
251 	 * paths from fd_batch_flush() (basically, the stuff that gets
252 	 * called from GMEM code), since in those code-paths the batch
253 	 * you care about is not necessarily the same as ctx->batch.
254 	 */
255 	struct fd_batch *batch;
256 
257 	/* NULL if there has been rendering since last flush.  Otherwise
258 	 * keeps a reference to the last fence so we can re-use it rather
259 	 * than having to flush no-op batch.
260 	 */
261 	struct pipe_fence_handle *last_fence;
262 
263 	/* Fence fd we are told to wait on via ->fence_server_sync() (or -1
264 	 * if none).  The in-fence is transferred over to the batch on the
265 	 * next draw/blit/grid.
266 	 *
267 	 * The reason for this extra complexity is that apps will typically
268 	 * do eglWaitSyncKHR()/etc at the beginning of the frame, before the
269 	 * first draw.  But mesa/st doesn't flush down framebuffer state
270 	 * change until we hit a draw, so at ->fence_server_sync() time, we
271 	 * don't yet have the correct batch.  If we created a batch at that
272 	 * point, it would be the wrong one, and we'd have to flush it pre-
273 	 * maturely, causing us to stall early in the frame where we could
274 	 * be building up cmdstream.
275 	 */
276 	int in_fence_fd;
277 
278 	/* track last known reset status globally and per-context to
279 	 * determine if more resets occurred since then.  If global reset
280 	 * count increases, it means some other context crashed.  If
281 	 * per-context reset count increases, it means we crashed the
282 	 * gpu.
283 	 */
284 	uint32_t context_reset_count, global_reset_count;
285 
286 	/* Are we in process of shadowing a resource? Used to detect recursion
287 	 * in transfer_map, and skip unneeded synchronization.
288 	 */
289 	bool in_shadow : 1;
290 
291 	/* Ie. in blit situation where we no longer care about previous framebuffer
292 	 * contents.  Main point is to eliminate blits from fd_try_shadow_resource().
293 	 * For example, in case of texture upload + gen-mipmaps.
294 	 */
295 	bool in_discard_blit : 1;
296 
297 	/* points to either scissor or disabled_scissor depending on rast state: */
298 	struct pipe_scissor_state *current_scissor;
299 
300 	struct pipe_scissor_state scissor;
301 
302 	/* we don't have a disable/enable bit for scissor, so instead we keep
303 	 * a disabled-scissor state which matches the entire bound framebuffer
304 	 * and use that when scissor is not enabled.
305 	 */
306 	struct pipe_scissor_state disabled_scissor;
307 
308 	/* Per vsc pipe bo's (a2xx-a5xx): */
309 	struct fd_bo *vsc_pipe_bo[32];
310 
311 	/* which state objects need to be re-emit'd: */
312 	enum fd_dirty_3d_state dirty;
313 
314 	/* per shader-stage dirty status: */
315 	enum fd_dirty_shader_state dirty_shader[PIPE_SHADER_TYPES];
316 
317 	void *compute;
318 	struct pipe_blend_state *blend;
319 	struct pipe_rasterizer_state *rasterizer;
320 	struct pipe_depth_stencil_alpha_state *zsa;
321 
322 	struct fd_texture_stateobj tex[PIPE_SHADER_TYPES];
323 
324 	struct fd_program_stateobj prog;
325 
326 	struct fd_vertex_state vtx;
327 
328 	struct pipe_blend_color blend_color;
329 	struct pipe_stencil_ref stencil_ref;
330 	unsigned sample_mask;
331 	unsigned min_samples;
332 	/* local context fb state, for when ctx->batch is null: */
333 	struct pipe_framebuffer_state framebuffer;
334 	struct pipe_poly_stipple stipple;
335 	struct pipe_viewport_state viewport;
336 	struct pipe_scissor_state viewport_scissor;
337 	struct fd_constbuf_stateobj constbuf[PIPE_SHADER_TYPES];
338 	struct fd_shaderbuf_stateobj shaderbuf[PIPE_SHADER_TYPES];
339 	struct fd_shaderimg_stateobj shaderimg[PIPE_SHADER_TYPES];
340 	struct fd_streamout_stateobj streamout;
341 	struct fd_global_bindings_stateobj global_bindings;
342 	struct pipe_clip_state ucp;
343 
344 	struct pipe_query *cond_query;
345 	bool cond_cond; /* inverted rendering condition */
346 	uint cond_mode;
347 
348 	struct pipe_debug_callback debug;
349 
350 	/* Called on rebind_resource() for any per-gen cleanup required: */
351 	void (*rebind_resource)(struct fd_context *ctx, struct fd_resource *rsc);
352 
353 	/* GMEM/tile handling fxns: */
354 	void (*emit_tile_init)(struct fd_batch *batch);
355 	void (*emit_tile_prep)(struct fd_batch *batch, const struct fd_tile *tile);
356 	void (*emit_tile_mem2gmem)(struct fd_batch *batch, const struct fd_tile *tile);
357 	void (*emit_tile_renderprep)(struct fd_batch *batch, const struct fd_tile *tile);
358 	void (*emit_tile)(struct fd_batch *batch, const struct fd_tile *tile);
359 	void (*emit_tile_gmem2mem)(struct fd_batch *batch, const struct fd_tile *tile);
360 	void (*emit_tile_fini)(struct fd_batch *batch);   /* optional */
361 
362 	/* optional, for GMEM bypass: */
363 	void (*emit_sysmem_prep)(struct fd_batch *batch);
364 	void (*emit_sysmem_fini)(struct fd_batch *batch);
365 
366 	/* draw: */
367 	bool (*draw_vbo)(struct fd_context *ctx, const struct pipe_draw_info *info,
368 			unsigned index_offset);
369 	bool (*clear)(struct fd_context *ctx, unsigned buffers,
370 			const union pipe_color_union *color, double depth, unsigned stencil);
371 
372 	/* compute: */
373 	void (*launch_grid)(struct fd_context *ctx, const struct pipe_grid_info *info);
374 
375 	/* query: */
376 	struct fd_query * (*create_query)(struct fd_context *ctx, unsigned query_type, unsigned index);
377 	void (*query_prepare)(struct fd_batch *batch, uint32_t num_tiles);
378 	void (*query_prepare_tile)(struct fd_batch *batch, uint32_t n,
379 			struct fd_ringbuffer *ring);
380 	void (*query_set_stage)(struct fd_batch *batch, enum fd_render_stage stage);
381 
382 	/* blitter: */
383 	bool (*blit)(struct fd_context *ctx, const struct pipe_blit_info *info);
384 	void (*clear_ubwc)(struct fd_batch *batch, struct fd_resource *rsc);
385 
386 	/* handling for barriers: */
387 	void (*framebuffer_barrier)(struct fd_context *ctx);
388 
389 	/* logger: */
390 	void (*record_timestamp)(struct fd_ringbuffer *ring, struct fd_bo *bo, unsigned offset);
391 	uint64_t (*ts_to_ns)(uint64_t ts);
392 
393 	struct list_head log_chunks;  /* list of flushed log chunks in fifo order */
394 	unsigned frame_nr;            /* frame counter (for fd_log) */
395 	FILE *log_out;
396 
397 	/*
398 	 * Common pre-cooked VBO state (used for a3xx and later):
399 	 */
400 
401 	/* for clear/gmem->mem vertices, and mem->gmem */
402 	struct pipe_resource *solid_vbuf;
403 
404 	/* for mem->gmem tex coords: */
405 	struct pipe_resource *blit_texcoord_vbuf;
406 
407 	/* vertex state for solid_vbuf:
408 	 *    - solid_vbuf / 12 / R32G32B32_FLOAT
409 	 */
410 	struct fd_vertex_state solid_vbuf_state;
411 
412 	/* vertex state for blit_prog:
413 	 *    - blit_texcoord_vbuf / 8 / R32G32_FLOAT
414 	 *    - solid_vbuf / 12 / R32G32B32_FLOAT
415 	 */
416 	struct fd_vertex_state blit_vbuf_state;
417 
418 	/*
419 	 * Info about state of previous draw, for state that comes from
420 	 * pipe_draw_info (ie. not part of a CSO).  This allows us to
421 	 * skip some register emit when the state doesn't change from
422 	 * draw-to-draw
423 	 */
424 	struct {
425 		bool dirty;               /* last draw state unknown */
426 		bool primitive_restart;
427 		uint32_t index_start;
428 		uint32_t instance_start;
429 		uint32_t restart_index;
430 		uint32_t streamout_mask;
431 	} last;
432 };
433 
434 static inline struct fd_context *
fd_context(struct pipe_context * pctx)435 fd_context(struct pipe_context *pctx)
436 {
437 	return (struct fd_context *)pctx;
438 }
439 
440 static inline void
fd_context_assert_locked(struct fd_context * ctx)441 fd_context_assert_locked(struct fd_context *ctx)
442 {
443 	fd_screen_assert_locked(ctx->screen);
444 }
445 
446 static inline void
fd_context_lock(struct fd_context * ctx)447 fd_context_lock(struct fd_context *ctx)
448 {
449 	fd_screen_lock(ctx->screen);
450 }
451 
452 static inline void
fd_context_unlock(struct fd_context * ctx)453 fd_context_unlock(struct fd_context *ctx)
454 {
455 	fd_screen_unlock(ctx->screen);
456 }
457 
458 /* mark all state dirty: */
459 static inline void
fd_context_all_dirty(struct fd_context * ctx)460 fd_context_all_dirty(struct fd_context *ctx)
461 {
462 	ctx->last.dirty = true;
463 	ctx->dirty = ~0;
464 	for (unsigned i = 0; i < PIPE_SHADER_TYPES; i++)
465 		ctx->dirty_shader[i] = ~0;
466 }
467 
468 static inline void
fd_context_all_clean(struct fd_context * ctx)469 fd_context_all_clean(struct fd_context *ctx)
470 {
471 	ctx->last.dirty = false;
472 	ctx->dirty = 0;
473 	for (unsigned i = 0; i < PIPE_SHADER_TYPES; i++) {
474 		/* don't mark compute state as clean, since it is not emitted
475 		 * during normal draw call.  The places that call _all_dirty(),
476 		 * it is safe to mark compute state dirty as well, but the
477 		 * inverse is not true.
478 		 */
479 		if (i == PIPE_SHADER_COMPUTE)
480 			continue;
481 		ctx->dirty_shader[i] = 0;
482 	}
483 }
484 
485 static inline struct pipe_scissor_state *
fd_context_get_scissor(struct fd_context * ctx)486 fd_context_get_scissor(struct fd_context *ctx)
487 {
488 	return ctx->current_scissor;
489 }
490 
491 static inline bool
fd_supported_prim(struct fd_context * ctx,unsigned prim)492 fd_supported_prim(struct fd_context *ctx, unsigned prim)
493 {
494 	return (1 << prim) & ctx->primtype_mask;
495 }
496 
497 /**
498  * If we have a pending fence_server_sync() (GPU side sync), flush now.
499  * The alternative to try to track this with batch dependencies gets
500  * hairy quickly.
501  *
502  * Call this before switching to a different batch, to handle this case.
503  */
504 static inline void
fd_context_switch_from(struct fd_context * ctx)505 fd_context_switch_from(struct fd_context *ctx)
506 {
507 	if (ctx->batch && (ctx->batch->in_fence_fd != -1))
508 		fd_batch_flush(ctx->batch);
509 }
510 
511 /**
512  * If there is a pending fence-fd that we need to sync on, this will
513  * transfer the reference to the next batch we are going to render
514  * to.
515  */
516 static inline void
fd_context_switch_to(struct fd_context * ctx,struct fd_batch * batch)517 fd_context_switch_to(struct fd_context *ctx, struct fd_batch *batch)
518 {
519 	if (ctx->in_fence_fd != -1) {
520 		sync_accumulate("freedreno", &batch->in_fence_fd, ctx->in_fence_fd);
521 		close(ctx->in_fence_fd);
522 		ctx->in_fence_fd = -1;
523 	}
524 }
525 
526 static inline struct fd_batch *
fd_context_batch(struct fd_context * ctx)527 fd_context_batch(struct fd_context *ctx)
528 {
529 	if (unlikely(!ctx->batch)) {
530 		struct fd_batch *batch =
531 			fd_batch_from_fb(&ctx->screen->batch_cache, ctx, &ctx->framebuffer);
532 		util_copy_framebuffer_state(&batch->framebuffer, &ctx->framebuffer);
533 		ctx->batch = batch;
534 		fd_context_all_dirty(ctx);
535 	}
536 	fd_context_switch_to(ctx, ctx->batch);
537 	return ctx->batch;
538 }
539 
540 static inline void
fd_batch_set_stage(struct fd_batch * batch,enum fd_render_stage stage)541 fd_batch_set_stage(struct fd_batch *batch, enum fd_render_stage stage)
542 {
543 	struct fd_context *ctx = batch->ctx;
544 
545 	if (ctx->query_set_stage)
546 		ctx->query_set_stage(batch, stage);
547 
548 	batch->stage = stage;
549 }
550 
551 void fd_context_setup_common_vbos(struct fd_context *ctx);
552 void fd_context_cleanup_common_vbos(struct fd_context *ctx);
553 void fd_emit_string(struct fd_ringbuffer *ring, const char *string, int len);
554 void fd_emit_string5(struct fd_ringbuffer *ring, const char *string, int len);
555 
556 struct pipe_context * fd_context_init(struct fd_context *ctx,
557 		struct pipe_screen *pscreen, const uint8_t *primtypes,
558 		void *priv, unsigned flags);
559 
560 void fd_context_destroy(struct pipe_context *pctx);
561 
562 #endif /* FREEDRENO_CONTEXT_H_ */
563