aboutsummaryrefslogtreecommitdiffstats
path: root/src/mesa/drivers/dri/i965/brw_wm_surface_state.c
blob: 91712c738c5b33bec6cdbe949747ea53af100337 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
/*
 Copyright (C) Intel Corp.  2006.  All Rights Reserved.
 Intel funded Tungsten Graphics to
 develop this 3D driver.

 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice (including the
 next paragraph) shall be included in all copies or substantial
 portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 **********************************************************************/
 /*
  * Authors:
  *   Keith Whitwell <keithw@vmware.com>
  */


#include "main/context.h"
#include "main/blend.h"
#include "main/mtypes.h"
#include "main/samplerobj.h"
#include "main/shaderimage.h"
#include "main/teximage.h"
#include "program/prog_parameter.h"
#include "program/prog_instruction.h"
#include "main/framebuffer.h"
#include "main/shaderapi.h"

#include "isl/isl.h"

#include "intel_mipmap_tree.h"
#include "intel_batchbuffer.h"
#include "intel_tex.h"
#include "intel_fbo.h"
#include "intel_buffer_objects.h"

#include "brw_context.h"
#include "brw_state.h"
#include "brw_defines.h"
#include "brw_wm.h"

enum {
   INTEL_RENDERBUFFER_LAYERED = 1 << 0,
   INTEL_AUX_BUFFER_DISABLED = 1 << 1,
};

struct surface_state_info {
   unsigned num_dwords;
   unsigned ss_align; /* Required alignment of RENDER_SURFACE_STATE in bytes */
   unsigned reloc_dw;
   unsigned aux_reloc_dw;
   unsigned tex_mocs;
   unsigned rb_mocs;
};

static const struct surface_state_info surface_state_infos[] = {
   [4] = {6,  32, 1,  0},
   [5] = {6,  32, 1,  0},
   [6] = {6,  32, 1,  0},
   [7] = {8,  32, 1,  6,  GEN7_MOCS_L3, GEN7_MOCS_L3},
   [8] = {13, 64, 8,  10, BDW_MOCS_WB,  BDW_MOCS_PTE},
   [9] = {16, 64, 8,  10, SKL_MOCS_WB,  SKL_MOCS_PTE},
};

static void
brw_emit_surface_state(struct brw_context *brw,
                       struct intel_mipmap_tree *mt, uint32_t flags,
                       GLenum target, struct isl_view view,
                       uint32_t mocs, uint32_t *surf_offset, int surf_index,
                       unsigned read_domains, unsigned write_domains)
{
   const struct surface_state_info ss_info = surface_state_infos[brw->gen];
   uint32_t tile_x = 0, tile_y = 0;
   uint32_t offset = mt->offset;

   struct isl_surf surf;
   intel_miptree_get_isl_surf(brw, mt, &surf);

   surf.dim = get_isl_surf_dim(target);

   const enum isl_dim_layout dim_layout =
      get_isl_dim_layout(&brw->screen->devinfo, mt->tiling, target);

   if (surf.dim_layout != dim_layout) {
      /* The layout of the specified texture target is not compatible with the
       * actual layout of the miptree structure in memory -- You're entering
       * dangerous territory, this can only possibly work if you only intended
       * to access a single level and slice of the texture, and the hardware
       * supports the tile offset feature in order to allow non-tile-aligned
       * base offsets, since we'll have to point the hardware to the first
       * texel of the level instead of relying on the usual base level/layer
       * controls.
       */
      assert(brw->has_surface_tile_offset);
      assert(view.levels == 1 && view.array_len == 1);

      offset += intel_miptree_get_tile_offsets(mt, view.base_level,
                                               view.base_array_layer,
                                               &tile_x, &tile_y);

      /* Minify the logical dimensions of the texture. */
      const unsigned l = view.base_level - mt->first_level;
      surf.logical_level0_px.width = minify(surf.logical_level0_px.width, l);
      surf.logical_level0_px.height = surf.dim <= ISL_SURF_DIM_1D ? 1 :
         minify(surf.logical_level0_px.height, l);
      surf.logical_level0_px.depth = surf.dim <= ISL_SURF_DIM_2D ? 1 :
         minify(surf.logical_level0_px.depth, l);

      /* Only the base level and layer can be addressed with the overridden
       * layout.
       */
      surf.logical_level0_px.array_len = 1;
      surf.levels = 1;
      surf.dim_layout = dim_layout;

      /* The requested slice of the texture is now at the base level and
       * layer.
       */
      view.base_level = 0;
      view.base_array_layer = 0;
   }

   union isl_color_value clear_color = { .u32 = { 0, 0, 0, 0 } };

   struct isl_surf *aux_surf = NULL, aux_surf_s;
   uint64_t aux_offset = 0;
   enum isl_aux_usage aux_usage = ISL_AUX_USAGE_NONE;
   if (mt->mcs_mt && !(flags & INTEL_AUX_BUFFER_DISABLED)) {
      intel_miptree_get_aux_isl_surf(brw, mt, &aux_surf_s, &aux_usage);
      aux_surf = &aux_surf_s;
      assert(mt->mcs_mt->offset == 0);
      aux_offset = mt->mcs_mt->bo->offset64;

      /* We only really need a clear color if we also have an auxiliary
       * surfacae.  Without one, it does nothing.
       */
      clear_color = intel_miptree_get_isl_clear_color(brw, mt);
   }

   uint32_t *dw = __brw_state_batch(brw, AUB_TRACE_SURFACE_STATE,
                                    ss_info.num_dwords * 4, ss_info.ss_align,
                                    surf_index, surf_offset);

   isl_surf_fill_state(&brw->isl_dev, dw, .surf = &surf, .view = &view,
                       .address = mt->bo->offset64 + offset,
                       .aux_surf = aux_surf, .aux_usage = aux_usage,
                       .aux_address = aux_offset,
                       .mocs = mocs, .clear_color = clear_color,
                       .x_offset_sa = tile_x, .y_offset_sa = tile_y);

   drm_intel_bo_emit_reloc(brw->batch.bo,
                           *surf_offset + 4 * ss_info.reloc_dw,
                           mt->bo, offset,
                           read_domains, write_domains);

   if (aux_surf) {
      /* On gen7 and prior, the upper 20 bits of surface state DWORD 6 are the
       * upper 20 bits of the GPU address of the MCS buffer; the lower 12 bits
       * contain other control information.  Since buffer addresses are always
       * on 4k boundaries (and thus have their lower 12 bits zero), we can use
       * an ordinary reloc to do the necessary address translation.
       */
      assert((aux_offset & 0xfff) == 0);
      drm_intel_bo_emit_reloc(brw->batch.bo,
                              *surf_offset + 4 * ss_info.aux_reloc_dw,
                              mt->mcs_mt->bo, dw[ss_info.aux_reloc_dw] & 0xfff,
                              read_domains, write_domains);
   }
}

uint32_t
brw_update_renderbuffer_surface(struct brw_context *brw,
                                struct gl_renderbuffer *rb,
                                uint32_t flags, unsigned unit /* unused */,
                                uint32_t surf_index)
{
   struct gl_context *ctx = &brw->ctx;
   struct intel_renderbuffer *irb = intel_renderbuffer(rb);
   struct intel_mipmap_tree *mt = irb->mt;

   if (brw->gen < 9) {
      assert(!(flags & INTEL_AUX_BUFFER_DISABLED));
   }

   assert(brw_render_target_supported(brw, rb));
   intel_miptree_used_for_rendering(mt);

   mesa_format rb_format = _mesa_get_render_format(ctx, intel_rb_format(irb));
   if (unlikely(!brw->format_supported_as_render_target[rb_format])) {
      _mesa_problem(ctx, "%s: renderbuffer format %s unsupported\n",
                    __func__, _mesa_get_format_name(rb_format));
   }

   const unsigned layer_multiplier =
      (irb->mt->msaa_layout == INTEL_MSAA_LAYOUT_UMS ||
       irb->mt->msaa_layout == INTEL_MSAA_LAYOUT_CMS) ?
      MAX2(irb->mt->num_samples, 1) : 1;

   struct isl_view view = {
      .format = brw->render_target_format[rb_format],
      .base_level = irb->mt_level - irb->mt->first_level,
      .levels = 1,
      .base_array_layer = irb->mt_layer / layer_multiplier,
      .array_len = MAX2(irb->layer_count, 1),
      .swizzle = ISL_SWIZZLE_IDENTITY,
      .usage = ISL_SURF_USAGE_RENDER_TARGET_BIT,
   };

   uint32_t offset;
   brw_emit_surface_state(brw, mt, flags, mt->target, view,
                          surface_state_infos[brw->gen].rb_mocs,
                          &offset, surf_index,
                          I915_GEM_DOMAIN_RENDER,
                          I915_GEM_DOMAIN_RENDER);
   return offset;
}

GLuint
translate_tex_target(GLenum target)
{
   switch (target) {
   case GL_TEXTURE_1D:
   case GL_TEXTURE_1D_ARRAY_EXT:
      return BRW_SURFACE_1D;

   case GL_TEXTURE_RECTANGLE_NV:
      return BRW_SURFACE_2D;

   case GL_TEXTURE_2D:
   case GL_TEXTURE_2D_ARRAY_EXT:
   case GL_TEXTURE_EXTERNAL_OES:
   case GL_TEXTURE_2D_MULTISAMPLE:
   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
      return BRW_SURFACE_2D;

   case GL_TEXTURE_3D:
      return BRW_SURFACE_3D;

   case GL_TEXTURE_CUBE_MAP:
   case GL_TEXTURE_CUBE_MAP_ARRAY:
      return BRW_SURFACE_CUBE;

   default:
      unreachable("not reached");
   }
}

uint32_t
brw_get_surface_tiling_bits(uint32_t tiling)
{
   switch (tiling) {
   case I915_TILING_X:
      return BRW_SURFACE_TILED;
   case I915_TILING_Y:
      return BRW_SURFACE_TILED | BRW_SURFACE_TILED_Y;
   default:
      return 0;
   }
}


uint32_t
brw_get_surface_num_multisamples(unsigned num_samples)
{
   if (num_samples > 1)
      return BRW_SURFACE_MULTISAMPLECOUNT_4;
   else
      return BRW_SURFACE_MULTISAMPLECOUNT_1;
}

/**
 * Compute the combination of DEPTH_TEXTURE_MODE and EXT_texture_swizzle
 * swizzling.
 */
int
brw_get_texture_swizzle(const struct gl_context *ctx,
                        const struct gl_texture_object *t)
{
   const struct gl_texture_image *img = t->Image[0][t->BaseLevel];

   int swizzles[SWIZZLE_NIL + 1] = {
      SWIZZLE_X,
      SWIZZLE_Y,
      SWIZZLE_Z,
      SWIZZLE_W,
      SWIZZLE_ZERO,
      SWIZZLE_ONE,
      SWIZZLE_NIL
   };

   if (img->_BaseFormat == GL_DEPTH_COMPONENT ||
       img->_BaseFormat == GL_DEPTH_STENCIL) {
      GLenum depth_mode = t->DepthMode;

      /* In ES 3.0, DEPTH_TEXTURE_MODE is expected to be GL_RED for textures
       * with depth component data specified with a sized internal format.
       * Otherwise, it's left at the old default, GL_LUMINANCE.
       */
      if (_mesa_is_gles3(ctx) &&
          img->InternalFormat != GL_DEPTH_COMPONENT &&
          img->InternalFormat != GL_DEPTH_STENCIL) {
         depth_mode = GL_RED;
      }

      switch (depth_mode) {
      case GL_ALPHA:
         swizzles[0] = SWIZZLE_ZERO;
         swizzles[1] = SWIZZLE_ZERO;
         swizzles[2] = SWIZZLE_ZERO;
         swizzles[3] = SWIZZLE_X;
         break;
      case GL_LUMINANCE:
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_X;
         swizzles[2] = SWIZZLE_X;
         swizzles[3] = SWIZZLE_ONE;
         break;
      case GL_INTENSITY:
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_X;
         swizzles[2] = SWIZZLE_X;
         swizzles[3] = SWIZZLE_X;
         break;
      case GL_RED:
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_ZERO;
         swizzles[2] = SWIZZLE_ZERO;
         swizzles[3] = SWIZZLE_ONE;
         break;
      }
   }

   GLenum datatype = _mesa_get_format_datatype(img->TexFormat);

   /* If the texture's format is alpha-only, force R, G, and B to
    * 0.0. Similarly, if the texture's format has no alpha channel,
    * force the alpha value read to 1.0. This allows for the
    * implementation to use an RGBA texture for any of these formats
    * without leaking any unexpected values.
    */
   switch (img->_BaseFormat) {
   case GL_ALPHA:
      swizzles[0] = SWIZZLE_ZERO;
      swizzles[1] = SWIZZLE_ZERO;
      swizzles[2] = SWIZZLE_ZERO;
      break;
   case GL_LUMINANCE:
      if (t->_IsIntegerFormat || datatype == GL_SIGNED_NORMALIZED) {
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_X;
         swizzles[2] = SWIZZLE_X;
         swizzles[3] = SWIZZLE_ONE;
      }
      break;
   case GL_LUMINANCE_ALPHA:
      if (datatype == GL_SIGNED_NORMALIZED) {
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_X;
         swizzles[2] = SWIZZLE_X;
         swizzles[3] = SWIZZLE_W;
      }
      break;
   case GL_INTENSITY:
      if (datatype == GL_SIGNED_NORMALIZED) {
         swizzles[0] = SWIZZLE_X;
         swizzles[1] = SWIZZLE_X;
         swizzles[2] = SWIZZLE_X;
         swizzles[3] = SWIZZLE_X;
      }
      break;
   case GL_RED:
   case GL_RG:
   case GL_RGB:
      if (_mesa_get_format_bits(img->TexFormat, GL_ALPHA_BITS) > 0)
         swizzles[3] = SWIZZLE_ONE;
      break;
   }

   return MAKE_SWIZZLE4(swizzles[GET_SWZ(t->_Swizzle, 0)],
                        swizzles[GET_SWZ(t->_Swizzle, 1)],
                        swizzles[GET_SWZ(t->_Swizzle, 2)],
                        swizzles[GET_SWZ(t->_Swizzle, 3)]);
}

/**
 * Convert an swizzle enumeration (i.e. SWIZZLE_X) to one of the Gen7.5+
 * "Shader Channel Select" enumerations (i.e. HSW_SCS_RED).  The mappings are
 *
 * SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W, SWIZZLE_ZERO, SWIZZLE_ONE
 *         0          1          2          3             4            5
 *         4          5          6          7             0            1
 *   SCS_RED, SCS_GREEN,  SCS_BLUE, SCS_ALPHA,     SCS_ZERO,     SCS_ONE
 *
 * which is simply adding 4 then modding by 8 (or anding with 7).
 *
 * We then may need to apply workarounds for textureGather hardware bugs.
 */
static unsigned
swizzle_to_scs(GLenum swizzle, bool need_green_to_blue)
{
   unsigned scs = (swizzle + 4) & 7;

   return (need_green_to_blue && scs == HSW_SCS_GREEN) ? HSW_SCS_BLUE : scs;
}

static unsigned
brw_find_matching_rb(const struct gl_framebuffer *fb,
                     const struct intel_mipmap_tree *mt)
{
   for (unsigned i = 0; i < fb->_NumColorDrawBuffers; i++) {
      const struct intel_renderbuffer *irb =
         intel_renderbuffer(fb->_ColorDrawBuffers[i]);

      if (irb && irb->mt == mt)
         return i;
   }

   return fb->_NumColorDrawBuffers;
}

static inline bool
brw_texture_view_sane(const struct brw_context *brw,
                      const struct intel_mipmap_tree *mt, unsigned format)
{
   /* There are special cases only for lossless compression. */
   if (!intel_miptree_is_lossless_compressed(brw, mt))
      return true;

   if (isl_format_supports_lossless_compression(&brw->screen->devinfo,
                                                format))
      return true;

   /* Logic elsewhere needs to take care to resolve the color buffer prior
    * to sampling it as non-compressed.
    */
   if (mt->fast_clear_state != INTEL_FAST_CLEAR_STATE_RESOLVED)
      return false;

   const struct gl_framebuffer *fb = brw->ctx.DrawBuffer;
   const unsigned rb_index = brw_find_matching_rb(fb, mt);

   if (rb_index == fb->_NumColorDrawBuffers)
      return true;

   /* Underlying surface is compressed but it is sampled using a format that
    * the sampling engine doesn't support as compressed. Compression must be
    * disabled for both sampling engine and data port in case the same surface
    * is used also as render target.
    */
   return brw->draw_aux_buffer_disabled[rb_index];
}

static bool
brw_disable_aux_surface(const struct brw_context *brw,
                        const struct intel_mipmap_tree *mt)
{
   /* Nothing to disable. */
   if (!mt->mcs_mt)
      return false;

   /* There are special cases only for lossless compression. */
   if (!intel_miptree_is_lossless_compressed(brw, mt))
      return mt->fast_clear_state == INTEL_FAST_CLEAR_STATE_RESOLVED;

   const struct gl_framebuffer *fb = brw->ctx.DrawBuffer;
   const unsigned rb_index = brw_find_matching_rb(fb, mt);

   /* If we are drawing into this with compression enabled, then we must also
    * enable compression when texturing from it regardless of
    * fast_clear_state.  If we don't then, after the first draw call with
    * this setup, there will be data in the CCS which won't get picked up by
    * subsequent texturing operations as required by ARB_texture_barrier.
    * Since we don't want to re-emit the binding table or do a resolve
    * operation every draw call, the easiest thing to do is just enable
    * compression on the texturing side.  This is completely safe to do
    * since, if compressed texturing weren't allowed, we would have disabled
    * compression of render targets in whatever_that_function_is_called().
    */
   if (rb_index < fb->_NumColorDrawBuffers) {
      if (brw->draw_aux_buffer_disabled[rb_index]) {
         assert(mt->fast_clear_state == INTEL_FAST_CLEAR_STATE_RESOLVED);
      }

      return brw->draw_aux_buffer_disabled[rb_index];
   }

   return mt->fast_clear_state == INTEL_FAST_CLEAR_STATE_RESOLVED;
}

void
brw_update_texture_surface(struct gl_context *ctx,
                           unsigned unit,
                           uint32_t *surf_offset,
                           bool for_gather,
                           uint32_t plane)
{
   struct brw_context *brw = brw_context(ctx);
   struct gl_texture_object *obj = ctx->Texture.Unit[unit]._Current;

   if (obj->Target == GL_TEXTURE_BUFFER) {
      brw_update_buffer_texture_surface(ctx, unit, surf_offset);

   } else {
      struct intel_texture_object *intel_obj = intel_texture_object(obj);
      struct intel_mipmap_tree *mt = intel_obj->mt;

      if (plane > 0) {
         if (mt->plane[plane - 1] == NULL)
            return;
         mt = mt->plane[plane - 1];
      }

      struct gl_sampler_object *sampler = _mesa_get_samplerobj(ctx, unit);
      /* If this is a view with restricted NumLayers, then our effective depth
       * is not just the miptree depth.
       */
      const unsigned view_num_layers =
         (obj->Immutable && obj->Target != GL_TEXTURE_3D) ? obj->NumLayers :
                                                            mt->logical_depth0;

      /* Handling GL_ALPHA as a surface format override breaks 1.30+ style
       * texturing functions that return a float, as our code generation always
       * selects the .x channel (which would always be 0).
       */
      struct gl_texture_image *firstImage = obj->Image[0][obj->BaseLevel];
      const bool alpha_depth = obj->DepthMode == GL_ALPHA &&
         (firstImage->_BaseFormat == GL_DEPTH_COMPONENT ||
          firstImage->_BaseFormat == GL_DEPTH_STENCIL);
      const unsigned swizzle = (unlikely(alpha_depth) ? SWIZZLE_XYZW :
                                brw_get_texture_swizzle(&brw->ctx, obj));

      mesa_format mesa_fmt = plane == 0 ? intel_obj->_Format : mt->format;
      unsigned format = translate_tex_format(brw, mesa_fmt,
                                             sampler->sRGBDecode);

      /* Implement gen6 and gen7 gather work-around */
      bool need_green_to_blue = false;
      if (for_gather) {
         if (brw->gen == 7 && format == BRW_SURFACEFORMAT_R32G32_FLOAT) {
            format = BRW_SURFACEFORMAT_R32G32_FLOAT_LD;
            need_green_to_blue = brw->is_haswell;
         } else if (brw->gen == 6) {
            /* Sandybridge's gather4 message is broken for integer formats.
             * To work around this, we pretend the surface is UNORM for
             * 8 or 16-bit formats, and emit shader instructions to recover
             * the real INT/UINT value.  For 32-bit formats, we pretend
             * the surface is FLOAT, and simply reinterpret the resulting
             * bits.
             */
            switch (format) {
            case BRW_SURFACEFORMAT_R8_SINT:
            case BRW_SURFACEFORMAT_R8_UINT:
               format = BRW_SURFACEFORMAT_R8_UNORM;
               break;

            case BRW_SURFACEFORMAT_R16_SINT:
            case BRW_SURFACEFORMAT_R16_UINT:
               format = BRW_SURFACEFORMAT_R16_UNORM;
               break;

            case BRW_SURFACEFORMAT_R32_SINT:
            case BRW_SURFACEFORMAT_R32_UINT:
               format = BRW_SURFACEFORMAT_R32_FLOAT;
               break;

            default:
               break;
            }
         }
      }

      if (obj->StencilSampling && firstImage->_BaseFormat == GL_DEPTH_STENCIL) {
         if (brw->gen <= 7) {
            assert(mt->r8stencil_mt && !mt->stencil_mt->r8stencil_needs_update);
            mt = mt->r8stencil_mt;
         } else {
            mt = mt->stencil_mt;
         }
         format = BRW_SURFACEFORMAT_R8_UINT;
      } else if (brw->gen <= 7 && mt->format == MESA_FORMAT_S_UINT8) {
         assert(mt->r8stencil_mt && !mt->r8stencil_needs_update);
         mt = mt->r8stencil_mt;
         format = BRW_SURFACEFORMAT_R8_UINT;
      }

      const int surf_index = surf_offset - &brw->wm.base.surf_offset[0];

      struct isl_view view = {
         .format = format,
         .base_level = obj->MinLevel + obj->BaseLevel,
         .levels = intel_obj->_MaxLevel - obj->BaseLevel + 1,
         .base_array_layer = obj->MinLayer,
         .array_len = view_num_layers,
         .swizzle = {
            .r = swizzle_to_scs(GET_SWZ(swizzle, 0), need_green_to_blue),
            .g = swizzle_to_scs(GET_SWZ(swizzle, 1), need_green_to_blue),
            .b = swizzle_to_scs(GET_SWZ(swizzle, 2), need_green_to_blue),
            .a = swizzle_to_scs(GET_SWZ(swizzle, 3), need_green_to_blue),
         },
         .usage = ISL_SURF_USAGE_TEXTURE_BIT,
      };

      if (obj->Target == GL_TEXTURE_CUBE_MAP ||
          obj->Target == GL_TEXTURE_CUBE_MAP_ARRAY)
         view.usage |= ISL_SURF_USAGE_CUBE_BIT;

      assert(brw_texture_view_sane(brw, mt, format));

      const int flags =
         brw_disable_aux_surface(brw, mt) ? INTEL_AUX_BUFFER_DISABLED : 0;
      brw_emit_surface_state(brw, mt, flags, mt->target, view,
                             surface_state_infos[brw->gen].tex_mocs,
                             surf_offset, surf_index,
                             I915_GEM_DOMAIN_SAMPLER, 0);
   }
}

void
brw_emit_buffer_surface_state(struct brw_context *brw,
                              uint32_t *out_offset,
                              drm_intel_bo *bo,
                              unsigned buffer_offset,
                              unsigned surface_format,
                              unsigned buffer_size,
                              unsigned pitch,
                              bool rw)
{
   const struct surface_state_info ss_info = surface_state_infos[brw->gen];

   uint32_t *dw = brw_state_batch(brw, AUB_TRACE_SURFACE_STATE,
                                  ss_info.num_dwords * 4, ss_info.ss_align,
                                  out_offset);

   isl_buffer_fill_state(&brw->isl_dev, dw,
                         .address = (bo ? bo->offset64 : 0) + buffer_offset,
                         .size = buffer_size,
                         .format = surface_format,
                         .stride = pitch,
                         .mocs = ss_info.tex_mocs);

   if (bo) {
      drm_intel_bo_emit_reloc(brw->batch.bo,
                              *out_offset + 4 * ss_info.reloc_dw,
                              bo, buffer_offset,
                              I915_GEM_DOMAIN_SAMPLER,
                              (rw ? I915_GEM_DOMAIN_SAMPLER : 0));
   }
}

void
brw_update_buffer_texture_surface(struct gl_context *ctx,
                                  unsigned unit,
                                  uint32_t *surf_offset)
{
   struct brw_context *brw = brw_context(ctx);
   struct gl_texture_object *tObj = ctx->Texture.Unit[unit]._Current;
   struct intel_buffer_object *intel_obj =
      intel_buffer_object(tObj->BufferObject);
   uint32_t size = tObj->BufferSize;
   drm_intel_bo *bo = NULL;
   mesa_format format = tObj->_BufferObjectFormat;
   uint32_t brw_format = brw_format_for_mesa_format(format);
   int texel_size = _mesa_get_format_bytes(format);

   if (intel_obj) {
      size = MIN2(size, intel_obj->Base.Size);
      bo = intel_bufferobj_buffer(brw, intel_obj, tObj->BufferOffset, size);
   }

   if (brw_format == 0 && format != MESA_FORMAT_RGBA_FLOAT32) {
      _mesa_problem(NULL, "bad format %s for texture buffer\n",
		    _mesa_get_format_name(format));
   }

   brw_emit_buffer_surface_state(brw, surf_offset, bo,
                                 tObj->BufferOffset,
                                 brw_format,
                                 size,
                                 texel_size,
                                 false /* rw */);
}

/**
 * Create the constant buffer surface.  Vertex/fragment shader constants will be
 * read from this buffer with Data Port Read instructions/messages.
 */
void
brw_create_constant_surface(struct brw_context *brw,
			    drm_intel_bo *bo,
			    uint32_t offset,
			    uint32_t size,
			    uint32_t *out_offset)
{
   brw_emit_buffer_surface_state(brw, out_offset, bo, offset,
                                 BRW_SURFACEFORMAT_R32G32B32A32_FLOAT,
                                 size, 1, false);
}

/**
 * Create the buffer surface. Shader buffer variables will be
 * read from / write to this buffer with Data Port Read/Write
 * instructions/messages.
 */
void
brw_create_buffer_surface(struct brw_context *brw,
                          drm_intel_bo *bo,
                          uint32_t offset,
                          uint32_t size,
                          uint32_t *out_offset)
{
   /* Use a raw surface so we can reuse existing untyped read/write/atomic
    * messages. We need these specifically for the fragment shader since they
    * include a pixel mask header that we need to ensure correct behavior
    * with helper invocations, which cannot write to the buffer.
    */
   brw_emit_buffer_surface_state(brw, out_offset, bo, offset,
                                 BRW_SURFACEFORMAT_RAW,
                                 size, 1, true);
}

/**
 * Set up a binding table entry for use by stream output logic (transform
 * feedback).
 *
 * buffer_size_minus_1 must be less than BRW_MAX_NUM_BUFFER_ENTRIES.
 */
void
brw_update_sol_surface(struct brw_context *brw,
                       struct gl_buffer_object *buffer_obj,
                       uint32_t *out_offset, unsigned num_vector_components,
                       unsigned stride_dwords, unsigned offset_dwords)
{
   struct intel_buffer_object *intel_bo = intel_buffer_object(buffer_obj);
   uint32_t offset_bytes = 4 * offset_dwords;
   drm_intel_bo *bo = intel_bufferobj_buffer(brw, intel_bo,
                                             offset_bytes,
                                             buffer_obj->Size - offset_bytes);
   uint32_t *surf = brw_state_batch(brw, AUB_TRACE_SURFACE_STATE, 6 * 4, 32,
                                    out_offset);
   uint32_t pitch_minus_1 = 4*stride_dwords - 1;
   size_t size_dwords = buffer_obj->Size / 4;
   uint32_t buffer_size_minus_1, width, height, depth, surface_format;

   /* FIXME: can we rely on core Mesa to ensure that the buffer isn't
    * too big to map using a single binding table entry?
    */
   assert((size_dwords - offset_dwords) / stride_dwords
          <= BRW_MAX_NUM_BUFFER_ENTRIES);

   if (size_dwords > offset_dwords + num_vector_components) {
      /* There is room for at least 1 transform feedback output in the buffer.
       * Compute the number of additional transform feedback outputs the
       * buffer has room for.
       */
      buffer_size_minus_1 =
         (size_dwords - offset_dwords - num_vector_components) / stride_dwords;
   } else {
      /* There isn't even room for a single transform feedback output in the
       * buffer.  We can't configure the binding table entry to prevent output
       * entirely; we'll have to rely on the geometry shader to detect
       * overflow.  But to minimize the damage in case of a bug, set up the
       * binding table entry to just allow a single output.
       */
      buffer_size_minus_1 = 0;
   }
   width = buffer_size_minus_1 & 0x7f;
   height = (buffer_size_minus_1 & 0xfff80) >> 7;
   depth = (buffer_size_minus_1 & 0x7f00000) >> 20;

   switch (num_vector_components) {
   case 1:
      surface_format = BRW_SURFACEFORMAT_R32_FLOAT;
      break;
   case 2:
      surface_format = BRW_SURFACEFORMAT_R32G32_FLOAT;
      break;
   case 3:
      surface_format = BRW_SURFACEFORMAT_R32G32B32_FLOAT;
      break;
   case 4:
      surface_format = BRW_SURFACEFORMAT_R32G32B32A32_FLOAT;
      break;
   default:
      unreachable("Invalid vector size for transform feedback output");
   }

   surf[0] = BRW_SURFACE_BUFFER << BRW_SURFACE_TYPE_SHIFT |
      BRW_SURFACE_MIPMAPLAYOUT_BELOW << BRW_SURFACE_MIPLAYOUT_SHIFT |
      surface_format << BRW_SURFACE_FORMAT_SHIFT |
      BRW_SURFACE_RC_READ_WRITE;
   surf[1] = bo->offset64 + offset_bytes; /* reloc */
   surf[2] = (width << BRW_SURFACE_WIDTH_SHIFT |
	      height << BRW_SURFACE_HEIGHT_SHIFT);
   surf[3] = (depth << BRW_SURFACE_DEPTH_SHIFT |
              pitch_minus_1 << BRW_SURFACE_PITCH_SHIFT);
   surf[4] = 0;
   surf[5] = 0;

   /* Emit relocation to surface contents. */
   drm_intel_bo_emit_reloc(brw->batch.bo,
			   *out_offset + 4,
			   bo, offset_bytes,
			   I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER);
}

/* Creates a new WM constant buffer reflecting the current fragment program's
 * constants, if needed by the fragment program.
 *
 * Otherwise, constants go through the CURBEs using the brw_constant_buffer
 * state atom.
 */
static void
brw_upload_wm_pull_constants(struct brw_context *brw)
{
   struct brw_stage_state *stage_state = &brw->wm.base;
   /* BRW_NEW_FRAGMENT_PROGRAM */
   struct brw_fragment_program *fp =
      (struct brw_fragment_program *) brw->fragment_program;
   /* BRW_NEW_FS_PROG_DATA */
   struct brw_stage_prog_data *prog_data = &brw->wm.prog_data->base;

   _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_FRAGMENT);
   /* _NEW_PROGRAM_CONSTANTS */
   brw_upload_pull_constants(brw, BRW_NEW_SURFACES, &fp->program.Base,
                             stage_state, prog_data);
}

const struct brw_tracked_state brw_wm_pull_constants = {
   .dirty = {
      .mesa = _NEW_PROGRAM_CONSTANTS,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_FRAGMENT_PROGRAM |
             BRW_NEW_FS_PROG_DATA,
   },
   .emit = brw_upload_wm_pull_constants,
};

/**
 * Creates a null renderbuffer surface.
 *
 * This is used when the shader doesn't write to any color output.  An FB
 * write to target 0 will still be emitted, because that's how the thread is
 * terminated (and computed depth is returned), so we need to have the
 * hardware discard the target 0 color output..
 */
static void
brw_emit_null_surface_state(struct brw_context *brw,
                            unsigned width,
                            unsigned height,
                            unsigned samples,
                            uint32_t *out_offset)
{
   /* From the Sandy bridge PRM, Vol4 Part1 p71 (Surface Type: Programming
    * Notes):
    *
    *     A null surface will be used in instances where an actual surface is
    *     not bound. When a write message is generated to a null surface, no
    *     actual surface is written to. When a read message (including any
    *     sampling engine message) is generated to a null surface, the result
    *     is all zeros. Note that a null surface type is allowed to be used
    *     with all messages, even if it is not specificially indicated as
    *     supported. All of the remaining fields in surface state are ignored
    *     for null surfaces, with the following exceptions:
    *
    *     - [DevSNB+]: Width, Height, Depth, and LOD fields must match the
    *       depth buffer’s corresponding state for all render target surfaces,
    *       including null.
    *
    *     - Surface Format must be R8G8B8A8_UNORM.
    */
   unsigned surface_type = BRW_SURFACE_NULL;
   drm_intel_bo *bo = NULL;
   unsigned pitch_minus_1 = 0;
   uint32_t multisampling_state = 0;
   uint32_t *surf = brw_state_batch(brw, AUB_TRACE_SURFACE_STATE, 6 * 4, 32,
                                    out_offset);

   if (samples > 1) {
      /* On Gen6, null render targets seem to cause GPU hangs when
       * multisampling.  So work around this problem by rendering into dummy
       * color buffer.
       *
       * To decrease the amount of memory needed by the workaround buffer, we
       * set its pitch to 128 bytes (the width of a Y tile).  This means that
       * the amount of memory needed for the workaround buffer is
       * (width_in_tiles + height_in_tiles - 1) tiles.
       *
       * Note that since the workaround buffer will be interpreted by the
       * hardware as an interleaved multisampled buffer, we need to compute
       * width_in_tiles and height_in_tiles by dividing the width and height
       * by 16 rather than the normal Y-tile size of 32.
       */
      unsigned width_in_tiles = ALIGN(width, 16) / 16;
      unsigned height_in_tiles = ALIGN(height, 16) / 16;
      unsigned size_needed = (width_in_tiles + height_in_tiles - 1) * 4096;
      brw_get_scratch_bo(brw, &brw->wm.multisampled_null_render_target_bo,
                         size_needed);
      bo = brw->wm.multisampled_null_render_target_bo;
      surface_type = BRW_SURFACE_2D;
      pitch_minus_1 = 127;
      multisampling_state = brw_get_surface_num_multisamples(samples);
   }

   surf[0] = (surface_type << BRW_SURFACE_TYPE_SHIFT |
	      BRW_SURFACEFORMAT_B8G8R8A8_UNORM << BRW_SURFACE_FORMAT_SHIFT);
   if (brw->gen < 6) {
      surf[0] |= (1 << BRW_SURFACE_WRITEDISABLE_R_SHIFT |
		  1 << BRW_SURFACE_WRITEDISABLE_G_SHIFT |
		  1 << BRW_SURFACE_WRITEDISABLE_B_SHIFT |
		  1 << BRW_SURFACE_WRITEDISABLE_A_SHIFT);
   }
   surf[1] = bo ? bo->offset64 : 0;
   surf[2] = ((width - 1) << BRW_SURFACE_WIDTH_SHIFT |
              (height - 1) << BRW_SURFACE_HEIGHT_SHIFT);

   /* From Sandy bridge PRM, Vol4 Part1 p82 (Tiled Surface: Programming
    * Notes):
    *
    *     If Surface Type is SURFTYPE_NULL, this field must be TRUE
    */
   surf[3] = (BRW_SURFACE_TILED | BRW_SURFACE_TILED_Y |
              pitch_minus_1 << BRW_SURFACE_PITCH_SHIFT);
   surf[4] = multisampling_state;
   surf[5] = 0;

   if (bo) {
      drm_intel_bo_emit_reloc(brw->batch.bo,
                              *out_offset + 4,
                              bo, 0,
                              I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER);
   }
}

/**
 * Sets up a surface state structure to point at the given region.
 * While it is only used for the front/back buffer currently, it should be
 * usable for further buffers when doing ARB_draw_buffer support.
 */
static uint32_t
gen4_update_renderbuffer_surface(struct brw_context *brw,
                                 struct gl_renderbuffer *rb,
                                 uint32_t flags, unsigned unit,
                                 uint32_t surf_index)
{
   struct gl_context *ctx = &brw->ctx;
   struct intel_renderbuffer *irb = intel_renderbuffer(rb);
   struct intel_mipmap_tree *mt = irb->mt;
   uint32_t *surf;
   uint32_t tile_x, tile_y;
   uint32_t format = 0;
   uint32_t offset;
   /* _NEW_BUFFERS */
   mesa_format rb_format = _mesa_get_render_format(ctx, intel_rb_format(irb));
   /* BRW_NEW_FS_PROG_DATA */

   assert(!(flags & INTEL_RENDERBUFFER_LAYERED));
   assert(!(flags & INTEL_AUX_BUFFER_DISABLED));

   if (rb->TexImage && !brw->has_surface_tile_offset) {
      intel_renderbuffer_get_tile_offsets(irb, &tile_x, &tile_y);

      if (tile_x != 0 || tile_y != 0) {
	 /* Original gen4 hardware couldn't draw to a non-tile-aligned
	  * destination in a miptree unless you actually setup your renderbuffer
	  * as a miptree and used the fragile lod/array_index/etc. controls to
	  * select the image.  So, instead, we just make a new single-level
	  * miptree and render into that.
	  */
	 intel_renderbuffer_move_to_temp(brw, irb, false);
	 mt = irb->mt;
      }
   }

   intel_miptree_used_for_rendering(irb->mt);

   surf = brw_state_batch(brw, AUB_TRACE_SURFACE_STATE, 6 * 4, 32, &offset);

   format = brw->render_target_format[rb_format];
   if (unlikely(!brw->format_supported_as_render_target[rb_format])) {
      _mesa_problem(ctx, "%s: renderbuffer format %s unsupported\n",
                    __func__, _mesa_get_format_name(rb_format));
   }

   surf[0] = (BRW_SURFACE_2D << BRW_SURFACE_TYPE_SHIFT |
	      format << BRW_SURFACE_FORMAT_SHIFT);

   /* reloc */
   assert(mt->offset % mt->cpp == 0);
   surf[1] = (intel_renderbuffer_get_tile_offsets(irb, &tile_x, &tile_y) +
	      mt->bo->offset64 + mt->offset);

   surf[2] = ((rb->Width - 1) << BRW_SURFACE_WIDTH_SHIFT |
	      (rb->Height - 1) << BRW_SURFACE_HEIGHT_SHIFT);

   surf[3] = (brw_get_surface_tiling_bits(mt->tiling) |
	      (mt->pitch - 1) << BRW_SURFACE_PITCH_SHIFT);

   surf[4] = brw_get_surface_num_multisamples(mt->num_samples);

   assert(brw->has_surface_tile_offset || (tile_x == 0 && tile_y == 0));
   /* Note that the low bits of these fields are missing, so
    * there's the possibility of getting in trouble.
    */
   assert(tile_x % 4 == 0);
   assert(tile_y % 2 == 0);
   surf[5] = ((tile_x / 4) << BRW_SURFACE_X_OFFSET_SHIFT |
	      (tile_y / 2) << BRW_SURFACE_Y_OFFSET_SHIFT |
	      (mt->valign == 4 ? BRW_SURFACE_VERTICAL_ALIGN_ENABLE : 0));

   if (brw->gen < 6) {
      /* _NEW_COLOR */
      if (!ctx->Color.ColorLogicOpEnabled && !ctx->Color._AdvancedBlendMode &&
          (ctx->Color.BlendEnabled & (1 << unit)))
	 surf[0] |= BRW_SURFACE_BLEND_ENABLED;

      if (!ctx->Color.ColorMask[unit][0])
	 surf[0] |= 1 << BRW_SURFACE_WRITEDISABLE_R_SHIFT;
      if (!ctx->Color.ColorMask[unit][1])
	 surf[0] |= 1 << BRW_SURFACE_WRITEDISABLE_G_SHIFT;
      if (!ctx->Color.ColorMask[unit][2])
	 surf[0] |= 1 << BRW_SURFACE_WRITEDISABLE_B_SHIFT;

      /* As mentioned above, disable writes to the alpha component when the
       * renderbuffer is XRGB.
       */
      if (ctx->DrawBuffer->Visual.alphaBits == 0 ||
	  !ctx->Color.ColorMask[unit][3]) {
	 surf[0] |= 1 << BRW_SURFACE_WRITEDISABLE_A_SHIFT;
      }
   }

   drm_intel_bo_emit_reloc(brw->batch.bo,
                           offset + 4,
                           mt->bo,
                           surf[1] - mt->bo->offset64,
                           I915_GEM_DOMAIN_RENDER,
                           I915_GEM_DOMAIN_RENDER);

   return offset;
}

/**
 * Construct SURFACE_STATE objects for renderbuffers/draw buffers.
 */
void
brw_update_renderbuffer_surfaces(struct brw_context *brw,
                                 const struct gl_framebuffer *fb,
                                 uint32_t render_target_start,
                                 uint32_t *surf_offset)
{
   GLuint i;
   const unsigned int w = _mesa_geometric_width(fb);
   const unsigned int h = _mesa_geometric_height(fb);
   const unsigned int s = _mesa_geometric_samples(fb);

   /* Update surfaces for drawing buffers */
   if (fb->_NumColorDrawBuffers >= 1) {
      for (i = 0; i < fb->_NumColorDrawBuffers; i++) {
         const uint32_t surf_index = render_target_start + i;
         const int flags = (_mesa_geometric_layers(fb) > 0 ?
                              INTEL_RENDERBUFFER_LAYERED : 0) |
                           (brw->draw_aux_buffer_disabled[i] ?
                              INTEL_AUX_BUFFER_DISABLED : 0);

	 if (intel_renderbuffer(fb->_ColorDrawBuffers[i])) {
            surf_offset[surf_index] =
               brw->vtbl.update_renderbuffer_surface(
                  brw, fb->_ColorDrawBuffers[i], flags, i, surf_index);
	 } else {
            brw->vtbl.emit_null_surface_state(brw, w, h, s,
               &surf_offset[surf_index]);
	 }
      }
   } else {
      const uint32_t surf_index = render_target_start;
      brw->vtbl.emit_null_surface_state(brw, w, h, s,
         &surf_offset[surf_index]);
   }
}

static void
update_renderbuffer_surfaces(struct brw_context *brw)
{
   const struct gl_context *ctx = &brw->ctx;

   /* _NEW_BUFFERS | _NEW_COLOR */
   const struct gl_framebuffer *fb = ctx->DrawBuffer;
   brw_update_renderbuffer_surfaces(
      brw, fb,
      brw->wm.prog_data->binding_table.render_target_start,
      brw->wm.base.surf_offset);
   brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
}

const struct brw_tracked_state brw_renderbuffer_surfaces = {
   .dirty = {
      .mesa = _NEW_BUFFERS |
              _NEW_COLOR,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_FS_PROG_DATA,
   },
   .emit = update_renderbuffer_surfaces,
};

const struct brw_tracked_state gen6_renderbuffer_surfaces = {
   .dirty = {
      .mesa = _NEW_BUFFERS,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP,
   },
   .emit = update_renderbuffer_surfaces,
};

static void
update_renderbuffer_read_surfaces(struct brw_context *brw)
{
   const struct gl_context *ctx = &brw->ctx;

   /* BRW_NEW_FRAGMENT_PROGRAM */
   if (!ctx->Extensions.MESA_shader_framebuffer_fetch &&
       brw->fragment_program &&
       brw->fragment_program->Base.OutputsRead) {
      /* _NEW_BUFFERS */
      const struct gl_framebuffer *fb = ctx->DrawBuffer;

      for (unsigned i = 0; i < fb->_NumColorDrawBuffers; i++) {
         struct gl_renderbuffer *rb = fb->_ColorDrawBuffers[i];
         const struct intel_renderbuffer *irb = intel_renderbuffer(rb);
         /* BRW_NEW_FS_PROG_DATA */
         const unsigned surf_index =
            brw->wm.prog_data->binding_table.render_target_read_start + i;
         uint32_t *surf_offset = &brw->wm.base.surf_offset[surf_index];

         if (irb) {
            const unsigned format = brw->render_target_format[
               _mesa_get_render_format(ctx, intel_rb_format(irb))];
            assert(isl_format_supports_sampling(&brw->screen->devinfo,
                                                format));

            /* Override the target of the texture if the render buffer is a
             * single slice of a 3D texture (since the minimum array element
             * field of the surface state structure is ignored by the sampler
             * unit for 3D textures on some hardware), or if the render buffer
             * is a 1D array (since shaders always provide the array index
             * coordinate at the Z component to avoid state-dependent
             * recompiles when changing the texture target of the
             * framebuffer).
             */
            const GLenum target =
               (irb->mt->target == GL_TEXTURE_3D &&
                irb->layer_count == 1) ? GL_TEXTURE_2D :
               irb->mt->target == GL_TEXTURE_1D_ARRAY ? GL_TEXTURE_2D_ARRAY :
               irb->mt->target;

            /* intel_renderbuffer::mt_layer is expressed in sample units for
             * the UMS and CMS multisample layouts, but
             * intel_renderbuffer::layer_count is expressed in units of whole
             * logical layers regardless of the multisample layout.
             */
            const unsigned mt_layer_unit =
               (irb->mt->msaa_layout == INTEL_MSAA_LAYOUT_UMS ||
                irb->mt->msaa_layout == INTEL_MSAA_LAYOUT_CMS) ?
               MAX2(irb->mt->num_samples, 1) : 1;

            const struct isl_view view = {
               .format = format,
               .base_level = irb->mt_level - irb->mt->first_level,
               .levels = 1,
               .base_array_layer = irb->mt_layer / mt_layer_unit,
               .array_len = irb->layer_count,
               .swizzle = ISL_SWIZZLE_IDENTITY,
               .usage = ISL_SURF_USAGE_TEXTURE_BIT,
            };

            const int flags = brw->draw_aux_buffer_disabled[i] ?
                                 INTEL_AUX_BUFFER_DISABLED : 0;
            brw_emit_surface_state(brw, irb->mt, flags, target, view,
                                   surface_state_infos[brw->gen].tex_mocs,
                                   surf_offset, surf_index,
                                   I915_GEM_DOMAIN_SAMPLER, 0);

         } else {
            brw->vtbl.emit_null_surface_state(
               brw, _mesa_geometric_width(fb), _mesa_geometric_height(fb),
               _mesa_geometric_samples(fb), surf_offset);
         }
      }

      brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
   }
}

const struct brw_tracked_state brw_renderbuffer_read_surfaces = {
   .dirty = {
      .mesa = _NEW_BUFFERS,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_FRAGMENT_PROGRAM |
             BRW_NEW_FS_PROG_DATA,
   },
   .emit = update_renderbuffer_read_surfaces,
};

static void
update_stage_texture_surfaces(struct brw_context *brw,
                              const struct gl_program *prog,
                              struct brw_stage_state *stage_state,
                              bool for_gather, uint32_t plane)
{
   if (!prog)
      return;

   struct gl_context *ctx = &brw->ctx;

   uint32_t *surf_offset = stage_state->surf_offset;

   /* BRW_NEW_*_PROG_DATA */
   if (for_gather)
      surf_offset += stage_state->prog_data->binding_table.gather_texture_start;
   else
      surf_offset += stage_state->prog_data->binding_table.plane_start[plane];

   unsigned num_samplers = util_last_bit(prog->SamplersUsed);
   for (unsigned s = 0; s < num_samplers; s++) {
      surf_offset[s] = 0;

      if (prog->SamplersUsed & (1 << s)) {
         const unsigned unit = prog->SamplerUnits[s];

         /* _NEW_TEXTURE */
         if (ctx->Texture.Unit[unit]._Current) {
            brw_update_texture_surface(ctx, unit, surf_offset + s, for_gather, plane);
         }
      }
   }
}


/**
 * Construct SURFACE_STATE objects for enabled textures.
 */
static void
brw_update_texture_surfaces(struct brw_context *brw)
{
   /* BRW_NEW_VERTEX_PROGRAM */
   struct gl_program *vs = (struct gl_program *) brw->vertex_program;

   /* BRW_NEW_TESS_PROGRAMS */
   struct gl_program *tcs = (struct gl_program *) brw->tess_ctrl_program;
   struct gl_program *tes = (struct gl_program *) brw->tess_eval_program;

   /* BRW_NEW_GEOMETRY_PROGRAM */
   struct gl_program *gs = (struct gl_program *) brw->geometry_program;

   /* BRW_NEW_FRAGMENT_PROGRAM */
   struct gl_program *fs = (struct gl_program *) brw->fragment_program;

   /* _NEW_TEXTURE */
   update_stage_texture_surfaces(brw, vs, &brw->vs.base, false, 0);
   update_stage_texture_surfaces(brw, tcs, &brw->tcs.base, false, 0);
   update_stage_texture_surfaces(brw, tes, &brw->tes.base, false, 0);
   update_stage_texture_surfaces(brw, gs, &brw->gs.base, false, 0);
   update_stage_texture_surfaces(brw, fs, &brw->wm.base, false, 0);

   /* emit alternate set of surface state for gather. this
    * allows the surface format to be overriden for only the
    * gather4 messages. */
   if (brw->gen < 8) {
      if (vs && vs->UsesGather)
         update_stage_texture_surfaces(brw, vs, &brw->vs.base, true, 0);
      if (tcs && tcs->UsesGather)
         update_stage_texture_surfaces(brw, tcs, &brw->tcs.base, true, 0);
      if (tes && tes->UsesGather)
         update_stage_texture_surfaces(brw, tes, &brw->tes.base, true, 0);
      if (gs && gs->UsesGather)
         update_stage_texture_surfaces(brw, gs, &brw->gs.base, true, 0);
      if (fs && fs->UsesGather)
         update_stage_texture_surfaces(brw, fs, &brw->wm.base, true, 0);
   }

   if (fs) {
      update_stage_texture_surfaces(brw, fs, &brw->wm.base, false, 1);
      update_stage_texture_surfaces(brw, fs, &brw->wm.base, false, 2);
   }

   brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
}

const struct brw_tracked_state brw_texture_surfaces = {
   .dirty = {
      .mesa = _NEW_TEXTURE,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_FRAGMENT_PROGRAM |
             BRW_NEW_FS_PROG_DATA |
             BRW_NEW_GEOMETRY_PROGRAM |
             BRW_NEW_GS_PROG_DATA |
             BRW_NEW_TESS_PROGRAMS |
             BRW_NEW_TCS_PROG_DATA |
             BRW_NEW_TES_PROG_DATA |
             BRW_NEW_TEXTURE_BUFFER |
             BRW_NEW_VERTEX_PROGRAM |
             BRW_NEW_VS_PROG_DATA,
   },
   .emit = brw_update_texture_surfaces,
};

static void
brw_update_cs_texture_surfaces(struct brw_context *brw)
{
   /* BRW_NEW_COMPUTE_PROGRAM */
   struct gl_program *cs = (struct gl_program *) brw->compute_program;

   /* _NEW_TEXTURE */
   update_stage_texture_surfaces(brw, cs, &brw->cs.base, false, 0);

   /* emit alternate set of surface state for gather. this
    * allows the surface format to be overriden for only the
    * gather4 messages.
    */
   if (brw->gen < 8) {
      if (cs && cs->UsesGather)
         update_stage_texture_surfaces(brw, cs, &brw->cs.base, true, 0);
   }

   brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
}

const struct brw_tracked_state brw_cs_texture_surfaces = {
   .dirty = {
      .mesa = _NEW_TEXTURE,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_COMPUTE_PROGRAM,
   },
   .emit = brw_update_cs_texture_surfaces,
};


void
brw_upload_ubo_surfaces(struct brw_context *brw,
			struct gl_linked_shader *shader,
                        struct brw_stage_state *stage_state,
                        struct brw_stage_prog_data *prog_data)
{
   struct gl_context *ctx = &brw->ctx;

   if (!shader)
      return;

   uint32_t *ubo_surf_offsets =
      &stage_state->surf_offset[prog_data->binding_table.ubo_start];

   for (int i = 0; i < shader->NumUniformBlocks; i++) {
      struct gl_uniform_buffer_binding *binding =
         &ctx->UniformBufferBindings[shader->UniformBlocks[i]->Binding];

      if (binding->BufferObject == ctx->Shared->NullBufferObj) {
         brw->vtbl.emit_null_surface_state(brw, 1, 1, 1, &ubo_surf_offsets[i]);
      } else {
         struct intel_buffer_object *intel_bo =
            intel_buffer_object(binding->BufferObject);
         GLsizeiptr size = binding->BufferObject->Size - binding->Offset;
         if (!binding->AutomaticSize)
            size = MIN2(size, binding->Size);
         drm_intel_bo *bo =
            intel_bufferobj_buffer(brw, intel_bo,
                                   binding->Offset,
                                   size);
         brw_create_constant_surface(brw, bo, binding->Offset,
                                     size,
                                     &ubo_surf_offsets[i]);
      }
   }

   uint32_t *ssbo_surf_offsets =
      &stage_state->surf_offset[prog_data->binding_table.ssbo_start];

   for (int i = 0; i < shader->NumShaderStorageBlocks; i++) {
      struct gl_shader_storage_buffer_binding *binding =
         &ctx->ShaderStorageBufferBindings[shader->ShaderStorageBlocks[i]->Binding];

      if (binding->BufferObject == ctx->Shared->NullBufferObj) {
         brw->vtbl.emit_null_surface_state(brw, 1, 1, 1, &ssbo_surf_offsets[i]);
      } else {
         struct intel_buffer_object *intel_bo =
            intel_buffer_object(binding->BufferObject);
         GLsizeiptr size = binding->BufferObject->Size - binding->Offset;
         if (!binding->AutomaticSize)
            size = MIN2(size, binding->Size);
         drm_intel_bo *bo =
            intel_bufferobj_buffer(brw, intel_bo,
                                   binding->Offset,
                                   size);
         brw_create_buffer_surface(brw, bo, binding->Offset,
                                   size,
                                   &ssbo_surf_offsets[i]);
      }
   }

   if (shader->NumUniformBlocks || shader->NumShaderStorageBlocks)
      brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
}

static void
brw_upload_wm_ubo_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog = ctx->_Shader->_CurrentFragmentProgram;

   if (!prog)
      return;

   /* BRW_NEW_FS_PROG_DATA */
   brw_upload_ubo_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
                           &brw->wm.base, &brw->wm.prog_data->base);
}

const struct brw_tracked_state brw_wm_ubo_surfaces = {
   .dirty = {
      .mesa = _NEW_PROGRAM,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_FS_PROG_DATA |
             BRW_NEW_UNIFORM_BUFFER,
   },
   .emit = brw_upload_wm_ubo_surfaces,
};

static void
brw_upload_cs_ubo_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog =
      ctx->_Shader->CurrentProgram[MESA_SHADER_COMPUTE];

   if (!prog)
      return;

   /* BRW_NEW_CS_PROG_DATA */
   brw_upload_ubo_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_COMPUTE],
                           &brw->cs.base, &brw->cs.prog_data->base);
}

const struct brw_tracked_state brw_cs_ubo_surfaces = {
   .dirty = {
      .mesa = _NEW_PROGRAM,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_CS_PROG_DATA |
             BRW_NEW_UNIFORM_BUFFER,
   },
   .emit = brw_upload_cs_ubo_surfaces,
};

void
brw_upload_abo_surfaces(struct brw_context *brw,
                        struct gl_linked_shader *shader,
                        struct brw_stage_state *stage_state,
                        struct brw_stage_prog_data *prog_data)
{
   struct gl_context *ctx = &brw->ctx;
   uint32_t *surf_offsets =
      &stage_state->surf_offset[prog_data->binding_table.abo_start];

   if (shader && shader->NumAtomicBuffers) {
      for (unsigned i = 0; i < shader->NumAtomicBuffers; i++) {
         struct gl_atomic_buffer_binding *binding =
            &ctx->AtomicBufferBindings[shader->AtomicBuffers[i]->Binding];
         struct intel_buffer_object *intel_bo =
            intel_buffer_object(binding->BufferObject);
         drm_intel_bo *bo = intel_bufferobj_buffer(
            brw, intel_bo, binding->Offset, intel_bo->Base.Size - binding->Offset);

         brw_emit_buffer_surface_state(brw, &surf_offsets[i], bo,
                                       binding->Offset, BRW_SURFACEFORMAT_RAW,
                                       bo->size - binding->Offset, 1, true);
      }

      brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
   }
}

static void
brw_upload_wm_abo_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog = ctx->_Shader->_CurrentFragmentProgram;

   if (prog) {
      /* BRW_NEW_FS_PROG_DATA */
      brw_upload_abo_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
                              &brw->wm.base, &brw->wm.prog_data->base);
   }
}

const struct brw_tracked_state brw_wm_abo_surfaces = {
   .dirty = {
      .mesa = _NEW_PROGRAM,
      .brw = BRW_NEW_ATOMIC_BUFFER |
             BRW_NEW_BLORP |
             BRW_NEW_BATCH |
             BRW_NEW_FS_PROG_DATA,
   },
   .emit = brw_upload_wm_abo_surfaces,
};

static void
brw_upload_cs_abo_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog =
      ctx->_Shader->CurrentProgram[MESA_SHADER_COMPUTE];

   if (prog) {
      /* BRW_NEW_CS_PROG_DATA */
      brw_upload_abo_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_COMPUTE],
                              &brw->cs.base, &brw->cs.prog_data->base);
   }
}

const struct brw_tracked_state brw_cs_abo_surfaces = {
   .dirty = {
      .mesa = _NEW_PROGRAM,
      .brw = BRW_NEW_ATOMIC_BUFFER |
             BRW_NEW_BLORP |
             BRW_NEW_BATCH |
             BRW_NEW_CS_PROG_DATA,
   },
   .emit = brw_upload_cs_abo_surfaces,
};

static void
brw_upload_cs_image_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog =
      ctx->_Shader->CurrentProgram[MESA_SHADER_COMPUTE];

   if (prog) {
      /* BRW_NEW_CS_PROG_DATA, BRW_NEW_IMAGE_UNITS, _NEW_TEXTURE */
      brw_upload_image_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_COMPUTE],
                                &brw->cs.base, &brw->cs.prog_data->base);
   }
}

const struct brw_tracked_state brw_cs_image_surfaces = {
   .dirty = {
      .mesa = _NEW_TEXTURE | _NEW_PROGRAM,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_CS_PROG_DATA |
             BRW_NEW_IMAGE_UNITS
   },
   .emit = brw_upload_cs_image_surfaces,
};

static uint32_t
get_image_format(struct brw_context *brw, mesa_format format, GLenum access)
{
   const struct gen_device_info *devinfo = &brw->screen->devinfo;
   uint32_t hw_format = brw_format_for_mesa_format(format);
   if (access == GL_WRITE_ONLY) {
      return hw_format;
   } else if (isl_has_matching_typed_storage_image_format(devinfo, hw_format)) {
      /* Typed surface reads support a very limited subset of the shader
       * image formats.  Translate it into the closest format the
       * hardware supports.
       */
      return isl_lower_storage_image_format(devinfo, hw_format);
   } else {
      /* The hardware doesn't actually support a typed format that we can use
       * so we have to fall back to untyped read/write messages.
       */
      return BRW_SURFACEFORMAT_RAW;
   }
}

static void
update_default_image_param(struct brw_context *brw,
                           struct gl_image_unit *u,
                           unsigned surface_idx,
                           struct brw_image_param *param)
{
   memset(param, 0, sizeof(*param));
   param->surface_idx = surface_idx;
   /* Set the swizzling shifts to all-ones to effectively disable swizzling --
    * See emit_address_calculation() in brw_fs_surface_builder.cpp for a more
    * detailed explanation of these parameters.
    */
   param->swizzling[0] = 0xff;
   param->swizzling[1] = 0xff;
}

static void
update_buffer_image_param(struct brw_context *brw,
                          struct gl_image_unit *u,
                          unsigned surface_idx,
                          struct brw_image_param *param)
{
   struct gl_buffer_object *obj = u->TexObj->BufferObject;
   const uint32_t size = MIN2((uint32_t)u->TexObj->BufferSize, obj->Size);
   update_default_image_param(brw, u, surface_idx, param);

   param->size[0] = size / _mesa_get_format_bytes(u->_ActualFormat);
   param->stride[0] = _mesa_get_format_bytes(u->_ActualFormat);
}

static void
update_texture_image_param(struct brw_context *brw,
                           struct gl_image_unit *u,
                           unsigned surface_idx,
                           struct brw_image_param *param)
{
   struct intel_mipmap_tree *mt = intel_texture_object(u->TexObj)->mt;

   update_default_image_param(brw, u, surface_idx, param);

   param->size[0] = minify(mt->logical_width0, u->Level);
   param->size[1] = minify(mt->logical_height0, u->Level);
   param->size[2] = (!u->Layered ? 1 :
                     u->TexObj->Target == GL_TEXTURE_CUBE_MAP ? 6 :
                     u->TexObj->Target == GL_TEXTURE_3D ?
                     minify(mt->logical_depth0, u->Level) :
                     mt->logical_depth0);

   intel_miptree_get_image_offset(mt, u->Level, u->_Layer,
                                  &param->offset[0],
                                  &param->offset[1]);

   param->stride[0] = mt->cpp;
   param->stride[1] = mt->pitch / mt->cpp;
   param->stride[2] =
      brw_miptree_get_horizontal_slice_pitch(brw, mt, u->Level);
   param->stride[3] =
      brw_miptree_get_vertical_slice_pitch(brw, mt, u->Level);

   if (mt->tiling == I915_TILING_X) {
      /* An X tile is a rectangular block of 512x8 bytes. */
      param->tiling[0] = _mesa_logbase2(512 / mt->cpp);
      param->tiling[1] = _mesa_logbase2(8);

      if (brw->has_swizzling) {
         /* Right shifts required to swizzle bits 9 and 10 of the memory
          * address with bit 6.
          */
         param->swizzling[0] = 3;
         param->swizzling[1] = 4;
      }
   } else if (mt->tiling == I915_TILING_Y) {
      /* The layout of a Y-tiled surface in memory isn't really fundamentally
       * different to the layout of an X-tiled surface, we simply pretend that
       * the surface is broken up in a number of smaller 16Bx32 tiles, each
       * one arranged in X-major order just like is the case for X-tiling.
       */
      param->tiling[0] = _mesa_logbase2(16 / mt->cpp);
      param->tiling[1] = _mesa_logbase2(32);

      if (brw->has_swizzling) {
         /* Right shift required to swizzle bit 9 of the memory address with
          * bit 6.
          */
         param->swizzling[0] = 3;
      }
   }

   /* 3D textures are arranged in 2D in memory with 2^lod slices per row.  The
    * address calculation algorithm (emit_address_calculation() in
    * brw_fs_surface_builder.cpp) handles this as a sort of tiling with
    * modulus equal to the LOD.
    */
   param->tiling[2] = (u->TexObj->Target == GL_TEXTURE_3D ? u->Level :
                       0);
}

static void
update_image_surface(struct brw_context *brw,
                     struct gl_image_unit *u,
                     GLenum access,
                     unsigned surface_idx,
                     uint32_t *surf_offset,
                     struct brw_image_param *param)
{
   if (_mesa_is_image_unit_valid(&brw->ctx, u)) {
      struct gl_texture_object *obj = u->TexObj;
      const unsigned format = get_image_format(brw, u->_ActualFormat, access);

      if (obj->Target == GL_TEXTURE_BUFFER) {
         struct intel_buffer_object *intel_obj =
            intel_buffer_object(obj->BufferObject);
         const unsigned texel_size = (format == BRW_SURFACEFORMAT_RAW ? 1 :
                                      _mesa_get_format_bytes(u->_ActualFormat));

         brw_emit_buffer_surface_state(
            brw, surf_offset, intel_obj->buffer, obj->BufferOffset,
            format, intel_obj->Base.Size, texel_size,
            access != GL_READ_ONLY);

         update_buffer_image_param(brw, u, surface_idx, param);

      } else {
         struct intel_texture_object *intel_obj = intel_texture_object(obj);
         struct intel_mipmap_tree *mt = intel_obj->mt;

         if (format == BRW_SURFACEFORMAT_RAW) {
            brw_emit_buffer_surface_state(
               brw, surf_offset, mt->bo, mt->offset,
               format, mt->bo->size - mt->offset, 1 /* pitch */,
               access != GL_READ_ONLY);

         } else {
            const unsigned num_layers = (!u->Layered ? 1 :
                                         obj->Target == GL_TEXTURE_CUBE_MAP ? 6 :
                                         mt->logical_depth0);

            struct isl_view view = {
               .format = format,
               .base_level = obj->MinLevel + u->Level,
               .levels = 1,
               .base_array_layer = obj->MinLayer + u->_Layer,
               .array_len = num_layers,
               .swizzle = ISL_SWIZZLE_IDENTITY,
               .usage = ISL_SURF_USAGE_STORAGE_BIT,
            };

            const int surf_index = surf_offset - &brw->wm.base.surf_offset[0];
            const int flags =
               mt->fast_clear_state == INTEL_FAST_CLEAR_STATE_RESOLVED ?
               INTEL_AUX_BUFFER_DISABLED : 0;
            brw_emit_surface_state(brw, mt, flags, mt->target, view,
                                   surface_state_infos[brw->gen].tex_mocs,
                                   surf_offset, surf_index,
                                   I915_GEM_DOMAIN_SAMPLER,
                                   access == GL_READ_ONLY ? 0 :
                                             I915_GEM_DOMAIN_SAMPLER);
         }

         update_texture_image_param(brw, u, surface_idx, param);
      }

   } else {
      brw->vtbl.emit_null_surface_state(brw, 1, 1, 1, surf_offset);
      update_default_image_param(brw, u, surface_idx, param);
   }
}

void
brw_upload_image_surfaces(struct brw_context *brw,
                          struct gl_linked_shader *shader,
                          struct brw_stage_state *stage_state,
                          struct brw_stage_prog_data *prog_data)
{
   struct gl_context *ctx = &brw->ctx;

   if (shader && shader->NumImages) {
      for (unsigned i = 0; i < shader->NumImages; i++) {
         struct gl_image_unit *u = &ctx->ImageUnits[shader->ImageUnits[i]];
         const unsigned surf_idx = prog_data->binding_table.image_start + i;

         update_image_surface(brw, u, shader->ImageAccess[i],
                              surf_idx,
                              &stage_state->surf_offset[surf_idx],
                              &prog_data->image_param[i]);
      }

      brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
      /* This may have changed the image metadata dependent on the context
       * image unit state and passed to the program as uniforms, make sure
       * that push and pull constants are reuploaded.
       */
      brw->NewGLState |= _NEW_PROGRAM_CONSTANTS;
   }
}

static void
brw_upload_wm_image_surfaces(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* BRW_NEW_FRAGMENT_PROGRAM */
   struct gl_shader_program *prog = ctx->_Shader->_CurrentFragmentProgram;

   if (prog) {
      /* BRW_NEW_FS_PROG_DATA, BRW_NEW_IMAGE_UNITS, _NEW_TEXTURE */
      brw_upload_image_surfaces(brw, prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
                                &brw->wm.base, &brw->wm.prog_data->base);
   }
}

const struct brw_tracked_state brw_wm_image_surfaces = {
   .dirty = {
      .mesa = _NEW_TEXTURE,
      .brw = BRW_NEW_BATCH |
             BRW_NEW_BLORP |
             BRW_NEW_FRAGMENT_PROGRAM |
             BRW_NEW_FS_PROG_DATA |
             BRW_NEW_IMAGE_UNITS
   },
   .emit = brw_upload_wm_image_surfaces,
};

void
gen4_init_vtable_surface_functions(struct brw_context *brw)
{
   brw->vtbl.update_renderbuffer_surface = gen4_update_renderbuffer_surface;
   brw->vtbl.emit_null_surface_state = brw_emit_null_surface_state;
}

void
gen6_init_vtable_surface_functions(struct brw_context *brw)
{
   gen4_init_vtable_surface_functions(brw);
   brw->vtbl.update_renderbuffer_surface = brw_update_renderbuffer_surface;
}

static void
brw_upload_cs_work_groups_surface(struct brw_context *brw)
{
   struct gl_context *ctx = &brw->ctx;
   /* _NEW_PROGRAM */
   struct gl_shader_program *prog =
      ctx->_Shader->CurrentProgram[MESA_SHADER_COMPUTE];
   /* BRW_NEW_CS_PROG_DATA */
   const struct brw_cs_prog_data *cs_prog_data = brw->cs.prog_data;

   if (prog && cs_prog_data->uses_num_work_groups) {
      const unsigned surf_idx =
         cs_prog_data->binding_table.work_groups_start;
      uint32_t *surf_offset = &brw->cs.base.surf_offset[surf_idx];
      drm_intel_bo *bo;
      uint32_t bo_offset;

      if (brw->compute.num_work_groups_bo == NULL) {
         bo = NULL;
         intel_upload_data(brw,
                           (void *)brw->compute.num_work_groups,
                           3 * sizeof(GLuint),
                           sizeof(GLuint),
                           &bo,
                           &bo_offset);
      } else {
         bo = brw->compute.num_work_groups_bo;
         bo_offset = brw->compute.num_work_groups_offset;
      }

      brw_emit_buffer_surface_state(brw, surf_offset,
                                    bo, bo_offset,
                                    BRW_SURFACEFORMAT_RAW,
                                    3 * sizeof(GLuint), 1, true);
      brw->ctx.NewDriverState |= BRW_NEW_SURFACES;
   }
}

const struct brw_tracked_state brw_cs_work_groups_surface = {
   .dirty = {
      .brw = BRW_NEW_BLORP |
             BRW_NEW_CS_PROG_DATA |
             BRW_NEW_CS_WORK_GROUPS
   },
   .emit = brw_upload_cs_work_groups_surface,
};