1 /*
2  * © Copyright 2018 Alyssa Rosenzweig
3  * Copyright © 2014-2017 Broadcom
4  * Copyright (C) 2017 Intel Corporation
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  */
26 
27 #include <sys/poll.h>
28 #include <errno.h>
29 
30 #include "pan_bo.h"
31 #include "pan_context.h"
32 #include "pan_minmax_cache.h"
33 #include "panfrost-quirks.h"
34 
35 #include "util/macros.h"
36 #include "util/format/u_format.h"
37 #include "util/u_inlines.h"
38 #include "util/u_upload_mgr.h"
39 #include "util/u_memory.h"
40 #include "util/u_vbuf.h"
41 #include "util/half_float.h"
42 #include "util/u_helpers.h"
43 #include "util/format/u_format.h"
44 #include "util/u_prim.h"
45 #include "util/u_prim_restart.h"
46 #include "indices/u_primconvert.h"
47 #include "tgsi/tgsi_parse.h"
48 #include "tgsi/tgsi_from_mesa.h"
49 #include "util/u_math.h"
50 
51 #include "pan_screen.h"
52 #include "pan_blending.h"
53 #include "pan_blend_shaders.h"
54 #include "pan_cmdstream.h"
55 #include "pan_util.h"
56 #include "pandecode/decode.h"
57 #include "util/pan_lower_framebuffer.h"
58 
59 struct midgard_tiler_descriptor
panfrost_emit_midg_tiler(struct panfrost_batch * batch,unsigned vertex_count)60 panfrost_emit_midg_tiler(struct panfrost_batch *batch, unsigned vertex_count)
61 {
62         struct panfrost_device *device = pan_device(batch->ctx->base.screen);
63         bool hierarchy = !(device->quirks & MIDGARD_NO_HIER_TILING);
64         struct midgard_tiler_descriptor t = {0};
65         unsigned height = batch->key.height;
66         unsigned width = batch->key.width;
67 
68         t.hierarchy_mask =
69                 panfrost_choose_hierarchy_mask(width, height, vertex_count, hierarchy);
70 
71         /* Compute the polygon header size and use that to offset the body */
72 
73         unsigned header_size = panfrost_tiler_header_size(
74                                        width, height, t.hierarchy_mask, hierarchy);
75 
76         t.polygon_list_size = panfrost_tiler_full_size(
77                                      width, height, t.hierarchy_mask, hierarchy);
78 
79         /* Sanity check */
80 
81         if (vertex_count) {
82                 struct panfrost_bo *tiler_heap;
83 
84                 tiler_heap = panfrost_batch_get_tiler_heap(batch);
85                 t.polygon_list = panfrost_batch_get_polygon_list(batch,
86                                                                  header_size +
87                                                                  t.polygon_list_size);
88 
89 
90                 /* Allow the entire tiler heap */
91                 t.heap_start = tiler_heap->gpu;
92                 t.heap_end = tiler_heap->gpu + tiler_heap->size;
93         } else {
94                 struct panfrost_bo *tiler_dummy;
95 
96                 tiler_dummy = panfrost_batch_get_tiler_dummy(batch);
97                 header_size = MALI_TILER_MINIMUM_HEADER_SIZE;
98 
99                 /* The tiler is disabled, so don't allow the tiler heap */
100                 t.heap_start = tiler_dummy->gpu;
101                 t.heap_end = t.heap_start;
102 
103                 /* Use a dummy polygon list */
104                 t.polygon_list = tiler_dummy->gpu;
105 
106                 /* Disable the tiler */
107                 if (hierarchy)
108                         t.hierarchy_mask |= MALI_TILER_DISABLED;
109                 else {
110                         t.hierarchy_mask = MALI_TILER_USER;
111                         t.polygon_list_size = MALI_TILER_MINIMUM_HEADER_SIZE + 4;
112 
113                         /* We don't have a WRITE_VALUE job, so write the polygon list manually */
114                         uint32_t *polygon_list_body = (uint32_t *) (tiler_dummy->cpu + header_size);
115                         polygon_list_body[0] = 0xa0000000; /* TODO: Just that? */
116                 }
117         }
118 
119         t.polygon_list_body =
120                 t.polygon_list + header_size;
121 
122         return t;
123 }
124 
125 static void
panfrost_clear(struct pipe_context * pipe,unsigned buffers,const struct pipe_scissor_state * scissor_state,const union pipe_color_union * color,double depth,unsigned stencil)126 panfrost_clear(
127         struct pipe_context *pipe,
128         unsigned buffers,
129         const struct pipe_scissor_state *scissor_state,
130         const union pipe_color_union *color,
131         double depth, unsigned stencil)
132 {
133         struct panfrost_context *ctx = pan_context(pipe);
134 
135         /* TODO: panfrost_get_fresh_batch_for_fbo() instantiates a new batch if
136          * the existing batch targeting this FBO has draws. We could probably
137          * avoid that by replacing plain clears by quad-draws with a specific
138          * color/depth/stencil value, thus avoiding the generation of extra
139          * fragment jobs.
140          */
141         struct panfrost_batch *batch = panfrost_get_fresh_batch_for_fbo(ctx);
142 
143         panfrost_batch_add_fbo_bos(batch);
144         panfrost_batch_clear(batch, buffers, color, depth, stencil);
145 }
146 
147 /* Reset per-frame context, called on context initialisation as well as after
148  * flushing a frame */
149 
150 void
panfrost_invalidate_frame(struct panfrost_context * ctx)151 panfrost_invalidate_frame(struct panfrost_context *ctx)
152 {
153         /* TODO: When does this need to be handled? */
154         ctx->active_queries = true;
155 }
156 
157 bool
panfrost_writes_point_size(struct panfrost_context * ctx)158 panfrost_writes_point_size(struct panfrost_context *ctx)
159 {
160         assert(ctx->shader[PIPE_SHADER_VERTEX]);
161         struct panfrost_shader_state *vs = panfrost_get_shader_state(ctx, PIPE_SHADER_VERTEX);
162 
163         return vs->writes_point_size && ctx->active_prim == PIPE_PRIM_POINTS;
164 }
165 
166 void
panfrost_vertex_state_upd_attr_offs(struct panfrost_context * ctx,struct mali_vertex_tiler_postfix * vertex_postfix)167 panfrost_vertex_state_upd_attr_offs(struct panfrost_context *ctx,
168                                     struct mali_vertex_tiler_postfix *vertex_postfix)
169 {
170         if (!ctx->vertex)
171                 return;
172 
173         struct panfrost_vertex_state *so = ctx->vertex;
174 
175         /* Fixup offsets for the second pass. Recall that the hardware
176          * calculates attribute addresses as:
177          *
178          *      addr = base + (stride * vtx) + src_offset;
179          *
180          * However, on Mali, base must be aligned to 64-bytes, so we
181          * instead let:
182          *
183          *      base' = base & ~63 = base - (base & 63)
184          *
185          * To compensate when using base' (see emit_vertex_data), we have
186          * to adjust src_offset by the masked off piece:
187          *
188          *      addr' = base' + (stride * vtx) + (src_offset + (base & 63))
189          *            = base - (base & 63) + (stride * vtx) + src_offset + (base & 63)
190          *            = base + (stride * vtx) + src_offset
191          *            = addr;
192          *
193          * QED.
194          */
195 
196         unsigned start = vertex_postfix->offset_start;
197 
198         for (unsigned i = 0; i < so->num_elements; ++i) {
199                 unsigned vbi = so->pipe[i].vertex_buffer_index;
200                 struct pipe_vertex_buffer *buf = &ctx->vertex_buffers[vbi];
201 
202                 /* Adjust by the masked off bits of the offset. Make sure we
203                  * read src_offset from so->hw (which is not GPU visible)
204                  * rather than target (which is) due to caching effects */
205 
206                 unsigned src_offset = so->pipe[i].src_offset;
207 
208                 /* BOs aligned to 4k so guaranteed aligned to 64 */
209                 src_offset += (buf->buffer_offset & 63);
210 
211                 /* Also, somewhat obscurely per-instance data needs to be
212                  * offset in response to a delayed start in an indexed draw */
213 
214                 if (so->pipe[i].instance_divisor && ctx->instance_count > 1 && start)
215                         src_offset -= buf->stride * start;
216 
217                 so->hw[i].src_offset = src_offset;
218         }
219 }
220 
221 /* Compute number of UBOs active (more specifically, compute the highest UBO
222  * number addressable -- if there are gaps, include them in the count anyway).
223  * We always include UBO #0 in the count, since we *need* uniforms enabled for
224  * sysvals. */
225 
226 unsigned
panfrost_ubo_count(struct panfrost_context * ctx,enum pipe_shader_type stage)227 panfrost_ubo_count(struct panfrost_context *ctx, enum pipe_shader_type stage)
228 {
229         unsigned mask = ctx->constant_buffer[stage].enabled_mask | 1;
230         return 32 - __builtin_clz(mask);
231 }
232 
233 /* The entire frame is in memory -- send it off to the kernel! */
234 
235 void
panfrost_flush(struct pipe_context * pipe,struct pipe_fence_handle ** fence,unsigned flags)236 panfrost_flush(
237         struct pipe_context *pipe,
238         struct pipe_fence_handle **fence,
239         unsigned flags)
240 {
241         struct panfrost_context *ctx = pan_context(pipe);
242         struct panfrost_device *dev = pan_device(pipe->screen);
243         uint32_t syncobj = 0;
244 
245         if (fence)
246                 drmSyncobjCreate(dev->fd, 0, &syncobj);
247 
248         /* Submit all pending jobs */
249         panfrost_flush_all_batches(ctx, syncobj);
250 
251         if (fence) {
252                 struct panfrost_fence *f = panfrost_fence_create(ctx, syncobj);
253                 pipe->screen->fence_reference(pipe->screen, fence, NULL);
254                 *fence = (struct pipe_fence_handle *)f;
255         }
256 
257         if (dev->debug & PAN_DBG_TRACE)
258                 pandecode_next_frame();
259 }
260 
261 static void
panfrost_texture_barrier(struct pipe_context * pipe,unsigned flags)262 panfrost_texture_barrier(struct pipe_context *pipe, unsigned flags)
263 {
264         struct panfrost_context *ctx = pan_context(pipe);
265         panfrost_flush_all_batches(ctx, 0);
266 }
267 
268 #define DEFINE_CASE(c) case PIPE_PRIM_##c: return MALI_##c;
269 
270 static int
g2m_draw_mode(enum pipe_prim_type mode)271 g2m_draw_mode(enum pipe_prim_type mode)
272 {
273         switch (mode) {
274                 DEFINE_CASE(POINTS);
275                 DEFINE_CASE(LINES);
276                 DEFINE_CASE(LINE_LOOP);
277                 DEFINE_CASE(LINE_STRIP);
278                 DEFINE_CASE(TRIANGLES);
279                 DEFINE_CASE(TRIANGLE_STRIP);
280                 DEFINE_CASE(TRIANGLE_FAN);
281                 DEFINE_CASE(QUADS);
282                 DEFINE_CASE(QUAD_STRIP);
283                 DEFINE_CASE(POLYGON);
284 
285         default:
286                 unreachable("Invalid draw mode");
287         }
288 }
289 
290 #undef DEFINE_CASE
291 
292 static bool
panfrost_scissor_culls_everything(struct panfrost_context * ctx)293 panfrost_scissor_culls_everything(struct panfrost_context *ctx)
294 {
295         const struct pipe_scissor_state *ss = &ctx->scissor;
296 
297         /* Check if we're scissoring at all */
298 
299         if (!(ctx->rasterizer && ctx->rasterizer->base.scissor))
300                 return false;
301 
302         return (ss->minx == ss->maxx) || (ss->miny == ss->maxy);
303 }
304 
305 /* Count generated primitives (when there is no geom/tess shaders) for
306  * transform feedback */
307 
308 static void
panfrost_statistics_record(struct panfrost_context * ctx,const struct pipe_draw_info * info)309 panfrost_statistics_record(
310                 struct panfrost_context *ctx,
311                 const struct pipe_draw_info *info)
312 {
313         if (!ctx->active_queries)
314                 return;
315 
316         uint32_t prims = u_prims_for_vertices(info->mode, info->count);
317         ctx->prims_generated += prims;
318 
319         if (!ctx->streamout.num_targets)
320                 return;
321 
322         ctx->tf_prims_generated += prims;
323 }
324 
325 static void
panfrost_update_streamout_offsets(struct panfrost_context * ctx)326 panfrost_update_streamout_offsets(struct panfrost_context *ctx)
327 {
328         for (unsigned i = 0; i < ctx->streamout.num_targets; ++i) {
329                 unsigned count;
330 
331                 count = u_stream_outputs_for_vertices(ctx->active_prim,
332                                                       ctx->vertex_count);
333                 ctx->streamout.offsets[i] += count;
334         }
335 }
336 
337 static void
panfrost_draw_vbo(struct pipe_context * pipe,const struct pipe_draw_info * info)338 panfrost_draw_vbo(
339         struct pipe_context *pipe,
340         const struct pipe_draw_info *info)
341 {
342         struct panfrost_context *ctx = pan_context(pipe);
343 
344         /* First of all, check the scissor to see if anything is drawn at all.
345          * If it's not, we drop the draw (mostly a conformance issue;
346          * well-behaved apps shouldn't hit this) */
347 
348         if (panfrost_scissor_culls_everything(ctx))
349                 return;
350 
351         int mode = info->mode;
352 
353         /* Fallback unsupported restart index */
354         unsigned primitive_index = (1 << (info->index_size * 8)) - 1;
355 
356         if (info->primitive_restart && info->index_size
357             && info->restart_index != primitive_index) {
358                 util_draw_vbo_without_prim_restart(pipe, info);
359                 return;
360         }
361 
362         /* Fallback for unsupported modes */
363 
364         assert(ctx->rasterizer != NULL);
365 
366         if (!(ctx->draw_modes & (1 << mode))) {
367                 if (mode == PIPE_PRIM_QUADS && info->count == 4 && !ctx->rasterizer->base.flatshade) {
368                         mode = PIPE_PRIM_TRIANGLE_FAN;
369                 } else {
370                         if (info->count < 4) {
371                                 /* Degenerate case? */
372                                 return;
373                         }
374 
375                         util_primconvert_save_rasterizer_state(ctx->primconvert, &ctx->rasterizer->base);
376                         util_primconvert_draw_vbo(ctx->primconvert, info);
377                         return;
378                 }
379         }
380 
381         /* Now that we have a guaranteed terminating path, find the job.
382          * Assignment commented out to prevent unused warning */
383 
384         struct panfrost_batch *batch = panfrost_get_batch_for_fbo(ctx);
385 
386         panfrost_batch_add_fbo_bos(batch);
387         panfrost_batch_set_requirements(batch);
388 
389         /* Take into account a negative bias */
390         ctx->vertex_count = info->count + abs(info->index_bias);
391         ctx->instance_count = info->instance_count;
392         ctx->active_prim = info->mode;
393 
394         struct mali_vertex_tiler_prefix vertex_prefix, tiler_prefix;
395         struct mali_vertex_tiler_postfix vertex_postfix, tiler_postfix;
396         union midgard_primitive_size primitive_size;
397         unsigned vertex_count;
398 
399         panfrost_vt_init(ctx, PIPE_SHADER_VERTEX, &vertex_prefix, &vertex_postfix);
400         panfrost_vt_init(ctx, PIPE_SHADER_FRAGMENT, &tiler_prefix, &tiler_postfix);
401 
402         panfrost_vt_set_draw_info(ctx, info, g2m_draw_mode(mode),
403                                   &vertex_postfix, &tiler_prefix,
404                                   &tiler_postfix, &vertex_count,
405                                   &ctx->padded_count);
406 
407         panfrost_statistics_record(ctx, info);
408 
409         /* Dispatch "compute jobs" for the vertex/tiler pair as (1,
410          * vertex_count, 1) */
411 
412         panfrost_pack_work_groups_fused(&vertex_prefix, &tiler_prefix,
413                                         1, vertex_count, info->instance_count,
414                                         1, 1, 1);
415 
416         /* Emit all sort of descriptors. */
417         panfrost_emit_vertex_data(batch, &vertex_postfix);
418         panfrost_emit_varying_descriptor(batch,
419                                          ctx->padded_count *
420                                          ctx->instance_count,
421                                          &vertex_postfix, &tiler_postfix,
422                                          &primitive_size);
423         panfrost_emit_shader_meta(batch, PIPE_SHADER_VERTEX, &vertex_postfix);
424         panfrost_emit_shader_meta(batch, PIPE_SHADER_FRAGMENT, &tiler_postfix);
425         panfrost_emit_vertex_attr_meta(batch, &vertex_postfix);
426         panfrost_emit_sampler_descriptors(batch, PIPE_SHADER_VERTEX, &vertex_postfix);
427         panfrost_emit_sampler_descriptors(batch, PIPE_SHADER_FRAGMENT, &tiler_postfix);
428         panfrost_emit_texture_descriptors(batch, PIPE_SHADER_VERTEX, &vertex_postfix);
429         panfrost_emit_texture_descriptors(batch, PIPE_SHADER_FRAGMENT, &tiler_postfix);
430         panfrost_emit_const_buf(batch, PIPE_SHADER_VERTEX, &vertex_postfix);
431         panfrost_emit_const_buf(batch, PIPE_SHADER_FRAGMENT, &tiler_postfix);
432         panfrost_emit_viewport(batch, &tiler_postfix);
433 
434         panfrost_vt_update_primitive_size(ctx, &tiler_prefix, &primitive_size);
435 
436         /* Fire off the draw itself */
437         panfrost_emit_vertex_tiler_jobs(batch, &vertex_prefix, &vertex_postfix,
438                                                &tiler_prefix, &tiler_postfix,
439                                                &primitive_size);
440 
441         /* Adjust the batch stack size based on the new shader stack sizes. */
442         panfrost_batch_adjust_stack_size(batch);
443 
444         /* Increment transform feedback offsets */
445         panfrost_update_streamout_offsets(ctx);
446 }
447 
448 /* CSO state */
449 
450 static void
panfrost_generic_cso_delete(struct pipe_context * pctx,void * hwcso)451 panfrost_generic_cso_delete(struct pipe_context *pctx, void *hwcso)
452 {
453         free(hwcso);
454 }
455 
456 static void *
panfrost_create_rasterizer_state(struct pipe_context * pctx,const struct pipe_rasterizer_state * cso)457 panfrost_create_rasterizer_state(
458         struct pipe_context *pctx,
459         const struct pipe_rasterizer_state *cso)
460 {
461         struct panfrost_rasterizer *so = CALLOC_STRUCT(panfrost_rasterizer);
462 
463         so->base = *cso;
464 
465         return so;
466 }
467 
468 static void
panfrost_bind_rasterizer_state(struct pipe_context * pctx,void * hwcso)469 panfrost_bind_rasterizer_state(
470         struct pipe_context *pctx,
471         void *hwcso)
472 {
473         struct panfrost_context *ctx = pan_context(pctx);
474 
475         ctx->rasterizer = hwcso;
476 
477         if (!hwcso)
478                 return;
479 
480         /* Gauranteed with the core GL call, so don't expose ARB_polygon_offset */
481         assert(ctx->rasterizer->base.offset_clamp == 0.0);
482 
483         /* Point sprites are emulated */
484 
485         struct panfrost_shader_state *variant = panfrost_get_shader_state(ctx, PIPE_SHADER_FRAGMENT);
486 
487         if (ctx->rasterizer->base.sprite_coord_enable || (variant && variant->point_sprite_mask))
488                 ctx->base.bind_fs_state(&ctx->base, ctx->shader[PIPE_SHADER_FRAGMENT]);
489 }
490 
491 static void *
panfrost_create_vertex_elements_state(struct pipe_context * pctx,unsigned num_elements,const struct pipe_vertex_element * elements)492 panfrost_create_vertex_elements_state(
493         struct pipe_context *pctx,
494         unsigned num_elements,
495         const struct pipe_vertex_element *elements)
496 {
497         struct panfrost_vertex_state *so = CALLOC_STRUCT(panfrost_vertex_state);
498         struct panfrost_device *dev = pan_device(pctx->screen);
499 
500         so->num_elements = num_elements;
501         memcpy(so->pipe, elements, sizeof(*elements) * num_elements);
502 
503         for (int i = 0; i < num_elements; ++i) {
504                 so->hw[i].index = i;
505 
506                 enum pipe_format fmt = elements[i].src_format;
507                 const struct util_format_description *desc = util_format_description(fmt);
508                 so->hw[i].unknown1 = 0x2;
509 
510                 if (dev->quirks & HAS_SWIZZLES)
511                         so->hw[i].swizzle = panfrost_translate_swizzle_4(desc->swizzle);
512                 else
513                         so->hw[i].swizzle = panfrost_bifrost_swizzle(desc->nr_channels);
514 
515                 enum mali_format hw_format = panfrost_pipe_format_table[desc->format].hw;
516                 so->hw[i].format = hw_format;
517                 assert(hw_format);
518         }
519 
520         /* Let's also prepare vertex builtins */
521         so->hw[PAN_VERTEX_ID].format = MALI_R32UI;
522         if (dev->quirks & HAS_SWIZZLES)
523                 so->hw[PAN_VERTEX_ID].swizzle = panfrost_get_default_swizzle(1);
524         else
525                 so->hw[PAN_VERTEX_ID].swizzle = panfrost_bifrost_swizzle(1);
526 
527         so->hw[PAN_INSTANCE_ID].format = MALI_R32UI;
528         if (dev->quirks & HAS_SWIZZLES)
529                 so->hw[PAN_INSTANCE_ID].swizzle = panfrost_get_default_swizzle(1);
530         else
531                 so->hw[PAN_INSTANCE_ID].swizzle = panfrost_bifrost_swizzle(1);
532 
533         return so;
534 }
535 
536 static void
panfrost_bind_vertex_elements_state(struct pipe_context * pctx,void * hwcso)537 panfrost_bind_vertex_elements_state(
538         struct pipe_context *pctx,
539         void *hwcso)
540 {
541         struct panfrost_context *ctx = pan_context(pctx);
542         ctx->vertex = hwcso;
543 }
544 
545 static void *
panfrost_create_shader_state(struct pipe_context * pctx,const struct pipe_shader_state * cso,enum pipe_shader_type stage)546 panfrost_create_shader_state(
547         struct pipe_context *pctx,
548         const struct pipe_shader_state *cso,
549         enum pipe_shader_type stage)
550 {
551         struct panfrost_shader_variants *so = CALLOC_STRUCT(panfrost_shader_variants);
552         struct panfrost_device *dev = pan_device(pctx->screen);
553         so->base = *cso;
554 
555         /* Token deep copy to prevent memory corruption */
556 
557         if (cso->type == PIPE_SHADER_IR_TGSI)
558                 so->base.tokens = tgsi_dup_tokens(so->base.tokens);
559 
560         /* Precompile for shader-db if we need to */
561         if (unlikely((dev->debug & PAN_DBG_PRECOMPILE) && cso->type == PIPE_SHADER_IR_NIR)) {
562                 struct panfrost_context *ctx = pan_context(pctx);
563 
564                 struct panfrost_shader_state state;
565                 uint64_t outputs_written;
566 
567                 panfrost_shader_compile(ctx, PIPE_SHADER_IR_NIR,
568                                         so->base.ir.nir,
569                                         tgsi_processor_to_shader_stage(stage),
570                                         &state, &outputs_written);
571         }
572 
573         return so;
574 }
575 
576 static void
panfrost_delete_shader_state(struct pipe_context * pctx,void * so)577 panfrost_delete_shader_state(
578         struct pipe_context *pctx,
579         void *so)
580 {
581         struct panfrost_shader_variants *cso = (struct panfrost_shader_variants *) so;
582 
583         if (cso->base.type == PIPE_SHADER_IR_TGSI) {
584                 /* TODO: leaks TGSI tokens! */
585         }
586 
587         for (unsigned i = 0; i < cso->variant_count; ++i) {
588                 struct panfrost_shader_state *shader_state = &cso->variants[i];
589                 panfrost_bo_unreference(shader_state->bo);
590                 shader_state->bo = NULL;
591         }
592         free(cso->variants);
593 
594         free(so);
595 }
596 
597 static void *
panfrost_create_sampler_state(struct pipe_context * pctx,const struct pipe_sampler_state * cso)598 panfrost_create_sampler_state(
599         struct pipe_context *pctx,
600         const struct pipe_sampler_state *cso)
601 {
602         struct panfrost_sampler_state *so = CALLOC_STRUCT(panfrost_sampler_state);
603         struct panfrost_device *device = pan_device(pctx->screen);
604 
605         so->base = *cso;
606 
607         if (device->quirks & IS_BIFROST)
608                 panfrost_sampler_desc_init_bifrost(cso, &so->bifrost_hw);
609         else
610                 panfrost_sampler_desc_init(cso, &so->midgard_hw);
611 
612         return so;
613 }
614 
615 static void
panfrost_bind_sampler_states(struct pipe_context * pctx,enum pipe_shader_type shader,unsigned start_slot,unsigned num_sampler,void ** sampler)616 panfrost_bind_sampler_states(
617         struct pipe_context *pctx,
618         enum pipe_shader_type shader,
619         unsigned start_slot, unsigned num_sampler,
620         void **sampler)
621 {
622         assert(start_slot == 0);
623 
624         struct panfrost_context *ctx = pan_context(pctx);
625 
626         /* XXX: Should upload, not just copy? */
627         ctx->sampler_count[shader] = num_sampler;
628         memcpy(ctx->samplers[shader], sampler, num_sampler * sizeof (void *));
629 }
630 
631 static bool
panfrost_variant_matches(struct panfrost_context * ctx,struct panfrost_shader_state * variant,enum pipe_shader_type type)632 panfrost_variant_matches(
633         struct panfrost_context *ctx,
634         struct panfrost_shader_state *variant,
635         enum pipe_shader_type type)
636 {
637         struct panfrost_device *dev = pan_device(ctx->base.screen);
638         struct pipe_rasterizer_state *rasterizer = &ctx->rasterizer->base;
639         struct pipe_alpha_state *alpha = &ctx->depth_stencil->alpha;
640 
641         bool is_fragment = (type == PIPE_SHADER_FRAGMENT);
642 
643         if (is_fragment && (alpha->enabled || variant->alpha_state.enabled)) {
644                 /* Make sure enable state is at least the same */
645                 if (alpha->enabled != variant->alpha_state.enabled) {
646                         return false;
647                 }
648 
649                 /* Check that the contents of the test are the same */
650                 bool same_func = alpha->func == variant->alpha_state.func;
651                 bool same_ref = alpha->ref_value == variant->alpha_state.ref_value;
652 
653                 if (!(same_func && same_ref)) {
654                         return false;
655                 }
656         }
657 
658         if (variant->outputs_read) {
659                 struct pipe_framebuffer_state *fb = &ctx->pipe_framebuffer;
660 
661                 unsigned i;
662                 BITSET_FOREACH_SET(i, &variant->outputs_read, 8) {
663                         enum pipe_format fmt = PIPE_FORMAT_R8G8B8A8_UNORM;
664 
665                         if ((fb->nr_cbufs > i) && fb->cbufs[i])
666                                 fmt = fb->cbufs[i]->format;
667 
668                         const struct util_format_description *desc =
669                                 util_format_description(fmt);
670 
671                         if (pan_format_class_load(desc, dev->quirks) == PAN_FORMAT_NATIVE)
672                                 fmt = PIPE_FORMAT_NONE;
673 
674                         if (variant->rt_formats[i] != fmt)
675                                 return false;
676                 }
677         }
678 
679         /* Point sprites TODO on bifrost, always pass */
680         if (is_fragment && rasterizer && (rasterizer->sprite_coord_enable |
681                                           variant->point_sprite_mask)
682                         && !(dev->quirks & IS_BIFROST)) {
683                 /* Ensure the same varyings are turned to point sprites */
684                 if (rasterizer->sprite_coord_enable != variant->point_sprite_mask)
685                         return false;
686 
687                 /* Ensure the orientation is correct */
688                 bool upper_left =
689                         rasterizer->sprite_coord_mode ==
690                         PIPE_SPRITE_COORD_UPPER_LEFT;
691 
692                 if (variant->point_sprite_upper_left != upper_left)
693                         return false;
694         }
695 
696         /* Otherwise, we're good to go */
697         return true;
698 }
699 
700 /**
701  * Fix an uncompiled shader's stream output info, and produce a bitmask
702  * of which VARYING_SLOT_* are captured for stream output.
703  *
704  * Core Gallium stores output->register_index as a "slot" number, where
705  * slots are assigned consecutively to all outputs in info->outputs_written.
706  * This naive packing of outputs doesn't work for us - we too have slots,
707  * but the layout is defined by the VUE map, which we won't have until we
708  * compile a specific shader variant.  So, we remap these and simply store
709  * VARYING_SLOT_* in our copy's output->register_index fields.
710  *
711  * We then produce a bitmask of outputs which are used for SO.
712  *
713  * Implementation from iris.
714  */
715 
716 static uint64_t
update_so_info(struct pipe_stream_output_info * so_info,uint64_t outputs_written)717 update_so_info(struct pipe_stream_output_info *so_info,
718                uint64_t outputs_written)
719 {
720 	uint64_t so_outputs = 0;
721 	uint8_t reverse_map[64] = {0};
722 	unsigned slot = 0;
723 
724 	while (outputs_written)
725 		reverse_map[slot++] = u_bit_scan64(&outputs_written);
726 
727 	for (unsigned i = 0; i < so_info->num_outputs; i++) {
728 		struct pipe_stream_output *output = &so_info->output[i];
729 
730 		/* Map Gallium's condensed "slots" back to real VARYING_SLOT_* enums */
731 		output->register_index = reverse_map[output->register_index];
732 
733 		so_outputs |= 1ull << output->register_index;
734 	}
735 
736 	return so_outputs;
737 }
738 
739 static void
panfrost_bind_shader_state(struct pipe_context * pctx,void * hwcso,enum pipe_shader_type type)740 panfrost_bind_shader_state(
741         struct pipe_context *pctx,
742         void *hwcso,
743         enum pipe_shader_type type)
744 {
745         struct panfrost_context *ctx = pan_context(pctx);
746         struct panfrost_device *dev = pan_device(ctx->base.screen);
747         ctx->shader[type] = hwcso;
748 
749         if (!hwcso) return;
750 
751         /* Match the appropriate variant */
752 
753         signed variant = -1;
754         struct panfrost_shader_variants *variants = (struct panfrost_shader_variants *) hwcso;
755 
756         for (unsigned i = 0; i < variants->variant_count; ++i) {
757                 if (panfrost_variant_matches(ctx, &variants->variants[i], type)) {
758                         variant = i;
759                         break;
760                 }
761         }
762 
763         if (variant == -1) {
764                 /* No variant matched, so create a new one */
765                 variant = variants->variant_count++;
766 
767                 if (variants->variant_count > variants->variant_space) {
768                         unsigned old_space = variants->variant_space;
769 
770                         variants->variant_space *= 2;
771                         if (variants->variant_space == 0)
772                                 variants->variant_space = 1;
773 
774                         /* Arbitrary limit to stop runaway programs from
775                          * creating an unbounded number of shader variants. */
776                         assert(variants->variant_space < 1024);
777 
778                         unsigned msize = sizeof(struct panfrost_shader_state);
779                         variants->variants = realloc(variants->variants,
780                                                      variants->variant_space * msize);
781 
782                         memset(&variants->variants[old_space], 0,
783                                (variants->variant_space - old_space) * msize);
784                 }
785 
786                 struct panfrost_shader_state *v =
787                                 &variants->variants[variant];
788 
789                 if (type == PIPE_SHADER_FRAGMENT) {
790                         v->alpha_state = ctx->depth_stencil->alpha;
791 
792                         struct pipe_framebuffer_state *fb = &ctx->pipe_framebuffer;
793                         for (unsigned i = 0; i < fb->nr_cbufs; ++i) {
794                                 enum pipe_format fmt = PIPE_FORMAT_R8G8B8A8_UNORM;
795 
796                                 if ((fb->nr_cbufs > i) && fb->cbufs[i])
797                                         fmt = fb->cbufs[i]->format;
798 
799                                 const struct util_format_description *desc =
800                                         util_format_description(fmt);
801 
802                                 if (pan_format_class_load(desc, dev->quirks) == PAN_FORMAT_NATIVE)
803                                         fmt = PIPE_FORMAT_NONE;
804 
805                                 v->rt_formats[i] = fmt;
806                         }
807 
808                         /* Point sprites are TODO on Bifrost */
809                         if (ctx->rasterizer && !(dev->quirks & IS_BIFROST)) {
810                                 v->point_sprite_mask = ctx->rasterizer->base.sprite_coord_enable;
811                                 v->point_sprite_upper_left =
812                                         ctx->rasterizer->base.sprite_coord_mode ==
813                                         PIPE_SPRITE_COORD_UPPER_LEFT;
814                         }
815                 }
816         }
817 
818         /* Select this variant */
819         variants->active_variant = variant;
820 
821         struct panfrost_shader_state *shader_state = &variants->variants[variant];
822         assert(panfrost_variant_matches(ctx, shader_state, type));
823 
824         /* We finally have a variant, so compile it */
825 
826         if (!shader_state->compiled) {
827                 uint64_t outputs_written = 0;
828 
829                 panfrost_shader_compile(ctx, variants->base.type,
830                                         variants->base.type == PIPE_SHADER_IR_NIR ?
831                                         variants->base.ir.nir :
832                                         variants->base.tokens,
833                                         tgsi_processor_to_shader_stage(type),
834                                         shader_state,
835                                         &outputs_written);
836 
837                 shader_state->compiled = true;
838 
839                 /* Fixup the stream out information, since what Gallium returns
840                  * normally is mildly insane */
841 
842                 shader_state->stream_output = variants->base.stream_output;
843                 shader_state->so_mask =
844                         update_so_info(&shader_state->stream_output, outputs_written);
845         }
846 }
847 
848 static void *
panfrost_create_vs_state(struct pipe_context * pctx,const struct pipe_shader_state * hwcso)849 panfrost_create_vs_state(struct pipe_context *pctx, const struct pipe_shader_state *hwcso)
850 {
851         return panfrost_create_shader_state(pctx, hwcso, PIPE_SHADER_VERTEX);
852 }
853 
854 static void *
panfrost_create_fs_state(struct pipe_context * pctx,const struct pipe_shader_state * hwcso)855 panfrost_create_fs_state(struct pipe_context *pctx, const struct pipe_shader_state *hwcso)
856 {
857         return panfrost_create_shader_state(pctx, hwcso, PIPE_SHADER_FRAGMENT);
858 }
859 
860 static void
panfrost_bind_vs_state(struct pipe_context * pctx,void * hwcso)861 panfrost_bind_vs_state(struct pipe_context *pctx, void *hwcso)
862 {
863         panfrost_bind_shader_state(pctx, hwcso, PIPE_SHADER_VERTEX);
864 }
865 
866 static void
panfrost_bind_fs_state(struct pipe_context * pctx,void * hwcso)867 panfrost_bind_fs_state(struct pipe_context *pctx, void *hwcso)
868 {
869         panfrost_bind_shader_state(pctx, hwcso, PIPE_SHADER_FRAGMENT);
870 }
871 
872 static void
panfrost_set_vertex_buffers(struct pipe_context * pctx,unsigned start_slot,unsigned num_buffers,const struct pipe_vertex_buffer * buffers)873 panfrost_set_vertex_buffers(
874         struct pipe_context *pctx,
875         unsigned start_slot,
876         unsigned num_buffers,
877         const struct pipe_vertex_buffer *buffers)
878 {
879         struct panfrost_context *ctx = pan_context(pctx);
880 
881         util_set_vertex_buffers_mask(ctx->vertex_buffers, &ctx->vb_mask, buffers, start_slot, num_buffers);
882 }
883 
884 static void
panfrost_set_constant_buffer(struct pipe_context * pctx,enum pipe_shader_type shader,uint index,const struct pipe_constant_buffer * buf)885 panfrost_set_constant_buffer(
886         struct pipe_context *pctx,
887         enum pipe_shader_type shader, uint index,
888         const struct pipe_constant_buffer *buf)
889 {
890         struct panfrost_context *ctx = pan_context(pctx);
891         struct panfrost_constant_buffer *pbuf = &ctx->constant_buffer[shader];
892 
893         util_copy_constant_buffer(&pbuf->cb[index], buf);
894 
895         unsigned mask = (1 << index);
896 
897         if (unlikely(!buf)) {
898                 pbuf->enabled_mask &= ~mask;
899                 pbuf->dirty_mask &= ~mask;
900                 return;
901         }
902 
903         pbuf->enabled_mask |= mask;
904         pbuf->dirty_mask |= mask;
905 }
906 
907 static void
panfrost_set_stencil_ref(struct pipe_context * pctx,const struct pipe_stencil_ref * ref)908 panfrost_set_stencil_ref(
909         struct pipe_context *pctx,
910         const struct pipe_stencil_ref *ref)
911 {
912         struct panfrost_context *ctx = pan_context(pctx);
913         ctx->stencil_ref = *ref;
914 }
915 
916 void
panfrost_create_sampler_view_bo(struct panfrost_sampler_view * so,struct pipe_context * pctx,struct pipe_resource * texture)917 panfrost_create_sampler_view_bo(struct panfrost_sampler_view *so,
918                                 struct pipe_context *pctx,
919                                 struct pipe_resource *texture)
920 {
921         struct panfrost_device *device = pan_device(pctx->screen);
922         struct panfrost_resource *prsrc = (struct panfrost_resource *)texture;
923         enum pipe_format format = so->base.format;
924         assert(prsrc->bo);
925 
926         /* Format to access the stencil portion of a Z32_S8 texture */
927         if (format == PIPE_FORMAT_X32_S8X24_UINT) {
928                 assert(prsrc->separate_stencil);
929                 texture = &prsrc->separate_stencil->base;
930                 prsrc = (struct panfrost_resource *)texture;
931                 format = texture->format;
932         }
933 
934         const struct util_format_description *desc = util_format_description(format);
935 
936         bool fake_rgtc = !panfrost_supports_compressed_format(device, MALI_BC4_UNORM);
937 
938         if (desc->layout == UTIL_FORMAT_LAYOUT_RGTC && fake_rgtc) {
939                 if (desc->is_snorm)
940                         format = PIPE_FORMAT_R8G8B8A8_SNORM;
941                 else
942                         format = PIPE_FORMAT_R8G8B8A8_UNORM;
943                 desc = util_format_description(format);
944         }
945 
946         so->texture_bo = prsrc->bo->gpu;
947         so->layout = prsrc->layout;
948 
949         unsigned char user_swizzle[4] = {
950                 so->base.swizzle_r,
951                 so->base.swizzle_g,
952                 so->base.swizzle_b,
953                 so->base.swizzle_a
954         };
955 
956         /* In the hardware, array_size refers specifically to array textures,
957          * whereas in Gallium, it also covers cubemaps */
958 
959         unsigned array_size = texture->array_size;
960         unsigned depth = texture->depth0;
961 
962         if (so->base.target == PIPE_TEXTURE_CUBE) {
963                 /* TODO: Cubemap arrays */
964                 assert(array_size == 6);
965                 array_size /= 6;
966         }
967 
968         /* MSAA only supported for 2D textures (and 2D texture arrays via an
969          * extension currently unimplemented */
970 
971         if (so->base.target == PIPE_TEXTURE_2D) {
972                 assert(depth == 1);
973                 depth = texture->nr_samples;
974         } else {
975                 /* MSAA only supported for 2D textures */
976                 assert(texture->nr_samples <= 1);
977         }
978 
979         enum mali_texture_type type =
980                 panfrost_translate_texture_type(so->base.target);
981 
982         if (device->quirks & IS_BIFROST) {
983                 unsigned char composed_swizzle[4];
984                 util_format_compose_swizzles(desc->swizzle, user_swizzle, composed_swizzle);
985 
986                 unsigned size = panfrost_estimate_texture_payload_size(
987                                 so->base.u.tex.first_level,
988                                 so->base.u.tex.last_level,
989                                 so->base.u.tex.first_layer,
990                                 so->base.u.tex.last_layer,
991                                 texture->nr_samples,
992                                 type, prsrc->layout);
993 
994                 so->bo = panfrost_bo_create(device, size, 0);
995 
996                 so->bifrost_descriptor = rzalloc(pctx, struct bifrost_texture_descriptor);
997                 panfrost_new_texture_bifrost(
998                                 so->bifrost_descriptor,
999                                 texture->width0, texture->height0,
1000                                 depth, array_size,
1001                                 format,
1002                                 type, prsrc->layout,
1003                                 so->base.u.tex.first_level,
1004                                 so->base.u.tex.last_level,
1005                                 so->base.u.tex.first_layer,
1006                                 so->base.u.tex.last_layer,
1007                                 texture->nr_samples,
1008                                 prsrc->cubemap_stride,
1009                                 panfrost_translate_swizzle_4(composed_swizzle),
1010                                 prsrc->bo->gpu,
1011                                 prsrc->slices,
1012                                 so->bo);
1013         } else {
1014                 unsigned size = panfrost_estimate_texture_payload_size(
1015                                 so->base.u.tex.first_level,
1016                                 so->base.u.tex.last_level,
1017                                 so->base.u.tex.first_layer,
1018                                 so->base.u.tex.last_layer,
1019                                 texture->nr_samples,
1020                                 type, prsrc->layout);
1021                 size += sizeof(struct mali_texture_descriptor);
1022 
1023                 so->bo = panfrost_bo_create(device, size, 0);
1024 
1025                 panfrost_new_texture(
1026                                 so->bo->cpu,
1027                                 texture->width0, texture->height0,
1028                                 depth, array_size,
1029                                 format,
1030                                 type, prsrc->layout,
1031                                 so->base.u.tex.first_level,
1032                                 so->base.u.tex.last_level,
1033                                 so->base.u.tex.first_layer,
1034                                 so->base.u.tex.last_layer,
1035                                 texture->nr_samples,
1036                                 prsrc->cubemap_stride,
1037                                 panfrost_translate_swizzle_4(user_swizzle),
1038                                 prsrc->bo->gpu,
1039                                 prsrc->slices);
1040         }
1041 }
1042 
1043 static struct pipe_sampler_view *
panfrost_create_sampler_view(struct pipe_context * pctx,struct pipe_resource * texture,const struct pipe_sampler_view * template)1044 panfrost_create_sampler_view(
1045         struct pipe_context *pctx,
1046         struct pipe_resource *texture,
1047         const struct pipe_sampler_view *template)
1048 {
1049         struct panfrost_sampler_view *so = rzalloc(pctx, struct panfrost_sampler_view);
1050 
1051         pipe_reference(NULL, &texture->reference);
1052 
1053         so->base = *template;
1054         so->base.texture = texture;
1055         so->base.reference.count = 1;
1056         so->base.context = pctx;
1057 
1058         panfrost_create_sampler_view_bo(so, pctx, texture);
1059 
1060         return (struct pipe_sampler_view *) so;
1061 }
1062 
1063 static void
panfrost_set_sampler_views(struct pipe_context * pctx,enum pipe_shader_type shader,unsigned start_slot,unsigned num_views,struct pipe_sampler_view ** views)1064 panfrost_set_sampler_views(
1065         struct pipe_context *pctx,
1066         enum pipe_shader_type shader,
1067         unsigned start_slot, unsigned num_views,
1068         struct pipe_sampler_view **views)
1069 {
1070         struct panfrost_context *ctx = pan_context(pctx);
1071         unsigned new_nr = 0;
1072         unsigned i;
1073 
1074         assert(start_slot == 0);
1075 
1076         for (i = 0; i < num_views; ++i) {
1077                 if (views[i])
1078                         new_nr = i + 1;
1079 		pipe_sampler_view_reference((struct pipe_sampler_view **)&ctx->sampler_views[shader][i],
1080 		                            views[i]);
1081         }
1082 
1083         for (; i < ctx->sampler_view_count[shader]; i++) {
1084 		pipe_sampler_view_reference((struct pipe_sampler_view **)&ctx->sampler_views[shader][i],
1085 		                            NULL);
1086         }
1087         ctx->sampler_view_count[shader] = new_nr;
1088 }
1089 
1090 static void
panfrost_sampler_view_destroy(struct pipe_context * pctx,struct pipe_sampler_view * pview)1091 panfrost_sampler_view_destroy(
1092         struct pipe_context *pctx,
1093         struct pipe_sampler_view *pview)
1094 {
1095         struct panfrost_sampler_view *view = (struct panfrost_sampler_view *) pview;
1096 
1097         pipe_resource_reference(&pview->texture, NULL);
1098         panfrost_bo_unreference(view->bo);
1099         if (view->bifrost_descriptor)
1100                 ralloc_free(view->bifrost_descriptor);
1101         ralloc_free(view);
1102 }
1103 
1104 static void
panfrost_set_shader_buffers(struct pipe_context * pctx,enum pipe_shader_type shader,unsigned start,unsigned count,const struct pipe_shader_buffer * buffers,unsigned writable_bitmask)1105 panfrost_set_shader_buffers(
1106         struct pipe_context *pctx,
1107         enum pipe_shader_type shader,
1108         unsigned start, unsigned count,
1109         const struct pipe_shader_buffer *buffers,
1110         unsigned writable_bitmask)
1111 {
1112         struct panfrost_context *ctx = pan_context(pctx);
1113 
1114         util_set_shader_buffers_mask(ctx->ssbo[shader], &ctx->ssbo_mask[shader],
1115                         buffers, start, count);
1116 }
1117 
1118 /* Hints that a framebuffer should use AFBC where possible */
1119 
1120 static void
panfrost_hint_afbc(struct panfrost_device * device,const struct pipe_framebuffer_state * fb)1121 panfrost_hint_afbc(
1122                 struct panfrost_device *device,
1123                 const struct pipe_framebuffer_state *fb)
1124 {
1125         /* AFBC implemenation incomplete; hide it */
1126         if (!(device->debug & PAN_DBG_AFBC)) return;
1127 
1128         /* Hint AFBC to the resources bound to each color buffer */
1129 
1130         for (unsigned i = 0; i < fb->nr_cbufs; ++i) {
1131                 struct pipe_surface *surf = fb->cbufs[i];
1132                 struct panfrost_resource *rsrc = pan_resource(surf->texture);
1133                 panfrost_resource_hint_layout(device, rsrc, MALI_TEXTURE_AFBC, 1);
1134         }
1135 
1136         /* Also hint it to the depth buffer */
1137 
1138         if (fb->zsbuf) {
1139                 struct panfrost_resource *rsrc = pan_resource(fb->zsbuf->texture);
1140                 panfrost_resource_hint_layout(device, rsrc, MALI_TEXTURE_AFBC, 1);
1141         }
1142 }
1143 
1144 static void
panfrost_set_framebuffer_state(struct pipe_context * pctx,const struct pipe_framebuffer_state * fb)1145 panfrost_set_framebuffer_state(struct pipe_context *pctx,
1146                                const struct pipe_framebuffer_state *fb)
1147 {
1148         struct panfrost_context *ctx = pan_context(pctx);
1149 
1150         panfrost_hint_afbc(pan_device(pctx->screen), fb);
1151         util_copy_framebuffer_state(&ctx->pipe_framebuffer, fb);
1152         ctx->batch = NULL;
1153         panfrost_invalidate_frame(ctx);
1154 
1155         /* We may need to generate a new variant if the fragment shader is
1156          * keyed to the framebuffer format (due to EXT_framebuffer_fetch) */
1157         struct panfrost_shader_variants *fs = ctx->shader[PIPE_SHADER_FRAGMENT];
1158 
1159         if (fs && fs->variant_count && fs->variants[fs->active_variant].outputs_read)
1160                 ctx->base.bind_fs_state(&ctx->base, fs);
1161 }
1162 
1163 static void *
panfrost_create_depth_stencil_state(struct pipe_context * pipe,const struct pipe_depth_stencil_alpha_state * depth_stencil)1164 panfrost_create_depth_stencil_state(struct pipe_context *pipe,
1165                                     const struct pipe_depth_stencil_alpha_state *depth_stencil)
1166 {
1167         return mem_dup(depth_stencil, sizeof(*depth_stencil));
1168 }
1169 
1170 static void
panfrost_bind_depth_stencil_state(struct pipe_context * pipe,void * cso)1171 panfrost_bind_depth_stencil_state(struct pipe_context *pipe,
1172                                   void *cso)
1173 {
1174         struct panfrost_context *ctx = pan_context(pipe);
1175         struct pipe_depth_stencil_alpha_state *depth_stencil = cso;
1176         ctx->depth_stencil = depth_stencil;
1177 
1178         if (!depth_stencil)
1179                 return;
1180 
1181         /* Alpha does not exist in the hardware (it's not in ES3), so it's
1182          * emulated in the fragment shader */
1183 
1184         if (depth_stencil->alpha.enabled) {
1185                 /* We need to trigger a new shader (maybe) */
1186                 ctx->base.bind_fs_state(&ctx->base, ctx->shader[PIPE_SHADER_FRAGMENT]);
1187         }
1188 
1189         /* Bounds test not implemented */
1190         assert(!depth_stencil->depth.bounds_test);
1191 }
1192 
1193 static void
panfrost_delete_depth_stencil_state(struct pipe_context * pipe,void * depth)1194 panfrost_delete_depth_stencil_state(struct pipe_context *pipe, void *depth)
1195 {
1196         free( depth );
1197 }
1198 
1199 static void
panfrost_set_sample_mask(struct pipe_context * pipe,unsigned sample_mask)1200 panfrost_set_sample_mask(struct pipe_context *pipe,
1201                          unsigned sample_mask)
1202 {
1203         struct panfrost_context *ctx = pan_context(pipe);
1204         ctx->sample_mask = sample_mask;
1205 }
1206 
1207 static void
panfrost_set_min_samples(struct pipe_context * pipe,unsigned min_samples)1208 panfrost_set_min_samples(struct pipe_context *pipe,
1209                          unsigned min_samples)
1210 {
1211         struct panfrost_context *ctx = pan_context(pipe);
1212         ctx->min_samples = min_samples;
1213 }
1214 
1215 
1216 static void
panfrost_set_clip_state(struct pipe_context * pipe,const struct pipe_clip_state * clip)1217 panfrost_set_clip_state(struct pipe_context *pipe,
1218                         const struct pipe_clip_state *clip)
1219 {
1220         //struct panfrost_context *panfrost = pan_context(pipe);
1221 }
1222 
1223 static void
panfrost_set_viewport_states(struct pipe_context * pipe,unsigned start_slot,unsigned num_viewports,const struct pipe_viewport_state * viewports)1224 panfrost_set_viewport_states(struct pipe_context *pipe,
1225                              unsigned start_slot,
1226                              unsigned num_viewports,
1227                              const struct pipe_viewport_state *viewports)
1228 {
1229         struct panfrost_context *ctx = pan_context(pipe);
1230 
1231         assert(start_slot == 0);
1232         assert(num_viewports == 1);
1233 
1234         ctx->pipe_viewport = *viewports;
1235 }
1236 
1237 static void
panfrost_set_scissor_states(struct pipe_context * pipe,unsigned start_slot,unsigned num_scissors,const struct pipe_scissor_state * scissors)1238 panfrost_set_scissor_states(struct pipe_context *pipe,
1239                             unsigned start_slot,
1240                             unsigned num_scissors,
1241                             const struct pipe_scissor_state *scissors)
1242 {
1243         struct panfrost_context *ctx = pan_context(pipe);
1244 
1245         assert(start_slot == 0);
1246         assert(num_scissors == 1);
1247 
1248         ctx->scissor = *scissors;
1249 }
1250 
1251 static void
panfrost_set_polygon_stipple(struct pipe_context * pipe,const struct pipe_poly_stipple * stipple)1252 panfrost_set_polygon_stipple(struct pipe_context *pipe,
1253                              const struct pipe_poly_stipple *stipple)
1254 {
1255         //struct panfrost_context *panfrost = pan_context(pipe);
1256 }
1257 
1258 static void
panfrost_set_active_query_state(struct pipe_context * pipe,bool enable)1259 panfrost_set_active_query_state(struct pipe_context *pipe,
1260                                 bool enable)
1261 {
1262         struct panfrost_context *ctx = pan_context(pipe);
1263         ctx->active_queries = enable;
1264 }
1265 
1266 static void
panfrost_destroy(struct pipe_context * pipe)1267 panfrost_destroy(struct pipe_context *pipe)
1268 {
1269         struct panfrost_context *panfrost = pan_context(pipe);
1270 
1271         if (panfrost->blitter)
1272                 util_blitter_destroy(panfrost->blitter);
1273 
1274         if (panfrost->blitter_wallpaper)
1275                 util_blitter_destroy(panfrost->blitter_wallpaper);
1276 
1277         util_unreference_framebuffer_state(&panfrost->pipe_framebuffer);
1278         u_upload_destroy(pipe->stream_uploader);
1279 
1280         ralloc_free(pipe);
1281 }
1282 
1283 static struct pipe_query *
panfrost_create_query(struct pipe_context * pipe,unsigned type,unsigned index)1284 panfrost_create_query(struct pipe_context *pipe,
1285                       unsigned type,
1286                       unsigned index)
1287 {
1288         struct panfrost_query *q = rzalloc(pipe, struct panfrost_query);
1289 
1290         q->type = type;
1291         q->index = index;
1292 
1293         return (struct pipe_query *) q;
1294 }
1295 
1296 static void
panfrost_destroy_query(struct pipe_context * pipe,struct pipe_query * q)1297 panfrost_destroy_query(struct pipe_context *pipe, struct pipe_query *q)
1298 {
1299         struct panfrost_query *query = (struct panfrost_query *) q;
1300 
1301         if (query->bo) {
1302                 panfrost_bo_unreference(query->bo);
1303                 query->bo = NULL;
1304         }
1305 
1306         ralloc_free(q);
1307 }
1308 
1309 static bool
panfrost_begin_query(struct pipe_context * pipe,struct pipe_query * q)1310 panfrost_begin_query(struct pipe_context *pipe, struct pipe_query *q)
1311 {
1312         struct panfrost_context *ctx = pan_context(pipe);
1313         struct panfrost_query *query = (struct panfrost_query *) q;
1314 
1315         switch (query->type) {
1316         case PIPE_QUERY_OCCLUSION_COUNTER:
1317         case PIPE_QUERY_OCCLUSION_PREDICATE:
1318         case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE:
1319                 /* Allocate a bo for the query results to be stored */
1320                 if (!query->bo) {
1321                         query->bo = panfrost_bo_create(
1322                                         pan_device(ctx->base.screen),
1323                                         sizeof(unsigned), 0);
1324                 }
1325 
1326                 unsigned *result = (unsigned *)query->bo->cpu;
1327                 *result = 0; /* Default to 0 if nothing at all drawn. */
1328                 ctx->occlusion_query = query;
1329                 break;
1330 
1331         /* Geometry statistics are computed in the driver. XXX: geom/tess
1332          * shaders.. */
1333 
1334         case PIPE_QUERY_PRIMITIVES_GENERATED:
1335                 query->start = ctx->prims_generated;
1336                 break;
1337         case PIPE_QUERY_PRIMITIVES_EMITTED:
1338                 query->start = ctx->tf_prims_generated;
1339                 break;
1340 
1341         default:
1342                 /* TODO: timestamp queries, etc? */
1343                 break;
1344         }
1345 
1346         return true;
1347 }
1348 
1349 static bool
panfrost_end_query(struct pipe_context * pipe,struct pipe_query * q)1350 panfrost_end_query(struct pipe_context *pipe, struct pipe_query *q)
1351 {
1352         struct panfrost_context *ctx = pan_context(pipe);
1353         struct panfrost_query *query = (struct panfrost_query *) q;
1354 
1355         switch (query->type) {
1356         case PIPE_QUERY_OCCLUSION_COUNTER:
1357         case PIPE_QUERY_OCCLUSION_PREDICATE:
1358         case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE:
1359                 ctx->occlusion_query = NULL;
1360                 break;
1361         case PIPE_QUERY_PRIMITIVES_GENERATED:
1362                 query->end = ctx->prims_generated;
1363                 break;
1364         case PIPE_QUERY_PRIMITIVES_EMITTED:
1365                 query->end = ctx->tf_prims_generated;
1366                 break;
1367         }
1368 
1369         return true;
1370 }
1371 
1372 static bool
panfrost_get_query_result(struct pipe_context * pipe,struct pipe_query * q,bool wait,union pipe_query_result * vresult)1373 panfrost_get_query_result(struct pipe_context *pipe,
1374                           struct pipe_query *q,
1375                           bool wait,
1376                           union pipe_query_result *vresult)
1377 {
1378         struct panfrost_query *query = (struct panfrost_query *) q;
1379         struct panfrost_context *ctx = pan_context(pipe);
1380 
1381 
1382         switch (query->type) {
1383         case PIPE_QUERY_OCCLUSION_COUNTER:
1384         case PIPE_QUERY_OCCLUSION_PREDICATE:
1385         case PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE:
1386                 panfrost_flush_batches_accessing_bo(ctx, query->bo, false);
1387                 panfrost_bo_wait(query->bo, INT64_MAX, false);
1388 
1389                 /* Read back the query results */
1390                 unsigned *result = (unsigned *) query->bo->cpu;
1391                 unsigned passed = *result;
1392 
1393                 if (query->type == PIPE_QUERY_OCCLUSION_COUNTER) {
1394                         vresult->u64 = passed;
1395                 } else {
1396                         vresult->b = !!passed;
1397                 }
1398 
1399                 break;
1400 
1401         case PIPE_QUERY_PRIMITIVES_GENERATED:
1402         case PIPE_QUERY_PRIMITIVES_EMITTED:
1403                 panfrost_flush_all_batches(ctx, 0);
1404                 vresult->u64 = query->end - query->start;
1405                 break;
1406 
1407         default:
1408                 /* TODO: more queries */
1409                 break;
1410         }
1411 
1412         return true;
1413 }
1414 
1415 static struct pipe_stream_output_target *
panfrost_create_stream_output_target(struct pipe_context * pctx,struct pipe_resource * prsc,unsigned buffer_offset,unsigned buffer_size)1416 panfrost_create_stream_output_target(struct pipe_context *pctx,
1417                                      struct pipe_resource *prsc,
1418                                      unsigned buffer_offset,
1419                                      unsigned buffer_size)
1420 {
1421         struct pipe_stream_output_target *target;
1422 
1423         target = rzalloc(pctx, struct pipe_stream_output_target);
1424 
1425         if (!target)
1426                 return NULL;
1427 
1428         pipe_reference_init(&target->reference, 1);
1429         pipe_resource_reference(&target->buffer, prsc);
1430 
1431         target->context = pctx;
1432         target->buffer_offset = buffer_offset;
1433         target->buffer_size = buffer_size;
1434 
1435         return target;
1436 }
1437 
1438 static void
panfrost_stream_output_target_destroy(struct pipe_context * pctx,struct pipe_stream_output_target * target)1439 panfrost_stream_output_target_destroy(struct pipe_context *pctx,
1440                                       struct pipe_stream_output_target *target)
1441 {
1442         pipe_resource_reference(&target->buffer, NULL);
1443         ralloc_free(target);
1444 }
1445 
1446 static void
panfrost_set_stream_output_targets(struct pipe_context * pctx,unsigned num_targets,struct pipe_stream_output_target ** targets,const unsigned * offsets)1447 panfrost_set_stream_output_targets(struct pipe_context *pctx,
1448                                    unsigned num_targets,
1449                                    struct pipe_stream_output_target **targets,
1450                                    const unsigned *offsets)
1451 {
1452         struct panfrost_context *ctx = pan_context(pctx);
1453         struct panfrost_streamout *so = &ctx->streamout;
1454 
1455         assert(num_targets <= ARRAY_SIZE(so->targets));
1456 
1457         for (unsigned i = 0; i < num_targets; i++) {
1458                 if (offsets[i] != -1)
1459                         so->offsets[i] = offsets[i];
1460 
1461                 pipe_so_target_reference(&so->targets[i], targets[i]);
1462         }
1463 
1464         for (unsigned i = 0; i < so->num_targets; i++)
1465                 pipe_so_target_reference(&so->targets[i], NULL);
1466 
1467         so->num_targets = num_targets;
1468 }
1469 
1470 struct pipe_context *
panfrost_create_context(struct pipe_screen * screen,void * priv,unsigned flags)1471 panfrost_create_context(struct pipe_screen *screen, void *priv, unsigned flags)
1472 {
1473         struct panfrost_context *ctx = rzalloc(screen, struct panfrost_context);
1474         struct pipe_context *gallium = (struct pipe_context *) ctx;
1475         struct panfrost_device *dev = pan_device(screen);
1476 
1477         gallium->screen = screen;
1478 
1479         gallium->destroy = panfrost_destroy;
1480 
1481         gallium->set_framebuffer_state = panfrost_set_framebuffer_state;
1482 
1483         gallium->flush = panfrost_flush;
1484         gallium->clear = panfrost_clear;
1485         gallium->draw_vbo = panfrost_draw_vbo;
1486         gallium->texture_barrier = panfrost_texture_barrier;
1487 
1488         gallium->set_vertex_buffers = panfrost_set_vertex_buffers;
1489         gallium->set_constant_buffer = panfrost_set_constant_buffer;
1490         gallium->set_shader_buffers = panfrost_set_shader_buffers;
1491 
1492         gallium->set_stencil_ref = panfrost_set_stencil_ref;
1493 
1494         gallium->create_sampler_view = panfrost_create_sampler_view;
1495         gallium->set_sampler_views = panfrost_set_sampler_views;
1496         gallium->sampler_view_destroy = panfrost_sampler_view_destroy;
1497 
1498         gallium->create_rasterizer_state = panfrost_create_rasterizer_state;
1499         gallium->bind_rasterizer_state = panfrost_bind_rasterizer_state;
1500         gallium->delete_rasterizer_state = panfrost_generic_cso_delete;
1501 
1502         gallium->create_vertex_elements_state = panfrost_create_vertex_elements_state;
1503         gallium->bind_vertex_elements_state = panfrost_bind_vertex_elements_state;
1504         gallium->delete_vertex_elements_state = panfrost_generic_cso_delete;
1505 
1506         gallium->create_fs_state = panfrost_create_fs_state;
1507         gallium->delete_fs_state = panfrost_delete_shader_state;
1508         gallium->bind_fs_state = panfrost_bind_fs_state;
1509 
1510         gallium->create_vs_state = panfrost_create_vs_state;
1511         gallium->delete_vs_state = panfrost_delete_shader_state;
1512         gallium->bind_vs_state = panfrost_bind_vs_state;
1513 
1514         gallium->create_sampler_state = panfrost_create_sampler_state;
1515         gallium->delete_sampler_state = panfrost_generic_cso_delete;
1516         gallium->bind_sampler_states = panfrost_bind_sampler_states;
1517 
1518         gallium->create_depth_stencil_alpha_state = panfrost_create_depth_stencil_state;
1519         gallium->bind_depth_stencil_alpha_state   = panfrost_bind_depth_stencil_state;
1520         gallium->delete_depth_stencil_alpha_state = panfrost_delete_depth_stencil_state;
1521 
1522         gallium->set_sample_mask = panfrost_set_sample_mask;
1523         gallium->set_min_samples = panfrost_set_min_samples;
1524 
1525         gallium->set_clip_state = panfrost_set_clip_state;
1526         gallium->set_viewport_states = panfrost_set_viewport_states;
1527         gallium->set_scissor_states = panfrost_set_scissor_states;
1528         gallium->set_polygon_stipple = panfrost_set_polygon_stipple;
1529         gallium->set_active_query_state = panfrost_set_active_query_state;
1530 
1531         gallium->create_query = panfrost_create_query;
1532         gallium->destroy_query = panfrost_destroy_query;
1533         gallium->begin_query = panfrost_begin_query;
1534         gallium->end_query = panfrost_end_query;
1535         gallium->get_query_result = panfrost_get_query_result;
1536 
1537         gallium->create_stream_output_target = panfrost_create_stream_output_target;
1538         gallium->stream_output_target_destroy = panfrost_stream_output_target_destroy;
1539         gallium->set_stream_output_targets = panfrost_set_stream_output_targets;
1540 
1541         panfrost_resource_context_init(gallium);
1542         panfrost_blend_context_init(gallium);
1543         panfrost_compute_context_init(gallium);
1544 
1545         gallium->stream_uploader = u_upload_create_default(gallium);
1546         gallium->const_uploader = gallium->stream_uploader;
1547         assert(gallium->stream_uploader);
1548 
1549         /* All of our GPUs support ES mode. Midgard supports additionally
1550          * QUADS/QUAD_STRIPS/POLYGON. Bifrost supports just QUADS. */
1551 
1552         ctx->draw_modes = (1 << (PIPE_PRIM_QUADS + 1)) - 1;
1553 
1554         if (!(dev->quirks & IS_BIFROST)) {
1555                 ctx->draw_modes |= (1 << PIPE_PRIM_QUAD_STRIP);
1556                 ctx->draw_modes |= (1 << PIPE_PRIM_POLYGON);
1557         }
1558 
1559         ctx->primconvert = util_primconvert_create(gallium, ctx->draw_modes);
1560 
1561         ctx->blitter = util_blitter_create(gallium);
1562         ctx->blitter_wallpaper = util_blitter_create(gallium);
1563 
1564         assert(ctx->blitter);
1565         assert(ctx->blitter_wallpaper);
1566 
1567         /* Prepare for render! */
1568 
1569         panfrost_batch_init(ctx);
1570         panfrost_invalidate_frame(ctx);
1571 
1572         if (!(dev->quirks & IS_BIFROST)) {
1573                 for (unsigned c = 0; c < PIPE_MAX_COLOR_BUFS; ++c)
1574                         ctx->blit_blend.rt[c].shaders = _mesa_hash_table_u64_create(ctx);
1575         }
1576 
1577         /* By default mask everything on */
1578         ctx->sample_mask = ~0;
1579 
1580         return gallium;
1581 }
1582