aboutsummaryrefslogtreecommitdiffstats
path: root/src/amd/vulkan/radv_cmd_buffer.c
blob: 2f16832119768f13a62b3743c6f88128a18ee313 (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
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
/*
 * Copyright © 2016 Red Hat.
 * Copyright © 2016 Bas Nieuwenhuizen
 *
 * based in part on anv driver which is:
 * Copyright © 2015 Intel Corporation
 *
 * 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 AUTHORS OR COPYRIGHT HOLDERS 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.
 */

#include "radv_private.h"
#include "radv_radeon_winsys.h"
#include "radv_shader.h"
#include "radv_cs.h"
#include "sid.h"
#include "gfx9d.h"
#include "vk_format.h"
#include "radv_debug.h"
#include "radv_meta.h"

#include "ac_debug.h"

enum {
	RADV_PREFETCH_VBO_DESCRIPTORS	= (1 << 0),
	RADV_PREFETCH_VS		= (1 << 1),
	RADV_PREFETCH_TCS		= (1 << 2),
	RADV_PREFETCH_TES		= (1 << 3),
	RADV_PREFETCH_GS		= (1 << 4),
	RADV_PREFETCH_PS		= (1 << 5),
	RADV_PREFETCH_SHADERS		= (RADV_PREFETCH_VS  |
					   RADV_PREFETCH_TCS |
					   RADV_PREFETCH_TES |
					   RADV_PREFETCH_GS  |
					   RADV_PREFETCH_PS)
};

static void radv_handle_image_transition(struct radv_cmd_buffer *cmd_buffer,
					 struct radv_image *image,
					 VkImageLayout src_layout,
					 VkImageLayout dst_layout,
					 uint32_t src_family,
					 uint32_t dst_family,
					 const VkImageSubresourceRange *range,
					 VkImageAspectFlags pending_clears);

const struct radv_dynamic_state default_dynamic_state = {
	.viewport = {
		.count = 0,
	},
	.scissor = {
		.count = 0,
	},
	.line_width = 1.0f,
	.depth_bias = {
		.bias = 0.0f,
		.clamp = 0.0f,
		.slope = 0.0f,
	},
	.blend_constants = { 0.0f, 0.0f, 0.0f, 0.0f },
	.depth_bounds = {
		.min = 0.0f,
		.max = 1.0f,
	},
	.stencil_compare_mask = {
		.front = ~0u,
		.back = ~0u,
	},
	.stencil_write_mask = {
		.front = ~0u,
		.back = ~0u,
	},
	.stencil_reference = {
		.front = 0u,
		.back = 0u,
	},
};

static void
radv_bind_dynamic_state(struct radv_cmd_buffer *cmd_buffer,
			const struct radv_dynamic_state *src)
{
	struct radv_dynamic_state *dest = &cmd_buffer->state.dynamic;
	uint32_t copy_mask = src->mask;
	uint32_t dest_mask = 0;

	/* Make sure to copy the number of viewports/scissors because they can
	 * only be specified at pipeline creation time.
	 */
	dest->viewport.count = src->viewport.count;
	dest->scissor.count = src->scissor.count;
	dest->discard_rectangle.count = src->discard_rectangle.count;

	if (copy_mask & RADV_DYNAMIC_VIEWPORT) {
		if (memcmp(&dest->viewport.viewports, &src->viewport.viewports,
			   src->viewport.count * sizeof(VkViewport))) {
			typed_memcpy(dest->viewport.viewports,
				     src->viewport.viewports,
				     src->viewport.count);
			dest_mask |= RADV_DYNAMIC_VIEWPORT;
		}
	}

	if (copy_mask & RADV_DYNAMIC_SCISSOR) {
		if (memcmp(&dest->scissor.scissors, &src->scissor.scissors,
			   src->scissor.count * sizeof(VkRect2D))) {
			typed_memcpy(dest->scissor.scissors,
				     src->scissor.scissors, src->scissor.count);
			dest_mask |= RADV_DYNAMIC_SCISSOR;
		}
	}

	if (copy_mask & RADV_DYNAMIC_LINE_WIDTH) {
		if (dest->line_width != src->line_width) {
			dest->line_width = src->line_width;
			dest_mask |= RADV_DYNAMIC_LINE_WIDTH;
		}
	}

	if (copy_mask & RADV_DYNAMIC_DEPTH_BIAS) {
		if (memcmp(&dest->depth_bias, &src->depth_bias,
			   sizeof(src->depth_bias))) {
			dest->depth_bias = src->depth_bias;
			dest_mask |= RADV_DYNAMIC_DEPTH_BIAS;
		}
	}

	if (copy_mask & RADV_DYNAMIC_BLEND_CONSTANTS) {
		if (memcmp(&dest->blend_constants, &src->blend_constants,
			   sizeof(src->blend_constants))) {
			typed_memcpy(dest->blend_constants,
				     src->blend_constants, 4);
			dest_mask |= RADV_DYNAMIC_BLEND_CONSTANTS;
		}
	}

	if (copy_mask & RADV_DYNAMIC_DEPTH_BOUNDS) {
		if (memcmp(&dest->depth_bounds, &src->depth_bounds,
			   sizeof(src->depth_bounds))) {
			dest->depth_bounds = src->depth_bounds;
			dest_mask |= RADV_DYNAMIC_DEPTH_BOUNDS;
		}
	}

	if (copy_mask & RADV_DYNAMIC_STENCIL_COMPARE_MASK) {
		if (memcmp(&dest->stencil_compare_mask,
			   &src->stencil_compare_mask,
			   sizeof(src->stencil_compare_mask))) {
			dest->stencil_compare_mask = src->stencil_compare_mask;
			dest_mask |= RADV_DYNAMIC_STENCIL_COMPARE_MASK;
		}
	}

	if (copy_mask & RADV_DYNAMIC_STENCIL_WRITE_MASK) {
		if (memcmp(&dest->stencil_write_mask, &src->stencil_write_mask,
			   sizeof(src->stencil_write_mask))) {
			dest->stencil_write_mask = src->stencil_write_mask;
			dest_mask |= RADV_DYNAMIC_STENCIL_WRITE_MASK;
		}
	}

	if (copy_mask & RADV_DYNAMIC_STENCIL_REFERENCE) {
		if (memcmp(&dest->stencil_reference, &src->stencil_reference,
			   sizeof(src->stencil_reference))) {
			dest->stencil_reference = src->stencil_reference;
			dest_mask |= RADV_DYNAMIC_STENCIL_REFERENCE;
		}
	}

	if (copy_mask & RADV_DYNAMIC_DISCARD_RECTANGLE) {
		if (memcmp(&dest->discard_rectangle.rectangles, &src->discard_rectangle.rectangles,
			   src->discard_rectangle.count * sizeof(VkRect2D))) {
			typed_memcpy(dest->discard_rectangle.rectangles,
				     src->discard_rectangle.rectangles,
				     src->discard_rectangle.count);
			dest_mask |= RADV_DYNAMIC_DISCARD_RECTANGLE;
		}
	}

	cmd_buffer->state.dirty |= dest_mask;
}

bool radv_cmd_buffer_uses_mec(struct radv_cmd_buffer *cmd_buffer)
{
	return cmd_buffer->queue_family_index == RADV_QUEUE_COMPUTE &&
	       cmd_buffer->device->physical_device->rad_info.chip_class >= CIK;
}

enum ring_type radv_queue_family_to_ring(int f) {
	switch (f) {
	case RADV_QUEUE_GENERAL:
		return RING_GFX;
	case RADV_QUEUE_COMPUTE:
		return RING_COMPUTE;
	case RADV_QUEUE_TRANSFER:
		return RING_DMA;
	default:
		unreachable("Unknown queue family");
	}
}

static VkResult radv_create_cmd_buffer(
	struct radv_device *                         device,
	struct radv_cmd_pool *                       pool,
	VkCommandBufferLevel                        level,
	VkCommandBuffer*                            pCommandBuffer)
{
	struct radv_cmd_buffer *cmd_buffer;
	unsigned ring;
	cmd_buffer = vk_zalloc(&pool->alloc, sizeof(*cmd_buffer), 8,
			       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
	if (cmd_buffer == NULL)
		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

	cmd_buffer->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
	cmd_buffer->device = device;
	cmd_buffer->pool = pool;
	cmd_buffer->level = level;

	if (pool) {
		list_addtail(&cmd_buffer->pool_link, &pool->cmd_buffers);
		cmd_buffer->queue_family_index = pool->queue_family_index;

	} else {
		/* Init the pool_link so we can safely call list_del when we destroy
		 * the command buffer
		 */
		list_inithead(&cmd_buffer->pool_link);
		cmd_buffer->queue_family_index = RADV_QUEUE_GENERAL;
	}

	ring = radv_queue_family_to_ring(cmd_buffer->queue_family_index);

	cmd_buffer->cs = device->ws->cs_create(device->ws, ring);
	if (!cmd_buffer->cs) {
		vk_free(&cmd_buffer->pool->alloc, cmd_buffer);
		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
	}

	*pCommandBuffer = radv_cmd_buffer_to_handle(cmd_buffer);

	list_inithead(&cmd_buffer->upload.list);

	return VK_SUCCESS;
}

static void
radv_cmd_buffer_destroy(struct radv_cmd_buffer *cmd_buffer)
{
	list_del(&cmd_buffer->pool_link);

	list_for_each_entry_safe(struct radv_cmd_buffer_upload, up,
				 &cmd_buffer->upload.list, list) {
		cmd_buffer->device->ws->buffer_destroy(up->upload_bo);
		list_del(&up->list);
		free(up);
	}

	if (cmd_buffer->upload.upload_bo)
		cmd_buffer->device->ws->buffer_destroy(cmd_buffer->upload.upload_bo);
	cmd_buffer->device->ws->cs_destroy(cmd_buffer->cs);

	for (unsigned i = 0; i < VK_PIPELINE_BIND_POINT_RANGE_SIZE; i++)
		free(cmd_buffer->descriptors[i].push_set.set.mapped_ptr);

	vk_free(&cmd_buffer->pool->alloc, cmd_buffer);
}

static VkResult
radv_reset_cmd_buffer(struct radv_cmd_buffer *cmd_buffer)
{

	cmd_buffer->device->ws->cs_reset(cmd_buffer->cs);

	list_for_each_entry_safe(struct radv_cmd_buffer_upload, up,
				 &cmd_buffer->upload.list, list) {
		cmd_buffer->device->ws->buffer_destroy(up->upload_bo);
		list_del(&up->list);
		free(up);
	}

	cmd_buffer->push_constant_stages = 0;
	cmd_buffer->scratch_size_needed = 0;
	cmd_buffer->compute_scratch_size_needed = 0;
	cmd_buffer->esgs_ring_size_needed = 0;
	cmd_buffer->gsvs_ring_size_needed = 0;
	cmd_buffer->tess_rings_needed = false;
	cmd_buffer->sample_positions_needed = false;

	if (cmd_buffer->upload.upload_bo)
		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs,
				   cmd_buffer->upload.upload_bo);
	cmd_buffer->upload.offset = 0;

	cmd_buffer->record_result = VK_SUCCESS;

	for (unsigned i = 0; i < VK_PIPELINE_BIND_POINT_RANGE_SIZE; i++) {
		cmd_buffer->descriptors[i].dirty = 0;
		cmd_buffer->descriptors[i].valid = 0;
		cmd_buffer->descriptors[i].push_dirty = false;
	}

	if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
		unsigned num_db = cmd_buffer->device->physical_device->rad_info.num_render_backends;
		unsigned eop_bug_offset;
		void *fence_ptr;

		radv_cmd_buffer_upload_alloc(cmd_buffer, 8, 0,
					     &cmd_buffer->gfx9_fence_offset,
					     &fence_ptr);
		cmd_buffer->gfx9_fence_bo = cmd_buffer->upload.upload_bo;

		/* Allocate a buffer for the EOP bug on GFX9. */
		radv_cmd_buffer_upload_alloc(cmd_buffer, 16 * num_db, 0,
					     &eop_bug_offset, &fence_ptr);
		cmd_buffer->gfx9_eop_bug_va =
			radv_buffer_get_va(cmd_buffer->upload.upload_bo);
		cmd_buffer->gfx9_eop_bug_va += eop_bug_offset;
	}

	cmd_buffer->status = RADV_CMD_BUFFER_STATUS_INITIAL;

	return cmd_buffer->record_result;
}

static bool
radv_cmd_buffer_resize_upload_buf(struct radv_cmd_buffer *cmd_buffer,
				  uint64_t min_needed)
{
	uint64_t new_size;
	struct radeon_winsys_bo *bo;
	struct radv_cmd_buffer_upload *upload;
	struct radv_device *device = cmd_buffer->device;

	new_size = MAX2(min_needed, 16 * 1024);
	new_size = MAX2(new_size, 2 * cmd_buffer->upload.size);

	bo = device->ws->buffer_create(device->ws,
				       new_size, 4096,
				       RADEON_DOMAIN_GTT,
				       RADEON_FLAG_CPU_ACCESS|
				       RADEON_FLAG_NO_INTERPROCESS_SHARING |
				       RADEON_FLAG_32BIT);

	if (!bo) {
		cmd_buffer->record_result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
		return false;
	}

	radv_cs_add_buffer(device->ws, cmd_buffer->cs, bo);
	if (cmd_buffer->upload.upload_bo) {
		upload = malloc(sizeof(*upload));

		if (!upload) {
			cmd_buffer->record_result = VK_ERROR_OUT_OF_HOST_MEMORY;
			device->ws->buffer_destroy(bo);
			return false;
		}

		memcpy(upload, &cmd_buffer->upload, sizeof(*upload));
		list_add(&upload->list, &cmd_buffer->upload.list);
	}

	cmd_buffer->upload.upload_bo = bo;
	cmd_buffer->upload.size = new_size;
	cmd_buffer->upload.offset = 0;
	cmd_buffer->upload.map = device->ws->buffer_map(cmd_buffer->upload.upload_bo);

	if (!cmd_buffer->upload.map) {
		cmd_buffer->record_result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
		return false;
	}

	return true;
}

bool
radv_cmd_buffer_upload_alloc(struct radv_cmd_buffer *cmd_buffer,
			     unsigned size,
			     unsigned alignment,
			     unsigned *out_offset,
			     void **ptr)
{
	uint64_t offset = align(cmd_buffer->upload.offset, alignment);
	if (offset + size > cmd_buffer->upload.size) {
		if (!radv_cmd_buffer_resize_upload_buf(cmd_buffer, size))
			return false;
		offset = 0;
	}

	*out_offset = offset;
	*ptr = cmd_buffer->upload.map + offset;

	cmd_buffer->upload.offset = offset + size;
	return true;
}

bool
radv_cmd_buffer_upload_data(struct radv_cmd_buffer *cmd_buffer,
			    unsigned size, unsigned alignment,
			    const void *data, unsigned *out_offset)
{
	uint8_t *ptr;

	if (!radv_cmd_buffer_upload_alloc(cmd_buffer, size, alignment,
					  out_offset, (void **)&ptr))
		return false;

	if (ptr)
		memcpy(ptr, data, size);

	return true;
}

static void
radv_emit_write_data_packet(struct radv_cmd_buffer *cmd_buffer, uint64_t va,
			    unsigned count, const uint32_t *data)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;

	radeon_check_space(cmd_buffer->device->ws, cs, 4 + count);

	radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 2 + count, 0));
	radeon_emit(cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
		    S_370_WR_CONFIRM(1) |
		    S_370_ENGINE_SEL(V_370_ME));
	radeon_emit(cs, va);
	radeon_emit(cs, va >> 32);
	radeon_emit_array(cs, data, count);
}

void radv_cmd_buffer_trace_emit(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_device *device = cmd_buffer->device;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint64_t va;

	va = radv_buffer_get_va(device->trace_bo);
	if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY)
		va += 4;

	++cmd_buffer->state.trace_id;
	radv_emit_write_data_packet(cmd_buffer, va, 1,
				    &cmd_buffer->state.trace_id);

	radeon_check_space(cmd_buffer->device->ws, cs, 2);

	radeon_emit(cs, PKT3(PKT3_NOP, 0, 0));
	radeon_emit(cs, AC_ENCODE_TRACE_POINT(cmd_buffer->state.trace_id));
}

static void
radv_cmd_buffer_after_draw(struct radv_cmd_buffer *cmd_buffer,
			   enum radv_cmd_flush_bits flags)
{
	if (cmd_buffer->device->instance->debug_flags & RADV_DEBUG_SYNC_SHADERS) {
		uint32_t *ptr = NULL;
		uint64_t va = 0;

		assert(flags & (RADV_CMD_FLAG_PS_PARTIAL_FLUSH |
				RADV_CMD_FLAG_CS_PARTIAL_FLUSH));

		if (cmd_buffer->device->physical_device->rad_info.chip_class == GFX9) {
			va = radv_buffer_get_va(cmd_buffer->gfx9_fence_bo) +
			     cmd_buffer->gfx9_fence_offset;
			ptr = &cmd_buffer->gfx9_fence_idx;
		}

		radeon_check_space(cmd_buffer->device->ws, cmd_buffer->cs, 4);

		/* Force wait for graphics or compute engines to be idle. */
		si_cs_emit_cache_flush(cmd_buffer->cs,
				       cmd_buffer->device->physical_device->rad_info.chip_class,
				       ptr, va,
				       radv_cmd_buffer_uses_mec(cmd_buffer),
				       flags, cmd_buffer->gfx9_eop_bug_va);
	}

	if (unlikely(cmd_buffer->device->trace_bo))
		radv_cmd_buffer_trace_emit(cmd_buffer);
}

static void
radv_save_pipeline(struct radv_cmd_buffer *cmd_buffer,
		   struct radv_pipeline *pipeline, enum ring_type ring)
{
	struct radv_device *device = cmd_buffer->device;
	uint32_t data[2];
	uint64_t va;

	va = radv_buffer_get_va(device->trace_bo);

	switch (ring) {
	case RING_GFX:
		va += 8;
		break;
	case RING_COMPUTE:
		va += 16;
		break;
	default:
		assert(!"invalid ring type");
	}

	data[0] = (uintptr_t)pipeline;
	data[1] = (uintptr_t)pipeline >> 32;

	radv_emit_write_data_packet(cmd_buffer, va, 2, data);
}

void radv_set_descriptor_set(struct radv_cmd_buffer *cmd_buffer,
			     VkPipelineBindPoint bind_point,
			     struct radv_descriptor_set *set,
			     unsigned idx)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);

	descriptors_state->sets[idx] = set;

	descriptors_state->valid |= (1u << idx); /* active descriptors */
	descriptors_state->dirty |= (1u << idx);
}

static void
radv_save_descriptors(struct radv_cmd_buffer *cmd_buffer,
		      VkPipelineBindPoint bind_point)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	struct radv_device *device = cmd_buffer->device;
	uint32_t data[MAX_SETS * 2] = {};
	uint64_t va;
	unsigned i;
	va = radv_buffer_get_va(device->trace_bo) + 24;

	for_each_bit(i, descriptors_state->valid) {
		struct radv_descriptor_set *set = descriptors_state->sets[i];
		data[i * 2] = (uintptr_t)set;
		data[i * 2 + 1] = (uintptr_t)set >> 32;
	}

	radv_emit_write_data_packet(cmd_buffer, va, MAX_SETS * 2, data);
}

struct radv_userdata_info *
radv_lookup_user_sgpr(struct radv_pipeline *pipeline,
		      gl_shader_stage stage,
		      int idx)
{
	struct radv_shader_variant *shader = radv_get_shader(pipeline, stage);
	return &shader->info.user_sgprs_locs.shader_data[idx];
}

static void
radv_emit_userdata_address(struct radv_cmd_buffer *cmd_buffer,
			   struct radv_pipeline *pipeline,
			   gl_shader_stage stage,
			   int idx, uint64_t va)
{
	struct radv_userdata_info *loc = radv_lookup_user_sgpr(pipeline, stage, idx);
	uint32_t base_reg = pipeline->user_data_0[stage];
	if (loc->sgpr_idx == -1)
		return;

	assert(loc->num_sgprs == (HAVE_32BIT_POINTERS ? 1 : 2));
	assert(!loc->indirect);

	radv_emit_shader_pointer(cmd_buffer->device, cmd_buffer->cs,
				 base_reg + loc->sgpr_idx * 4, va, false);
}

static void
radv_emit_descriptor_pointers(struct radv_cmd_buffer *cmd_buffer,
			      struct radv_pipeline *pipeline,
			      struct radv_descriptor_state *descriptors_state,
			      gl_shader_stage stage)
{
	struct radv_device *device = cmd_buffer->device;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint32_t sh_base = pipeline->user_data_0[stage];
	struct radv_userdata_locations *locs =
		&pipeline->shaders[stage]->info.user_sgprs_locs;
	unsigned mask = locs->descriptor_sets_enabled;

	mask &= descriptors_state->dirty & descriptors_state->valid;

	while (mask) {
		int start, count;

		u_bit_scan_consecutive_range(&mask, &start, &count);

		struct radv_userdata_info *loc = &locs->descriptor_sets[start];
		unsigned sh_offset = sh_base + loc->sgpr_idx * 4;

		radv_emit_shader_pointer_head(cs, sh_offset, count,
					      HAVE_32BIT_POINTERS);
		for (int i = 0; i < count; i++) {
			struct radv_descriptor_set *set =
				descriptors_state->sets[start + i];

			radv_emit_shader_pointer_body(device, cs, set->va,
						      HAVE_32BIT_POINTERS);
		}
	}
}

static void
radv_update_multisample_state(struct radv_cmd_buffer *cmd_buffer,
			      struct radv_pipeline *pipeline)
{
	int num_samples = pipeline->graphics.ms.num_samples;
	struct radv_multisample_state *ms = &pipeline->graphics.ms;
	struct radv_pipeline *old_pipeline = cmd_buffer->state.emitted_pipeline;

	if (pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.needs_sample_positions)
		cmd_buffer->sample_positions_needed = true;

	if (old_pipeline && num_samples == old_pipeline->graphics.ms.num_samples)
		return;

	radeon_set_context_reg_seq(cmd_buffer->cs, R_028BDC_PA_SC_LINE_CNTL, 2);
	radeon_emit(cmd_buffer->cs, ms->pa_sc_line_cntl);
	radeon_emit(cmd_buffer->cs, ms->pa_sc_aa_config);

	radeon_set_context_reg(cmd_buffer->cs, R_028A48_PA_SC_MODE_CNTL_0, ms->pa_sc_mode_cntl_0);

	radv_cayman_emit_msaa_sample_locs(cmd_buffer->cs, num_samples);

	/* GFX9: Flush DFSM when the AA mode changes. */
	if (cmd_buffer->device->dfsm_allowed) {
		radeon_emit(cmd_buffer->cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
		radeon_emit(cmd_buffer->cs, EVENT_TYPE(V_028A90_FLUSH_DFSM) | EVENT_INDEX(0));
	}
}

static void
radv_emit_shader_prefetch(struct radv_cmd_buffer *cmd_buffer,
			  struct radv_shader_variant *shader)
{
	uint64_t va;

	if (!shader)
		return;

	va = radv_buffer_get_va(shader->bo) + shader->bo_offset;

	si_cp_dma_prefetch(cmd_buffer, va, shader->code_size);
}

static void
radv_emit_prefetch_L2(struct radv_cmd_buffer *cmd_buffer,
		      struct radv_pipeline *pipeline,
		      bool vertex_stage_only)
{
	struct radv_cmd_state *state = &cmd_buffer->state;
	uint32_t mask = state->prefetch_L2_mask;

	if (vertex_stage_only) {
		/* Fast prefetch path for starting draws as soon as possible.
		 */
		mask = state->prefetch_L2_mask & (RADV_PREFETCH_VS |
						  RADV_PREFETCH_VBO_DESCRIPTORS);
	}

	if (mask & RADV_PREFETCH_VS)
		radv_emit_shader_prefetch(cmd_buffer,
					  pipeline->shaders[MESA_SHADER_VERTEX]);

	if (mask & RADV_PREFETCH_VBO_DESCRIPTORS)
		si_cp_dma_prefetch(cmd_buffer, state->vb_va, state->vb_size);

	if (mask & RADV_PREFETCH_TCS)
		radv_emit_shader_prefetch(cmd_buffer,
					  pipeline->shaders[MESA_SHADER_TESS_CTRL]);

	if (mask & RADV_PREFETCH_TES)
		radv_emit_shader_prefetch(cmd_buffer,
					  pipeline->shaders[MESA_SHADER_TESS_EVAL]);

	if (mask & RADV_PREFETCH_GS) {
		radv_emit_shader_prefetch(cmd_buffer,
					  pipeline->shaders[MESA_SHADER_GEOMETRY]);
		radv_emit_shader_prefetch(cmd_buffer, pipeline->gs_copy_shader);
	}

	if (mask & RADV_PREFETCH_PS)
		radv_emit_shader_prefetch(cmd_buffer,
					  pipeline->shaders[MESA_SHADER_FRAGMENT]);

	state->prefetch_L2_mask &= ~mask;
}

static void
radv_emit_rbplus_state(struct radv_cmd_buffer *cmd_buffer)
{
	if (!cmd_buffer->device->physical_device->rbplus_allowed)
		return;

	struct radv_pipeline *pipeline = cmd_buffer->state.pipeline;
	struct radv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
	const struct radv_subpass *subpass = cmd_buffer->state.subpass;

	unsigned sx_ps_downconvert = 0;
	unsigned sx_blend_opt_epsilon = 0;
	unsigned sx_blend_opt_control = 0;

	for (unsigned i = 0; i < subpass->color_count; ++i) {
		if (subpass->color_attachments[i].attachment == VK_ATTACHMENT_UNUSED) {
			sx_blend_opt_control |= S_02875C_MRT0_COLOR_OPT_DISABLE(1) << (i * 4);
			sx_blend_opt_control |= S_02875C_MRT0_ALPHA_OPT_DISABLE(1) << (i * 4);
			continue;
		}

		int idx = subpass->color_attachments[i].attachment;
		struct radv_color_buffer_info *cb = &framebuffer->attachments[idx].cb;

		unsigned format = G_028C70_FORMAT(cb->cb_color_info);
		unsigned swap = G_028C70_COMP_SWAP(cb->cb_color_info);
		uint32_t spi_format = (pipeline->graphics.col_format >> (i * 4)) & 0xf;
		uint32_t colormask = (pipeline->graphics.cb_target_mask >> (i * 4)) & 0xf;

		bool has_alpha, has_rgb;

		/* Set if RGB and A are present. */
		has_alpha = !G_028C74_FORCE_DST_ALPHA_1(cb->cb_color_attrib);

		if (format == V_028C70_COLOR_8 ||
		    format == V_028C70_COLOR_16 ||
		    format == V_028C70_COLOR_32)
			has_rgb = !has_alpha;
		else
			has_rgb = true;

		/* Check the colormask and export format. */
		if (!(colormask & 0x7))
			has_rgb = false;
		if (!(colormask & 0x8))
			has_alpha = false;

		if (spi_format == V_028714_SPI_SHADER_ZERO) {
			has_rgb = false;
			has_alpha = false;
		}

		/* Disable value checking for disabled channels. */
		if (!has_rgb)
			sx_blend_opt_control |= S_02875C_MRT0_COLOR_OPT_DISABLE(1) << (i * 4);
		if (!has_alpha)
			sx_blend_opt_control |= S_02875C_MRT0_ALPHA_OPT_DISABLE(1) << (i * 4);

		/* Enable down-conversion for 32bpp and smaller formats. */
		switch (format) {
		case V_028C70_COLOR_8:
		case V_028C70_COLOR_8_8:
		case V_028C70_COLOR_8_8_8_8:
			/* For 1 and 2-channel formats, use the superset thereof. */
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR ||
			    spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
			    spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_8_8_8_8 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_8BIT_FORMAT << (i * 4);
			}
			break;

		case V_028C70_COLOR_5_6_5:
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_5_6_5 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_6BIT_FORMAT << (i * 4);
			}
			break;

		case V_028C70_COLOR_1_5_5_5:
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_1_5_5_5 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_5BIT_FORMAT << (i * 4);
			}
			break;

		case V_028C70_COLOR_4_4_4_4:
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_4_4_4_4 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_4BIT_FORMAT << (i * 4);
			}
			break;

		case V_028C70_COLOR_32:
			if (swap == V_028C70_SWAP_STD &&
			    spi_format == V_028714_SPI_SHADER_32_R)
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_R << (i * 4);
			else if (swap == V_028C70_SWAP_ALT_REV &&
				 spi_format == V_028714_SPI_SHADER_32_AR)
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_A << (i * 4);
			break;

		case V_028C70_COLOR_16:
		case V_028C70_COLOR_16_16:
			/* For 1-channel formats, use the superset thereof. */
			if (spi_format == V_028714_SPI_SHADER_UNORM16_ABGR ||
			    spi_format == V_028714_SPI_SHADER_SNORM16_ABGR ||
			    spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
			    spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
				if (swap == V_028C70_SWAP_STD ||
				    swap == V_028C70_SWAP_STD_REV)
					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_GR << (i * 4);
				else
					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_AR << (i * 4);
			}
			break;

		case V_028C70_COLOR_10_11_11:
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_10_11_11 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_11BIT_FORMAT << (i * 4);
			}
			break;

		case V_028C70_COLOR_2_10_10_10:
			if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
				sx_ps_downconvert |= V_028754_SX_RT_EXPORT_2_10_10_10 << (i * 4);
				sx_blend_opt_epsilon |= V_028758_10BIT_FORMAT << (i * 4);
			}
			break;
		}
	}

	for (unsigned i = subpass->color_count; i < 8; ++i) {
		sx_blend_opt_control |= S_02875C_MRT0_COLOR_OPT_DISABLE(1) << (i * 4);
		sx_blend_opt_control |= S_02875C_MRT0_ALPHA_OPT_DISABLE(1) << (i * 4);
	}
	radeon_set_context_reg_seq(cmd_buffer->cs, R_028754_SX_PS_DOWNCONVERT, 3);
	radeon_emit(cmd_buffer->cs, sx_ps_downconvert);
	radeon_emit(cmd_buffer->cs, sx_blend_opt_epsilon);
	radeon_emit(cmd_buffer->cs, sx_blend_opt_control);
}

static void
radv_emit_graphics_pipeline(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_pipeline *pipeline = cmd_buffer->state.pipeline;

	if (!pipeline || cmd_buffer->state.emitted_pipeline == pipeline)
		return;

	radv_update_multisample_state(cmd_buffer, pipeline);

	cmd_buffer->scratch_size_needed =
	                          MAX2(cmd_buffer->scratch_size_needed,
	                               pipeline->max_waves * pipeline->scratch_bytes_per_wave);

	if (!cmd_buffer->state.emitted_pipeline ||
	    cmd_buffer->state.emitted_pipeline->graphics.can_use_guardband !=
	     pipeline->graphics.can_use_guardband)
		cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_SCISSOR;

	radeon_emit_array(cmd_buffer->cs, pipeline->cs.buf, pipeline->cs.cdw);

	for (unsigned i = 0; i < MESA_SHADER_COMPUTE; i++) {
		if (!pipeline->shaders[i])
			continue;

		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs,
				   pipeline->shaders[i]->bo);
	}

	if (radv_pipeline_has_gs(pipeline))
		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs,
				   pipeline->gs_copy_shader->bo);

	if (unlikely(cmd_buffer->device->trace_bo))
		radv_save_pipeline(cmd_buffer, pipeline, RING_GFX);

	cmd_buffer->state.emitted_pipeline = pipeline;

	cmd_buffer->state.dirty &= ~RADV_CMD_DIRTY_PIPELINE;
}

static void
radv_emit_viewport(struct radv_cmd_buffer *cmd_buffer)
{
	si_write_viewport(cmd_buffer->cs, 0, cmd_buffer->state.dynamic.viewport.count,
			  cmd_buffer->state.dynamic.viewport.viewports);
}

static void
radv_emit_scissor(struct radv_cmd_buffer *cmd_buffer)
{
	uint32_t count = cmd_buffer->state.dynamic.scissor.count;

	si_write_scissors(cmd_buffer->cs, 0, count,
			  cmd_buffer->state.dynamic.scissor.scissors,
			  cmd_buffer->state.dynamic.viewport.viewports,
			  cmd_buffer->state.emitted_pipeline->graphics.can_use_guardband);
}

static void
radv_emit_discard_rectangle(struct radv_cmd_buffer *cmd_buffer)
{
	if (!cmd_buffer->state.dynamic.discard_rectangle.count)
		return;

	radeon_set_context_reg_seq(cmd_buffer->cs, R_028210_PA_SC_CLIPRECT_0_TL,
	                           cmd_buffer->state.dynamic.discard_rectangle.count * 2);
	for (unsigned i = 0; i < cmd_buffer->state.dynamic.discard_rectangle.count; ++i) {
		VkRect2D rect = cmd_buffer->state.dynamic.discard_rectangle.rectangles[i];
		radeon_emit(cmd_buffer->cs, S_028210_TL_X(rect.offset.x) | S_028210_TL_Y(rect.offset.y));
		radeon_emit(cmd_buffer->cs, S_028214_BR_X(rect.offset.x + rect.extent.width) |
		                            S_028214_BR_Y(rect.offset.y + rect.extent.height));
	}
}

static void
radv_emit_line_width(struct radv_cmd_buffer *cmd_buffer)
{
	unsigned width = cmd_buffer->state.dynamic.line_width * 8;

	radeon_set_context_reg(cmd_buffer->cs, R_028A08_PA_SU_LINE_CNTL,
			       S_028A08_WIDTH(CLAMP(width, 0, 0xFFF)));
}

static void
radv_emit_blend_constants(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_dynamic_state *d = &cmd_buffer->state.dynamic;

	radeon_set_context_reg_seq(cmd_buffer->cs, R_028414_CB_BLEND_RED, 4);
	radeon_emit_array(cmd_buffer->cs, (uint32_t *)d->blend_constants, 4);
}

static void
radv_emit_stencil(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_dynamic_state *d = &cmd_buffer->state.dynamic;

	radeon_set_context_reg_seq(cmd_buffer->cs,
				   R_028430_DB_STENCILREFMASK, 2);
	radeon_emit(cmd_buffer->cs,
		    S_028430_STENCILTESTVAL(d->stencil_reference.front) |
		    S_028430_STENCILMASK(d->stencil_compare_mask.front) |
		    S_028430_STENCILWRITEMASK(d->stencil_write_mask.front) |
		    S_028430_STENCILOPVAL(1));
	radeon_emit(cmd_buffer->cs,
		    S_028434_STENCILTESTVAL_BF(d->stencil_reference.back) |
		    S_028434_STENCILMASK_BF(d->stencil_compare_mask.back) |
		    S_028434_STENCILWRITEMASK_BF(d->stencil_write_mask.back) |
		    S_028434_STENCILOPVAL_BF(1));
}

static void
radv_emit_depth_bounds(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_dynamic_state *d = &cmd_buffer->state.dynamic;

	radeon_set_context_reg(cmd_buffer->cs, R_028020_DB_DEPTH_BOUNDS_MIN,
			       fui(d->depth_bounds.min));
	radeon_set_context_reg(cmd_buffer->cs, R_028024_DB_DEPTH_BOUNDS_MAX,
			       fui(d->depth_bounds.max));
}

static void
radv_emit_depth_bias(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_dynamic_state *d = &cmd_buffer->state.dynamic;
	unsigned slope = fui(d->depth_bias.slope * 16.0f);
	unsigned bias = fui(d->depth_bias.bias * cmd_buffer->state.offset_scale);


	radeon_set_context_reg_seq(cmd_buffer->cs,
				   R_028B7C_PA_SU_POLY_OFFSET_CLAMP, 5);
	radeon_emit(cmd_buffer->cs, fui(d->depth_bias.clamp)); /* CLAMP */
	radeon_emit(cmd_buffer->cs, slope); /* FRONT SCALE */
	radeon_emit(cmd_buffer->cs, bias); /* FRONT OFFSET */
	radeon_emit(cmd_buffer->cs, slope); /* BACK SCALE */
	radeon_emit(cmd_buffer->cs, bias); /* BACK OFFSET */
}

static void
radv_emit_fb_color_state(struct radv_cmd_buffer *cmd_buffer,
			 int index,
			 struct radv_attachment_info *att,
			 struct radv_image *image,
			 VkImageLayout layout)
{
	bool is_vi = cmd_buffer->device->physical_device->rad_info.chip_class >= VI;
	struct radv_color_buffer_info *cb = &att->cb;
	uint32_t cb_color_info = cb->cb_color_info;

	if (!radv_layout_dcc_compressed(image, layout,
	                                radv_image_queue_family_mask(image,
	                                                             cmd_buffer->queue_family_index,
	                                                             cmd_buffer->queue_family_index))) {
		cb_color_info &= C_028C70_DCC_ENABLE;
	}

	if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
		radeon_set_context_reg_seq(cmd_buffer->cs, R_028C60_CB_COLOR0_BASE + index * 0x3c, 11);
		radeon_emit(cmd_buffer->cs, cb->cb_color_base);
		radeon_emit(cmd_buffer->cs, S_028C64_BASE_256B(cb->cb_color_base >> 32));
		radeon_emit(cmd_buffer->cs, cb->cb_color_attrib2);
		radeon_emit(cmd_buffer->cs, cb->cb_color_view);
		radeon_emit(cmd_buffer->cs, cb_color_info);
		radeon_emit(cmd_buffer->cs, cb->cb_color_attrib);
		radeon_emit(cmd_buffer->cs, cb->cb_dcc_control);
		radeon_emit(cmd_buffer->cs, cb->cb_color_cmask);
		radeon_emit(cmd_buffer->cs, S_028C80_BASE_256B(cb->cb_color_cmask >> 32));
		radeon_emit(cmd_buffer->cs, cb->cb_color_fmask);
		radeon_emit(cmd_buffer->cs, S_028C88_BASE_256B(cb->cb_color_fmask >> 32));

		radeon_set_context_reg_seq(cmd_buffer->cs, R_028C94_CB_COLOR0_DCC_BASE + index * 0x3c, 2);
		radeon_emit(cmd_buffer->cs, cb->cb_dcc_base);
		radeon_emit(cmd_buffer->cs, S_028C98_BASE_256B(cb->cb_dcc_base >> 32));
		
		radeon_set_context_reg(cmd_buffer->cs, R_0287A0_CB_MRT0_EPITCH + index * 4,
				       S_0287A0_EPITCH(att->attachment->image->surface.u.gfx9.surf.epitch));
	} else {
		radeon_set_context_reg_seq(cmd_buffer->cs, R_028C60_CB_COLOR0_BASE + index * 0x3c, 11);
		radeon_emit(cmd_buffer->cs, cb->cb_color_base);
		radeon_emit(cmd_buffer->cs, cb->cb_color_pitch);
		radeon_emit(cmd_buffer->cs, cb->cb_color_slice);
		radeon_emit(cmd_buffer->cs, cb->cb_color_view);
		radeon_emit(cmd_buffer->cs, cb_color_info);
		radeon_emit(cmd_buffer->cs, cb->cb_color_attrib);
		radeon_emit(cmd_buffer->cs, cb->cb_dcc_control);
		radeon_emit(cmd_buffer->cs, cb->cb_color_cmask);
		radeon_emit(cmd_buffer->cs, cb->cb_color_cmask_slice);
		radeon_emit(cmd_buffer->cs, cb->cb_color_fmask);
		radeon_emit(cmd_buffer->cs, cb->cb_color_fmask_slice);

		if (is_vi) { /* DCC BASE */
			radeon_set_context_reg(cmd_buffer->cs, R_028C94_CB_COLOR0_DCC_BASE + index * 0x3c, cb->cb_dcc_base);
		}
	}
}

static void
radv_update_zrange_precision(struct radv_cmd_buffer *cmd_buffer,
			     struct radv_ds_buffer_info *ds,
			     struct radv_image *image, VkImageLayout layout,
			     bool requires_cond_write)
{
	uint32_t db_z_info = ds->db_z_info;
	uint32_t db_z_info_reg;

	if (!radv_image_is_tc_compat_htile(image))
		return;

	if (!radv_layout_has_htile(image, layout,
	                           radv_image_queue_family_mask(image,
	                                                        cmd_buffer->queue_family_index,
	                                                        cmd_buffer->queue_family_index))) {
		db_z_info &= C_028040_TILE_SURFACE_ENABLE;
	}

	db_z_info &= C_028040_ZRANGE_PRECISION;

	if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
		db_z_info_reg = R_028038_DB_Z_INFO;
	} else {
		db_z_info_reg = R_028040_DB_Z_INFO;
	}

	/* When we don't know the last fast clear value we need to emit a
	 * conditional packet, otherwise we can update DB_Z_INFO directly.
	 */
	if (requires_cond_write) {
		radeon_emit(cmd_buffer->cs, PKT3(PKT3_COND_WRITE, 7, 0));

		const uint32_t write_space = 0 << 8;	/* register */
		const uint32_t poll_space = 1 << 4;	/* memory */
		const uint32_t function = 3 << 0;	/* equal to the reference */
		const uint32_t options = write_space | poll_space | function;
		radeon_emit(cmd_buffer->cs, options);

		/* poll address - location of the depth clear value */
		uint64_t va = radv_buffer_get_va(image->bo);
		va += image->offset + image->clear_value_offset;

		/* In presence of stencil format, we have to adjust the base
		 * address because the first value is the stencil clear value.
		 */
		if (vk_format_is_stencil(image->vk_format))
			va += 4;

		radeon_emit(cmd_buffer->cs, va);
		radeon_emit(cmd_buffer->cs, va >> 32);

		radeon_emit(cmd_buffer->cs, fui(0.0f));		 /* reference value */
		radeon_emit(cmd_buffer->cs, (uint32_t)-1);	 /* comparison mask */
		radeon_emit(cmd_buffer->cs, db_z_info_reg >> 2); /* write address low */
		radeon_emit(cmd_buffer->cs, 0u);		 /* write address high */
		radeon_emit(cmd_buffer->cs, db_z_info);
	} else {
		radeon_set_context_reg(cmd_buffer->cs, db_z_info_reg, db_z_info);
	}
}

static void
radv_emit_fb_ds_state(struct radv_cmd_buffer *cmd_buffer,
		      struct radv_ds_buffer_info *ds,
		      struct radv_image *image,
		      VkImageLayout layout)
{
	uint32_t db_z_info = ds->db_z_info;
	uint32_t db_stencil_info = ds->db_stencil_info;

	if (!radv_layout_has_htile(image, layout,
	                           radv_image_queue_family_mask(image,
	                                                        cmd_buffer->queue_family_index,
	                                                        cmd_buffer->queue_family_index))) {
		db_z_info &= C_028040_TILE_SURFACE_ENABLE;
		db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
	}

	radeon_set_context_reg(cmd_buffer->cs, R_028008_DB_DEPTH_VIEW, ds->db_depth_view);
	radeon_set_context_reg(cmd_buffer->cs, R_028ABC_DB_HTILE_SURFACE, ds->db_htile_surface);


	if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
		radeon_set_context_reg_seq(cmd_buffer->cs, R_028014_DB_HTILE_DATA_BASE, 3);
		radeon_emit(cmd_buffer->cs, ds->db_htile_data_base);
		radeon_emit(cmd_buffer->cs, S_028018_BASE_HI(ds->db_htile_data_base >> 32));
		radeon_emit(cmd_buffer->cs, ds->db_depth_size);

		radeon_set_context_reg_seq(cmd_buffer->cs, R_028038_DB_Z_INFO, 10);
		radeon_emit(cmd_buffer->cs, db_z_info);			/* DB_Z_INFO */
		radeon_emit(cmd_buffer->cs, db_stencil_info);	        /* DB_STENCIL_INFO */
		radeon_emit(cmd_buffer->cs, ds->db_z_read_base);	/* DB_Z_READ_BASE */
		radeon_emit(cmd_buffer->cs, S_028044_BASE_HI(ds->db_z_read_base >> 32));	/* DB_Z_READ_BASE_HI */
		radeon_emit(cmd_buffer->cs, ds->db_stencil_read_base);	/* DB_STENCIL_READ_BASE */
		radeon_emit(cmd_buffer->cs, S_02804C_BASE_HI(ds->db_stencil_read_base >> 32)); /* DB_STENCIL_READ_BASE_HI */
		radeon_emit(cmd_buffer->cs, ds->db_z_write_base);	/* DB_Z_WRITE_BASE */
		radeon_emit(cmd_buffer->cs, S_028054_BASE_HI(ds->db_z_write_base >> 32));	/* DB_Z_WRITE_BASE_HI */
		radeon_emit(cmd_buffer->cs, ds->db_stencil_write_base);	/* DB_STENCIL_WRITE_BASE */
		radeon_emit(cmd_buffer->cs, S_02805C_BASE_HI(ds->db_stencil_write_base >> 32)); /* DB_STENCIL_WRITE_BASE_HI */

		radeon_set_context_reg_seq(cmd_buffer->cs, R_028068_DB_Z_INFO2, 2);
		radeon_emit(cmd_buffer->cs, ds->db_z_info2);
		radeon_emit(cmd_buffer->cs, ds->db_stencil_info2);
	} else {
		radeon_set_context_reg(cmd_buffer->cs, R_028014_DB_HTILE_DATA_BASE, ds->db_htile_data_base);

		radeon_set_context_reg_seq(cmd_buffer->cs, R_02803C_DB_DEPTH_INFO, 9);
		radeon_emit(cmd_buffer->cs, ds->db_depth_info);	/* R_02803C_DB_DEPTH_INFO */
		radeon_emit(cmd_buffer->cs, db_z_info);			/* R_028040_DB_Z_INFO */
		radeon_emit(cmd_buffer->cs, db_stencil_info);	        /* R_028044_DB_STENCIL_INFO */
		radeon_emit(cmd_buffer->cs, ds->db_z_read_base);	/* R_028048_DB_Z_READ_BASE */
		radeon_emit(cmd_buffer->cs, ds->db_stencil_read_base);	/* R_02804C_DB_STENCIL_READ_BASE */
		radeon_emit(cmd_buffer->cs, ds->db_z_write_base);	/* R_028050_DB_Z_WRITE_BASE */
		radeon_emit(cmd_buffer->cs, ds->db_stencil_write_base);	/* R_028054_DB_STENCIL_WRITE_BASE */
		radeon_emit(cmd_buffer->cs, ds->db_depth_size);	/* R_028058_DB_DEPTH_SIZE */
		radeon_emit(cmd_buffer->cs, ds->db_depth_slice);	/* R_02805C_DB_DEPTH_SLICE */

	}

	/* Update the ZRANGE_PRECISION value for the TC-compat bug. */
	radv_update_zrange_precision(cmd_buffer, ds, image, layout, true);

	radeon_set_context_reg(cmd_buffer->cs, R_028B78_PA_SU_POLY_OFFSET_DB_FMT_CNTL,
			       ds->pa_su_poly_offset_db_fmt_cntl);
}

/**
 * Update the fast clear depth/stencil values if the image is bound as a
 * depth/stencil buffer.
 */
static void
radv_update_bound_fast_clear_ds(struct radv_cmd_buffer *cmd_buffer,
				struct radv_image *image,
				VkClearDepthStencilValue ds_clear_value,
				VkImageAspectFlags aspects)
{
	struct radv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
	const struct radv_subpass *subpass = cmd_buffer->state.subpass;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	struct radv_attachment_info *att;
	uint32_t att_idx;

	if (!framebuffer || !subpass)
		return;

	att_idx = subpass->depth_stencil_attachment.attachment;
	if (att_idx == VK_ATTACHMENT_UNUSED)
		return;

	att = &framebuffer->attachments[att_idx];
	if (att->attachment->image != image)
		return;

	radeon_set_context_reg_seq(cs, R_028028_DB_STENCIL_CLEAR, 2);
	radeon_emit(cs, ds_clear_value.stencil);
	radeon_emit(cs, fui(ds_clear_value.depth));

	/* Update the ZRANGE_PRECISION value for the TC-compat bug. This is
	 * only needed when clearing Z to 0.0.
	 */
	if ((aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
	    ds_clear_value.depth == 0.0) {
		VkImageLayout layout = subpass->depth_stencil_attachment.layout;

		radv_update_zrange_precision(cmd_buffer, &att->ds, image,
					     layout, false);
	}
}

/**
 * Set the clear depth/stencil values to the image's metadata.
 */
static void
radv_set_ds_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
			   struct radv_image *image,
			   VkClearDepthStencilValue ds_clear_value,
			   VkImageAspectFlags aspects)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint64_t va = radv_buffer_get_va(image->bo);
	unsigned reg_offset = 0, reg_count = 0;

	va += image->offset + image->clear_value_offset;

	if (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
		++reg_count;
	} else {
		++reg_offset;
		va += 4;
	}
	if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT)
		++reg_count;

	radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 2 + reg_count, 0));
	radeon_emit(cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
			S_370_WR_CONFIRM(1) |
			S_370_ENGINE_SEL(V_370_PFP));
	radeon_emit(cs, va);
	radeon_emit(cs, va >> 32);
	if (aspects & VK_IMAGE_ASPECT_STENCIL_BIT)
		radeon_emit(cs, ds_clear_value.stencil);
	if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT)
		radeon_emit(cs, fui(ds_clear_value.depth));
}

/**
 * Update the clear depth/stencil values for this image.
 */
void
radv_update_ds_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
			      struct radv_image *image,
			      VkClearDepthStencilValue ds_clear_value,
			      VkImageAspectFlags aspects)
{
	assert(radv_image_has_htile(image));

	radv_set_ds_clear_metadata(cmd_buffer, image, ds_clear_value, aspects);

	radv_update_bound_fast_clear_ds(cmd_buffer, image, ds_clear_value,
				        aspects);
}

/**
 * Load the clear depth/stencil values from the image's metadata.
 */
static void
radv_load_ds_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
			    struct radv_image *image)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	VkImageAspectFlags aspects = vk_format_aspects(image->vk_format);
	uint64_t va = radv_buffer_get_va(image->bo);
	unsigned reg_offset = 0, reg_count = 0;

	va += image->offset + image->clear_value_offset;

	if (!radv_image_has_htile(image))
		return;

	if (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
		++reg_count;
	} else {
		++reg_offset;
		va += 4;
	}
	if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT)
		++reg_count;

	radeon_emit(cs, PKT3(PKT3_COPY_DATA, 4, 0));
	radeon_emit(cs, COPY_DATA_SRC_SEL(COPY_DATA_MEM) |
			COPY_DATA_DST_SEL(COPY_DATA_REG) |
			(reg_count == 2 ? COPY_DATA_COUNT_SEL : 0));
	radeon_emit(cs, va);
	radeon_emit(cs, va >> 32);
	radeon_emit(cs, (R_028028_DB_STENCIL_CLEAR + 4 * reg_offset) >> 2);
	radeon_emit(cs, 0);

	radeon_emit(cs, PKT3(PKT3_PFP_SYNC_ME, 0, 0));
	radeon_emit(cs, 0);
}

/*
 * With DCC some colors don't require CMASK elimination before being
 * used as a texture. This sets a predicate value to determine if the
 * cmask eliminate is required.
 */
void
radv_set_dcc_need_cmask_elim_pred(struct radv_cmd_buffer *cmd_buffer,
				  struct radv_image *image,
				  bool value)
{
	uint64_t pred_val = value;
	uint64_t va = radv_buffer_get_va(image->bo);
	va += image->offset + image->dcc_pred_offset;

	assert(radv_image_has_dcc(image));

	radeon_emit(cmd_buffer->cs, PKT3(PKT3_WRITE_DATA, 4, 0));
	radeon_emit(cmd_buffer->cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
				    S_370_WR_CONFIRM(1) |
				    S_370_ENGINE_SEL(V_370_PFP));
	radeon_emit(cmd_buffer->cs, va);
	radeon_emit(cmd_buffer->cs, va >> 32);
	radeon_emit(cmd_buffer->cs, pred_val);
	radeon_emit(cmd_buffer->cs, pred_val >> 32);
}

/**
 * Update the fast clear color values if the image is bound as a color buffer.
 */
static void
radv_update_bound_fast_clear_color(struct radv_cmd_buffer *cmd_buffer,
				   struct radv_image *image,
				   int cb_idx,
				   uint32_t color_values[2])
{
	struct radv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
	const struct radv_subpass *subpass = cmd_buffer->state.subpass;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	struct radv_attachment_info *att;
	uint32_t att_idx;

	if (!framebuffer || !subpass)
		return;

	att_idx = subpass->color_attachments[cb_idx].attachment;
	if (att_idx == VK_ATTACHMENT_UNUSED)
		return;

	att = &framebuffer->attachments[att_idx];
	if (att->attachment->image != image)
		return;

	radeon_set_context_reg_seq(cs, R_028C8C_CB_COLOR0_CLEAR_WORD0 + cb_idx * 0x3c, 2);
	radeon_emit(cs, color_values[0]);
	radeon_emit(cs, color_values[1]);
}

/**
 * Set the clear color values to the image's metadata.
 */
static void
radv_set_color_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
			      struct radv_image *image,
			      uint32_t color_values[2])
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint64_t va = radv_buffer_get_va(image->bo);

	va += image->offset + image->clear_value_offset;

	assert(radv_image_has_cmask(image) || radv_image_has_dcc(image));

	radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 4, 0));
	radeon_emit(cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
			S_370_WR_CONFIRM(1) |
			S_370_ENGINE_SEL(V_370_PFP));
	radeon_emit(cs, va);
	radeon_emit(cs, va >> 32);
	radeon_emit(cs, color_values[0]);
	radeon_emit(cs, color_values[1]);
}

/**
 * Update the clear color values for this image.
 */
void
radv_update_color_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
				 struct radv_image *image,
				 int cb_idx,
				 uint32_t color_values[2])
{
	assert(radv_image_has_cmask(image) || radv_image_has_dcc(image));

	radv_set_color_clear_metadata(cmd_buffer, image, color_values);

	radv_update_bound_fast_clear_color(cmd_buffer, image, cb_idx,
					   color_values);
}

/**
 * Load the clear color values from the image's metadata.
 */
static void
radv_load_color_clear_metadata(struct radv_cmd_buffer *cmd_buffer,
			       struct radv_image *image,
			       int cb_idx)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint64_t va = radv_buffer_get_va(image->bo);

	va += image->offset + image->clear_value_offset;

	if (!radv_image_has_cmask(image) && !radv_image_has_dcc(image))
		return;

	uint32_t reg = R_028C8C_CB_COLOR0_CLEAR_WORD0 + cb_idx * 0x3c;

	radeon_emit(cs, PKT3(PKT3_COPY_DATA, 4, cmd_buffer->state.predicating));
	radeon_emit(cs, COPY_DATA_SRC_SEL(COPY_DATA_MEM) |
			COPY_DATA_DST_SEL(COPY_DATA_REG) |
			COPY_DATA_COUNT_SEL);
	radeon_emit(cs, va);
	radeon_emit(cs, va >> 32);
	radeon_emit(cs, reg >> 2);
	radeon_emit(cs, 0);

	radeon_emit(cs, PKT3(PKT3_PFP_SYNC_ME, 0, cmd_buffer->state.predicating));
	radeon_emit(cs, 0);
}

static void
radv_emit_framebuffer_state(struct radv_cmd_buffer *cmd_buffer)
{
	int i;
	struct radv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
	const struct radv_subpass *subpass = cmd_buffer->state.subpass;

	/* this may happen for inherited secondary recording */
	if (!framebuffer)
		return;

	for (i = 0; i < 8; ++i) {
		if (i >= subpass->color_count || subpass->color_attachments[i].attachment == VK_ATTACHMENT_UNUSED) {
			radeon_set_context_reg(cmd_buffer->cs, R_028C70_CB_COLOR0_INFO + i * 0x3C,
				       S_028C70_FORMAT(V_028C70_COLOR_INVALID));
			continue;
		}

		int idx = subpass->color_attachments[i].attachment;
		struct radv_attachment_info *att = &framebuffer->attachments[idx];
		struct radv_image *image = att->attachment->image;
		VkImageLayout layout = subpass->color_attachments[i].layout;

		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs, att->attachment->bo);

		assert(att->attachment->aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT);
		radv_emit_fb_color_state(cmd_buffer, i, att, image, layout);

		radv_load_color_clear_metadata(cmd_buffer, image, i);
	}

	if(subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
		int idx = subpass->depth_stencil_attachment.attachment;
		VkImageLayout layout = subpass->depth_stencil_attachment.layout;
		struct radv_attachment_info *att = &framebuffer->attachments[idx];
		struct radv_image *image = att->attachment->image;
		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs, att->attachment->bo);
		MAYBE_UNUSED uint32_t queue_mask = radv_image_queue_family_mask(image,
										cmd_buffer->queue_family_index,
										cmd_buffer->queue_family_index);
		/* We currently don't support writing decompressed HTILE */
		assert(radv_layout_has_htile(image, layout, queue_mask) ==
		       radv_layout_is_htile_compressed(image, layout, queue_mask));

		radv_emit_fb_ds_state(cmd_buffer, &att->ds, image, layout);

		if (att->ds.offset_scale != cmd_buffer->state.offset_scale) {
			cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS;
			cmd_buffer->state.offset_scale = att->ds.offset_scale;
		}
		radv_load_ds_clear_metadata(cmd_buffer, image);
	} else {
		if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9)
			radeon_set_context_reg_seq(cmd_buffer->cs, R_028038_DB_Z_INFO, 2);
		else
			radeon_set_context_reg_seq(cmd_buffer->cs, R_028040_DB_Z_INFO, 2);

		radeon_emit(cmd_buffer->cs, S_028040_FORMAT(V_028040_Z_INVALID)); /* DB_Z_INFO */
		radeon_emit(cmd_buffer->cs, S_028044_FORMAT(V_028044_STENCIL_INVALID)); /* DB_STENCIL_INFO */
	}
	radeon_set_context_reg(cmd_buffer->cs, R_028208_PA_SC_WINDOW_SCISSOR_BR,
			       S_028208_BR_X(framebuffer->width) |
			       S_028208_BR_Y(framebuffer->height));

	if (cmd_buffer->device->dfsm_allowed) {
		radeon_emit(cmd_buffer->cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
		radeon_emit(cmd_buffer->cs, EVENT_TYPE(V_028A90_BREAK_BATCH) | EVENT_INDEX(0));
	}

	cmd_buffer->state.dirty &= ~RADV_CMD_DIRTY_FRAMEBUFFER;
}

static void
radv_emit_index_buffer(struct radv_cmd_buffer *cmd_buffer)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	struct radv_cmd_state *state = &cmd_buffer->state;

	if (state->index_type != state->last_index_type) {
		if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
			radeon_set_uconfig_reg_idx(cs, R_03090C_VGT_INDEX_TYPE,
						   2, state->index_type);
		} else {
			radeon_emit(cs, PKT3(PKT3_INDEX_TYPE, 0, 0));
			radeon_emit(cs, state->index_type);
		}

		state->last_index_type = state->index_type;
	}

	radeon_emit(cs, PKT3(PKT3_INDEX_BASE, 1, 0));
	radeon_emit(cs, state->index_va);
	radeon_emit(cs, state->index_va >> 32);

	radeon_emit(cs, PKT3(PKT3_INDEX_BUFFER_SIZE, 0, 0));
	radeon_emit(cs, state->max_index_count);

	cmd_buffer->state.dirty &= ~RADV_CMD_DIRTY_INDEX_BUFFER;
}

void radv_set_db_count_control(struct radv_cmd_buffer *cmd_buffer)
{
	bool has_perfect_queries = cmd_buffer->state.perfect_occlusion_queries_enabled;
	struct radv_pipeline *pipeline = cmd_buffer->state.pipeline;
	uint32_t pa_sc_mode_cntl_1 =
		pipeline ? pipeline->graphics.ms.pa_sc_mode_cntl_1 : 0;
	uint32_t db_count_control;

	if(!cmd_buffer->state.active_occlusion_queries) {
		if (cmd_buffer->device->physical_device->rad_info.chip_class >= CIK) {
			if (G_028A4C_OUT_OF_ORDER_PRIMITIVE_ENABLE(pa_sc_mode_cntl_1) &&
			    pipeline->graphics.disable_out_of_order_rast_for_occlusion &&
			    has_perfect_queries) {
				/* Re-enable out-of-order rasterization if the
				 * bound pipeline supports it and if it's has
				 * been disabled before starting any perfect
				 * occlusion queries.
				 */
				radeon_set_context_reg(cmd_buffer->cs,
						       R_028A4C_PA_SC_MODE_CNTL_1,
						       pa_sc_mode_cntl_1);
			}
		}
		db_count_control = S_028004_ZPASS_INCREMENT_DISABLE(1);
	} else {
		const struct radv_subpass *subpass = cmd_buffer->state.subpass;
		uint32_t sample_rate = subpass ? util_logbase2(subpass->max_sample_count) : 0;

		if (cmd_buffer->device->physical_device->rad_info.chip_class >= CIK) {
			db_count_control =
				S_028004_PERFECT_ZPASS_COUNTS(has_perfect_queries) |
				S_028004_SAMPLE_RATE(sample_rate) |
				S_028004_ZPASS_ENABLE(1) |
				S_028004_SLICE_EVEN_ENABLE(1) |
				S_028004_SLICE_ODD_ENABLE(1);

			if (G_028A4C_OUT_OF_ORDER_PRIMITIVE_ENABLE(pa_sc_mode_cntl_1) &&
			    pipeline->graphics.disable_out_of_order_rast_for_occlusion &&
			    has_perfect_queries) {
				/* If the bound pipeline has enabled
				 * out-of-order rasterization, we should
				 * disable it before starting any perfect
				 * occlusion queries.
				 */
				pa_sc_mode_cntl_1 &= C_028A4C_OUT_OF_ORDER_PRIMITIVE_ENABLE;

				radeon_set_context_reg(cmd_buffer->cs,
						       R_028A4C_PA_SC_MODE_CNTL_1,
						       pa_sc_mode_cntl_1);
			}
		} else {
			db_count_control = S_028004_PERFECT_ZPASS_COUNTS(1) |
				S_028004_SAMPLE_RATE(sample_rate);
		}
	}

	radeon_set_context_reg(cmd_buffer->cs, R_028004_DB_COUNT_CONTROL, db_count_control);
}

static void
radv_cmd_buffer_flush_dynamic_state(struct radv_cmd_buffer *cmd_buffer)
{
	uint32_t states = cmd_buffer->state.dirty & cmd_buffer->state.emitted_pipeline->graphics.needed_dynamic_state;

	if (states & (RADV_CMD_DIRTY_DYNAMIC_VIEWPORT))
		radv_emit_viewport(cmd_buffer);

	if (states & (RADV_CMD_DIRTY_DYNAMIC_SCISSOR | RADV_CMD_DIRTY_DYNAMIC_VIEWPORT) &&
	    !cmd_buffer->device->physical_device->has_scissor_bug)
		radv_emit_scissor(cmd_buffer);

	if (states & RADV_CMD_DIRTY_DYNAMIC_LINE_WIDTH)
		radv_emit_line_width(cmd_buffer);

	if (states & RADV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS)
		radv_emit_blend_constants(cmd_buffer);

	if (states & (RADV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE |
				       RADV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK |
				       RADV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK))
		radv_emit_stencil(cmd_buffer);

	if (states & RADV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS)
		radv_emit_depth_bounds(cmd_buffer);

	if (states & RADV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS)
		radv_emit_depth_bias(cmd_buffer);

	if (states & RADV_CMD_DIRTY_DYNAMIC_DISCARD_RECTANGLE)
		radv_emit_discard_rectangle(cmd_buffer);

	cmd_buffer->state.dirty &= ~states;
}

static void
radv_flush_push_descriptors(struct radv_cmd_buffer *cmd_buffer,
			    VkPipelineBindPoint bind_point)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	struct radv_descriptor_set *set = &descriptors_state->push_set.set;
	unsigned bo_offset;

	if (!radv_cmd_buffer_upload_data(cmd_buffer, set->size, 32,
					 set->mapped_ptr,
					 &bo_offset))
		return;

	set->va = radv_buffer_get_va(cmd_buffer->upload.upload_bo);
	set->va += bo_offset;
}

static void
radv_flush_indirect_descriptor_sets(struct radv_cmd_buffer *cmd_buffer,
				    VkPipelineBindPoint bind_point)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	uint8_t ptr_size = HAVE_32BIT_POINTERS ? 1 : 2;
	uint32_t size = MAX_SETS * 4 * ptr_size;
	uint32_t offset;
	void *ptr;
	
	if (!radv_cmd_buffer_upload_alloc(cmd_buffer, size,
					  256, &offset, &ptr))
		return;

	for (unsigned i = 0; i < MAX_SETS; i++) {
		uint32_t *uptr = ((uint32_t *)ptr) + i * ptr_size;
		uint64_t set_va = 0;
		struct radv_descriptor_set *set = descriptors_state->sets[i];
		if (descriptors_state->valid & (1u << i))
			set_va = set->va;
		uptr[0] = set_va & 0xffffffff;
		if (ptr_size == 2)
			uptr[1] = set_va >> 32;
	}

	uint64_t va = radv_buffer_get_va(cmd_buffer->upload.upload_bo);
	va += offset;

	if (cmd_buffer->state.pipeline) {
		if (cmd_buffer->state.pipeline->shaders[MESA_SHADER_VERTEX])
			radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_VERTEX,
						   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);

		if (cmd_buffer->state.pipeline->shaders[MESA_SHADER_FRAGMENT])
			radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_FRAGMENT,
						   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);

		if (radv_pipeline_has_gs(cmd_buffer->state.pipeline))
			radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_GEOMETRY,
						   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);

		if (radv_pipeline_has_tess(cmd_buffer->state.pipeline))
			radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_TESS_CTRL,
						   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);

		if (radv_pipeline_has_tess(cmd_buffer->state.pipeline))
			radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_TESS_EVAL,
						   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);
	}

	if (cmd_buffer->state.compute_pipeline)
		radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.compute_pipeline, MESA_SHADER_COMPUTE,
					   AC_UD_INDIRECT_DESCRIPTOR_SETS, va);
}

static void
radv_flush_descriptors(struct radv_cmd_buffer *cmd_buffer,
		       VkShaderStageFlags stages)
{
	VkPipelineBindPoint bind_point = stages & VK_SHADER_STAGE_COMPUTE_BIT ?
					 VK_PIPELINE_BIND_POINT_COMPUTE :
					 VK_PIPELINE_BIND_POINT_GRAPHICS;
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	struct radv_cmd_state *state = &cmd_buffer->state;
	bool flush_indirect_descriptors;

	if (!descriptors_state->dirty)
		return;

	if (descriptors_state->push_dirty)
		radv_flush_push_descriptors(cmd_buffer, bind_point);

	flush_indirect_descriptors =
		(bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS &&
		 state->pipeline && state->pipeline->need_indirect_descriptor_sets) ||
		(bind_point == VK_PIPELINE_BIND_POINT_COMPUTE &&
		 state->compute_pipeline && state->compute_pipeline->need_indirect_descriptor_sets);

	if (flush_indirect_descriptors)
		radv_flush_indirect_descriptor_sets(cmd_buffer, bind_point);

	MAYBE_UNUSED unsigned cdw_max = radeon_check_space(cmd_buffer->device->ws,
	                                                   cmd_buffer->cs,
	                                                   MAX_SETS * MESA_SHADER_STAGES * 4);

	if (cmd_buffer->state.pipeline) {
		radv_foreach_stage(stage, stages) {
			if (!cmd_buffer->state.pipeline->shaders[stage])
				continue;

			radv_emit_descriptor_pointers(cmd_buffer,
						      cmd_buffer->state.pipeline,
						      descriptors_state, stage);
		}
	}

	if (cmd_buffer->state.compute_pipeline &&
	    (stages & VK_SHADER_STAGE_COMPUTE_BIT)) {
		radv_emit_descriptor_pointers(cmd_buffer,
					      cmd_buffer->state.compute_pipeline,
					      descriptors_state,
					      MESA_SHADER_COMPUTE);
	}

	descriptors_state->dirty = 0;
	descriptors_state->push_dirty = false;

	assert(cmd_buffer->cs->cdw <= cdw_max);

	if (unlikely(cmd_buffer->device->trace_bo))
		radv_save_descriptors(cmd_buffer, bind_point);
}

static void
radv_flush_constants(struct radv_cmd_buffer *cmd_buffer,
		     VkShaderStageFlags stages)
{
	struct radv_pipeline *pipeline = stages & VK_SHADER_STAGE_COMPUTE_BIT
					 ? cmd_buffer->state.compute_pipeline
					 : cmd_buffer->state.pipeline;
	VkPipelineBindPoint bind_point = stages & VK_SHADER_STAGE_COMPUTE_BIT ?
					 VK_PIPELINE_BIND_POINT_COMPUTE :
					 VK_PIPELINE_BIND_POINT_GRAPHICS;
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	struct radv_pipeline_layout *layout = pipeline->layout;
	struct radv_shader_variant *shader, *prev_shader;
	unsigned offset;
	void *ptr;
	uint64_t va;

	stages &= cmd_buffer->push_constant_stages;
	if (!stages ||
	    (!layout->push_constant_size && !layout->dynamic_offset_count))
		return;

	if (!radv_cmd_buffer_upload_alloc(cmd_buffer, layout->push_constant_size +
					  16 * layout->dynamic_offset_count,
					  256, &offset, &ptr))
		return;

	memcpy(ptr, cmd_buffer->push_constants, layout->push_constant_size);
	memcpy((char*)ptr + layout->push_constant_size,
	       descriptors_state->dynamic_buffers,
	       16 * layout->dynamic_offset_count);

	va = radv_buffer_get_va(cmd_buffer->upload.upload_bo);
	va += offset;

	MAYBE_UNUSED unsigned cdw_max = radeon_check_space(cmd_buffer->device->ws,
	                                                   cmd_buffer->cs, MESA_SHADER_STAGES * 4);

	prev_shader = NULL;
	radv_foreach_stage(stage, stages) {
		shader = radv_get_shader(pipeline, stage);

		/* Avoid redundantly emitting the address for merged stages. */
		if (shader && shader != prev_shader) {
			radv_emit_userdata_address(cmd_buffer, pipeline, stage,
						   AC_UD_PUSH_CONSTANTS, va);

			prev_shader = shader;
		}
	}

	cmd_buffer->push_constant_stages &= ~stages;
	assert(cmd_buffer->cs->cdw <= cdw_max);
}

static void
radv_flush_vertex_descriptors(struct radv_cmd_buffer *cmd_buffer,
			      bool pipeline_is_dirty)
{
	if ((pipeline_is_dirty ||
	    (cmd_buffer->state.dirty & RADV_CMD_DIRTY_VERTEX_BUFFER)) &&
	    cmd_buffer->state.pipeline->vertex_elements.count &&
	    radv_get_shader(cmd_buffer->state.pipeline, MESA_SHADER_VERTEX)->info.info.vs.has_vertex_buffers) {
		struct radv_vertex_elements_info *velems = &cmd_buffer->state.pipeline->vertex_elements;
		unsigned vb_offset;
		void *vb_ptr;
		uint32_t i = 0;
		uint32_t count = velems->count;
		uint64_t va;

		/* allocate some descriptor state for vertex buffers */
		if (!radv_cmd_buffer_upload_alloc(cmd_buffer, count * 16, 256,
						  &vb_offset, &vb_ptr))
			return;

		for (i = 0; i < count; i++) {
			uint32_t *desc = &((uint32_t *)vb_ptr)[i * 4];
			uint32_t offset;
			int vb = velems->binding[i];
			struct radv_buffer *buffer = cmd_buffer->vertex_bindings[vb].buffer;
			uint32_t stride = cmd_buffer->state.pipeline->binding_stride[vb];

			va = radv_buffer_get_va(buffer->bo);

			offset = cmd_buffer->vertex_bindings[vb].offset + velems->offset[i];
			va += offset + buffer->offset;
			desc[0] = va;
			desc[1] = S_008F04_BASE_ADDRESS_HI(va >> 32) | S_008F04_STRIDE(stride);
			if (cmd_buffer->device->physical_device->rad_info.chip_class <= CIK && stride)
				desc[2] = (buffer->size - offset - velems->format_size[i]) / stride + 1;
			else
				desc[2] = buffer->size - offset;
			desc[3] = velems->rsrc_word3[i];
		}

		va = radv_buffer_get_va(cmd_buffer->upload.upload_bo);
		va += vb_offset;

		radv_emit_userdata_address(cmd_buffer, cmd_buffer->state.pipeline, MESA_SHADER_VERTEX,
					   AC_UD_VS_VERTEX_BUFFERS, va);

		cmd_buffer->state.vb_va = va;
		cmd_buffer->state.vb_size = count * 16;
		cmd_buffer->state.prefetch_L2_mask |= RADV_PREFETCH_VBO_DESCRIPTORS;
	}
	cmd_buffer->state.dirty &= ~RADV_CMD_DIRTY_VERTEX_BUFFER;
}

static void
radv_upload_graphics_shader_descriptors(struct radv_cmd_buffer *cmd_buffer, bool pipeline_is_dirty)
{
	radv_flush_vertex_descriptors(cmd_buffer, pipeline_is_dirty);
	radv_flush_descriptors(cmd_buffer, VK_SHADER_STAGE_ALL_GRAPHICS);
	radv_flush_constants(cmd_buffer, VK_SHADER_STAGE_ALL_GRAPHICS);
}

static void
radv_emit_draw_registers(struct radv_cmd_buffer *cmd_buffer, bool indexed_draw,
			 bool instanced_draw, bool indirect_draw,
			 uint32_t draw_vertex_count)
{
	struct radeon_info *info = &cmd_buffer->device->physical_device->rad_info;
	struct radv_cmd_state *state = &cmd_buffer->state;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint32_t ia_multi_vgt_param;
	int32_t primitive_reset_en;

	/* Draw state. */
	ia_multi_vgt_param =
		si_get_ia_multi_vgt_param(cmd_buffer, instanced_draw,
					  indirect_draw, draw_vertex_count);

	if (state->last_ia_multi_vgt_param != ia_multi_vgt_param) {
		if (info->chip_class >= GFX9) {
			radeon_set_uconfig_reg_idx(cs,
						   R_030960_IA_MULTI_VGT_PARAM,
						   4, ia_multi_vgt_param);
		} else if (info->chip_class >= CIK) {
			radeon_set_context_reg_idx(cs,
						   R_028AA8_IA_MULTI_VGT_PARAM,
						   1, ia_multi_vgt_param);
		} else {
			radeon_set_context_reg(cs, R_028AA8_IA_MULTI_VGT_PARAM,
					       ia_multi_vgt_param);
		}
		state->last_ia_multi_vgt_param = ia_multi_vgt_param;
	}

	/* Primitive restart. */
	primitive_reset_en =
		indexed_draw && state->pipeline->graphics.prim_restart_enable;

	if (primitive_reset_en != state->last_primitive_reset_en) {
		state->last_primitive_reset_en = primitive_reset_en;
		if (info->chip_class >= GFX9) {
			radeon_set_uconfig_reg(cs,
					       R_03092C_VGT_MULTI_PRIM_IB_RESET_EN,
					       primitive_reset_en);
		} else {
			radeon_set_context_reg(cs,
					       R_028A94_VGT_MULTI_PRIM_IB_RESET_EN,
					       primitive_reset_en);
		}
	}

	if (primitive_reset_en) {
		uint32_t primitive_reset_index =
			state->index_type ? 0xffffffffu : 0xffffu;

		if (primitive_reset_index != state->last_primitive_reset_index) {
			radeon_set_context_reg(cs,
					       R_02840C_VGT_MULTI_PRIM_IB_RESET_INDX,
					       primitive_reset_index);
			state->last_primitive_reset_index = primitive_reset_index;
		}
	}
}

static void radv_stage_flush(struct radv_cmd_buffer *cmd_buffer,
			     VkPipelineStageFlags src_stage_mask)
{
	if (src_stage_mask & (VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT |
	                      VK_PIPELINE_STAGE_TRANSFER_BIT |
	                      VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT |
	                      VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)) {
		cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_CS_PARTIAL_FLUSH;
	}

	if (src_stage_mask & (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
			      VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
			      VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT |
			      VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
			      VK_PIPELINE_STAGE_TRANSFER_BIT |
			      VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT |
			      VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT |
			      VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)) {
		cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_PS_PARTIAL_FLUSH;
	} else if (src_stage_mask & (VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT |
	                             VK_PIPELINE_STAGE_VERTEX_INPUT_BIT |
	                             VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
				     VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
				     VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
				     VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
		cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_VS_PARTIAL_FLUSH;
	}
}

static enum radv_cmd_flush_bits
radv_src_access_flush(struct radv_cmd_buffer *cmd_buffer,
		      VkAccessFlags src_flags,
		      struct radv_image *image)
{
	bool flush_CB_meta = true, flush_DB_meta = true;
	enum radv_cmd_flush_bits flush_bits = 0;
	uint32_t b;

	if (image) {
		if (!radv_image_has_CB_metadata(image))
			flush_CB_meta = false;
		if (!radv_image_has_htile(image))
			flush_DB_meta = false;
	}

	for_each_bit(b, src_flags) {
		switch ((VkAccessFlagBits)(1 << b)) {
		case VK_ACCESS_SHADER_WRITE_BIT:
			flush_bits |= RADV_CMD_FLAG_WRITEBACK_GLOBAL_L2;
			break;
		case VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT:
			flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB;
			if (flush_CB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;
			break;
		case VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT:
			flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB;
			if (flush_DB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;
			break;
		case VK_ACCESS_TRANSFER_WRITE_BIT:
			flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB |
			              RADV_CMD_FLAG_FLUSH_AND_INV_DB |
			              RADV_CMD_FLAG_INV_GLOBAL_L2;

			if (flush_CB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;
			if (flush_DB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;
			break;
		default:
			break;
		}
	}
	return flush_bits;
}

static enum radv_cmd_flush_bits
radv_dst_access_flush(struct radv_cmd_buffer *cmd_buffer,
                      VkAccessFlags dst_flags,
                      struct radv_image *image)
{
	bool flush_CB_meta = true, flush_DB_meta = true;
	enum radv_cmd_flush_bits flush_bits = 0;
	bool flush_CB = true, flush_DB = true;
	bool image_is_coherent = false;
	uint32_t b;

	if (image) {
		if (!(image->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
			flush_CB = false;
			flush_DB = false;
		}

		if (!radv_image_has_CB_metadata(image))
			flush_CB_meta = false;
		if (!radv_image_has_htile(image))
			flush_DB_meta = false;

		if (cmd_buffer->device->physical_device->rad_info.chip_class >= GFX9) {
			if (image->info.samples == 1 &&
			    (image->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
					     VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
			    !vk_format_is_stencil(image->vk_format)) {
				/* Single-sample color and single-sample depth
				 * (not stencil) are coherent with shaders on
				 * GFX9.
				 */
				image_is_coherent = true;
			}
		}
	}

	for_each_bit(b, dst_flags) {
		switch ((VkAccessFlagBits)(1 << b)) {
		case VK_ACCESS_INDIRECT_COMMAND_READ_BIT:
		case VK_ACCESS_INDEX_READ_BIT:
			break;
		case VK_ACCESS_UNIFORM_READ_BIT:
			flush_bits |= RADV_CMD_FLAG_INV_VMEM_L1 | RADV_CMD_FLAG_INV_SMEM_L1;
			break;
		case VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT:
		case VK_ACCESS_TRANSFER_READ_BIT:
		case VK_ACCESS_INPUT_ATTACHMENT_READ_BIT:
			flush_bits |= RADV_CMD_FLAG_INV_VMEM_L1 |
			              RADV_CMD_FLAG_INV_GLOBAL_L2;
			break;
		case VK_ACCESS_SHADER_READ_BIT:
			flush_bits |= RADV_CMD_FLAG_INV_VMEM_L1;

			if (!image_is_coherent)
				flush_bits |= RADV_CMD_FLAG_INV_GLOBAL_L2;
			break;
		case VK_ACCESS_COLOR_ATTACHMENT_READ_BIT:
			if (flush_CB)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB;
			if (flush_CB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;
			break;
		case VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT:
			if (flush_DB)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB;
			if (flush_DB_meta)
				flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;
			break;
		default:
			break;
		}
	}
	return flush_bits;
}

void radv_subpass_barrier(struct radv_cmd_buffer *cmd_buffer,
			  const struct radv_subpass_barrier *barrier)
{
	cmd_buffer->state.flush_bits |= radv_src_access_flush(cmd_buffer, barrier->src_access_mask,
							      NULL);
	radv_stage_flush(cmd_buffer, barrier->src_stage_mask);
	cmd_buffer->state.flush_bits |= radv_dst_access_flush(cmd_buffer, barrier->dst_access_mask,
	                                                      NULL);
}

static void radv_handle_subpass_image_transition(struct radv_cmd_buffer *cmd_buffer,
						 struct radv_subpass_attachment att)
{
	unsigned idx = att.attachment;
	struct radv_image_view *view = cmd_buffer->state.framebuffer->attachments[idx].attachment;
	VkImageSubresourceRange range;
	range.aspectMask = 0;
	range.baseMipLevel = view->base_mip;
	range.levelCount = 1;
	range.baseArrayLayer = view->base_layer;
	range.layerCount = cmd_buffer->state.framebuffer->layers;

	radv_handle_image_transition(cmd_buffer,
				     view->image,
				     cmd_buffer->state.attachments[idx].current_layout,
				     att.layout, 0, 0, &range,
				     cmd_buffer->state.attachments[idx].pending_clear_aspects);

	cmd_buffer->state.attachments[idx].current_layout = att.layout;


}

void
radv_cmd_buffer_set_subpass(struct radv_cmd_buffer *cmd_buffer,
			    const struct radv_subpass *subpass, bool transitions)
{
	if (transitions) {
		radv_subpass_barrier(cmd_buffer, &subpass->start_barrier);

		for (unsigned i = 0; i < subpass->color_count; ++i) {
			if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED)
				radv_handle_subpass_image_transition(cmd_buffer,
				                                     subpass->color_attachments[i]);
		}

		for (unsigned i = 0; i < subpass->input_count; ++i) {
			radv_handle_subpass_image_transition(cmd_buffer,
							subpass->input_attachments[i]);
		}

		if (subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
			radv_handle_subpass_image_transition(cmd_buffer,
							subpass->depth_stencil_attachment);
		}
	}

	cmd_buffer->state.subpass = subpass;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_FRAMEBUFFER;
}

static VkResult
radv_cmd_state_setup_attachments(struct radv_cmd_buffer *cmd_buffer,
				 struct radv_render_pass *pass,
				 const VkRenderPassBeginInfo *info)
{
	struct radv_cmd_state *state = &cmd_buffer->state;

	if (pass->attachment_count == 0) {
		state->attachments = NULL;
		return VK_SUCCESS;
	}

	state->attachments = vk_alloc(&cmd_buffer->pool->alloc,
					pass->attachment_count *
					sizeof(state->attachments[0]),
					8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
	if (state->attachments == NULL) {
		cmd_buffer->record_result = VK_ERROR_OUT_OF_HOST_MEMORY;
		return cmd_buffer->record_result;
	}

	for (uint32_t i = 0; i < pass->attachment_count; ++i) {
		struct radv_render_pass_attachment *att = &pass->attachments[i];
		VkImageAspectFlags att_aspects = vk_format_aspects(att->format);
		VkImageAspectFlags clear_aspects = 0;

		if (att_aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
			/* color attachment */
			if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
				clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
			}
		} else {
			/* depthstencil attachment */
			if ((att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
			    att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
				clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
				if ((att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
				    att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE)
					clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
			}
			if ((att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
			    att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
				clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
			}
		}

		state->attachments[i].pending_clear_aspects = clear_aspects;
		state->attachments[i].cleared_views = 0;
		if (clear_aspects && info) {
			assert(info->clearValueCount > i);
			state->attachments[i].clear_value = info->pClearValues[i];
		}

		state->attachments[i].current_layout = att->initial_layout;
	}

	return VK_SUCCESS;
}

VkResult radv_AllocateCommandBuffers(
	VkDevice _device,
	const VkCommandBufferAllocateInfo *pAllocateInfo,
	VkCommandBuffer *pCommandBuffers)
{
	RADV_FROM_HANDLE(radv_device, device, _device);
	RADV_FROM_HANDLE(radv_cmd_pool, pool, pAllocateInfo->commandPool);

	VkResult result = VK_SUCCESS;
	uint32_t i;

	for (i = 0; i < pAllocateInfo->commandBufferCount; i++) {

		if (!list_empty(&pool->free_cmd_buffers)) {
			struct radv_cmd_buffer *cmd_buffer = list_first_entry(&pool->free_cmd_buffers, struct radv_cmd_buffer, pool_link);

			list_del(&cmd_buffer->pool_link);
			list_addtail(&cmd_buffer->pool_link, &pool->cmd_buffers);

			result = radv_reset_cmd_buffer(cmd_buffer);
			cmd_buffer->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
			cmd_buffer->level = pAllocateInfo->level;

			pCommandBuffers[i] = radv_cmd_buffer_to_handle(cmd_buffer);
		} else {
			result = radv_create_cmd_buffer(device, pool, pAllocateInfo->level,
			                                &pCommandBuffers[i]);
		}
		if (result != VK_SUCCESS)
			break;
	}

	if (result != VK_SUCCESS) {
		radv_FreeCommandBuffers(_device, pAllocateInfo->commandPool,
					i, pCommandBuffers);

		/* From the Vulkan 1.0.66 spec:
		 *
		 * "vkAllocateCommandBuffers can be used to create multiple
		 *  command buffers. If the creation of any of those command
		 *  buffers fails, the implementation must destroy all
		 *  successfully created command buffer objects from this
		 *  command, set all entries of the pCommandBuffers array to
		 *  NULL and return the error."
		 */
		memset(pCommandBuffers, 0,
		       sizeof(*pCommandBuffers) * pAllocateInfo->commandBufferCount);
	}

	return result;
}

void radv_FreeCommandBuffers(
	VkDevice device,
	VkCommandPool commandPool,
	uint32_t commandBufferCount,
	const VkCommandBuffer *pCommandBuffers)
{
	for (uint32_t i = 0; i < commandBufferCount; i++) {
		RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, pCommandBuffers[i]);

		if (cmd_buffer) {
			if (cmd_buffer->pool) {
				list_del(&cmd_buffer->pool_link);
				list_addtail(&cmd_buffer->pool_link, &cmd_buffer->pool->free_cmd_buffers);
			} else
				radv_cmd_buffer_destroy(cmd_buffer);

		}
	}
}

VkResult radv_ResetCommandBuffer(
	VkCommandBuffer commandBuffer,
	VkCommandBufferResetFlags flags)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	return radv_reset_cmd_buffer(cmd_buffer);
}

VkResult radv_BeginCommandBuffer(
	VkCommandBuffer commandBuffer,
	const VkCommandBufferBeginInfo *pBeginInfo)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	VkResult result = VK_SUCCESS;

	if (cmd_buffer->status != RADV_CMD_BUFFER_STATUS_INITIAL) {
		/* If the command buffer has already been resetted with
		 * vkResetCommandBuffer, no need to do it again.
		 */
		result = radv_reset_cmd_buffer(cmd_buffer);
		if (result != VK_SUCCESS)
			return result;
	}

	memset(&cmd_buffer->state, 0, sizeof(cmd_buffer->state));
	cmd_buffer->state.last_primitive_reset_en = -1;
	cmd_buffer->state.last_index_type = -1;
	cmd_buffer->state.last_num_instances = -1;
	cmd_buffer->state.last_vertex_offset = -1;
	cmd_buffer->state.last_first_instance = -1;
	cmd_buffer->state.predication_type = -1;
	cmd_buffer->usage_flags = pBeginInfo->flags;

	if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY &&
	    (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) {
		assert(pBeginInfo->pInheritanceInfo);
		cmd_buffer->state.framebuffer = radv_framebuffer_from_handle(pBeginInfo->pInheritanceInfo->framebuffer);
		cmd_buffer->state.pass = radv_render_pass_from_handle(pBeginInfo->pInheritanceInfo->renderPass);

		struct radv_subpass *subpass =
			&cmd_buffer->state.pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];

		result = radv_cmd_state_setup_attachments(cmd_buffer, cmd_buffer->state.pass, NULL);
		if (result != VK_SUCCESS)
			return result;

		radv_cmd_buffer_set_subpass(cmd_buffer, subpass, false);
	}

	if (unlikely(cmd_buffer->device->trace_bo)) {
		struct radv_device *device = cmd_buffer->device;

		radv_cs_add_buffer(device->ws, cmd_buffer->cs,
				   device->trace_bo);

		radv_cmd_buffer_trace_emit(cmd_buffer);
	}

	cmd_buffer->status = RADV_CMD_BUFFER_STATUS_RECORDING;

	return result;
}

void radv_CmdBindVertexBuffers(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    firstBinding,
	uint32_t                                    bindingCount,
	const VkBuffer*                             pBuffers,
	const VkDeviceSize*                         pOffsets)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_vertex_binding *vb = cmd_buffer->vertex_bindings;
	bool changed = false;

	/* We have to defer setting up vertex buffer since we need the buffer
	 * stride from the pipeline. */

	assert(firstBinding + bindingCount <= MAX_VBS);
	for (uint32_t i = 0; i < bindingCount; i++) {
		uint32_t idx = firstBinding + i;

		if (!changed &&
		    (vb[idx].buffer != radv_buffer_from_handle(pBuffers[i]) ||
		     vb[idx].offset != pOffsets[i])) {
			changed = true;
		}

		vb[idx].buffer = radv_buffer_from_handle(pBuffers[i]);
		vb[idx].offset = pOffsets[i];

		radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs,
				   vb[idx].buffer->bo);
	}

	if (!changed) {
		/* No state changes. */
		return;
	}

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_VERTEX_BUFFER;
}

void radv_CmdBindIndexBuffer(
	VkCommandBuffer                             commandBuffer,
	VkBuffer buffer,
	VkDeviceSize offset,
	VkIndexType indexType)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, index_buffer, buffer);

	if (cmd_buffer->state.index_buffer == index_buffer &&
	    cmd_buffer->state.index_offset == offset &&
	    cmd_buffer->state.index_type == indexType) {
		/* No state changes. */
		return;
	}

	cmd_buffer->state.index_buffer = index_buffer;
	cmd_buffer->state.index_offset = offset;
	cmd_buffer->state.index_type = indexType; /* vk matches hw */
	cmd_buffer->state.index_va = radv_buffer_get_va(index_buffer->bo);
	cmd_buffer->state.index_va += index_buffer->offset + offset;

	int index_size_shift = cmd_buffer->state.index_type ? 2 : 1;
	cmd_buffer->state.max_index_count = (index_buffer->size - offset) >> index_size_shift;
	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_INDEX_BUFFER;
	radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs, index_buffer->bo);
}


static void
radv_bind_descriptor_set(struct radv_cmd_buffer *cmd_buffer,
			 VkPipelineBindPoint bind_point,
			 struct radv_descriptor_set *set, unsigned idx)
{
	struct radeon_winsys *ws = cmd_buffer->device->ws;

	radv_set_descriptor_set(cmd_buffer, bind_point, set, idx);

	assert(set);
	assert(!(set->layout->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR));

	if (!cmd_buffer->device->use_global_bo_list) {
		for (unsigned j = 0; j < set->layout->buffer_count; ++j)
			if (set->descriptors[j])
				radv_cs_add_buffer(ws, cmd_buffer->cs, set->descriptors[j]);
	}

	if(set->bo)
		radv_cs_add_buffer(ws, cmd_buffer->cs, set->bo);
}

void radv_CmdBindDescriptorSets(
	VkCommandBuffer                             commandBuffer,
	VkPipelineBindPoint                         pipelineBindPoint,
	VkPipelineLayout                            _layout,
	uint32_t                                    firstSet,
	uint32_t                                    descriptorSetCount,
	const VkDescriptorSet*                      pDescriptorSets,
	uint32_t                                    dynamicOffsetCount,
	const uint32_t*                             pDynamicOffsets)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_pipeline_layout, layout, _layout);
	unsigned dyn_idx = 0;

	const bool no_dynamic_bounds = cmd_buffer->device->instance->debug_flags & RADV_DEBUG_NO_DYNAMIC_BOUNDS;
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, pipelineBindPoint);

	for (unsigned i = 0; i < descriptorSetCount; ++i) {
		unsigned idx = i + firstSet;
		RADV_FROM_HANDLE(radv_descriptor_set, set, pDescriptorSets[i]);

		/* If the set is already bound we only need to update the
		 * (potentially changed) dynamic offsets. */
		if (descriptors_state->sets[idx] != set ||
		    !(descriptors_state->valid & (1u << idx))) {
			radv_bind_descriptor_set(cmd_buffer, pipelineBindPoint, set, idx);
		}

		for(unsigned j = 0; j < set->layout->dynamic_offset_count; ++j, ++dyn_idx) {
			unsigned idx = j + layout->set[i + firstSet].dynamic_offset_start;
			uint32_t *dst = descriptors_state->dynamic_buffers + idx * 4;
			assert(dyn_idx < dynamicOffsetCount);

			struct radv_descriptor_range *range = set->dynamic_descriptors + j;
			uint64_t va = range->va + pDynamicOffsets[dyn_idx];
			dst[0] = va;
			dst[1] = S_008F04_BASE_ADDRESS_HI(va >> 32);
			dst[2] = no_dynamic_bounds ? 0xffffffffu : range->size;
			dst[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
			         S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
			         S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
			         S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
			         S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
			         S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
			cmd_buffer->push_constant_stages |=
			                     set->layout->dynamic_shader_stages;
		}
	}
}

static bool radv_init_push_descriptor_set(struct radv_cmd_buffer *cmd_buffer,
                                          struct radv_descriptor_set *set,
                                          struct radv_descriptor_set_layout *layout,
					  VkPipelineBindPoint bind_point)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);
	set->size = layout->size;
	set->layout = layout;

	if (descriptors_state->push_set.capacity < set->size) {
		size_t new_size = MAX2(set->size, 1024);
		new_size = MAX2(new_size, 2 * descriptors_state->push_set.capacity);
		new_size = MIN2(new_size, 96 * MAX_PUSH_DESCRIPTORS);

		free(set->mapped_ptr);
		set->mapped_ptr = malloc(new_size);

		if (!set->mapped_ptr) {
			descriptors_state->push_set.capacity = 0;
			cmd_buffer->record_result = VK_ERROR_OUT_OF_HOST_MEMORY;
			return false;
		}

		descriptors_state->push_set.capacity = new_size;
	}

	return true;
}

void radv_meta_push_descriptor_set(
	struct radv_cmd_buffer*              cmd_buffer,
	VkPipelineBindPoint                  pipelineBindPoint,
	VkPipelineLayout                     _layout,
	uint32_t                             set,
	uint32_t                             descriptorWriteCount,
	const VkWriteDescriptorSet*          pDescriptorWrites)
{
	RADV_FROM_HANDLE(radv_pipeline_layout, layout, _layout);
	struct radv_descriptor_set *push_set = &cmd_buffer->meta_push_descriptors;
	unsigned bo_offset;

	assert(set == 0);
	assert(layout->set[set].layout->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR);

	push_set->size = layout->set[set].layout->size;
	push_set->layout = layout->set[set].layout;

	if (!radv_cmd_buffer_upload_alloc(cmd_buffer, push_set->size, 32,
	                                  &bo_offset,
	                                  (void**) &push_set->mapped_ptr))
		return;

	push_set->va = radv_buffer_get_va(cmd_buffer->upload.upload_bo);
	push_set->va += bo_offset;

	radv_update_descriptor_sets(cmd_buffer->device, cmd_buffer,
	                            radv_descriptor_set_to_handle(push_set),
	                            descriptorWriteCount, pDescriptorWrites, 0, NULL);

	radv_set_descriptor_set(cmd_buffer, pipelineBindPoint, push_set, set);
}

void radv_CmdPushDescriptorSetKHR(
	VkCommandBuffer                             commandBuffer,
	VkPipelineBindPoint                         pipelineBindPoint,
	VkPipelineLayout                            _layout,
	uint32_t                                    set,
	uint32_t                                    descriptorWriteCount,
	const VkWriteDescriptorSet*                 pDescriptorWrites)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_pipeline_layout, layout, _layout);
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, pipelineBindPoint);
	struct radv_descriptor_set *push_set = &descriptors_state->push_set.set;

	assert(layout->set[set].layout->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR);

	if (!radv_init_push_descriptor_set(cmd_buffer, push_set,
					   layout->set[set].layout,
					   pipelineBindPoint))
		return;

	radv_update_descriptor_sets(cmd_buffer->device, cmd_buffer,
	                            radv_descriptor_set_to_handle(push_set),
	                            descriptorWriteCount, pDescriptorWrites, 0, NULL);

	radv_set_descriptor_set(cmd_buffer, pipelineBindPoint, push_set, set);
	descriptors_state->push_dirty = true;
}

void radv_CmdPushDescriptorSetWithTemplateKHR(
	VkCommandBuffer                             commandBuffer,
	VkDescriptorUpdateTemplateKHR               descriptorUpdateTemplate,
	VkPipelineLayout                            _layout,
	uint32_t                                    set,
	const void*                                 pData)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_pipeline_layout, layout, _layout);
	RADV_FROM_HANDLE(radv_descriptor_update_template, templ, descriptorUpdateTemplate);
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, templ->bind_point);
	struct radv_descriptor_set *push_set = &descriptors_state->push_set.set;

	assert(layout->set[set].layout->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR);

	if (!radv_init_push_descriptor_set(cmd_buffer, push_set,
					   layout->set[set].layout,
					   templ->bind_point))
		return;

	radv_update_descriptor_set_with_template(cmd_buffer->device, cmd_buffer, push_set,
						 descriptorUpdateTemplate, pData);

	radv_set_descriptor_set(cmd_buffer, templ->bind_point, push_set, set);
	descriptors_state->push_dirty = true;
}

void radv_CmdPushConstants(VkCommandBuffer commandBuffer,
			   VkPipelineLayout layout,
			   VkShaderStageFlags stageFlags,
			   uint32_t offset,
			   uint32_t size,
			   const void* pValues)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	memcpy(cmd_buffer->push_constants + offset, pValues, size);
	cmd_buffer->push_constant_stages |= stageFlags;
}

VkResult radv_EndCommandBuffer(
	VkCommandBuffer                             commandBuffer)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	if (cmd_buffer->queue_family_index != RADV_QUEUE_TRANSFER) {
		if (cmd_buffer->device->physical_device->rad_info.chip_class == SI)
			cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_CS_PARTIAL_FLUSH | RADV_CMD_FLAG_PS_PARTIAL_FLUSH | RADV_CMD_FLAG_WRITEBACK_GLOBAL_L2;
		si_emit_cache_flush(cmd_buffer);
	}

	/* Make sure CP DMA is idle at the end of IBs because the kernel
	 * doesn't wait for it.
	 */
	si_cp_dma_wait_for_idle(cmd_buffer);

	vk_free(&cmd_buffer->pool->alloc, cmd_buffer->state.attachments);

	if (!cmd_buffer->device->ws->cs_finalize(cmd_buffer->cs))
		return vk_error(cmd_buffer->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);

	cmd_buffer->status = RADV_CMD_BUFFER_STATUS_EXECUTABLE;

	return cmd_buffer->record_result;
}

static void
radv_emit_compute_pipeline(struct radv_cmd_buffer *cmd_buffer)
{
	struct radv_pipeline *pipeline = cmd_buffer->state.compute_pipeline;

	if (!pipeline || pipeline == cmd_buffer->state.emitted_compute_pipeline)
		return;

	cmd_buffer->state.emitted_compute_pipeline = pipeline;

	radeon_check_space(cmd_buffer->device->ws, cmd_buffer->cs, pipeline->cs.cdw);
	radeon_emit_array(cmd_buffer->cs, pipeline->cs.buf, pipeline->cs.cdw);

	cmd_buffer->compute_scratch_size_needed =
	                          MAX2(cmd_buffer->compute_scratch_size_needed,
	                               pipeline->max_waves * pipeline->scratch_bytes_per_wave);

	radv_cs_add_buffer(cmd_buffer->device->ws, cmd_buffer->cs,
			   pipeline->shaders[MESA_SHADER_COMPUTE]->bo);

	if (unlikely(cmd_buffer->device->trace_bo))
		radv_save_pipeline(cmd_buffer, pipeline, RING_COMPUTE);
}

static void radv_mark_descriptor_sets_dirty(struct radv_cmd_buffer *cmd_buffer,
					    VkPipelineBindPoint bind_point)
{
	struct radv_descriptor_state *descriptors_state =
		radv_get_descriptors_state(cmd_buffer, bind_point);

	descriptors_state->dirty |= descriptors_state->valid;
}

void radv_CmdBindPipeline(
	VkCommandBuffer                             commandBuffer,
	VkPipelineBindPoint                         pipelineBindPoint,
	VkPipeline                                  _pipeline)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);

	switch (pipelineBindPoint) {
	case VK_PIPELINE_BIND_POINT_COMPUTE:
		if (cmd_buffer->state.compute_pipeline == pipeline)
			return;
		radv_mark_descriptor_sets_dirty(cmd_buffer, pipelineBindPoint);

		cmd_buffer->state.compute_pipeline = pipeline;
		cmd_buffer->push_constant_stages |= VK_SHADER_STAGE_COMPUTE_BIT;
		break;
	case VK_PIPELINE_BIND_POINT_GRAPHICS:
		if (cmd_buffer->state.pipeline == pipeline)
			return;
		radv_mark_descriptor_sets_dirty(cmd_buffer, pipelineBindPoint);

		cmd_buffer->state.pipeline = pipeline;
		if (!pipeline)
			break;

		cmd_buffer->state.dirty |= RADV_CMD_DIRTY_PIPELINE;
		cmd_buffer->push_constant_stages |= pipeline->active_stages;

		/* the new vertex shader might not have the same user regs */
		cmd_buffer->state.last_first_instance = -1;
		cmd_buffer->state.last_vertex_offset = -1;

		/* Prefetch all pipeline shaders at first draw time. */
		cmd_buffer->state.prefetch_L2_mask |= RADV_PREFETCH_SHADERS;

		radv_bind_dynamic_state(cmd_buffer, &pipeline->dynamic_state);

		if (pipeline->graphics.esgs_ring_size > cmd_buffer->esgs_ring_size_needed)
			cmd_buffer->esgs_ring_size_needed = pipeline->graphics.esgs_ring_size;
		if (pipeline->graphics.gsvs_ring_size > cmd_buffer->gsvs_ring_size_needed)
			cmd_buffer->gsvs_ring_size_needed = pipeline->graphics.gsvs_ring_size;

		if (radv_pipeline_has_tess(pipeline))
			cmd_buffer->tess_rings_needed = true;
		break;
	default:
		assert(!"invalid bind point");
		break;
	}
}

void radv_CmdSetViewport(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    firstViewport,
	uint32_t                                    viewportCount,
	const VkViewport*                           pViewports)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_cmd_state *state = &cmd_buffer->state;
	MAYBE_UNUSED const uint32_t total_count = firstViewport + viewportCount;

	assert(firstViewport < MAX_VIEWPORTS);
	assert(total_count >= 1 && total_count <= MAX_VIEWPORTS);

	memcpy(state->dynamic.viewport.viewports + firstViewport, pViewports,
	       viewportCount * sizeof(*pViewports));

	state->dirty |= RADV_CMD_DIRTY_DYNAMIC_VIEWPORT;
}

void radv_CmdSetScissor(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    firstScissor,
	uint32_t                                    scissorCount,
	const VkRect2D*                             pScissors)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_cmd_state *state = &cmd_buffer->state;
	MAYBE_UNUSED const uint32_t total_count = firstScissor + scissorCount;

	assert(firstScissor < MAX_SCISSORS);
	assert(total_count >= 1 && total_count <= MAX_SCISSORS);

	memcpy(state->dynamic.scissor.scissors + firstScissor, pScissors,
	       scissorCount * sizeof(*pScissors));

	state->dirty |= RADV_CMD_DIRTY_DYNAMIC_SCISSOR;
}

void radv_CmdSetLineWidth(
	VkCommandBuffer                             commandBuffer,
	float                                       lineWidth)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	cmd_buffer->state.dynamic.line_width = lineWidth;
	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_LINE_WIDTH;
}

void radv_CmdSetDepthBias(
	VkCommandBuffer                             commandBuffer,
	float                                       depthBiasConstantFactor,
	float                                       depthBiasClamp,
	float                                       depthBiasSlopeFactor)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	cmd_buffer->state.dynamic.depth_bias.bias = depthBiasConstantFactor;
	cmd_buffer->state.dynamic.depth_bias.clamp = depthBiasClamp;
	cmd_buffer->state.dynamic.depth_bias.slope = depthBiasSlopeFactor;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS;
}

void radv_CmdSetBlendConstants(
	VkCommandBuffer                             commandBuffer,
	const float                                 blendConstants[4])
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	memcpy(cmd_buffer->state.dynamic.blend_constants,
	       blendConstants, sizeof(float) * 4);

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS;
}

void radv_CmdSetDepthBounds(
	VkCommandBuffer                             commandBuffer,
	float                                       minDepthBounds,
	float                                       maxDepthBounds)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	cmd_buffer->state.dynamic.depth_bounds.min = minDepthBounds;
	cmd_buffer->state.dynamic.depth_bounds.max = maxDepthBounds;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS;
}

void radv_CmdSetStencilCompareMask(
	VkCommandBuffer                             commandBuffer,
	VkStencilFaceFlags                          faceMask,
	uint32_t                                    compareMask)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	if (faceMask & VK_STENCIL_FACE_FRONT_BIT)
		cmd_buffer->state.dynamic.stencil_compare_mask.front = compareMask;
	if (faceMask & VK_STENCIL_FACE_BACK_BIT)
		cmd_buffer->state.dynamic.stencil_compare_mask.back = compareMask;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK;
}

void radv_CmdSetStencilWriteMask(
	VkCommandBuffer                             commandBuffer,
	VkStencilFaceFlags                          faceMask,
	uint32_t                                    writeMask)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	if (faceMask & VK_STENCIL_FACE_FRONT_BIT)
		cmd_buffer->state.dynamic.stencil_write_mask.front = writeMask;
	if (faceMask & VK_STENCIL_FACE_BACK_BIT)
		cmd_buffer->state.dynamic.stencil_write_mask.back = writeMask;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK;
}

void radv_CmdSetStencilReference(
	VkCommandBuffer                             commandBuffer,
	VkStencilFaceFlags                          faceMask,
	uint32_t                                    reference)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	if (faceMask & VK_STENCIL_FACE_FRONT_BIT)
		cmd_buffer->state.dynamic.stencil_reference.front = reference;
	if (faceMask & VK_STENCIL_FACE_BACK_BIT)
		cmd_buffer->state.dynamic.stencil_reference.back = reference;

	cmd_buffer->state.dirty |= RADV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE;
}

void radv_CmdSetDiscardRectangleEXT(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    firstDiscardRectangle,
	uint32_t                                    discardRectangleCount,
	const VkRect2D*                             pDiscardRectangles)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_cmd_state *state = &cmd_buffer->state;
	MAYBE_UNUSED const uint32_t total_count = firstDiscardRectangle + discardRectangleCount;

	assert(firstDiscardRectangle < MAX_DISCARD_RECTANGLES);
	assert(total_count >= 1 && total_count <= MAX_DISCARD_RECTANGLES);

	typed_memcpy(&state->dynamic.discard_rectangle.rectangles[firstDiscardRectangle],
	             pDiscardRectangles, discardRectangleCount);

	state->dirty |= RADV_CMD_DIRTY_DYNAMIC_DISCARD_RECTANGLE;
}

void radv_CmdExecuteCommands(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    commandBufferCount,
	const VkCommandBuffer*                      pCmdBuffers)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, primary, commandBuffer);

	assert(commandBufferCount > 0);

	/* Emit pending flushes on primary prior to executing secondary */
	si_emit_cache_flush(primary);

	for (uint32_t i = 0; i < commandBufferCount; i++) {
		RADV_FROM_HANDLE(radv_cmd_buffer, secondary, pCmdBuffers[i]);

		primary->scratch_size_needed = MAX2(primary->scratch_size_needed,
		                                    secondary->scratch_size_needed);
		primary->compute_scratch_size_needed = MAX2(primary->compute_scratch_size_needed,
		                                            secondary->compute_scratch_size_needed);

		if (secondary->esgs_ring_size_needed > primary->esgs_ring_size_needed)
			primary->esgs_ring_size_needed = secondary->esgs_ring_size_needed;
		if (secondary->gsvs_ring_size_needed > primary->gsvs_ring_size_needed)
			primary->gsvs_ring_size_needed = secondary->gsvs_ring_size_needed;
		if (secondary->tess_rings_needed)
			primary->tess_rings_needed = true;
		if (secondary->sample_positions_needed)
			primary->sample_positions_needed = true;

		primary->device->ws->cs_execute_secondary(primary->cs, secondary->cs);


		/* When the secondary command buffer is compute only we don't
		 * need to re-emit the current graphics pipeline.
		 */
		if (secondary->state.emitted_pipeline) {
			primary->state.emitted_pipeline =
				secondary->state.emitted_pipeline;
		}

		/* When the secondary command buffer is graphics only we don't
		 * need to re-emit the current compute pipeline.
		 */
		if (secondary->state.emitted_compute_pipeline) {
			primary->state.emitted_compute_pipeline =
				secondary->state.emitted_compute_pipeline;
		}

		/* Only re-emit the draw packets when needed. */
		if (secondary->state.last_primitive_reset_en != -1) {
			primary->state.last_primitive_reset_en =
				secondary->state.last_primitive_reset_en;
		}

		if (secondary->state.last_primitive_reset_index) {
			primary->state.last_primitive_reset_index =
				secondary->state.last_primitive_reset_index;
		}

		if (secondary->state.last_ia_multi_vgt_param) {
			primary->state.last_ia_multi_vgt_param =
				secondary->state.last_ia_multi_vgt_param;
		}

		primary->state.last_first_instance = secondary->state.last_first_instance;
		primary->state.last_num_instances = secondary->state.last_num_instances;
		primary->state.last_vertex_offset = secondary->state.last_vertex_offset;

		if (secondary->state.last_index_type != -1) {
			primary->state.last_index_type =
				secondary->state.last_index_type;
		}
	}

	/* After executing commands from secondary buffers we have to dirty
	 * some states.
	 */
	primary->state.dirty |= RADV_CMD_DIRTY_PIPELINE |
				RADV_CMD_DIRTY_INDEX_BUFFER |
				RADV_CMD_DIRTY_DYNAMIC_ALL;
	radv_mark_descriptor_sets_dirty(primary, VK_PIPELINE_BIND_POINT_GRAPHICS);
	radv_mark_descriptor_sets_dirty(primary, VK_PIPELINE_BIND_POINT_COMPUTE);
}

VkResult radv_CreateCommandPool(
	VkDevice                                    _device,
	const VkCommandPoolCreateInfo*              pCreateInfo,
	const VkAllocationCallbacks*                pAllocator,
	VkCommandPool*                              pCmdPool)
{
	RADV_FROM_HANDLE(radv_device, device, _device);
	struct radv_cmd_pool *pool;

	pool = vk_alloc2(&device->alloc, pAllocator, sizeof(*pool), 8,
			   VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
	if (pool == NULL)
		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

	if (pAllocator)
		pool->alloc = *pAllocator;
	else
		pool->alloc = device->alloc;

	list_inithead(&pool->cmd_buffers);
	list_inithead(&pool->free_cmd_buffers);

	pool->queue_family_index = pCreateInfo->queueFamilyIndex;

	*pCmdPool = radv_cmd_pool_to_handle(pool);

	return VK_SUCCESS;

}

void radv_DestroyCommandPool(
	VkDevice                                    _device,
	VkCommandPool                               commandPool,
	const VkAllocationCallbacks*                pAllocator)
{
	RADV_FROM_HANDLE(radv_device, device, _device);
	RADV_FROM_HANDLE(radv_cmd_pool, pool, commandPool);

	if (!pool)
		return;

	list_for_each_entry_safe(struct radv_cmd_buffer, cmd_buffer,
				 &pool->cmd_buffers, pool_link) {
		radv_cmd_buffer_destroy(cmd_buffer);
	}

	list_for_each_entry_safe(struct radv_cmd_buffer, cmd_buffer,
				 &pool->free_cmd_buffers, pool_link) {
		radv_cmd_buffer_destroy(cmd_buffer);
	}

	vk_free2(&device->alloc, pAllocator, pool);
}

VkResult radv_ResetCommandPool(
	VkDevice                                    device,
	VkCommandPool                               commandPool,
	VkCommandPoolResetFlags                     flags)
{
	RADV_FROM_HANDLE(radv_cmd_pool, pool, commandPool);
	VkResult result;

	list_for_each_entry(struct radv_cmd_buffer, cmd_buffer,
			    &pool->cmd_buffers, pool_link) {
		result = radv_reset_cmd_buffer(cmd_buffer);
		if (result != VK_SUCCESS)
			return result;
	}

	return VK_SUCCESS;
}

void radv_TrimCommandPool(
    VkDevice                                    device,
    VkCommandPool                               commandPool,
    VkCommandPoolTrimFlagsKHR                   flags)
{
	RADV_FROM_HANDLE(radv_cmd_pool, pool, commandPool);

	if (!pool)
		return;

	list_for_each_entry_safe(struct radv_cmd_buffer, cmd_buffer,
				 &pool->free_cmd_buffers, pool_link) {
		radv_cmd_buffer_destroy(cmd_buffer);
	}
}

void radv_CmdBeginRenderPass(
	VkCommandBuffer                             commandBuffer,
	const VkRenderPassBeginInfo*                pRenderPassBegin,
	VkSubpassContents                           contents)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_render_pass, pass, pRenderPassBegin->renderPass);
	RADV_FROM_HANDLE(radv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);

	MAYBE_UNUSED unsigned cdw_max = radeon_check_space(cmd_buffer->device->ws,
							   cmd_buffer->cs, 2048);
	MAYBE_UNUSED VkResult result;

	cmd_buffer->state.framebuffer = framebuffer;
	cmd_buffer->state.pass = pass;
	cmd_buffer->state.render_area = pRenderPassBegin->renderArea;

	result = radv_cmd_state_setup_attachments(cmd_buffer, pass, pRenderPassBegin);
	if (result != VK_SUCCESS)
		return;

	radv_cmd_buffer_set_subpass(cmd_buffer, pass->subpasses, true);
	assert(cmd_buffer->cs->cdw <= cdw_max);

	radv_cmd_buffer_clear_subpass(cmd_buffer);
}

void radv_CmdBeginRenderPass2KHR(
    VkCommandBuffer                             commandBuffer,
    const VkRenderPassBeginInfo*                pRenderPassBeginInfo,
    const VkSubpassBeginInfoKHR*                pSubpassBeginInfo)
{
	radv_CmdBeginRenderPass(commandBuffer, pRenderPassBeginInfo,
				pSubpassBeginInfo->contents);
}

void radv_CmdNextSubpass(
    VkCommandBuffer                             commandBuffer,
    VkSubpassContents                           contents)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	radv_cmd_buffer_resolve_subpass(cmd_buffer);

	radeon_check_space(cmd_buffer->device->ws, cmd_buffer->cs,
					      2048);

	radv_cmd_buffer_set_subpass(cmd_buffer, cmd_buffer->state.subpass + 1, true);
	radv_cmd_buffer_clear_subpass(cmd_buffer);
}

void radv_CmdNextSubpass2KHR(
    VkCommandBuffer                             commandBuffer,
    const VkSubpassBeginInfoKHR*                pSubpassBeginInfo,
    const VkSubpassEndInfoKHR*                  pSubpassEndInfo)
{
	radv_CmdNextSubpass(commandBuffer, pSubpassBeginInfo->contents);
}

static void radv_emit_view_index(struct radv_cmd_buffer *cmd_buffer, unsigned index)
{
	struct radv_pipeline *pipeline = cmd_buffer->state.pipeline;
	for (unsigned stage = 0; stage < MESA_SHADER_STAGES; ++stage) {
		if (!radv_get_shader(pipeline, stage))
			continue;

		struct radv_userdata_info *loc = radv_lookup_user_sgpr(pipeline, stage, AC_UD_VIEW_INDEX);
		if (loc->sgpr_idx == -1)
			continue;
		uint32_t base_reg = pipeline->user_data_0[stage];
		radeon_set_sh_reg(cmd_buffer->cs, base_reg + loc->sgpr_idx * 4, index);

	}
	if (pipeline->gs_copy_shader) {
		struct radv_userdata_info *loc = &pipeline->gs_copy_shader->info.user_sgprs_locs.shader_data[AC_UD_VIEW_INDEX];
		if (loc->sgpr_idx != -1) {
			uint32_t base_reg = R_00B130_SPI_SHADER_USER_DATA_VS_0;
			radeon_set_sh_reg(cmd_buffer->cs, base_reg + loc->sgpr_idx * 4, index);
		}
	}
}

static void
radv_cs_emit_draw_packet(struct radv_cmd_buffer *cmd_buffer,
                         uint32_t vertex_count)
{
	radeon_emit(cmd_buffer->cs, PKT3(PKT3_DRAW_INDEX_AUTO, 1, cmd_buffer->state.predicating));
	radeon_emit(cmd_buffer->cs, vertex_count);
	radeon_emit(cmd_buffer->cs, V_0287F0_DI_SRC_SEL_AUTO_INDEX |
	                            S_0287F0_USE_OPAQUE(0));
}

static void
radv_cs_emit_draw_indexed_packet(struct radv_cmd_buffer *cmd_buffer,
                                 uint64_t index_va,
                                 uint32_t index_count)
{
	radeon_emit(cmd_buffer->cs, PKT3(PKT3_DRAW_INDEX_2, 4, cmd_buffer->state.predicating));
	radeon_emit(cmd_buffer->cs, cmd_buffer->state.max_index_count);
	radeon_emit(cmd_buffer->cs, index_va);
	radeon_emit(cmd_buffer->cs, index_va >> 32);
	radeon_emit(cmd_buffer->cs, index_count);
	radeon_emit(cmd_buffer->cs, V_0287F0_DI_SRC_SEL_DMA);
}

static void
radv_cs_emit_indirect_draw_packet(struct radv_cmd_buffer *cmd_buffer,
                                  bool indexed,
                                  uint32_t draw_count,
                                  uint64_t count_va,
                                  uint32_t stride)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	unsigned di_src_sel = indexed ? V_0287F0_DI_SRC_SEL_DMA
	                              : V_0287F0_DI_SRC_SEL_AUTO_INDEX;
	bool draw_id_enable = radv_get_shader(cmd_buffer->state.pipeline, MESA_SHADER_VERTEX)->info.info.vs.needs_draw_id;
	uint32_t base_reg = cmd_buffer->state.pipeline->graphics.vtx_base_sgpr;
	bool predicating = cmd_buffer->state.predicating;
	assert(base_reg);

	/* just reset draw state for vertex data */
	cmd_buffer->state.last_first_instance = -1;
	cmd_buffer->state.last_num_instances = -1;
	cmd_buffer->state.last_vertex_offset = -1;

	if (draw_count == 1 && !count_va && !draw_id_enable) {
		radeon_emit(cs, PKT3(indexed ? PKT3_DRAW_INDEX_INDIRECT :
				     PKT3_DRAW_INDIRECT, 3, predicating));
		radeon_emit(cs, 0);
		radeon_emit(cs, (base_reg - SI_SH_REG_OFFSET) >> 2);
		radeon_emit(cs, ((base_reg + 4) - SI_SH_REG_OFFSET) >> 2);
		radeon_emit(cs, di_src_sel);
	} else {
		radeon_emit(cs, PKT3(indexed ? PKT3_DRAW_INDEX_INDIRECT_MULTI :
				     PKT3_DRAW_INDIRECT_MULTI,
				     8, predicating));
		radeon_emit(cs, 0);
		radeon_emit(cs, (base_reg - SI_SH_REG_OFFSET) >> 2);
		radeon_emit(cs, ((base_reg + 4) - SI_SH_REG_OFFSET) >> 2);
		radeon_emit(cs, (((base_reg + 8) - SI_SH_REG_OFFSET) >> 2) |
			    S_2C3_DRAW_INDEX_ENABLE(draw_id_enable) |
			    S_2C3_COUNT_INDIRECT_ENABLE(!!count_va));
		radeon_emit(cs, draw_count); /* count */
		radeon_emit(cs, count_va); /* count_addr */
		radeon_emit(cs, count_va >> 32);
		radeon_emit(cs, stride); /* stride */
		radeon_emit(cs, di_src_sel);
	}
}

struct radv_draw_info {
	/**
	 * Number of vertices.
	 */
	uint32_t count;

	/**
	 * Index of the first vertex.
	 */
	int32_t vertex_offset;

	/**
	 * First instance id.
	 */
	uint32_t first_instance;

	/**
	 * Number of instances.
	 */
	uint32_t instance_count;

	/**
	 * First index (indexed draws only).
	 */
	uint32_t first_index;

	/**
	 * Whether it's an indexed draw.
	 */
	bool indexed;

	/**
	 * Indirect draw parameters resource.
	 */
	struct radv_buffer *indirect;
	uint64_t indirect_offset;
	uint32_t stride;

	/**
	 * Draw count parameters resource.
	 */
	struct radv_buffer *count_buffer;
	uint64_t count_buffer_offset;
};

static void
radv_emit_draw_packets(struct radv_cmd_buffer *cmd_buffer,
		       const struct radv_draw_info *info)
{
	struct radv_cmd_state *state = &cmd_buffer->state;
	struct radeon_winsys *ws = cmd_buffer->device->ws;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;

	if (info->indirect) {
		uint64_t va = radv_buffer_get_va(info->indirect->bo);
		uint64_t count_va = 0;

		va += info->indirect->offset + info->indirect_offset;

		radv_cs_add_buffer(ws, cs, info->indirect->bo);

		radeon_emit(cs, PKT3(PKT3_SET_BASE, 2, 0));
		radeon_emit(cs, 1);
		radeon_emit(cs, va);
		radeon_emit(cs, va >> 32);

		if (info->count_buffer) {
			count_va = radv_buffer_get_va(info->count_buffer->bo);
			count_va += info->count_buffer->offset +
				    info->count_buffer_offset;

			radv_cs_add_buffer(ws, cs, info->count_buffer->bo);
		}

		if (!state->subpass->view_mask) {
			radv_cs_emit_indirect_draw_packet(cmd_buffer,
							  info->indexed,
							  info->count,
							  count_va,
							  info->stride);
		} else {
			unsigned i;
			for_each_bit(i, state->subpass->view_mask) {
				radv_emit_view_index(cmd_buffer, i);

				radv_cs_emit_indirect_draw_packet(cmd_buffer,
								  info->indexed,
								  info->count,
								  count_va,
								  info->stride);
			}
		}
	} else {
		assert(state->pipeline->graphics.vtx_base_sgpr);

		if (info->vertex_offset != state->last_vertex_offset ||
		    info->first_instance != state->last_first_instance) {
			radeon_set_sh_reg_seq(cs, state->pipeline->graphics.vtx_base_sgpr,
					      state->pipeline->graphics.vtx_emit_num);

			radeon_emit(cs, info->vertex_offset);
			radeon_emit(cs, info->first_instance);
			if (state->pipeline->graphics.vtx_emit_num == 3)
				radeon_emit(cs, 0);
			state->last_first_instance = info->first_instance;
			state->last_vertex_offset = info->vertex_offset;
		}

		if (state->last_num_instances != info->instance_count) {
			radeon_emit(cs, PKT3(PKT3_NUM_INSTANCES, 0, false));
			radeon_emit(cs, info->instance_count);
			state->last_num_instances = info->instance_count;
		}

		if (info->indexed) {
			int index_size = state->index_type ? 4 : 2;
			uint64_t index_va;

			index_va = state->index_va;
			index_va += info->first_index * index_size;

			if (!state->subpass->view_mask) {
				radv_cs_emit_draw_indexed_packet(cmd_buffer,
								 index_va,
								 info->count);
			} else {
				unsigned i;
				for_each_bit(i, state->subpass->view_mask) {
					radv_emit_view_index(cmd_buffer, i);

					radv_cs_emit_draw_indexed_packet(cmd_buffer,
									 index_va,
									 info->count);
				}
			}
		} else {
			if (!state->subpass->view_mask) {
				radv_cs_emit_draw_packet(cmd_buffer, info->count);
			} else {
				unsigned i;
				for_each_bit(i, state->subpass->view_mask) {
					radv_emit_view_index(cmd_buffer, i);

					radv_cs_emit_draw_packet(cmd_buffer,
								 info->count);
				}
			}
		}
	}
}

/*
 * Vega and raven have a bug which triggers if there are multiple context
 * register contexts active at the same time with different scissor values.
 *
 * There are two possible workarounds:
 * 1) Wait for PS_PARTIAL_FLUSH every time the scissor is changed. That way
 *    there is only ever 1 active set of scissor values at the same time.
 *
 * 2) Whenever the hardware switches contexts we have to set the scissor
 *    registers again even if it is a noop. That way the new context gets
 *    the correct scissor values.
 *
 * This implements option 2. radv_need_late_scissor_emission needs to
 * return true on affected HW if radv_emit_all_graphics_states sets
 * any context registers.
 */
static bool radv_need_late_scissor_emission(struct radv_cmd_buffer *cmd_buffer,
                                            bool indexed_draw)
{
	struct radv_cmd_state *state = &cmd_buffer->state;

	if (!cmd_buffer->device->physical_device->has_scissor_bug)
		return false;

	uint32_t used_states = cmd_buffer->state.pipeline->graphics.needed_dynamic_state | ~RADV_CMD_DIRTY_DYNAMIC_ALL;

	/* Index & Vertex buffer don't change context regs, and pipeline is handled later. */
	used_states &= ~(RADV_CMD_DIRTY_INDEX_BUFFER | RADV_CMD_DIRTY_VERTEX_BUFFER | RADV_CMD_DIRTY_PIPELINE);

	/* Assume all state changes except  these two can imply context rolls. */
	if (cmd_buffer->state.dirty & used_states)
		return true;

	if (cmd_buffer->state.emitted_pipeline != cmd_buffer->state.pipeline)
		return true;

	if (indexed_draw && state->pipeline->graphics.prim_restart_enable &&
	    (state->index_type ? 0xffffffffu : 0xffffu) != state->last_primitive_reset_index)
		return true;

	return false;
}

static void
radv_emit_all_graphics_states(struct radv_cmd_buffer *cmd_buffer,
			      const struct radv_draw_info *info)
{
	bool late_scissor_emission = radv_need_late_scissor_emission(cmd_buffer, info->indexed);

	if ((cmd_buffer->state.dirty & RADV_CMD_DIRTY_FRAMEBUFFER) ||
	    cmd_buffer->state.emitted_pipeline != cmd_buffer->state.pipeline)
		radv_emit_rbplus_state(cmd_buffer);

	if (cmd_buffer->state.dirty & RADV_CMD_DIRTY_PIPELINE)
		radv_emit_graphics_pipeline(cmd_buffer);

	if (cmd_buffer->state.dirty & RADV_CMD_DIRTY_FRAMEBUFFER)
		radv_emit_framebuffer_state(cmd_buffer);

	if (info->indexed) {
		if (cmd_buffer->state.dirty & RADV_CMD_DIRTY_INDEX_BUFFER)
			radv_emit_index_buffer(cmd_buffer);
	} else {
		/* On CI and later, non-indexed draws overwrite VGT_INDEX_TYPE,
		 * so the state must be re-emitted before the next indexed
		 * draw.
		 */
		if (cmd_buffer->device->physical_device->rad_info.chip_class >= CIK) {
			cmd_buffer->state.last_index_type = -1;
			cmd_buffer->state.dirty |= RADV_CMD_DIRTY_INDEX_BUFFER;
		}
	}

	radv_cmd_buffer_flush_dynamic_state(cmd_buffer);

	radv_emit_draw_registers(cmd_buffer, info->indexed,
				 info->instance_count > 1, info->indirect,
				 info->indirect ? 0 : info->count);

	if (late_scissor_emission)
		radv_emit_scissor(cmd_buffer);
}

static void
radv_draw(struct radv_cmd_buffer *cmd_buffer,
	  const struct radv_draw_info *info)
{
	bool has_prefetch =
		cmd_buffer->device->physical_device->rad_info.chip_class >= CIK;
	bool pipeline_is_dirty =
		(cmd_buffer->state.dirty & RADV_CMD_DIRTY_PIPELINE) &&
		cmd_buffer->state.pipeline != cmd_buffer->state.emitted_pipeline;

	MAYBE_UNUSED unsigned cdw_max =
		radeon_check_space(cmd_buffer->device->ws,
				   cmd_buffer->cs, 4096);

	/* Use optimal packet order based on whether we need to sync the
	 * pipeline.
	 */
	if (cmd_buffer->state.flush_bits & (RADV_CMD_FLAG_FLUSH_AND_INV_CB |
					    RADV_CMD_FLAG_FLUSH_AND_INV_DB |
					    RADV_CMD_FLAG_PS_PARTIAL_FLUSH |
					    RADV_CMD_FLAG_CS_PARTIAL_FLUSH)) {
		/* If we have to wait for idle, set all states first, so that
		 * all SET packets are processed in parallel with previous draw
		 * calls. Then upload descriptors, set shader pointers, and
		 * draw, and prefetch at the end. This ensures that the time
		 * the CUs are idle is very short. (there are only SET_SH
		 * packets between the wait and the draw)
		 */
		radv_emit_all_graphics_states(cmd_buffer, info);
		si_emit_cache_flush(cmd_buffer);
		/* <-- CUs are idle here --> */

		radv_upload_graphics_shader_descriptors(cmd_buffer, pipeline_is_dirty);

		radv_emit_draw_packets(cmd_buffer, info);
		/* <-- CUs are busy here --> */

		/* Start prefetches after the draw has been started. Both will
		 * run in parallel, but starting the draw first is more
		 * important.
		 */
		if (has_prefetch && cmd_buffer->state.prefetch_L2_mask) {
			radv_emit_prefetch_L2(cmd_buffer,
					      cmd_buffer->state.pipeline, false);
		}
	} else {
		/* If we don't wait for idle, start prefetches first, then set
		 * states, and draw at the end.
		 */
		si_emit_cache_flush(cmd_buffer);

		if (has_prefetch && cmd_buffer->state.prefetch_L2_mask) {
			/* Only prefetch the vertex shader and VBO descriptors
			 * in order to start the draw as soon as possible.
			 */
			radv_emit_prefetch_L2(cmd_buffer,
					      cmd_buffer->state.pipeline, true);
		}

		radv_upload_graphics_shader_descriptors(cmd_buffer, pipeline_is_dirty);

		radv_emit_all_graphics_states(cmd_buffer, info);
		radv_emit_draw_packets(cmd_buffer, info);

		/* Prefetch the remaining shaders after the draw has been
		 * started.
		 */
		if (has_prefetch && cmd_buffer->state.prefetch_L2_mask) {
			radv_emit_prefetch_L2(cmd_buffer,
					      cmd_buffer->state.pipeline, false);
		}
	}

	assert(cmd_buffer->cs->cdw <= cdw_max);
	radv_cmd_buffer_after_draw(cmd_buffer, RADV_CMD_FLAG_PS_PARTIAL_FLUSH);
}

void radv_CmdDraw(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    vertexCount,
	uint32_t                                    instanceCount,
	uint32_t                                    firstVertex,
	uint32_t                                    firstInstance)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_draw_info info = {};

	info.count = vertexCount;
	info.instance_count = instanceCount;
	info.first_instance = firstInstance;
	info.vertex_offset = firstVertex;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndexed(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    indexCount,
	uint32_t                                    instanceCount,
	uint32_t                                    firstIndex,
	int32_t                                     vertexOffset,
	uint32_t                                    firstInstance)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_draw_info info = {};

	info.indexed = true;
	info.count = indexCount;
	info.instance_count = instanceCount;
	info.first_index = firstIndex;
	info.vertex_offset = vertexOffset;
	info.first_instance = firstInstance;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndirect(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	uint32_t                                    drawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	struct radv_draw_info info = {};

	info.count = drawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndexedIndirect(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	uint32_t                                    drawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	struct radv_draw_info info = {};

	info.indexed = true;
	info.count = drawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndirectCountAMD(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	VkBuffer                                    _countBuffer,
	VkDeviceSize                                countBufferOffset,
	uint32_t                                    maxDrawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	RADV_FROM_HANDLE(radv_buffer, count_buffer, _countBuffer);
	struct radv_draw_info info = {};

	info.count = maxDrawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.count_buffer = count_buffer;
	info.count_buffer_offset = countBufferOffset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndexedIndirectCountAMD(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	VkBuffer                                    _countBuffer,
	VkDeviceSize                                countBufferOffset,
	uint32_t                                    maxDrawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	RADV_FROM_HANDLE(radv_buffer, count_buffer, _countBuffer);
	struct radv_draw_info info = {};

	info.indexed = true;
	info.count = maxDrawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.count_buffer = count_buffer;
	info.count_buffer_offset = countBufferOffset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndirectCountKHR(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	VkBuffer                                    _countBuffer,
	VkDeviceSize                                countBufferOffset,
	uint32_t                                    maxDrawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	RADV_FROM_HANDLE(radv_buffer, count_buffer, _countBuffer);
	struct radv_draw_info info = {};

	info.count = maxDrawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.count_buffer = count_buffer;
	info.count_buffer_offset = countBufferOffset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

void radv_CmdDrawIndexedIndirectCountKHR(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset,
	VkBuffer                                    _countBuffer,
	VkDeviceSize                                countBufferOffset,
	uint32_t                                    maxDrawCount,
	uint32_t                                    stride)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	RADV_FROM_HANDLE(radv_buffer, count_buffer, _countBuffer);
	struct radv_draw_info info = {};

	info.indexed = true;
	info.count = maxDrawCount;
	info.indirect = buffer;
	info.indirect_offset = offset;
	info.count_buffer = count_buffer;
	info.count_buffer_offset = countBufferOffset;
	info.stride = stride;

	radv_draw(cmd_buffer, &info);
}

struct radv_dispatch_info {
	/**
	 * Determine the layout of the grid (in block units) to be used.
	 */
	uint32_t blocks[3];

	/**
	 * A starting offset for the grid. If unaligned is set, the offset
	 * must still be aligned.
	 */
	uint32_t offsets[3];
	/**
	 * Whether it's an unaligned compute dispatch.
	 */
	bool unaligned;

	/**
	 * Indirect compute parameters resource.
	 */
	struct radv_buffer *indirect;
	uint64_t indirect_offset;
};

static void
radv_emit_dispatch_packets(struct radv_cmd_buffer *cmd_buffer,
			   const struct radv_dispatch_info *info)
{
	struct radv_pipeline *pipeline = cmd_buffer->state.compute_pipeline;
	struct radv_shader_variant *compute_shader = pipeline->shaders[MESA_SHADER_COMPUTE];
	unsigned dispatch_initiator = cmd_buffer->device->dispatch_initiator;
	struct radeon_winsys *ws = cmd_buffer->device->ws;
	bool predicating = cmd_buffer->state.predicating;
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	struct radv_userdata_info *loc;

	loc = radv_lookup_user_sgpr(pipeline, MESA_SHADER_COMPUTE,
				    AC_UD_CS_GRID_SIZE);

	MAYBE_UNUSED unsigned cdw_max = radeon_check_space(ws, cs, 25);

	if (info->indirect) {
		uint64_t va = radv_buffer_get_va(info->indirect->bo);

		va += info->indirect->offset + info->indirect_offset;

		radv_cs_add_buffer(ws, cs, info->indirect->bo);

		if (loc->sgpr_idx != -1) {
			for (unsigned i = 0; i < 3; ++i) {
				radeon_emit(cs, PKT3(PKT3_COPY_DATA, 4, 0));
				radeon_emit(cs, COPY_DATA_SRC_SEL(COPY_DATA_MEM) |
						COPY_DATA_DST_SEL(COPY_DATA_REG));
				radeon_emit(cs, (va +  4 * i));
				radeon_emit(cs, (va + 4 * i) >> 32);
				radeon_emit(cs, ((R_00B900_COMPUTE_USER_DATA_0
						 + loc->sgpr_idx * 4) >> 2) + i);
				radeon_emit(cs, 0);
			}
		}

		if (radv_cmd_buffer_uses_mec(cmd_buffer)) {
			radeon_emit(cs, PKT3(PKT3_DISPATCH_INDIRECT, 2, predicating) |
					PKT3_SHADER_TYPE_S(1));
			radeon_emit(cs, va);
			radeon_emit(cs, va >> 32);
			radeon_emit(cs, dispatch_initiator);
		} else {
			radeon_emit(cs, PKT3(PKT3_SET_BASE, 2, 0) |
					PKT3_SHADER_TYPE_S(1));
			radeon_emit(cs, 1);
			radeon_emit(cs, va);
			radeon_emit(cs, va >> 32);

			radeon_emit(cs, PKT3(PKT3_DISPATCH_INDIRECT, 1, predicating) |
					PKT3_SHADER_TYPE_S(1));
			radeon_emit(cs, 0);
			radeon_emit(cs, dispatch_initiator);
		}
	} else {
		unsigned blocks[3] = { info->blocks[0], info->blocks[1], info->blocks[2] };
		unsigned offsets[3] = { info->offsets[0], info->offsets[1], info->offsets[2] };

		if (info->unaligned) {
			unsigned *cs_block_size = compute_shader->info.cs.block_size;
			unsigned remainder[3];

			/* If aligned, these should be an entire block size,
			 * not 0.
			 */
			remainder[0] = blocks[0] + cs_block_size[0] -
				       align_u32_npot(blocks[0], cs_block_size[0]);
			remainder[1] = blocks[1] + cs_block_size[1] -
				       align_u32_npot(blocks[1], cs_block_size[1]);
			remainder[2] = blocks[2] + cs_block_size[2] -
				       align_u32_npot(blocks[2], cs_block_size[2]);

			blocks[0] = round_up_u32(blocks[0], cs_block_size[0]);
			blocks[1] = round_up_u32(blocks[1], cs_block_size[1]);
			blocks[2] = round_up_u32(blocks[2], cs_block_size[2]);

			for(unsigned i = 0; i < 3; ++i) {
				assert(offsets[i] % cs_block_size[i] == 0);
				offsets[i] /= cs_block_size[i];
			}

			radeon_set_sh_reg_seq(cs, R_00B81C_COMPUTE_NUM_THREAD_X, 3);
			radeon_emit(cs,
				    S_00B81C_NUM_THREAD_FULL(cs_block_size[0]) |
				    S_00B81C_NUM_THREAD_PARTIAL(remainder[0]));
			radeon_emit(cs,
				    S_00B81C_NUM_THREAD_FULL(cs_block_size[1]) |
				    S_00B81C_NUM_THREAD_PARTIAL(remainder[1]));
			radeon_emit(cs,
				    S_00B81C_NUM_THREAD_FULL(cs_block_size[2]) |
				    S_00B81C_NUM_THREAD_PARTIAL(remainder[2]));

			dispatch_initiator |= S_00B800_PARTIAL_TG_EN(1);
		}

		if (loc->sgpr_idx != -1) {
			assert(!loc->indirect);
			assert(loc->num_sgprs == 3);

			radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0 +
						  loc->sgpr_idx * 4, 3);
			radeon_emit(cs, blocks[0]);
			radeon_emit(cs, blocks[1]);
			radeon_emit(cs, blocks[2]);
		}

		if (offsets[0] || offsets[1] || offsets[2]) {
			radeon_set_sh_reg_seq(cs, R_00B810_COMPUTE_START_X, 3);
			radeon_emit(cs, offsets[0]);
			radeon_emit(cs, offsets[1]);
			radeon_emit(cs, offsets[2]);

			/* The blocks in the packet are not counts but end values. */
			for (unsigned i = 0; i < 3; ++i)
				blocks[i] += offsets[i];
		} else {
			dispatch_initiator |= S_00B800_FORCE_START_AT_000(1);
		}

		radeon_emit(cs, PKT3(PKT3_DISPATCH_DIRECT, 3, predicating) |
				PKT3_SHADER_TYPE_S(1));
		radeon_emit(cs, blocks[0]);
		radeon_emit(cs, blocks[1]);
		radeon_emit(cs, blocks[2]);
		radeon_emit(cs, dispatch_initiator);
	}

	assert(cmd_buffer->cs->cdw <= cdw_max);
}

static void
radv_upload_compute_shader_descriptors(struct radv_cmd_buffer *cmd_buffer)
{
	radv_flush_descriptors(cmd_buffer, VK_SHADER_STAGE_COMPUTE_BIT);
	radv_flush_constants(cmd_buffer, VK_SHADER_STAGE_COMPUTE_BIT);
}

static void
radv_dispatch(struct radv_cmd_buffer *cmd_buffer,
	      const struct radv_dispatch_info *info)
{
	struct radv_pipeline *pipeline = cmd_buffer->state.compute_pipeline;
	bool has_prefetch =
		cmd_buffer->device->physical_device->rad_info.chip_class >= CIK;
	bool pipeline_is_dirty = pipeline &&
				 pipeline != cmd_buffer->state.emitted_compute_pipeline;

	if (cmd_buffer->state.flush_bits & (RADV_CMD_FLAG_FLUSH_AND_INV_CB |
					    RADV_CMD_FLAG_FLUSH_AND_INV_DB |
					    RADV_CMD_FLAG_PS_PARTIAL_FLUSH |
					    RADV_CMD_FLAG_CS_PARTIAL_FLUSH)) {
		/* If we have to wait for idle, set all states first, so that
		 * all SET packets are processed in parallel with previous draw
		 * calls. Then upload descriptors, set shader pointers, and
		 * dispatch, and prefetch at the end. This ensures that the
		 * time the CUs are idle is very short. (there are only SET_SH
		 * packets between the wait and the draw)
		 */
		radv_emit_compute_pipeline(cmd_buffer);
		si_emit_cache_flush(cmd_buffer);
		/* <-- CUs are idle here --> */

		radv_upload_compute_shader_descriptors(cmd_buffer);

		radv_emit_dispatch_packets(cmd_buffer, info);
		/* <-- CUs are busy here --> */

		/* Start prefetches after the dispatch has been started. Both
		 * will run in parallel, but starting the dispatch first is
		 * more important.
		 */
		if (has_prefetch && pipeline_is_dirty) {
			radv_emit_shader_prefetch(cmd_buffer,
						  pipeline->shaders[MESA_SHADER_COMPUTE]);
		}
	} else {
		/* If we don't wait for idle, start prefetches first, then set
		 * states, and dispatch at the end.
		 */
		si_emit_cache_flush(cmd_buffer);

		if (has_prefetch && pipeline_is_dirty) {
			radv_emit_shader_prefetch(cmd_buffer,
						  pipeline->shaders[MESA_SHADER_COMPUTE]);
		}

		radv_upload_compute_shader_descriptors(cmd_buffer);

		radv_emit_compute_pipeline(cmd_buffer);
		radv_emit_dispatch_packets(cmd_buffer, info);
	}

	radv_cmd_buffer_after_draw(cmd_buffer, RADV_CMD_FLAG_CS_PARTIAL_FLUSH);
}

void radv_CmdDispatchBase(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    base_x,
	uint32_t                                    base_y,
	uint32_t                                    base_z,
	uint32_t                                    x,
	uint32_t                                    y,
	uint32_t                                    z)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_dispatch_info info = {};

	info.blocks[0] = x;
	info.blocks[1] = y;
	info.blocks[2] = z;

	info.offsets[0] = base_x;
	info.offsets[1] = base_y;
	info.offsets[2] = base_z;
	radv_dispatch(cmd_buffer, &info);
}

void radv_CmdDispatch(
	VkCommandBuffer                             commandBuffer,
	uint32_t                                    x,
	uint32_t                                    y,
	uint32_t                                    z)
{
	radv_CmdDispatchBase(commandBuffer, 0, 0, 0, x, y, z);
}

void radv_CmdDispatchIndirect(
	VkCommandBuffer                             commandBuffer,
	VkBuffer                                    _buffer,
	VkDeviceSize                                offset)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
	struct radv_dispatch_info info = {};

	info.indirect = buffer;
	info.indirect_offset = offset;

	radv_dispatch(cmd_buffer, &info);
}

void radv_unaligned_dispatch(
	struct radv_cmd_buffer                      *cmd_buffer,
	uint32_t                                    x,
	uint32_t                                    y,
	uint32_t                                    z)
{
	struct radv_dispatch_info info = {};

	info.blocks[0] = x;
	info.blocks[1] = y;
	info.blocks[2] = z;
	info.unaligned = 1;

	radv_dispatch(cmd_buffer, &info);
}

void radv_CmdEndRenderPass(
	VkCommandBuffer                             commandBuffer)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	radv_subpass_barrier(cmd_buffer, &cmd_buffer->state.pass->end_barrier);

	radv_cmd_buffer_resolve_subpass(cmd_buffer);

	for (unsigned i = 0; i < cmd_buffer->state.framebuffer->attachment_count; ++i) {
		VkImageLayout layout = cmd_buffer->state.pass->attachments[i].final_layout;
		radv_handle_subpass_image_transition(cmd_buffer,
		                      (struct radv_subpass_attachment){i, layout});
	}

	vk_free(&cmd_buffer->pool->alloc, cmd_buffer->state.attachments);

	cmd_buffer->state.pass = NULL;
	cmd_buffer->state.subpass = NULL;
	cmd_buffer->state.attachments = NULL;
	cmd_buffer->state.framebuffer = NULL;
}

void radv_CmdEndRenderPass2KHR(
    VkCommandBuffer                             commandBuffer,
    const VkSubpassEndInfoKHR*                  pSubpassEndInfo)
{
	radv_CmdEndRenderPass(commandBuffer);
}

/*
 * For HTILE we have the following interesting clear words:
 *   0xfffff30f: Uncompressed, full depth range, for depth+stencil HTILE
 *   0xfffc000f: Uncompressed, full depth range, for depth only HTILE.
 *   0xfffffff0: Clear depth to 1.0
 *   0x00000000: Clear depth to 0.0
 */
static void radv_initialize_htile(struct radv_cmd_buffer *cmd_buffer,
                                  struct radv_image *image,
                                  const VkImageSubresourceRange *range,
                                  uint32_t clear_word)
{
	assert(range->baseMipLevel == 0);
	assert(range->levelCount == 1 || range->levelCount == VK_REMAINING_ARRAY_LAYERS);
	unsigned layer_count = radv_get_layerCount(image, range);
	uint64_t size = image->surface.htile_slice_size * layer_count;
	VkImageAspectFlags aspects = VK_IMAGE_ASPECT_DEPTH_BIT;
	uint64_t offset = image->offset + image->htile_offset +
	                  image->surface.htile_slice_size * range->baseArrayLayer;
	struct radv_cmd_state *state = &cmd_buffer->state;
	VkClearDepthStencilValue value = {};

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB |
			     RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;

	state->flush_bits |= radv_fill_buffer(cmd_buffer, image->bo, offset,
					      size, clear_word);

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;

	if (vk_format_is_stencil(image->vk_format))
		aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;

	radv_set_ds_clear_metadata(cmd_buffer, image, value, aspects);
}

static void radv_handle_depth_image_transition(struct radv_cmd_buffer *cmd_buffer,
					       struct radv_image *image,
					       VkImageLayout src_layout,
					       VkImageLayout dst_layout,
					       unsigned src_queue_mask,
					       unsigned dst_queue_mask,
					       const VkImageSubresourceRange *range,
					       VkImageAspectFlags pending_clears)
{
	if (!radv_image_has_htile(image))
		return;

	if (src_layout == VK_IMAGE_LAYOUT_UNDEFINED &&
	           radv_layout_has_htile(image, dst_layout, dst_queue_mask)) {
		/* TODO: merge with the clear if applicable */
		radv_initialize_htile(cmd_buffer, image, range, 0);
	} else if (!radv_layout_is_htile_compressed(image, src_layout, src_queue_mask) &&
	           radv_layout_is_htile_compressed(image, dst_layout, dst_queue_mask)) {
		uint32_t clear_value = vk_format_is_stencil(image->vk_format) ? 0xfffff30f : 0xfffc000f;
		radv_initialize_htile(cmd_buffer, image, range, clear_value);
	} else if (radv_layout_is_htile_compressed(image, src_layout, src_queue_mask) &&
	           !radv_layout_is_htile_compressed(image, dst_layout, dst_queue_mask)) {
		VkImageSubresourceRange local_range = *range;
		local_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
		local_range.baseMipLevel = 0;
		local_range.levelCount = 1;

		cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB |
		                                RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;

		radv_decompress_depth_image_inplace(cmd_buffer, image, &local_range);

		cmd_buffer->state.flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_DB |
		                                RADV_CMD_FLAG_FLUSH_AND_INV_DB_META;
	}
}

static void radv_initialise_cmask(struct radv_cmd_buffer *cmd_buffer,
				  struct radv_image *image, uint32_t value)
{
	struct radv_cmd_state *state = &cmd_buffer->state;

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB |
			    RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;

	state->flush_bits |= radv_clear_cmask(cmd_buffer, image, value);

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;
}

void radv_initialize_dcc(struct radv_cmd_buffer *cmd_buffer,
			 struct radv_image *image, uint32_t value)
{
	struct radv_cmd_state *state = &cmd_buffer->state;

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB |
			     RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;

	state->flush_bits |= radv_clear_dcc(cmd_buffer, image, value);

	state->flush_bits |= RADV_CMD_FLAG_FLUSH_AND_INV_CB |
			     RADV_CMD_FLAG_FLUSH_AND_INV_CB_META;
}

/**
 * Initialize DCC/FMASK/CMASK metadata for a color image.
 */
static void radv_init_color_image_metadata(struct radv_cmd_buffer *cmd_buffer,
					   struct radv_image *image,
					   VkImageLayout src_layout,
					   VkImageLayout dst_layout,
					   unsigned src_queue_mask,
					   unsigned dst_queue_mask)
{
	if (radv_image_has_cmask(image)) {
		uint32_t value = 0xffffffffu; /* Fully expanded mode. */

		/*  TODO: clarify this. */
		if (radv_image_has_fmask(image)) {
			value = 0xccccccccu;
		}

		radv_initialise_cmask(cmd_buffer, image, value);
	}

	if (radv_image_has_dcc(image)) {
		uint32_t value = 0xffffffffu; /* Fully expanded mode. */
		bool need_decompress_pass = false;

		if (radv_layout_dcc_compressed(image, dst_layout,
					       dst_queue_mask)) {
			value = 0x20202020u;
			need_decompress_pass = true;
		}

		radv_initialize_dcc(cmd_buffer, image, value);

		radv_set_dcc_need_cmask_elim_pred(cmd_buffer, image,
						  need_decompress_pass);
	}

	if (radv_image_has_cmask(image) || radv_image_has_dcc(image)) {
		uint32_t color_values[2] = {};
		radv_set_color_clear_metadata(cmd_buffer, image, color_values);
	}
}

/**
 * Handle color image transitions for DCC/FMASK/CMASK.
 */
static void radv_handle_color_image_transition(struct radv_cmd_buffer *cmd_buffer,
					       struct radv_image *image,
					       VkImageLayout src_layout,
					       VkImageLayout dst_layout,
					       unsigned src_queue_mask,
					       unsigned dst_queue_mask,
					       const VkImageSubresourceRange *range)
{
	if (src_layout == VK_IMAGE_LAYOUT_UNDEFINED) {
		radv_init_color_image_metadata(cmd_buffer, image,
					       src_layout, dst_layout,
					       src_queue_mask, dst_queue_mask);
		return;
	}

	if (radv_image_has_dcc(image)) {
		if (src_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
			radv_initialize_dcc(cmd_buffer, image, 0xffffffffu);
		} else if (radv_layout_dcc_compressed(image, src_layout, src_queue_mask) &&
		           !radv_layout_dcc_compressed(image, dst_layout, dst_queue_mask)) {
			radv_decompress_dcc(cmd_buffer, image, range);
		} else if (radv_layout_can_fast_clear(image, src_layout, src_queue_mask) &&
			   !radv_layout_can_fast_clear(image, dst_layout, dst_queue_mask)) {
			radv_fast_clear_flush_image_inplace(cmd_buffer, image, range);
		}
	} else if (radv_image_has_cmask(image) || radv_image_has_fmask(image)) {
		if (radv_layout_can_fast_clear(image, src_layout, src_queue_mask) &&
		    !radv_layout_can_fast_clear(image, dst_layout, dst_queue_mask)) {
			radv_fast_clear_flush_image_inplace(cmd_buffer, image, range);
		}
	}
}

static void radv_handle_image_transition(struct radv_cmd_buffer *cmd_buffer,
					 struct radv_image *image,
					 VkImageLayout src_layout,
					 VkImageLayout dst_layout,
					 uint32_t src_family,
					 uint32_t dst_family,
					 const VkImageSubresourceRange *range,
					 VkImageAspectFlags pending_clears)
{
	if (image->exclusive && src_family != dst_family) {
		/* This is an acquire or a release operation and there will be
		 * a corresponding release/acquire. Do the transition in the
		 * most flexible queue. */

		assert(src_family == cmd_buffer->queue_family_index ||
		       dst_family == cmd_buffer->queue_family_index);

		if (cmd_buffer->queue_family_index == RADV_QUEUE_TRANSFER)
			return;

		if (cmd_buffer->queue_family_index == RADV_QUEUE_COMPUTE &&
		    (src_family == RADV_QUEUE_GENERAL ||
		     dst_family == RADV_QUEUE_GENERAL))
			return;
	}

	unsigned src_queue_mask =
		radv_image_queue_family_mask(image, src_family,
					     cmd_buffer->queue_family_index);
	unsigned dst_queue_mask =
		radv_image_queue_family_mask(image, dst_family,
					     cmd_buffer->queue_family_index);

	if (vk_format_is_depth(image->vk_format)) {
		radv_handle_depth_image_transition(cmd_buffer, image,
						   src_layout, dst_layout,
						   src_queue_mask, dst_queue_mask,
						   range, pending_clears);
	} else {
		radv_handle_color_image_transition(cmd_buffer, image,
						   src_layout, dst_layout,
						   src_queue_mask, dst_queue_mask,
						   range);
	}
}

struct radv_barrier_info {
	uint32_t eventCount;
	const VkEvent *pEvents;
	VkPipelineStageFlags srcStageMask;
};

static void
radv_barrier(struct radv_cmd_buffer *cmd_buffer,
	     uint32_t memoryBarrierCount,
	     const VkMemoryBarrier *pMemoryBarriers,
	     uint32_t bufferMemoryBarrierCount,
	     const VkBufferMemoryBarrier *pBufferMemoryBarriers,
	     uint32_t imageMemoryBarrierCount,
	     const VkImageMemoryBarrier *pImageMemoryBarriers,
	     const struct radv_barrier_info *info)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	enum radv_cmd_flush_bits src_flush_bits = 0;
	enum radv_cmd_flush_bits dst_flush_bits = 0;

	for (unsigned i = 0; i < info->eventCount; ++i) {
		RADV_FROM_HANDLE(radv_event, event, info->pEvents[i]);
		uint64_t va = radv_buffer_get_va(event->bo);

		radv_cs_add_buffer(cmd_buffer->device->ws, cs, event->bo);

		MAYBE_UNUSED unsigned cdw_max = radeon_check_space(cmd_buffer->device->ws, cs, 7);

		si_emit_wait_fence(cs, va, 1, 0xffffffff);
		assert(cmd_buffer->cs->cdw <= cdw_max);
	}

	for (uint32_t i = 0; i < memoryBarrierCount; i++) {
		src_flush_bits |= radv_src_access_flush(cmd_buffer, pMemoryBarriers[i].srcAccessMask,
							NULL);
		dst_flush_bits |= radv_dst_access_flush(cmd_buffer, pMemoryBarriers[i].dstAccessMask,
		                                        NULL);
	}

	for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
		src_flush_bits |= radv_src_access_flush(cmd_buffer, pBufferMemoryBarriers[i].srcAccessMask,
							NULL);
		dst_flush_bits |= radv_dst_access_flush(cmd_buffer, pBufferMemoryBarriers[i].dstAccessMask,
		                                        NULL);
	}

	for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
		RADV_FROM_HANDLE(radv_image, image, pImageMemoryBarriers[i].image);

		src_flush_bits |= radv_src_access_flush(cmd_buffer, pImageMemoryBarriers[i].srcAccessMask,
							image);
		dst_flush_bits |= radv_dst_access_flush(cmd_buffer, pImageMemoryBarriers[i].dstAccessMask,
		                                        image);
	}

	radv_stage_flush(cmd_buffer, info->srcStageMask);
	cmd_buffer->state.flush_bits |= src_flush_bits;

	for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
		RADV_FROM_HANDLE(radv_image, image, pImageMemoryBarriers[i].image);
		radv_handle_image_transition(cmd_buffer, image,
					     pImageMemoryBarriers[i].oldLayout,
					     pImageMemoryBarriers[i].newLayout,
					     pImageMemoryBarriers[i].srcQueueFamilyIndex,
					     pImageMemoryBarriers[i].dstQueueFamilyIndex,
					     &pImageMemoryBarriers[i].subresourceRange,
					     0);
	}

	/* Make sure CP DMA is idle because the driver might have performed a
	 * DMA operation for copying or filling buffers/images.
	 */
	si_cp_dma_wait_for_idle(cmd_buffer);

	cmd_buffer->state.flush_bits |= dst_flush_bits;
}

void radv_CmdPipelineBarrier(
	VkCommandBuffer                             commandBuffer,
	VkPipelineStageFlags                        srcStageMask,
	VkPipelineStageFlags                        destStageMask,
	VkBool32                                    byRegion,
	uint32_t                                    memoryBarrierCount,
	const VkMemoryBarrier*                      pMemoryBarriers,
	uint32_t                                    bufferMemoryBarrierCount,
	const VkBufferMemoryBarrier*                pBufferMemoryBarriers,
	uint32_t                                    imageMemoryBarrierCount,
	const VkImageMemoryBarrier*                 pImageMemoryBarriers)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_barrier_info info;

	info.eventCount = 0;
	info.pEvents = NULL;
	info.srcStageMask = srcStageMask;

	radv_barrier(cmd_buffer, memoryBarrierCount, pMemoryBarriers,
		     bufferMemoryBarrierCount, pBufferMemoryBarriers,
		     imageMemoryBarrierCount, pImageMemoryBarriers, &info);
}


static void write_event(struct radv_cmd_buffer *cmd_buffer,
			struct radv_event *event,
			VkPipelineStageFlags stageMask,
			unsigned value)
{
	struct radeon_cmdbuf *cs = cmd_buffer->cs;
	uint64_t va = radv_buffer_get_va(event->bo);

	radv_cs_add_buffer(cmd_buffer->device->ws, cs, event->bo);

	MAYBE_UNUSED unsigned cdw_max = radeon_check_space(cmd_buffer->device->ws, cs, 18);

	/* Flags that only require a top-of-pipe event. */
	VkPipelineStageFlags top_of_pipe_flags =
		VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;

	/* Flags that only require a post-index-fetch event. */
	VkPipelineStageFlags post_index_fetch_flags =
		top_of_pipe_flags |
		VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT |
		VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;

	/* Make sure CP DMA is idle because the driver might have performed a
	 * DMA operation for copying or filling buffers/images.
	 */
	si_cp_dma_wait_for_idle(cmd_buffer);

	/* TODO: Emit EOS events for syncing PS/CS stages. */

	if (!(stageMask & ~top_of_pipe_flags)) {
		/* Just need to sync the PFP engine. */
		radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 3, 0));
		radeon_emit(cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
				S_370_WR_CONFIRM(1) |
				S_370_ENGINE_SEL(V_370_PFP));
		radeon_emit(cs, va);
		radeon_emit(cs, va >> 32);
		radeon_emit(cs, value);
	} else if (!(stageMask & ~post_index_fetch_flags)) {
		/* Sync ME because PFP reads index and indirect buffers. */
		radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 3, 0));
		radeon_emit(cs, S_370_DST_SEL(V_370_MEM_ASYNC) |
				S_370_WR_CONFIRM(1) |
				S_370_ENGINE_SEL(V_370_ME));
		radeon_emit(cs, va);
		radeon_emit(cs, va >> 32);
		radeon_emit(cs, value);
	} else {
		/* Otherwise, sync all prior GPU work using an EOP event. */
		si_cs_emit_write_event_eop(cs,
					   cmd_buffer->device->physical_device->rad_info.chip_class,
					   radv_cmd_buffer_uses_mec(cmd_buffer),
					   V_028A90_BOTTOM_OF_PIPE_TS, 0,
					   EOP_DATA_SEL_VALUE_32BIT, va, 2, value,
					   cmd_buffer->gfx9_eop_bug_va);
	}

	assert(cmd_buffer->cs->cdw <= cdw_max);
}

void radv_CmdSetEvent(VkCommandBuffer commandBuffer,
		      VkEvent _event,
		      VkPipelineStageFlags stageMask)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_event, event, _event);

	write_event(cmd_buffer, event, stageMask, 1);
}

void radv_CmdResetEvent(VkCommandBuffer commandBuffer,
			VkEvent _event,
			VkPipelineStageFlags stageMask)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_event, event, _event);

	write_event(cmd_buffer, event, stageMask, 0);
}

void radv_CmdWaitEvents(VkCommandBuffer commandBuffer,
			uint32_t eventCount,
			const VkEvent* pEvents,
			VkPipelineStageFlags srcStageMask,
			VkPipelineStageFlags dstStageMask,
			uint32_t memoryBarrierCount,
			const VkMemoryBarrier* pMemoryBarriers,
			uint32_t bufferMemoryBarrierCount,
			const VkBufferMemoryBarrier* pBufferMemoryBarriers,
			uint32_t imageMemoryBarrierCount,
			const VkImageMemoryBarrier* pImageMemoryBarriers)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	struct radv_barrier_info info;

	info.eventCount = eventCount;
	info.pEvents = pEvents;
	info.srcStageMask = 0;

	radv_barrier(cmd_buffer, memoryBarrierCount, pMemoryBarriers,
		     bufferMemoryBarrierCount, pBufferMemoryBarriers,
		     imageMemoryBarrierCount, pImageMemoryBarriers, &info);
}


void radv_CmdSetDeviceMask(VkCommandBuffer commandBuffer,
                           uint32_t deviceMask)
{
   /* No-op */
}

/* VK_EXT_conditional_rendering */
void radv_CmdBeginConditionalRenderingEXT(
	VkCommandBuffer                             commandBuffer,
	const VkConditionalRenderingBeginInfoEXT*   pConditionalRenderingBegin)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
	RADV_FROM_HANDLE(radv_buffer, buffer, pConditionalRenderingBegin->buffer);
	bool draw_visible = true;
	uint64_t va;

	va = radv_buffer_get_va(buffer->bo) + pConditionalRenderingBegin->offset;

	/* By default, if the 32-bit value at offset in buffer memory is zero,
	 * then the rendering commands are discarded, otherwise they are
	 * executed as normal. If the inverted flag is set, all commands are
	 * discarded if the value is non zero.
	 */
	if (pConditionalRenderingBegin->flags &
	    VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT) {
		draw_visible = false;
	}

	/* Enable predication for this command buffer. */
	si_emit_set_predication_state(cmd_buffer, draw_visible, va);
	cmd_buffer->state.predicating = true;

	/* Store conditional rendering user info. */
	cmd_buffer->state.predication_type = draw_visible;
	cmd_buffer->state.predication_va = va;
}

void radv_CmdEndConditionalRenderingEXT(
	VkCommandBuffer                             commandBuffer)
{
	RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);

	/* Disable predication for this command buffer. */
	si_emit_set_predication_state(cmd_buffer, false, 0);
	cmd_buffer->state.predicating = false;

	/* Reset conditional rendering user info. */
	cmd_buffer->state.predication_type = -1;
	cmd_buffer->state.predication_va = 0;
}