• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  Copyright 2003 VMware, Inc.
3  Copyright (C) Intel Corp.  2006.  All Rights Reserved.
4  Intel funded Tungsten Graphics to
5  develop this 3D driver.
6 
7  Permission is hereby granted, free of charge, to any person obtaining
8  a copy of this software and associated documentation files (the
9  "Software"), to deal in the Software without restriction, including
10  without limitation the rights to use, copy, modify, merge, publish,
11  distribute, sublicense, and/or sell copies of the Software, and to
12  permit persons to whom the Software is furnished to do so, subject to
13  the following conditions:
14 
15  The above copyright notice and this permission notice (including the
16  next paragraph) shall be included in all copies or substantial
17  portions of the Software.
18 
19  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22  IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
23  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 
27  **********************************************************************/
28  /*
29   * Authors:
30   *   Keith Whitwell <keithw@vmware.com>
31   */
32 
33 
34 #include "compiler/nir/nir.h"
35 #include "main/api_exec.h"
36 #include "main/context.h"
37 #include "main/fbobject.h"
38 #include "main/extensions.h"
39 #include "main/glthread.h"
40 #include "main/macros.h"
41 #include "main/points.h"
42 #include "main/version.h"
43 #include "main/vtxfmt.h"
44 #include "main/texobj.h"
45 #include "main/framebuffer.h"
46 #include "main/stencil.h"
47 #include "main/state.h"
48 #include "main/spirv_extensions.h"
49 #include "main/externalobjects.h"
50 
51 #include "vbo/vbo.h"
52 
53 #include "drivers/common/driverfuncs.h"
54 #include "drivers/common/meta.h"
55 #include "utils.h"
56 
57 #include "brw_context.h"
58 #include "brw_defines.h"
59 #include "brw_blorp.h"
60 #include "brw_draw.h"
61 #include "brw_state.h"
62 
63 #include "brw_batch.h"
64 #include "brw_buffer_objects.h"
65 #include "brw_buffers.h"
66 #include "brw_fbo.h"
67 #include "brw_mipmap_tree.h"
68 #include "brw_pixel.h"
69 #include "brw_image.h"
70 #include "brw_tex.h"
71 #include "brw_tex_obj.h"
72 
73 #include "swrast_setup/swrast_setup.h"
74 #include "tnl/tnl.h"
75 #include "tnl/t_pipeline.h"
76 #include "util/ralloc.h"
77 #include "util/debug.h"
78 #include "util/disk_cache.h"
79 #include "util/u_memory.h"
80 #include "isl/isl.h"
81 
82 #include "common/intel_defines.h"
83 #include "common/intel_uuid.h"
84 
85 #include "compiler/spirv/nir_spirv.h"
86 /***************************************
87  * Mesa's Driver Functions
88  ***************************************/
89 
90 const char *const brw_vendor_string = "Intel Open Source Technology Center";
91 
92 const char *
brw_get_renderer_string(const struct brw_screen * screen)93 brw_get_renderer_string(const struct brw_screen *screen)
94 {
95    static char buf[128];
96    const char *name = screen->devinfo.name;
97 
98    if (!name)
99       name = "Intel Unknown";
100 
101    snprintf(buf, sizeof(buf), "Mesa DRI %s", name);
102 
103    return buf;
104 }
105 
106 static const GLubyte *
brw_get_string(struct gl_context * ctx,GLenum name)107 brw_get_string(struct gl_context * ctx, GLenum name)
108 {
109    const struct brw_context *const brw = brw_context(ctx);
110 
111    switch (name) {
112    case GL_VENDOR:
113       return (GLubyte *) brw_vendor_string;
114 
115    case GL_RENDERER:
116       return
117          (GLubyte *) brw_get_renderer_string(brw->screen);
118 
119    default:
120       return NULL;
121    }
122 }
123 
124 static void
brw_set_background_context(struct gl_context * ctx,UNUSED struct util_queue_monitoring * queue_info)125 brw_set_background_context(struct gl_context *ctx,
126                            UNUSED struct util_queue_monitoring *queue_info)
127 {
128    struct brw_context *brw = brw_context(ctx);
129    __DRIcontext *driContext = brw->driContext;
130    __DRIscreen *driScreen = driContext->driScreenPriv;
131    const __DRIbackgroundCallableExtension *backgroundCallable =
132       driScreen->dri2.backgroundCallable;
133 
134    /* Note: Mesa will only call this function if we've called
135     * _mesa_enable_multithreading().  We only do that if the loader exposed
136     * the __DRI_BACKGROUND_CALLABLE extension.  So we know that
137     * backgroundCallable is not NULL.
138     */
139    backgroundCallable->setBackgroundContext(driContext->loaderPrivate);
140 }
141 
142 static struct gl_memory_object *
brw_new_memoryobj(struct gl_context * ctx,GLuint name)143 brw_new_memoryobj(struct gl_context *ctx, GLuint name)
144 {
145    struct brw_memory_object *memory_object = CALLOC_STRUCT(brw_memory_object);
146    if (!memory_object)
147       return NULL;
148 
149    _mesa_initialize_memory_object(ctx, &memory_object->Base, name);
150    return &memory_object->Base;
151 }
152 
153 static void
brw_delete_memoryobj(struct gl_context * ctx,struct gl_memory_object * memObj)154 brw_delete_memoryobj(struct gl_context *ctx, struct gl_memory_object *memObj)
155 {
156    struct brw_memory_object *memory_object = brw_memory_object(memObj);
157    brw_bo_unreference(memory_object->bo);
158    _mesa_delete_memory_object(ctx, memObj);
159 }
160 
161 static void
brw_import_memoryobj_fd(struct gl_context * ctx,struct gl_memory_object * obj,GLuint64 size,int fd)162 brw_import_memoryobj_fd(struct gl_context *ctx,
163                        struct gl_memory_object *obj,
164                        GLuint64 size,
165                        int fd)
166 {
167    struct brw_context *brw = brw_context(ctx);
168    struct brw_memory_object *memory_object = brw_memory_object(obj);
169 
170    memory_object->bo = brw_bo_gem_create_from_prime(brw->bufmgr, fd);
171    brw_bo_reference(memory_object->bo);
172    assert(memory_object->bo->size >= size);
173    close(fd);
174 }
175 
176 static void
brw_viewport(struct gl_context * ctx)177 brw_viewport(struct gl_context *ctx)
178 {
179    struct brw_context *brw = brw_context(ctx);
180    __DRIcontext *driContext = brw->driContext;
181 
182    if (_mesa_is_winsys_fbo(ctx->DrawBuffer)) {
183       if (driContext->driDrawablePriv)
184          dri2InvalidateDrawable(driContext->driDrawablePriv);
185       if (driContext->driReadablePriv)
186          dri2InvalidateDrawable(driContext->driReadablePriv);
187    }
188 }
189 
190 static void
brw_update_framebuffer(struct gl_context * ctx,struct gl_framebuffer * fb)191 brw_update_framebuffer(struct gl_context *ctx, struct gl_framebuffer *fb)
192 {
193    struct brw_context *brw = brw_context(ctx);
194 
195    /* Quantize the derived default number of samples
196     */
197    fb->DefaultGeometry._NumSamples =
198       brw_quantize_num_samples(brw->screen, fb->DefaultGeometry.NumSamples);
199 }
200 
201 static void
brw_update_state(struct gl_context * ctx)202 brw_update_state(struct gl_context * ctx)
203 {
204    GLuint new_state = ctx->NewState;
205    struct brw_context *brw = brw_context(ctx);
206 
207    if (ctx->swrast_context)
208       _swrast_InvalidateState(ctx, new_state);
209 
210    brw->NewGLState |= new_state;
211 
212    if (new_state & (_NEW_SCISSOR | _NEW_BUFFERS | _NEW_VIEWPORT))
213       _mesa_update_draw_buffer_bounds(ctx, ctx->DrawBuffer);
214 
215    if (new_state & (_NEW_STENCIL | _NEW_BUFFERS)) {
216       brw->stencil_enabled = _mesa_stencil_is_enabled(ctx);
217       brw->stencil_two_sided = _mesa_stencil_is_two_sided(ctx);
218       brw->stencil_write_enabled =
219          _mesa_stencil_is_write_enabled(ctx, brw->stencil_two_sided);
220    }
221 
222    if (new_state & _NEW_POLYGON)
223       brw->polygon_front_bit = _mesa_polygon_get_front_bit(ctx);
224 
225    if (new_state & _NEW_BUFFERS) {
226       brw_update_framebuffer(ctx, ctx->DrawBuffer);
227       if (ctx->DrawBuffer != ctx->ReadBuffer)
228          brw_update_framebuffer(ctx, ctx->ReadBuffer);
229    }
230 }
231 
232 #define flushFront(screen)      ((screen)->image.loader ? (screen)->image.loader->flushFrontBuffer : (screen)->dri2.loader->flushFrontBuffer)
233 
234 static void
brw_flush_front(struct gl_context * ctx)235 brw_flush_front(struct gl_context *ctx)
236 {
237    struct brw_context *brw = brw_context(ctx);
238    __DRIcontext *driContext = brw->driContext;
239    __DRIdrawable *driDrawable = driContext->driDrawablePriv;
240    __DRIscreen *const dri_screen = brw->screen->driScrnPriv;
241 
242    if (brw->front_buffer_dirty && _mesa_is_winsys_fbo(ctx->DrawBuffer)) {
243       if (flushFront(dri_screen) && driDrawable &&
244           driDrawable->loaderPrivate) {
245 
246          /* Resolve before flushing FAKE_FRONT_LEFT to FRONT_LEFT.
247           *
248           * This potentially resolves both front and back buffer. It
249           * is unnecessary to resolve the back, but harms nothing except
250           * performance. And no one cares about front-buffer render
251           * performance.
252           */
253          brw_resolve_for_dri2_flush(brw, driDrawable);
254          brw_batch_flush(brw);
255 
256          flushFront(dri_screen)(driDrawable, driDrawable->loaderPrivate);
257 
258          /* We set the dirty bit in brw_prepare_render() if we're
259           * front buffer rendering once we get there.
260           */
261          brw->front_buffer_dirty = false;
262       }
263    }
264 }
265 
266 static void
brw_display_shared_buffer(struct brw_context * brw)267 brw_display_shared_buffer(struct brw_context *brw)
268 {
269    __DRIcontext *dri_context = brw->driContext;
270    __DRIdrawable *dri_drawable = dri_context->driDrawablePriv;
271    __DRIscreen *dri_screen = brw->screen->driScrnPriv;
272    int fence_fd = -1;
273 
274    if (!brw->is_shared_buffer_bound)
275       return;
276 
277    if (!brw->is_shared_buffer_dirty)
278       return;
279 
280    if (brw->screen->has_exec_fence) {
281       /* This function is always called during a flush operation, so there is
282        * no need to flush again here. But we want to provide a fence_fd to the
283        * loader, and a redundant flush is the easiest way to acquire one.
284        */
285       if (brw_batch_flush_fence(brw, -1, &fence_fd))
286          return;
287    }
288 
289    dri_screen->mutableRenderBuffer.loader
290       ->displaySharedBuffer(dri_drawable, fence_fd,
291                             dri_drawable->loaderPrivate);
292    brw->is_shared_buffer_dirty = false;
293 }
294 
295 static void
brw_glFlush(struct gl_context * ctx,unsigned gallium_flush_flags)296 brw_glFlush(struct gl_context *ctx, unsigned gallium_flush_flags)
297 {
298    struct brw_context *brw = brw_context(ctx);
299 
300    brw_batch_flush(brw);
301    brw_flush_front(ctx);
302    brw_display_shared_buffer(brw);
303    brw->need_flush_throttle = true;
304 }
305 
306 static void
brw_glEnable(struct gl_context * ctx,GLenum cap,GLboolean state)307 brw_glEnable(struct gl_context *ctx, GLenum cap, GLboolean state)
308 {
309    struct brw_context *brw = brw_context(ctx);
310 
311    switch (cap) {
312    case GL_BLACKHOLE_RENDER_INTEL:
313       brw->frontend_noop = state;
314       brw_batch_flush(brw);
315       brw_batch_maybe_noop(brw);
316       /* Because we started previous batches with a potential
317        * MI_BATCH_BUFFER_END if NOOP was enabled, that means that anything
318        * that was ever emitted after that never made it to the HW. So when the
319        * blackhole state changes from NOOP->!NOOP reupload the entire state.
320        */
321       if (!brw->frontend_noop) {
322          brw->NewGLState = ~0u;
323          brw->ctx.NewDriverState = ~0ull;
324       }
325       break;
326    default:
327       break;
328    }
329 }
330 
331 static void
brw_finish(struct gl_context * ctx)332 brw_finish(struct gl_context * ctx)
333 {
334    struct brw_context *brw = brw_context(ctx);
335 
336    brw_glFlush(ctx, 0);
337 
338    if (brw->batch.last_bo)
339       brw_bo_wait_rendering(brw->batch.last_bo);
340 }
341 
342 static void
brw_get_device_uuid(struct gl_context * ctx,char * uuid)343 brw_get_device_uuid(struct gl_context *ctx, char *uuid)
344 {
345    struct brw_context *brw = brw_context(ctx);
346    struct brw_screen *screen = brw->screen;
347 
348    assert(GL_UUID_SIZE_EXT >= PIPE_UUID_SIZE);
349    memset(uuid, 0, GL_UUID_SIZE_EXT);
350    intel_uuid_compute_device_id((uint8_t *)uuid, &screen->isl_dev, PIPE_UUID_SIZE);
351 }
352 
353 
354 static void
brw_get_driver_uuid(struct gl_context * ctx,char * uuid)355 brw_get_driver_uuid(struct gl_context *ctx, char *uuid)
356 {
357    struct brw_context *brw = brw_context(ctx);
358    struct brw_screen *screen = brw->screen;
359 
360    assert(GL_UUID_SIZE_EXT >= PIPE_UUID_SIZE);
361    memset(uuid, 0, GL_UUID_SIZE_EXT);
362    intel_uuid_compute_driver_id((uint8_t *)uuid, &screen->devinfo, PIPE_UUID_SIZE);
363 }
364 
365 static void
brw_init_driver_functions(struct brw_context * brw,struct dd_function_table * functions)366 brw_init_driver_functions(struct brw_context *brw,
367                           struct dd_function_table *functions)
368 {
369    const struct intel_device_info *devinfo = &brw->screen->devinfo;
370 
371    _mesa_init_driver_functions(functions);
372 
373    /* GLX uses DRI2 invalidate events to handle window resizing.
374     * Unfortunately, EGL does not - libEGL is written in XCB (not Xlib),
375     * which doesn't provide a mechanism for snooping the event queues.
376     *
377     * So EGL still relies on viewport hacks to handle window resizing.
378     * This should go away with DRI3000.
379     */
380    if (!brw->driContext->driScreenPriv->dri2.useInvalidate)
381       functions->Viewport = brw_viewport;
382 
383    functions->Enable = brw_glEnable;
384    functions->Flush = brw_glFlush;
385    functions->Finish = brw_finish;
386    functions->GetString = brw_get_string;
387    functions->UpdateState = brw_update_state;
388 
389    brw_init_draw_functions(functions);
390    brw_init_texture_functions(functions);
391    brw_init_texture_image_functions(functions);
392    brw_init_texture_copy_image_functions(functions);
393    brw_init_copy_image_functions(functions);
394    brw_init_clear_functions(functions);
395    brw_init_buffer_functions(functions);
396    brw_init_pixel_functions(functions);
397    brw_init_buffer_object_functions(functions);
398    brw_init_syncobj_functions(functions);
399    brw_init_object_purgeable_functions(functions);
400 
401    brw_init_frag_prog_functions(functions);
402    brw_init_common_queryobj_functions(functions);
403    if (devinfo->verx10 >= 75)
404       hsw_init_queryobj_functions(functions);
405    else if (devinfo->ver >= 6)
406       gfx6_init_queryobj_functions(functions);
407    else
408       gfx4_init_queryobj_functions(functions);
409    brw_init_compute_functions(functions);
410    brw_init_conditional_render_functions(functions);
411 
412    functions->GenerateMipmap = brw_generate_mipmap;
413 
414    functions->QueryInternalFormat = brw_query_internal_format;
415 
416    functions->NewTransformFeedback = brw_new_transform_feedback;
417    functions->DeleteTransformFeedback = brw_delete_transform_feedback;
418    if (can_do_mi_math_and_lrr(brw->screen)) {
419       functions->BeginTransformFeedback = hsw_begin_transform_feedback;
420       functions->EndTransformFeedback = hsw_end_transform_feedback;
421       functions->PauseTransformFeedback = hsw_pause_transform_feedback;
422       functions->ResumeTransformFeedback = hsw_resume_transform_feedback;
423    } else if (devinfo->ver >= 7) {
424       functions->BeginTransformFeedback = gfx7_begin_transform_feedback;
425       functions->EndTransformFeedback = gfx7_end_transform_feedback;
426       functions->PauseTransformFeedback = gfx7_pause_transform_feedback;
427       functions->ResumeTransformFeedback = gfx7_resume_transform_feedback;
428       functions->GetTransformFeedbackVertexCount =
429          brw_get_transform_feedback_vertex_count;
430    } else {
431       functions->BeginTransformFeedback = brw_begin_transform_feedback;
432       functions->EndTransformFeedback = brw_end_transform_feedback;
433       functions->PauseTransformFeedback = brw_pause_transform_feedback;
434       functions->ResumeTransformFeedback = brw_resume_transform_feedback;
435       functions->GetTransformFeedbackVertexCount =
436          brw_get_transform_feedback_vertex_count;
437    }
438 
439    if (devinfo->ver >= 6)
440       functions->GetSamplePosition = gfx6_get_sample_position;
441 
442    /* GL_ARB_get_program_binary */
443    brw_program_binary_init(brw->screen->deviceID);
444    functions->GetProgramBinaryDriverSHA1 = brw_get_program_binary_driver_sha1;
445    functions->ProgramBinarySerializeDriverBlob = brw_serialize_program_binary;
446    functions->ProgramBinaryDeserializeDriverBlob =
447       brw_deserialize_program_binary;
448 
449    if (brw->screen->disk_cache) {
450       functions->ShaderCacheSerializeDriverBlob = brw_program_serialize_nir;
451    }
452 
453    functions->SetBackgroundContext = brw_set_background_context;
454 
455    functions->NewMemoryObject = brw_new_memoryobj;
456    functions->DeleteMemoryObject = brw_delete_memoryobj;
457    functions->ImportMemoryObjectFd = brw_import_memoryobj_fd;
458    functions->GetDeviceUuid = brw_get_device_uuid;
459    functions->GetDriverUuid = brw_get_driver_uuid;
460 }
461 
462 static void
brw_initialize_spirv_supported_capabilities(struct brw_context * brw)463 brw_initialize_spirv_supported_capabilities(struct brw_context *brw)
464 {
465    const struct intel_device_info *devinfo = &brw->screen->devinfo;
466    struct gl_context *ctx = &brw->ctx;
467 
468    /* The following SPIR-V capabilities are only supported on gfx7+. In theory
469     * you should enable the extension only on gfx7+, but just in case let's
470     * assert it.
471     */
472    assert(devinfo->ver >= 7);
473 
474    ctx->Const.SpirVCapabilities.atomic_storage = devinfo->ver >= 7;
475    ctx->Const.SpirVCapabilities.draw_parameters = true;
476    ctx->Const.SpirVCapabilities.float64 = devinfo->ver >= 8;
477    ctx->Const.SpirVCapabilities.geometry_streams = devinfo->ver >= 7;
478    ctx->Const.SpirVCapabilities.image_write_without_format = true;
479    ctx->Const.SpirVCapabilities.int64 = devinfo->ver >= 8;
480    ctx->Const.SpirVCapabilities.tessellation = true;
481    ctx->Const.SpirVCapabilities.transform_feedback = devinfo->ver >= 7;
482    ctx->Const.SpirVCapabilities.variable_pointers = true;
483    ctx->Const.SpirVCapabilities.integer_functions2 = devinfo->ver >= 8;
484 }
485 
486 static void
brw_initialize_context_constants(struct brw_context * brw)487 brw_initialize_context_constants(struct brw_context *brw)
488 {
489    const struct intel_device_info *devinfo = &brw->screen->devinfo;
490    struct gl_context *ctx = &brw->ctx;
491    const struct brw_compiler *compiler = brw->screen->compiler;
492 
493    const bool stage_exists[MESA_SHADER_STAGES] = {
494       [MESA_SHADER_VERTEX] = true,
495       [MESA_SHADER_TESS_CTRL] = devinfo->ver >= 7,
496       [MESA_SHADER_TESS_EVAL] = devinfo->ver >= 7,
497       [MESA_SHADER_GEOMETRY] = devinfo->ver >= 6,
498       [MESA_SHADER_FRAGMENT] = true,
499       [MESA_SHADER_COMPUTE] =
500          (_mesa_is_desktop_gl(ctx) &&
501           ctx->Const.MaxComputeWorkGroupSize[0] >= 1024) ||
502          (ctx->API == API_OPENGLES2 &&
503           ctx->Const.MaxComputeWorkGroupSize[0] >= 128),
504    };
505 
506    unsigned num_stages = 0;
507    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
508       if (stage_exists[i])
509          num_stages++;
510    }
511 
512    unsigned max_samplers =
513       devinfo->verx10 >= 75 ? BRW_MAX_TEX_UNIT : 16;
514 
515    ctx->Const.MaxDualSourceDrawBuffers = 1;
516    ctx->Const.MaxDrawBuffers = BRW_MAX_DRAW_BUFFERS;
517    ctx->Const.MaxCombinedShaderOutputResources =
518       MAX_IMAGE_UNITS + BRW_MAX_DRAW_BUFFERS;
519 
520    /* The timestamp register we can read for glGetTimestamp() is
521     * sometimes only 32 bits, before scaling to nanoseconds (depending
522     * on kernel).
523     *
524     * Once scaled to nanoseconds the timestamp would roll over at a
525     * non-power-of-two, so an application couldn't use
526     * GL_QUERY_COUNTER_BITS to handle rollover correctly.  Instead, we
527     * report 36 bits and truncate at that (rolling over 5 times as
528     * often as the HW counter), and when the 32-bit counter rolls
529     * over, it happens to also be at a rollover in the reported value
530     * from near (1<<36) to 0.
531     *
532     * The low 32 bits rolls over in ~343 seconds.  Our 36-bit result
533     * rolls over every ~69 seconds.
534     */
535    ctx->Const.QueryCounterBits.Timestamp = 36;
536 
537    ctx->Const.MaxTextureCoordUnits = 8; /* Mesa limit */
538    ctx->Const.MaxImageUnits = MAX_IMAGE_UNITS;
539    if (devinfo->ver >= 7) {
540       ctx->Const.MaxRenderbufferSize = 16384;
541       ctx->Const.MaxTextureSize = 16384;
542       ctx->Const.MaxCubeTextureLevels = 15; /* 16384 */
543    } else {
544       ctx->Const.MaxRenderbufferSize = 8192;
545       ctx->Const.MaxTextureSize = 8192;
546       ctx->Const.MaxCubeTextureLevels = 14; /* 8192 */
547    }
548    ctx->Const.Max3DTextureLevels = 12; /* 2048 */
549    ctx->Const.MaxArrayTextureLayers = devinfo->ver >= 7 ? 2048 : 512;
550    ctx->Const.MaxTextureMbytes = 1536;
551    ctx->Const.MaxTextureRectSize = devinfo->ver >= 7 ? 16384 : 8192;
552    ctx->Const.MaxTextureMaxAnisotropy = 16.0;
553    ctx->Const.MaxTextureLodBias = 15.0;
554    ctx->Const.StripTextureBorder = true;
555    if (devinfo->ver >= 7) {
556       ctx->Const.MaxProgramTextureGatherComponents = 4;
557       ctx->Const.MinProgramTextureGatherOffset = -32;
558       ctx->Const.MaxProgramTextureGatherOffset = 31;
559    } else if (devinfo->ver == 6) {
560       ctx->Const.MaxProgramTextureGatherComponents = 1;
561       ctx->Const.MinProgramTextureGatherOffset = -8;
562       ctx->Const.MaxProgramTextureGatherOffset = 7;
563    }
564 
565    ctx->Const.MaxUniformBlockSize = 65536;
566 
567    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
568       struct gl_program_constants *prog = &ctx->Const.Program[i];
569 
570       if (!stage_exists[i])
571          continue;
572 
573       prog->MaxTextureImageUnits = max_samplers;
574 
575       prog->MaxUniformBlocks = BRW_MAX_UBO;
576       prog->MaxCombinedUniformComponents =
577          prog->MaxUniformComponents +
578          ctx->Const.MaxUniformBlockSize / 4 * prog->MaxUniformBlocks;
579 
580       prog->MaxAtomicCounters = MAX_ATOMIC_COUNTERS;
581       prog->MaxAtomicBuffers = BRW_MAX_ABO;
582       prog->MaxImageUniforms = compiler->scalar_stage[i] ? BRW_MAX_IMAGES : 0;
583       prog->MaxShaderStorageBlocks = BRW_MAX_SSBO;
584    }
585 
586    ctx->Const.MaxTextureUnits =
587       MIN2(ctx->Const.MaxTextureCoordUnits,
588            ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
589 
590    ctx->Const.MaxUniformBufferBindings = num_stages * BRW_MAX_UBO;
591    ctx->Const.MaxCombinedUniformBlocks = num_stages * BRW_MAX_UBO;
592    ctx->Const.MaxCombinedAtomicBuffers = num_stages * BRW_MAX_ABO;
593    ctx->Const.MaxCombinedShaderStorageBlocks = num_stages * BRW_MAX_SSBO;
594    ctx->Const.MaxShaderStorageBufferBindings = num_stages * BRW_MAX_SSBO;
595    ctx->Const.MaxCombinedTextureImageUnits = num_stages * max_samplers;
596    ctx->Const.MaxCombinedImageUniforms = num_stages * BRW_MAX_IMAGES;
597 
598 
599    /* Hardware only supports a limited number of transform feedback buffers.
600     * So we need to override the Mesa default (which is based only on software
601     * limits).
602     */
603    ctx->Const.MaxTransformFeedbackBuffers = BRW_MAX_SOL_BUFFERS;
604 
605    /* On Gfx6, in the worst case, we use up one binding table entry per
606     * transform feedback component (see comments above the definition of
607     * BRW_MAX_SOL_BINDINGS, in brw_context.h), so we need to advertise a value
608     * for MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS equal to
609     * BRW_MAX_SOL_BINDINGS.
610     *
611     * In "separate components" mode, we need to divide this value by
612     * BRW_MAX_SOL_BUFFERS, so that the total number of binding table entries
613     * used up by all buffers will not exceed BRW_MAX_SOL_BINDINGS.
614     */
615    ctx->Const.MaxTransformFeedbackInterleavedComponents = BRW_MAX_SOL_BINDINGS;
616    ctx->Const.MaxTransformFeedbackSeparateComponents =
617       BRW_MAX_SOL_BINDINGS / BRW_MAX_SOL_BUFFERS;
618 
619    ctx->Const.AlwaysUseGetTransformFeedbackVertexCount =
620       !can_do_mi_math_and_lrr(brw->screen);
621 
622    int max_samples;
623    const int *msaa_modes = brw_supported_msaa_modes(brw->screen);
624    const int clamp_max_samples =
625       driQueryOptioni(&brw->screen->optionCache, "clamp_max_samples");
626 
627    if (clamp_max_samples < 0) {
628       max_samples = msaa_modes[0];
629    } else {
630       /* Select the largest supported MSAA mode that does not exceed
631        * clamp_max_samples.
632        */
633       max_samples = 0;
634       for (int i = 0; msaa_modes[i] != 0; ++i) {
635          if (msaa_modes[i] <= clamp_max_samples) {
636             max_samples = msaa_modes[i];
637             break;
638          }
639       }
640    }
641 
642    ctx->Const.MaxSamples = max_samples;
643    ctx->Const.MaxColorTextureSamples = max_samples;
644    ctx->Const.MaxDepthTextureSamples = max_samples;
645    ctx->Const.MaxIntegerSamples = max_samples;
646    ctx->Const.MaxImageSamples = 0;
647 
648    ctx->Const.MinLineWidth = 1.0;
649    ctx->Const.MinLineWidthAA = 1.0;
650    if (devinfo->ver >= 6) {
651       ctx->Const.MaxLineWidth = 7.375;
652       ctx->Const.MaxLineWidthAA = 7.375;
653       ctx->Const.LineWidthGranularity = 0.125;
654    } else {
655       ctx->Const.MaxLineWidth = 7.0;
656       ctx->Const.MaxLineWidthAA = 7.0;
657       ctx->Const.LineWidthGranularity = 0.5;
658    }
659 
660    /* For non-antialiased lines, we have to round the line width to the
661     * nearest whole number. Make sure that we don't advertise a line
662     * width that, when rounded, will be beyond the actual hardware
663     * maximum.
664     */
665    assert(roundf(ctx->Const.MaxLineWidth) <= ctx->Const.MaxLineWidth);
666 
667    ctx->Const.MinPointSize = 1.0;
668    ctx->Const.MinPointSizeAA = 1.0;
669    ctx->Const.MaxPointSize = 255.0;
670    ctx->Const.MaxPointSizeAA = 255.0;
671    ctx->Const.PointSizeGranularity = 1.0;
672 
673    if (devinfo->ver >= 5 || devinfo->is_g4x)
674       ctx->Const.MaxClipPlanes = 8;
675 
676    ctx->Const.GLSLFragCoordIsSysVal = true;
677    ctx->Const.GLSLFrontFacingIsSysVal = true;
678    ctx->Const.GLSLTessLevelsAsInputs = true;
679    ctx->Const.PrimitiveRestartForPatches = true;
680 
681    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeInstructions = 16 * 1024;
682    ctx->Const.Program[MESA_SHADER_VERTEX].MaxAluInstructions = 0;
683    ctx->Const.Program[MESA_SHADER_VERTEX].MaxTexInstructions = 0;
684    ctx->Const.Program[MESA_SHADER_VERTEX].MaxTexIndirections = 0;
685    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAluInstructions = 0;
686    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTexInstructions = 0;
687    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTexIndirections = 0;
688    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAttribs = 16;
689    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTemps = 256;
690    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAddressRegs = 1;
691    ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeParameters = 1024;
692    ctx->Const.Program[MESA_SHADER_VERTEX].MaxEnvParams =
693       MIN2(ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeParameters,
694            ctx->Const.Program[MESA_SHADER_VERTEX].MaxEnvParams);
695 
696    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeInstructions = 1024;
697    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAluInstructions = 1024;
698    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTexInstructions = 1024;
699    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTexIndirections = 1024;
700    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAttribs = 12;
701    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTemps = 256;
702    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAddressRegs = 0;
703    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeParameters = 1024;
704    ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxEnvParams =
705       MIN2(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeParameters,
706            ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxEnvParams);
707 
708    /* Fragment shaders use real, 32-bit twos-complement integers for all
709     * integer types.
710     */
711    ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.RangeMin = 31;
712    ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.RangeMax = 30;
713    ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.Precision = 0;
714    ctx->Const.Program[MESA_SHADER_FRAGMENT].HighInt = ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt;
715    ctx->Const.Program[MESA_SHADER_FRAGMENT].MediumInt = ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt;
716 
717    ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.RangeMin = 31;
718    ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.RangeMax = 30;
719    ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.Precision = 0;
720    ctx->Const.Program[MESA_SHADER_VERTEX].HighInt = ctx->Const.Program[MESA_SHADER_VERTEX].LowInt;
721    ctx->Const.Program[MESA_SHADER_VERTEX].MediumInt = ctx->Const.Program[MESA_SHADER_VERTEX].LowInt;
722 
723    /* Gfx6 converts quads to polygon in beginning of 3D pipeline,
724     * but we're not sure how it's actually done for vertex order,
725     * that affect provoking vertex decision. Always use last vertex
726     * convention for quad primitive which works as expected for now.
727     */
728    if (devinfo->ver >= 6)
729       ctx->Const.QuadsFollowProvokingVertexConvention = false;
730 
731    ctx->Const.NativeIntegers = true;
732 
733    /* Regarding the CMP instruction, the Ivybridge PRM says:
734     *
735     *   "For each enabled channel 0b or 1b is assigned to the appropriate flag
736     *    bit and 0/all zeros or all ones (e.g, byte 0xFF, word 0xFFFF, DWord
737     *    0xFFFFFFFF) is assigned to dst."
738     *
739     * but PRMs for earlier generations say
740     *
741     *   "In dword format, one GRF may store up to 8 results. When the register
742     *    is used later as a vector of Booleans, as only LSB at each channel
743     *    contains meaning [sic] data, software should make sure all higher bits
744     *    are masked out (e.g. by 'and-ing' an [sic] 0x01 constant)."
745     *
746     * We select the representation of a true boolean uniform to be ~0, and fix
747     * the results of Gen <= 5 CMP instruction's with -(result & 1).
748     */
749    ctx->Const.UniformBooleanTrue = ~0;
750 
751    /* From the gfx4 PRM, volume 4 page 127:
752     *
753     *     "For SURFTYPE_BUFFER non-rendertarget surfaces, this field specifies
754     *      the base address of the first element of the surface, computed in
755     *      software by adding the surface base address to the byte offset of
756     *      the element in the buffer."
757     *
758     * However, unaligned accesses are slower, so enforce buffer alignment.
759     *
760     * In order to push UBO data, 3DSTATE_CONSTANT_XS imposes an additional
761     * restriction: the start of the buffer needs to be 32B aligned.
762     */
763    ctx->Const.UniformBufferOffsetAlignment = 32;
764 
765    /* ShaderStorageBufferOffsetAlignment should be a cacheline (64 bytes) so
766     * that we can safely have the CPU and GPU writing the same SSBO on
767     * non-cachecoherent systems (our Atom CPUs). With UBOs, the GPU never
768     * writes, so there's no problem. For an SSBO, the GPU and the CPU can
769     * be updating disjoint regions of the buffer simultaneously and that will
770     * break if the regions overlap the same cacheline.
771     */
772    ctx->Const.ShaderStorageBufferOffsetAlignment = 64;
773    ctx->Const.TextureBufferOffsetAlignment = 16;
774    ctx->Const.MaxTextureBufferSize = 128 * 1024 * 1024;
775 
776    if (devinfo->ver >= 6) {
777       ctx->Const.MaxVarying = 32;
778       ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 128;
779       ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxInputComponents =
780          compiler->scalar_stage[MESA_SHADER_GEOMETRY] ? 128 : 64;
781       ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxOutputComponents = 128;
782       ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 128;
783       ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxInputComponents = 128;
784       ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxOutputComponents = 128;
785       ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxInputComponents = 128;
786       ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxOutputComponents = 128;
787    }
788 
789    /* We want the GLSL compiler to emit code that uses condition codes */
790    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
791       ctx->Const.ShaderCompilerOptions[i] =
792          brw->screen->compiler->glsl_compiler_options[i];
793    }
794 
795    if (devinfo->ver >= 7) {
796       ctx->Const.MaxViewportWidth = 32768;
797       ctx->Const.MaxViewportHeight = 32768;
798    }
799 
800    /* ARB_viewport_array, OES_viewport_array */
801    if (devinfo->ver >= 6) {
802       ctx->Const.MaxViewports = GFX6_NUM_VIEWPORTS;
803       ctx->Const.ViewportSubpixelBits = 8;
804 
805       /* Cast to float before negating because MaxViewportWidth is unsigned.
806        */
807       ctx->Const.ViewportBounds.Min = -(float)ctx->Const.MaxViewportWidth;
808       ctx->Const.ViewportBounds.Max = ctx->Const.MaxViewportWidth;
809    }
810 
811    /* ARB_gpu_shader5 */
812    if (devinfo->ver >= 7)
813       ctx->Const.MaxVertexStreams = MIN2(4, MAX_VERTEX_STREAMS);
814 
815    /* ARB_framebuffer_no_attachments */
816    ctx->Const.MaxFramebufferWidth = 16384;
817    ctx->Const.MaxFramebufferHeight = 16384;
818    ctx->Const.MaxFramebufferLayers = ctx->Const.MaxArrayTextureLayers;
819    ctx->Const.MaxFramebufferSamples = max_samples;
820 
821    /* OES_primitive_bounding_box */
822    ctx->Const.NoPrimitiveBoundingBoxOutput = true;
823 
824    /* TODO: We should be able to use STD430 packing by default on all hardware
825     * but some piglit tests [1] currently fail on SNB when this is enabled.
826     * The problem is the messages we're using for doing uniform pulls
827     * in the vec4 back-end on SNB is the OWORD block load instruction, which
828     * takes its offset in units of OWORDS (16 bytes).  On IVB+, we use the
829     * sampler which doesn't have these restrictions.
830     *
831     * In the scalar back-end, we use the sampler for dynamic uniform loads and
832     * pull an entire cache line at a time for constant offset loads both of
833     * which support almost any alignment.
834     *
835     * [1] glsl-1.40/uniform_buffer/vs-float-array-variable-index.shader_test
836     */
837    if (devinfo->ver >= 7)
838       ctx->Const.UseSTD430AsDefaultPacking = true;
839 
840    if (!(ctx->Const.ContextFlags & GL_CONTEXT_FLAG_DEBUG_BIT))
841       ctx->Const.AllowMappedBuffersDuringExecution = true;
842 
843    /* GL_ARB_get_program_binary */
844    ctx->Const.NumProgramBinaryFormats = 1;
845 }
846 
847 static void
brw_initialize_cs_context_constants(struct brw_context * brw)848 brw_initialize_cs_context_constants(struct brw_context *brw)
849 {
850    struct gl_context *ctx = &brw->ctx;
851    struct intel_device_info *devinfo = &brw->screen->devinfo;
852 
853    /* Maximum number of scalar compute shader invocations that can be run in
854     * parallel in the same subslice assuming SIMD32 dispatch.
855     */
856    const unsigned max_threads = devinfo->max_cs_workgroup_threads;
857    const uint32_t max_invocations = 32 * max_threads;
858    ctx->Const.MaxComputeWorkGroupSize[0] = max_invocations;
859    ctx->Const.MaxComputeWorkGroupSize[1] = max_invocations;
860    ctx->Const.MaxComputeWorkGroupSize[2] = max_invocations;
861    ctx->Const.MaxComputeWorkGroupInvocations = max_invocations;
862    ctx->Const.MaxComputeSharedMemorySize = 64 * 1024;
863 
864    /* Constants used for ARB_compute_variable_group_size. */
865    if (devinfo->ver >= 7) {
866       assert(max_invocations >= 512);
867       ctx->Const.MaxComputeVariableGroupSize[0] = max_invocations;
868       ctx->Const.MaxComputeVariableGroupSize[1] = max_invocations;
869       ctx->Const.MaxComputeVariableGroupSize[2] = max_invocations;
870       ctx->Const.MaxComputeVariableGroupInvocations = max_invocations;
871    }
872 }
873 
874 /**
875  * Process driconf (drirc) options, setting appropriate context flags.
876  *
877  * brw_init_extensions still pokes at optionCache directly, in order to
878  * avoid advertising various extensions.  No flags are set, so it makes
879  * sense to continue doing that there.
880  */
881 static void
brw_process_driconf_options(struct brw_context * brw)882 brw_process_driconf_options(struct brw_context *brw)
883 {
884    const struct intel_device_info *devinfo = &brw->screen->devinfo;
885    struct gl_context *ctx = &brw->ctx;
886    const driOptionCache *const options = &brw->screen->optionCache;
887 
888    if (INTEL_DEBUG(DEBUG_NO_HIZ)) {
889        brw->has_hiz = false;
890        /* On gfx6, you can only do separate stencil with HIZ. */
891        if (devinfo->ver == 6)
892           brw->has_separate_stencil = false;
893    }
894 
895    if (driQueryOptionb(options, "mesa_no_error"))
896       ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR;
897 
898    if (driQueryOptionb(options, "always_flush_batch")) {
899       fprintf(stderr, "flushing batchbuffer before/after each draw call\n");
900       brw->always_flush_batch = true;
901    }
902 
903    if (driQueryOptionb(options, "always_flush_cache")) {
904       fprintf(stderr, "flushing GPU caches before/after each draw call\n");
905       brw->always_flush_cache = true;
906    }
907 
908    if (driQueryOptionb(options, "disable_throttling")) {
909       fprintf(stderr, "disabling flush throttling\n");
910       brw->disable_throttling = true;
911    }
912 
913    brw->precompile = driQueryOptionb(&brw->screen->optionCache, "shader_precompile");
914 
915    if (driQueryOptionb(&brw->screen->optionCache, "precise_trig"))
916       brw->screen->compiler->precise_trig = true;
917 
918    ctx->Const.ForceGLSLExtensionsWarn =
919       driQueryOptionb(options, "force_glsl_extensions_warn");
920 
921    ctx->Const.ForceGLSLVersion =
922       driQueryOptioni(options, "force_glsl_version");
923 
924    ctx->Const.DisableGLSLLineContinuations =
925       driQueryOptionb(options, "disable_glsl_line_continuations");
926 
927    ctx->Const.AllowGLSLExtensionDirectiveMidShader =
928       driQueryOptionb(options, "allow_glsl_extension_directive_midshader");
929 
930    ctx->Const.AllowGLSLBuiltinVariableRedeclaration =
931       driQueryOptionb(options, "allow_glsl_builtin_variable_redeclaration");
932 
933    ctx->Const.AllowHigherCompatVersion =
934       driQueryOptionb(options, "allow_higher_compat_version");
935 
936    ctx->Const.ForceGLSLAbsSqrt =
937       driQueryOptionb(options, "force_glsl_abs_sqrt");
938 
939    ctx->Const.GLSLZeroInit = driQueryOptionb(options, "glsl_zero_init") ? 1 : 0;
940 
941    brw->dual_color_blend_by_location =
942       driQueryOptionb(options, "dual_color_blend_by_location");
943 
944    ctx->Const.AllowGLSLCrossStageInterpolationMismatch =
945       driQueryOptionb(options, "allow_glsl_cross_stage_interpolation_mismatch");
946 
947    char *vendor_str = driQueryOptionstr(options, "force_gl_vendor");
948    /* not an empty string */
949    if (*vendor_str)
950       ctx->Const.VendorOverride = vendor_str;
951 
952    ctx->Const.dri_config_options_sha1 =
953       ralloc_array(brw->mem_ctx, unsigned char, 20);
954    driComputeOptionsSha1(&brw->screen->optionCache,
955                          ctx->Const.dri_config_options_sha1);
956 }
957 
958 GLboolean
brw_create_context(gl_api api,const struct gl_config * mesaVis,__DRIcontext * driContextPriv,const struct __DriverContextConfig * ctx_config,unsigned * dri_ctx_error,void * sharedContextPrivate)959 brw_create_context(gl_api api,
960                    const struct gl_config *mesaVis,
961                    __DRIcontext *driContextPriv,
962                    const struct __DriverContextConfig *ctx_config,
963                    unsigned *dri_ctx_error,
964                    void *sharedContextPrivate)
965 {
966    struct gl_context *shareCtx = (struct gl_context *) sharedContextPrivate;
967    struct brw_screen *screen = driContextPriv->driScreenPriv->driverPrivate;
968    const struct intel_device_info *devinfo = &screen->devinfo;
969    struct dd_function_table functions;
970 
971    /* Only allow the __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS flag if the kernel
972     * provides us with context reset notifications.
973     */
974    uint32_t allowed_flags = __DRI_CTX_FLAG_DEBUG |
975                             __DRI_CTX_FLAG_FORWARD_COMPATIBLE |
976                             __DRI_CTX_FLAG_NO_ERROR;
977 
978    if (screen->has_context_reset_notification)
979       allowed_flags |= __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS;
980 
981    if (ctx_config->flags & ~allowed_flags) {
982       *dri_ctx_error = __DRI_CTX_ERROR_UNKNOWN_FLAG;
983       return false;
984    }
985 
986    if (ctx_config->attribute_mask &
987        ~(__DRIVER_CONTEXT_ATTRIB_RESET_STRATEGY |
988          __DRIVER_CONTEXT_ATTRIB_PRIORITY)) {
989       *dri_ctx_error = __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE;
990       return false;
991    }
992 
993    bool notify_reset =
994       ((ctx_config->attribute_mask & __DRIVER_CONTEXT_ATTRIB_RESET_STRATEGY) &&
995        ctx_config->reset_strategy != __DRI_CTX_RESET_NO_NOTIFICATION);
996 
997    struct brw_context *brw = align_calloc(sizeof(struct brw_context), 16);
998    if (!brw) {
999       fprintf(stderr, "%s: failed to alloc context\n", __func__);
1000       *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
1001       return false;
1002    }
1003    brw->mem_ctx = ralloc_context(NULL);
1004    brw->perf_ctx = intel_perf_new_context(brw->mem_ctx);
1005 
1006    driContextPriv->driverPrivate = brw;
1007    brw->driContext = driContextPriv;
1008    brw->screen = screen;
1009    brw->bufmgr = screen->bufmgr;
1010 
1011    brw->has_hiz = devinfo->has_hiz_and_separate_stencil;
1012    brw->has_separate_stencil = devinfo->has_hiz_and_separate_stencil;
1013 
1014    brw->has_swizzling = screen->hw_has_swizzling;
1015 
1016    /* We don't push UBOs on IVB and earlier because the restrictions on
1017     * 3DSTATE_CONSTANT_* make it really annoying to use push constants
1018     * without dynamic state base address.
1019     */
1020    brw->can_push_ubos = devinfo->verx10 >= 75;
1021 
1022    brw->isl_dev = screen->isl_dev;
1023 
1024    brw->vs.base.stage = MESA_SHADER_VERTEX;
1025    brw->tcs.base.stage = MESA_SHADER_TESS_CTRL;
1026    brw->tes.base.stage = MESA_SHADER_TESS_EVAL;
1027    brw->gs.base.stage = MESA_SHADER_GEOMETRY;
1028    brw->wm.base.stage = MESA_SHADER_FRAGMENT;
1029    brw->cs.base.stage = MESA_SHADER_COMPUTE;
1030 
1031    brw_init_driver_functions(brw, &functions);
1032 
1033    if (notify_reset)
1034       functions.GetGraphicsResetStatus = brw_get_graphics_reset_status;
1035 
1036    brw_process_driconf_options(brw);
1037 
1038    if (api == API_OPENGL_CORE &&
1039        driQueryOptionb(&screen->optionCache, "force_compat_profile")) {
1040       api = API_OPENGL_COMPAT;
1041    }
1042 
1043    struct gl_context *ctx = &brw->ctx;
1044 
1045    if (!_mesa_initialize_context(ctx, api, mesaVis, shareCtx, &functions)) {
1046       *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
1047       fprintf(stderr, "%s: failed to init mesa context\n", __func__);
1048       brw_destroy_context(driContextPriv);
1049       return false;
1050    }
1051 
1052    driContextSetFlags(ctx, ctx_config->flags);
1053 
1054    /* Initialize the software rasterizer and helper modules.
1055     *
1056     * As of GL 3.1 core, the gfx4+ driver doesn't need the swrast context for
1057     * software fallbacks (which we have to support on legacy GL to do weird
1058     * glDrawPixels(), glBitmap(), and other functions).
1059     */
1060    if (api != API_OPENGL_CORE && api != API_OPENGLES2) {
1061       _swrast_CreateContext(ctx);
1062    }
1063 
1064    _vbo_CreateContext(ctx, true);
1065    if (ctx->swrast_context) {
1066       _tnl_CreateContext(ctx);
1067       TNL_CONTEXT(ctx)->Driver.RunPipeline = _tnl_run_pipeline;
1068       _swsetup_CreateContext(ctx);
1069 
1070       /* Configure swrast to match hardware characteristics: */
1071       _swrast_allow_pixel_fog(ctx, false);
1072       _swrast_allow_vertex_fog(ctx, true);
1073    }
1074 
1075    _mesa_meta_init(ctx);
1076 
1077    if (INTEL_DEBUG(DEBUG_PERF))
1078       brw->perf_debug = true;
1079 
1080    brw_initialize_cs_context_constants(brw);
1081    brw_initialize_context_constants(brw);
1082 
1083    ctx->Const.ResetStrategy = notify_reset
1084       ? GL_LOSE_CONTEXT_ON_RESET_ARB : GL_NO_RESET_NOTIFICATION_ARB;
1085 
1086    /* Reinitialize the context point state.  It depends on ctx->Const values. */
1087    _mesa_init_point(ctx);
1088 
1089    brw_fbo_init(brw);
1090 
1091    brw_batch_init(brw);
1092 
1093    /* Create a new hardware context.  Using a hardware context means that
1094     * our GPU state will be saved/restored on context switch, allowing us
1095     * to assume that the GPU is in the same state we left it in.
1096     *
1097     * This is required for transform feedback buffer offsets, query objects,
1098     * and also allows us to reduce how much state we have to emit.
1099     */
1100    brw->hw_ctx = brw_create_hw_context(brw->bufmgr);
1101    if (!brw->hw_ctx && devinfo->ver >= 6) {
1102       fprintf(stderr, "Failed to create hardware context.\n");
1103       brw_destroy_context(driContextPriv);
1104       return false;
1105    }
1106 
1107    if (brw->hw_ctx) {
1108       int hw_priority = INTEL_CONTEXT_MEDIUM_PRIORITY;
1109       if (ctx_config->attribute_mask & __DRIVER_CONTEXT_ATTRIB_PRIORITY) {
1110          switch (ctx_config->priority) {
1111          case __DRI_CTX_PRIORITY_LOW:
1112             hw_priority = INTEL_CONTEXT_LOW_PRIORITY;
1113             break;
1114          case __DRI_CTX_PRIORITY_HIGH:
1115             hw_priority = INTEL_CONTEXT_HIGH_PRIORITY;
1116             break;
1117          }
1118       }
1119       if (hw_priority != I915_CONTEXT_DEFAULT_PRIORITY &&
1120           brw_hw_context_set_priority(brw->bufmgr, brw->hw_ctx, hw_priority)) {
1121          fprintf(stderr,
1122                  "Failed to set priority [%d:%d] for hardware context.\n",
1123                  ctx_config->priority, hw_priority);
1124          brw_destroy_context(driContextPriv);
1125          return false;
1126       }
1127    }
1128 
1129    if (brw_init_pipe_control(brw, devinfo)) {
1130       *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
1131       brw_destroy_context(driContextPriv);
1132       return false;
1133    }
1134 
1135    brw_upload_init(&brw->upload, brw->bufmgr, 65536);
1136 
1137    brw_init_state(brw);
1138 
1139    brw_init_extensions(ctx);
1140 
1141    brw_init_surface_formats(brw);
1142 
1143    brw_blorp_init(brw);
1144 
1145    brw->urb.size = devinfo->urb.size;
1146 
1147    if (devinfo->ver == 6)
1148       brw->urb.gs_present = false;
1149 
1150    brw->prim_restart.in_progress = false;
1151    brw->prim_restart.enable_cut_index = false;
1152    brw->gs.enabled = false;
1153    brw->clip.viewport_count = 1;
1154 
1155    brw->predicate.state = BRW_PREDICATE_STATE_RENDER;
1156 
1157    brw->max_gtt_map_object_size = screen->max_gtt_map_object_size;
1158 
1159    ctx->VertexProgram._MaintainTnlProgram = true;
1160    ctx->FragmentProgram._MaintainTexEnvProgram = true;
1161    _mesa_reset_vertex_processing_mode(ctx);
1162 
1163    brw_draw_init( brw );
1164 
1165    if ((ctx_config->flags & __DRI_CTX_FLAG_DEBUG) != 0) {
1166       /* Turn on some extra GL_ARB_debug_output generation. */
1167       brw->perf_debug = true;
1168    }
1169 
1170    if ((ctx_config->flags & __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS) != 0) {
1171       ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB;
1172       ctx->Const.RobustAccess = GL_TRUE;
1173    }
1174 
1175    if (INTEL_DEBUG(DEBUG_SHADER_TIME))
1176       brw_init_shader_time(brw);
1177 
1178    _mesa_override_extensions(ctx);
1179    _mesa_compute_version(ctx);
1180 
1181 #ifndef NDEBUG
1182    /* Enforce that the version of the context that was created is at least as
1183     * high as the version that was advertised via GLX / EGL / whatever window
1184     * system.
1185     */
1186    const __DRIscreen *const dri_screen = brw->screen->driScrnPriv;
1187 
1188    switch (api) {
1189    case API_OPENGL_COMPAT:
1190       assert(ctx->Version >= dri_screen->max_gl_compat_version);
1191       break;
1192    case API_OPENGLES:
1193       assert(ctx->Version >= dri_screen->max_gl_es1_version);
1194       break;
1195    case API_OPENGLES2:
1196       assert(ctx->Version >= dri_screen->max_gl_es2_version);
1197       break;
1198    case API_OPENGL_CORE:
1199       assert(ctx->Version >= dri_screen->max_gl_core_version);
1200       break;
1201    }
1202 #endif
1203 
1204    /* GL_ARB_gl_spirv */
1205    if (ctx->Extensions.ARB_gl_spirv) {
1206       brw_initialize_spirv_supported_capabilities(brw);
1207 
1208       if (ctx->Extensions.ARB_spirv_extensions) {
1209          /* GL_ARB_spirv_extensions */
1210          ctx->Const.SpirVExtensions = MALLOC_STRUCT(spirv_supported_extensions);
1211          _mesa_fill_supported_spirv_extensions(ctx->Const.SpirVExtensions,
1212                                                &ctx->Const.SpirVCapabilities);
1213       }
1214    }
1215 
1216    _mesa_initialize_dispatch_tables(ctx);
1217    _mesa_initialize_vbo_vtxfmt(ctx);
1218 
1219    if (ctx->Extensions.INTEL_performance_query)
1220       brw_init_performance_queries(brw);
1221 
1222    brw->ctx.Cache = brw->screen->disk_cache;
1223 
1224    if (driContextPriv->driScreenPriv->dri2.backgroundCallable &&
1225        driQueryOptionb(&screen->optionCache, "mesa_glthread")) {
1226       /* Loader supports multithreading, and so do we. */
1227       _mesa_glthread_init(ctx);
1228    }
1229 
1230    return true;
1231 }
1232 
1233 void
brw_destroy_context(__DRIcontext * driContextPriv)1234 brw_destroy_context(__DRIcontext *driContextPriv)
1235 {
1236    struct brw_context *brw =
1237       (struct brw_context *) driContextPriv->driverPrivate;
1238    struct gl_context *ctx = &brw->ctx;
1239 
1240    GET_CURRENT_CONTEXT(curctx);
1241 
1242    if (curctx == NULL) {
1243       /* No current context, but we need one to release
1244        * renderbuffer surface when we release framebuffer.
1245        * So temporarily bind the context.
1246        */
1247       _mesa_make_current(ctx, NULL, NULL);
1248    }
1249 
1250    _mesa_glthread_destroy(&brw->ctx);
1251 
1252    _mesa_meta_free(&brw->ctx);
1253 
1254    if (INTEL_DEBUG(DEBUG_SHADER_TIME)) {
1255       /* Force a report. */
1256       brw->shader_time.report_time = 0;
1257 
1258       brw_collect_and_report_shader_time(brw);
1259       brw_destroy_shader_time(brw);
1260    }
1261 
1262    blorp_finish(&brw->blorp);
1263 
1264    brw_destroy_state(brw);
1265    brw_draw_destroy(brw);
1266 
1267    brw_bo_unreference(brw->curbe.curbe_bo);
1268 
1269    brw_bo_unreference(brw->vs.base.scratch_bo);
1270    brw_bo_unreference(brw->tcs.base.scratch_bo);
1271    brw_bo_unreference(brw->tes.base.scratch_bo);
1272    brw_bo_unreference(brw->gs.base.scratch_bo);
1273    brw_bo_unreference(brw->wm.base.scratch_bo);
1274 
1275    brw_bo_unreference(brw->vs.base.push_const_bo);
1276    brw_bo_unreference(brw->tcs.base.push_const_bo);
1277    brw_bo_unreference(brw->tes.base.push_const_bo);
1278    brw_bo_unreference(brw->gs.base.push_const_bo);
1279    brw_bo_unreference(brw->wm.base.push_const_bo);
1280 
1281    brw_destroy_hw_context(brw->bufmgr, brw->hw_ctx);
1282 
1283    if (ctx->swrast_context) {
1284       _swsetup_DestroyContext(&brw->ctx);
1285       _tnl_DestroyContext(&brw->ctx);
1286    }
1287    _vbo_DestroyContext(&brw->ctx);
1288 
1289    if (ctx->swrast_context)
1290       _swrast_DestroyContext(&brw->ctx);
1291 
1292    brw_fini_pipe_control(brw);
1293    brw_batch_free(&brw->batch);
1294 
1295    brw_bo_unreference(brw->throttle_batch[1]);
1296    brw_bo_unreference(brw->throttle_batch[0]);
1297    brw->throttle_batch[1] = NULL;
1298    brw->throttle_batch[0] = NULL;
1299 
1300    /* free the Mesa context */
1301    _mesa_free_context_data(&brw->ctx, true);
1302 
1303    ralloc_free(brw->mem_ctx);
1304    align_free(brw);
1305    driContextPriv->driverPrivate = NULL;
1306 }
1307 
1308 GLboolean
brw_unbind_context(__DRIcontext * driContextPriv)1309 brw_unbind_context(__DRIcontext *driContextPriv)
1310 {
1311    struct gl_context *ctx = driContextPriv->driverPrivate;
1312    _mesa_glthread_finish(ctx);
1313 
1314    /* Unset current context and dispath table */
1315    _mesa_make_current(NULL, NULL, NULL);
1316 
1317    return true;
1318 }
1319 
1320 /**
1321  * Fixes up the context for GLES23 with our default-to-sRGB-capable behavior
1322  * on window system framebuffers.
1323  *
1324  * Desktop GL is fairly reasonable in its handling of sRGB: You can ask if
1325  * your renderbuffer can do sRGB encode, and you can flip a switch that does
1326  * sRGB encode if the renderbuffer can handle it.  You can ask specifically
1327  * for a visual where you're guaranteed to be capable, but it turns out that
1328  * everyone just makes all their ARGB8888 visuals capable and doesn't offer
1329  * incapable ones, because there's no difference between the two in resources
1330  * used.  Applications thus get built that accidentally rely on the default
1331  * visual choice being sRGB, so we make ours sRGB capable.  Everything sounds
1332  * great...
1333  *
1334  * But for GLES2/3, they decided that it was silly to not turn on sRGB encode
1335  * for sRGB renderbuffers you made with the GL_EXT_texture_sRGB equivalent.
1336  * So they removed the enable knob and made it "if the renderbuffer is sRGB
1337  * capable, do sRGB encode".  Then, for your window system renderbuffers, you
1338  * can ask for sRGB visuals and get sRGB encode, or not ask for sRGB visuals
1339  * and get no sRGB encode (assuming that both kinds of visual are available).
1340  * Thus our choice to support sRGB by default on our visuals for desktop would
1341  * result in broken rendering of GLES apps that aren't expecting sRGB encode.
1342  *
1343  * Unfortunately, renderbuffer setup happens before a context is created.  So
1344  * in brw_screen.c we always set up sRGB, and here, if you're a GLES2/3
1345  * context (without an sRGB visual), we go turn that back off before anyone
1346  * finds out.
1347  */
1348 static void
brw_gles3_srgb_workaround(struct brw_context * brw,struct gl_framebuffer * fb)1349 brw_gles3_srgb_workaround(struct brw_context *brw, struct gl_framebuffer *fb)
1350 {
1351    struct gl_context *ctx = &brw->ctx;
1352 
1353    if (_mesa_is_desktop_gl(ctx) || !fb->Visual.sRGBCapable)
1354       return;
1355 
1356    for (int i = 0; i < BUFFER_COUNT; i++) {
1357       struct gl_renderbuffer *rb = fb->Attachment[i].Renderbuffer;
1358 
1359       /* Check if sRGB was specifically asked for. */
1360       struct brw_renderbuffer *irb = brw_get_renderbuffer(fb, i);
1361       if (irb && irb->need_srgb)
1362          return;
1363 
1364       if (rb)
1365          rb->Format = _mesa_get_srgb_format_linear(rb->Format);
1366    }
1367    /* Disable sRGB from framebuffers that are not compatible. */
1368    fb->Visual.sRGBCapable = false;
1369 }
1370 
1371 GLboolean
brw_make_current(__DRIcontext * driContextPriv,__DRIdrawable * driDrawPriv,__DRIdrawable * driReadPriv)1372 brw_make_current(__DRIcontext *driContextPriv,
1373                  __DRIdrawable *driDrawPriv,
1374                  __DRIdrawable *driReadPriv)
1375 {
1376    struct brw_context *brw;
1377 
1378    if (driContextPriv)
1379       brw = (struct brw_context *) driContextPriv->driverPrivate;
1380    else
1381       brw = NULL;
1382 
1383    if (driContextPriv) {
1384       struct gl_context *ctx = &brw->ctx;
1385       struct gl_framebuffer *fb, *readFb;
1386 
1387       if (driDrawPriv == NULL) {
1388          fb = _mesa_get_incomplete_framebuffer();
1389       } else {
1390          fb = driDrawPriv->driverPrivate;
1391          driContextPriv->dri2.draw_stamp = driDrawPriv->dri2.stamp - 1;
1392       }
1393 
1394       if (driReadPriv == NULL) {
1395          readFb = _mesa_get_incomplete_framebuffer();
1396       } else {
1397          readFb = driReadPriv->driverPrivate;
1398          driContextPriv->dri2.read_stamp = driReadPriv->dri2.stamp - 1;
1399       }
1400 
1401       /* The sRGB workaround changes the renderbuffer's format. We must change
1402        * the format before the renderbuffer's miptree get's allocated, otherwise
1403        * the formats of the renderbuffer and its miptree will differ.
1404        */
1405       brw_gles3_srgb_workaround(brw, fb);
1406       brw_gles3_srgb_workaround(brw, readFb);
1407 
1408       /* If the context viewport hasn't been initialized, force a call out to
1409        * the loader to get buffers so we have a drawable size for the initial
1410        * viewport. */
1411       if (!brw->ctx.ViewportInitialized)
1412          brw_prepare_render(brw);
1413 
1414       _mesa_make_current(ctx, fb, readFb);
1415    } else {
1416       GET_CURRENT_CONTEXT(ctx);
1417       _mesa_glthread_finish(ctx);
1418       _mesa_make_current(NULL, NULL, NULL);
1419    }
1420 
1421    return true;
1422 }
1423 
1424 void
brw_resolve_for_dri2_flush(struct brw_context * brw,__DRIdrawable * drawable)1425 brw_resolve_for_dri2_flush(struct brw_context *brw,
1426                            __DRIdrawable *drawable)
1427 {
1428    const struct intel_device_info *devinfo = &brw->screen->devinfo;
1429 
1430    if (devinfo->ver < 6) {
1431       /* MSAA and fast color clear are not supported, so don't waste time
1432        * checking whether a resolve is needed.
1433        */
1434       return;
1435    }
1436 
1437    struct gl_framebuffer *fb = drawable->driverPrivate;
1438    struct brw_renderbuffer *rb;
1439 
1440    /* Usually, only the back buffer will need to be downsampled. However,
1441     * the front buffer will also need it if the user has rendered into it.
1442     */
1443    static const gl_buffer_index buffers[2] = {
1444          BUFFER_BACK_LEFT,
1445          BUFFER_FRONT_LEFT,
1446    };
1447 
1448    for (int i = 0; i < 2; ++i) {
1449       rb = brw_get_renderbuffer(fb, buffers[i]);
1450       if (rb == NULL || rb->mt == NULL)
1451          continue;
1452       if (rb->mt->surf.samples == 1) {
1453          assert(rb->mt_layer == 0 && rb->mt_level == 0 &&
1454                 rb->layer_count == 1);
1455          brw_miptree_prepare_external(brw, rb->mt);
1456       } else {
1457          brw_renderbuffer_downsample(brw, rb);
1458 
1459          /* Call prepare_external on the single-sample miptree to do any
1460           * needed resolves prior to handing it off to the window system.
1461           * This is needed in the case that rb->singlesample_mt is Y-tiled
1462           * with CCS_E enabled but without I915_FORMAT_MOD_Y_TILED_CCS_E.  In
1463           * this case, the MSAA resolve above will write compressed data into
1464           * rb->singlesample_mt.
1465           *
1466           * TODO: Some day, if we decide to care about the tiny performance
1467           * hit we're taking by doing the MSAA resolve and then a CCS resolve,
1468           * we could detect this case and just allocate the single-sampled
1469           * miptree without aux.  However, that would be a lot of plumbing and
1470           * this is a rather exotic case so it's not really worth it.
1471           */
1472          brw_miptree_prepare_external(brw, rb->singlesample_mt);
1473       }
1474    }
1475 }
1476 
1477 static unsigned
brw_bits_per_pixel(const struct brw_renderbuffer * rb)1478 brw_bits_per_pixel(const struct brw_renderbuffer *rb)
1479 {
1480    return _mesa_get_format_bytes(brw_rb_format(rb)) * 8;
1481 }
1482 
1483 static void
1484 brw_query_dri2_buffers(struct brw_context *brw,
1485                        __DRIdrawable *drawable,
1486                        __DRIbuffer **buffers,
1487                        int *count);
1488 
1489 static void
1490 brw_process_dri2_buffer(struct brw_context *brw,
1491                         __DRIdrawable *drawable,
1492                         __DRIbuffer *buffer,
1493                         struct brw_renderbuffer *rb,
1494                         const char *buffer_name);
1495 
1496 static void
1497 brw_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable);
1498 
1499 static void
brw_update_dri2_buffers(struct brw_context * brw,__DRIdrawable * drawable)1500 brw_update_dri2_buffers(struct brw_context *brw, __DRIdrawable *drawable)
1501 {
1502    struct gl_framebuffer *fb = drawable->driverPrivate;
1503    struct brw_renderbuffer *rb;
1504    __DRIbuffer *buffers = NULL;
1505    int count;
1506    const char *region_name;
1507 
1508    /* Set this up front, so that in case our buffers get invalidated
1509     * while we're getting new buffers, we don't clobber the stamp and
1510     * thus ignore the invalidate. */
1511    drawable->lastStamp = drawable->dri2.stamp;
1512 
1513    if (INTEL_DEBUG(DEBUG_DRI))
1514       fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1515 
1516    brw_query_dri2_buffers(brw, drawable, &buffers, &count);
1517 
1518    if (buffers == NULL)
1519       return;
1520 
1521    for (int i = 0; i < count; i++) {
1522        switch (buffers[i].attachment) {
1523        case __DRI_BUFFER_FRONT_LEFT:
1524            rb = brw_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1525            region_name = "dri2 front buffer";
1526            break;
1527 
1528        case __DRI_BUFFER_FAKE_FRONT_LEFT:
1529            rb = brw_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1530            region_name = "dri2 fake front buffer";
1531            break;
1532 
1533        case __DRI_BUFFER_BACK_LEFT:
1534            rb = brw_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1535            region_name = "dri2 back buffer";
1536            break;
1537 
1538        case __DRI_BUFFER_DEPTH:
1539        case __DRI_BUFFER_HIZ:
1540        case __DRI_BUFFER_DEPTH_STENCIL:
1541        case __DRI_BUFFER_STENCIL:
1542        case __DRI_BUFFER_ACCUM:
1543        default:
1544            fprintf(stderr,
1545                    "unhandled buffer attach event, attachment type %d\n",
1546                    buffers[i].attachment);
1547            return;
1548        }
1549 
1550        brw_process_dri2_buffer(brw, drawable, &buffers[i], rb, region_name);
1551    }
1552 
1553 }
1554 
1555 void
brw_update_renderbuffers(__DRIcontext * context,__DRIdrawable * drawable)1556 brw_update_renderbuffers(__DRIcontext *context, __DRIdrawable *drawable)
1557 {
1558    struct brw_context *brw = context->driverPrivate;
1559    __DRIscreen *dri_screen = brw->screen->driScrnPriv;
1560 
1561    /* Set this up front, so that in case our buffers get invalidated
1562     * while we're getting new buffers, we don't clobber the stamp and
1563     * thus ignore the invalidate. */
1564    drawable->lastStamp = drawable->dri2.stamp;
1565 
1566    if (INTEL_DEBUG(DEBUG_DRI))
1567       fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1568 
1569    if (dri_screen->image.loader)
1570       brw_update_image_buffers(brw, drawable);
1571    else
1572       brw_update_dri2_buffers(brw, drawable);
1573 
1574    driUpdateFramebufferSize(&brw->ctx, drawable);
1575 }
1576 
1577 /**
1578  * intel_prepare_render should be called anywhere that curent read/drawbuffer
1579  * state is required.
1580  */
1581 void
brw_prepare_render(struct brw_context * brw)1582 brw_prepare_render(struct brw_context *brw)
1583 {
1584    struct gl_context *ctx = &brw->ctx;
1585    __DRIcontext *driContext = brw->driContext;
1586    __DRIdrawable *drawable;
1587 
1588    drawable = driContext->driDrawablePriv;
1589    if (drawable && drawable->dri2.stamp != driContext->dri2.draw_stamp) {
1590       if (drawable->lastStamp != drawable->dri2.stamp)
1591          brw_update_renderbuffers(driContext, drawable);
1592       driContext->dri2.draw_stamp = drawable->dri2.stamp;
1593    }
1594 
1595    drawable = driContext->driReadablePriv;
1596    if (drawable && drawable->dri2.stamp != driContext->dri2.read_stamp) {
1597       if (drawable->lastStamp != drawable->dri2.stamp)
1598          brw_update_renderbuffers(driContext, drawable);
1599       driContext->dri2.read_stamp = drawable->dri2.stamp;
1600    }
1601 
1602    /* If we're currently rendering to the front buffer, the rendering
1603     * that will happen next will probably dirty the front buffer.  So
1604     * mark it as dirty here.
1605     */
1606    if (_mesa_is_front_buffer_drawing(ctx->DrawBuffer) &&
1607        ctx->DrawBuffer != _mesa_get_incomplete_framebuffer()) {
1608       brw->front_buffer_dirty = true;
1609    }
1610 
1611    if (brw->is_shared_buffer_bound) {
1612       /* Subsequent rendering will probably dirty the shared buffer. */
1613       brw->is_shared_buffer_dirty = true;
1614    }
1615 }
1616 
1617 /**
1618  * \brief Query DRI2 to obtain a DRIdrawable's buffers.
1619  *
1620  * To determine which DRI buffers to request, examine the renderbuffers
1621  * attached to the drawable's framebuffer. Then request the buffers with
1622  * DRI2GetBuffers() or DRI2GetBuffersWithFormat().
1623  *
1624  * This is called from brw_update_renderbuffers().
1625  *
1626  * \param drawable      Drawable whose buffers are queried.
1627  * \param buffers       [out] List of buffers returned by DRI2 query.
1628  * \param buffer_count  [out] Number of buffers returned.
1629  *
1630  * \see brw_update_renderbuffers()
1631  * \see DRI2GetBuffers()
1632  * \see DRI2GetBuffersWithFormat()
1633  */
1634 static void
brw_query_dri2_buffers(struct brw_context * brw,__DRIdrawable * drawable,__DRIbuffer ** buffers,int * buffer_count)1635 brw_query_dri2_buffers(struct brw_context *brw,
1636                        __DRIdrawable *drawable,
1637                        __DRIbuffer **buffers,
1638                        int *buffer_count)
1639 {
1640    __DRIscreen *dri_screen = brw->screen->driScrnPriv;
1641    struct gl_framebuffer *fb = drawable->driverPrivate;
1642    int i = 0;
1643    unsigned attachments[__DRI_BUFFER_COUNT];
1644 
1645    struct brw_renderbuffer *front_rb;
1646    struct brw_renderbuffer *back_rb;
1647 
1648    front_rb = brw_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1649    back_rb = brw_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1650 
1651    memset(attachments, 0, sizeof(attachments));
1652    if ((_mesa_is_front_buffer_drawing(fb) ||
1653         _mesa_is_front_buffer_reading(fb) ||
1654         !back_rb) && front_rb) {
1655       /* If a fake front buffer is in use, then querying for
1656        * __DRI_BUFFER_FRONT_LEFT will cause the server to copy the image from
1657        * the real front buffer to the fake front buffer.  So before doing the
1658        * query, we need to make sure all the pending drawing has landed in the
1659        * real front buffer.
1660        */
1661       brw_batch_flush(brw);
1662       brw_flush_front(&brw->ctx);
1663 
1664       attachments[i++] = __DRI_BUFFER_FRONT_LEFT;
1665       attachments[i++] = brw_bits_per_pixel(front_rb);
1666    } else if (front_rb && brw->front_buffer_dirty) {
1667       /* We have pending front buffer rendering, but we aren't querying for a
1668        * front buffer.  If the front buffer we have is a fake front buffer,
1669        * the X server is going to throw it away when it processes the query.
1670        * So before doing the query, make sure all the pending drawing has
1671        * landed in the real front buffer.
1672        */
1673       brw_batch_flush(brw);
1674       brw_flush_front(&brw->ctx);
1675    }
1676 
1677    if (back_rb) {
1678       attachments[i++] = __DRI_BUFFER_BACK_LEFT;
1679       attachments[i++] = brw_bits_per_pixel(back_rb);
1680    }
1681 
1682    assert(i <= ARRAY_SIZE(attachments));
1683 
1684    *buffers =
1685       dri_screen->dri2.loader->getBuffersWithFormat(drawable,
1686                                                     &drawable->w,
1687                                                     &drawable->h,
1688                                                     attachments, i / 2,
1689                                                     buffer_count,
1690                                                     drawable->loaderPrivate);
1691 }
1692 
1693 /**
1694  * \brief Assign a DRI buffer's DRM region to a renderbuffer.
1695  *
1696  * This is called from brw_update_renderbuffers().
1697  *
1698  * \par Note:
1699  *    DRI buffers whose attachment point is DRI2BufferStencil or
1700  *    DRI2BufferDepthStencil are handled as special cases.
1701  *
1702  * \param buffer_name is a human readable name, such as "dri2 front buffer",
1703  *        that is passed to brw_bo_gem_create_from_name().
1704  *
1705  * \see brw_update_renderbuffers()
1706  */
1707 static void
brw_process_dri2_buffer(struct brw_context * brw,__DRIdrawable * drawable,__DRIbuffer * buffer,struct brw_renderbuffer * rb,const char * buffer_name)1708 brw_process_dri2_buffer(struct brw_context *brw,
1709                         __DRIdrawable *drawable,
1710                         __DRIbuffer *buffer,
1711                         struct brw_renderbuffer *rb,
1712                         const char *buffer_name)
1713 {
1714    struct gl_framebuffer *fb = drawable->driverPrivate;
1715    struct brw_bo *bo;
1716 
1717    if (!rb)
1718       return;
1719 
1720    unsigned num_samples = rb->Base.Base.NumSamples;
1721 
1722    /* We try to avoid closing and reopening the same BO name, because the first
1723     * use of a mapping of the buffer involves a bunch of page faulting which is
1724     * moderately expensive.
1725     */
1726    struct brw_mipmap_tree *last_mt;
1727    if (num_samples == 0)
1728       last_mt = rb->mt;
1729    else
1730       last_mt = rb->singlesample_mt;
1731 
1732    uint32_t old_name = 0;
1733    if (last_mt) {
1734        /* The bo already has a name because the miptree was created by a
1735         * previous call to brw_process_dri2_buffer(). If a bo already has a
1736         * name, then brw_bo_flink() is a low-cost getter.  It does not
1737         * create a new name.
1738         */
1739       brw_bo_flink(last_mt->bo, &old_name);
1740    }
1741 
1742    if (old_name == buffer->name)
1743       return;
1744 
1745    if (INTEL_DEBUG(DEBUG_DRI)) {
1746       fprintf(stderr,
1747               "attaching buffer %d, at %d, cpp %d, pitch %d\n",
1748               buffer->name, buffer->attachment,
1749               buffer->cpp, buffer->pitch);
1750    }
1751 
1752    bo = brw_bo_gem_create_from_name(brw->bufmgr, buffer_name,
1753                                           buffer->name);
1754    if (!bo) {
1755       fprintf(stderr,
1756               "Failed to open BO for returned DRI2 buffer "
1757               "(%dx%d, %s, named %d).\n"
1758               "This is likely a bug in the X Server that will lead to a "
1759               "crash soon.\n",
1760               drawable->w, drawable->h, buffer_name, buffer->name);
1761       return;
1762    }
1763 
1764    uint32_t tiling, swizzle;
1765    brw_bo_get_tiling(bo, &tiling, &swizzle);
1766 
1767    struct brw_mipmap_tree *mt =
1768       brw_miptree_create_for_bo(brw,
1769                                 bo,
1770                                 brw_rb_format(rb),
1771                                 0,
1772                                 drawable->w,
1773                                 drawable->h,
1774                                 1,
1775                                 buffer->pitch,
1776                                 isl_tiling_from_i915_tiling(tiling),
1777                                 MIPTREE_CREATE_DEFAULT);
1778    if (!mt) {
1779       brw_bo_unreference(bo);
1780       return;
1781    }
1782 
1783    /* We got this BO from X11.  We cana't assume that we have coherent texture
1784     * access because X may suddenly decide to use it for scan-out which would
1785     * destroy coherency.
1786     */
1787    bo->cache_coherent = false;
1788 
1789    if (!brw_update_winsys_renderbuffer_miptree(brw, rb, mt,
1790                                                  drawable->w, drawable->h,
1791                                                  buffer->pitch)) {
1792       brw_bo_unreference(bo);
1793       brw_miptree_release(&mt);
1794       return;
1795    }
1796 
1797    if (_mesa_is_front_buffer_drawing(fb) &&
1798        (buffer->attachment == __DRI_BUFFER_FRONT_LEFT ||
1799         buffer->attachment == __DRI_BUFFER_FAKE_FRONT_LEFT) &&
1800        rb->Base.Base.NumSamples > 1) {
1801       brw_renderbuffer_upsample(brw, rb);
1802    }
1803 
1804    assert(rb->mt);
1805 
1806    brw_bo_unreference(bo);
1807 }
1808 
1809 /**
1810  * \brief Query DRI image loader to obtain a DRIdrawable's buffers.
1811  *
1812  * To determine which DRI buffers to request, examine the renderbuffers
1813  * attached to the drawable's framebuffer. Then request the buffers from
1814  * the image loader
1815  *
1816  * This is called from brw_update_renderbuffers().
1817  *
1818  * \param drawable      Drawable whose buffers are queried.
1819  * \param buffers       [out] List of buffers returned by DRI2 query.
1820  * \param buffer_count  [out] Number of buffers returned.
1821  *
1822  * \see brw_update_renderbuffers()
1823  */
1824 
1825 static void
brw_update_image_buffer(struct brw_context * intel,__DRIdrawable * drawable,struct brw_renderbuffer * rb,__DRIimage * buffer,enum __DRIimageBufferMask buffer_type)1826 brw_update_image_buffer(struct brw_context *intel,
1827                         __DRIdrawable *drawable,
1828                         struct brw_renderbuffer *rb,
1829                         __DRIimage *buffer,
1830                         enum __DRIimageBufferMask buffer_type)
1831 {
1832    struct gl_framebuffer *fb = drawable->driverPrivate;
1833 
1834    if (!rb || !buffer->bo)
1835       return;
1836 
1837    unsigned num_samples = rb->Base.Base.NumSamples;
1838 
1839    /* Check and see if we're already bound to the right
1840     * buffer object
1841     */
1842    struct brw_mipmap_tree *last_mt;
1843    if (num_samples == 0)
1844       last_mt = rb->mt;
1845    else
1846       last_mt = rb->singlesample_mt;
1847 
1848    if (last_mt && last_mt->bo == buffer->bo) {
1849       if (buffer_type == __DRI_IMAGE_BUFFER_SHARED) {
1850          brw_miptree_make_shareable(intel, last_mt);
1851       }
1852       return;
1853    }
1854 
1855    /* Only allow internal compression if samples == 0.  For multisampled
1856     * window system buffers, the only thing the single-sampled buffer is used
1857     * for is as a resolve target.  If we do any compression beyond what is
1858     * supported by the window system, we will just have to resolve so it's
1859     * probably better to just not bother.
1860     */
1861    const bool allow_internal_aux = (num_samples == 0);
1862 
1863    struct brw_mipmap_tree *mt =
1864       brw_miptree_create_for_dri_image(intel, buffer, GL_TEXTURE_2D,
1865                                        brw_rb_format(rb),
1866                                        allow_internal_aux);
1867    if (!mt)
1868       return;
1869 
1870    if (!brw_update_winsys_renderbuffer_miptree(intel, rb, mt,
1871                                                  buffer->width, buffer->height,
1872                                                  buffer->pitch)) {
1873       brw_miptree_release(&mt);
1874       return;
1875    }
1876 
1877    if (_mesa_is_front_buffer_drawing(fb) &&
1878        buffer_type == __DRI_IMAGE_BUFFER_FRONT &&
1879        rb->Base.Base.NumSamples > 1) {
1880       brw_renderbuffer_upsample(intel, rb);
1881    }
1882 
1883    if (buffer_type == __DRI_IMAGE_BUFFER_SHARED) {
1884       /* The compositor and the application may access this image
1885        * concurrently. The display hardware may even scanout the image while
1886        * the GPU is rendering to it.  Aux surfaces cause difficulty with
1887        * concurrent access, so permanently disable aux for this miptree.
1888        *
1889        * Perhaps we could improve overall application performance by
1890        * re-enabling the aux surface when EGL_RENDER_BUFFER transitions to
1891        * EGL_BACK_BUFFER, then disabling it again when EGL_RENDER_BUFFER
1892        * returns to EGL_SINGLE_BUFFER. I expect the wins and losses with this
1893        * approach to be highly dependent on the application's GL usage.
1894        *
1895        * I [chadv] expect clever disabling/reenabling to be counterproductive
1896        * in the use cases I care about: applications that render nearly
1897        * realtime handwriting to the surface while possibly undergiong
1898        * simultaneously scanout as a display plane. The app requires low
1899        * render latency. Even though the app spends most of its time in
1900        * shared-buffer mode, it also frequently transitions between
1901        * shared-buffer (EGL_SINGLE_BUFFER) and double-buffer (EGL_BACK_BUFFER)
1902        * mode.  Visual sutter during the transitions should be avoided.
1903        *
1904        * In this case, I [chadv] believe reducing the GPU workload at
1905        * shared-buffer/double-buffer transitions would offer a smoother app
1906        * experience than any savings due to aux compression. But I've
1907        * collected no data to prove my theory.
1908        */
1909       brw_miptree_make_shareable(intel, mt);
1910    }
1911 }
1912 
1913 static void
brw_update_image_buffers(struct brw_context * brw,__DRIdrawable * drawable)1914 brw_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable)
1915 {
1916    struct gl_framebuffer *fb = drawable->driverPrivate;
1917    __DRIscreen *dri_screen = brw->screen->driScrnPriv;
1918    struct brw_renderbuffer *front_rb;
1919    struct brw_renderbuffer *back_rb;
1920    struct __DRIimageList images;
1921    mesa_format format;
1922    uint32_t buffer_mask = 0;
1923    int ret;
1924 
1925    front_rb = brw_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1926    back_rb = brw_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1927 
1928    if (back_rb)
1929       format = brw_rb_format(back_rb);
1930    else if (front_rb)
1931       format = brw_rb_format(front_rb);
1932    else
1933       return;
1934 
1935    if (front_rb && (_mesa_is_front_buffer_drawing(fb) ||
1936                     _mesa_is_front_buffer_reading(fb) || !back_rb)) {
1937       buffer_mask |= __DRI_IMAGE_BUFFER_FRONT;
1938    }
1939 
1940    if (back_rb)
1941       buffer_mask |= __DRI_IMAGE_BUFFER_BACK;
1942 
1943    ret = dri_screen->image.loader->getBuffers(drawable,
1944                                               driGLFormatToImageFormat(format),
1945                                               &drawable->dri2.stamp,
1946                                               drawable->loaderPrivate,
1947                                               buffer_mask,
1948                                               &images);
1949    if (!ret)
1950       return;
1951 
1952    if (images.image_mask & __DRI_IMAGE_BUFFER_FRONT) {
1953       drawable->w = images.front->width;
1954       drawable->h = images.front->height;
1955       brw_update_image_buffer(brw, drawable, front_rb, images.front,
1956                               __DRI_IMAGE_BUFFER_FRONT);
1957    }
1958 
1959    if (images.image_mask & __DRI_IMAGE_BUFFER_BACK) {
1960       drawable->w = images.back->width;
1961       drawable->h = images.back->height;
1962       brw_update_image_buffer(brw, drawable, back_rb, images.back,
1963                               __DRI_IMAGE_BUFFER_BACK);
1964    }
1965 
1966    if (images.image_mask & __DRI_IMAGE_BUFFER_SHARED) {
1967       assert(images.image_mask == __DRI_IMAGE_BUFFER_SHARED);
1968       drawable->w = images.back->width;
1969       drawable->h = images.back->height;
1970       brw_update_image_buffer(brw, drawable, back_rb, images.back,
1971                               __DRI_IMAGE_BUFFER_SHARED);
1972       brw->is_shared_buffer_bound = true;
1973    } else {
1974       brw->is_shared_buffer_bound = false;
1975       brw->is_shared_buffer_dirty = false;
1976    }
1977 }
1978