summaryrefslogtreecommitdiff
path: root/src/intel/isl/isl.c
blob: d26d655ae283dfd61fdf01750ecc1cc4206cae39 (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
/*
 * 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 <assert.h>
#include <stdarg.h>
#include <stdio.h>

#include "genxml/genX_bits.h"

#include "isl.h"
#include "isl_gfx4.h"
#include "isl_gfx6.h"
#include "isl_gfx7.h"
#include "isl_gfx8.h"
#include "isl_gfx9.h"
#include "isl_gfx12.h"
#include "isl_priv.h"

void
isl_memcpy_linear_to_tiled(uint32_t xt1, uint32_t xt2,
                           uint32_t yt1, uint32_t yt2,
                           char *dst, const char *src,
                           uint32_t dst_pitch, int32_t src_pitch,
                           bool has_swizzling,
                           enum isl_tiling tiling,
                           isl_memcpy_type copy_type)
{
#ifdef USE_SSE41
   if (copy_type == ISL_MEMCPY_STREAMING_LOAD) {
      _isl_memcpy_linear_to_tiled_sse41(
         xt1, xt2, yt1, yt2, dst, src, dst_pitch, src_pitch, has_swizzling,
         tiling, copy_type);
      return;
   }
#endif

   _isl_memcpy_linear_to_tiled(
      xt1, xt2, yt1, yt2, dst, src, dst_pitch, src_pitch, has_swizzling,
      tiling, copy_type);
}

void
isl_memcpy_tiled_to_linear(uint32_t xt1, uint32_t xt2,
                           uint32_t yt1, uint32_t yt2,
                           char *dst, const char *src,
                           int32_t dst_pitch, uint32_t src_pitch,
                           bool has_swizzling,
                           enum isl_tiling tiling,
                           isl_memcpy_type copy_type)
{
#ifdef USE_SSE41
   if (copy_type == ISL_MEMCPY_STREAMING_LOAD) {
      _isl_memcpy_tiled_to_linear_sse41(
         xt1, xt2, yt1, yt2, dst, src, dst_pitch, src_pitch, has_swizzling,
         tiling, copy_type);
      return;
   }
#endif

   _isl_memcpy_tiled_to_linear(
      xt1, xt2, yt1, yt2, dst, src, dst_pitch, src_pitch, has_swizzling,
      tiling, copy_type);
}

void PRINTFLIKE(3, 4) UNUSED
__isl_finishme(const char *file, int line, const char *fmt, ...)
{
   va_list ap;
   char buf[512];

   va_start(ap, fmt);
   vsnprintf(buf, sizeof(buf), fmt, ap);
   va_end(ap);

   fprintf(stderr, "%s:%d: FINISHME: %s\n", file, line, buf);
}

static void
isl_device_setup_mocs(struct isl_device *dev)
{
   if (dev->info->ver >= 12) {
      if (dev->info->is_dg2) {
         /* L3CC=WB; BSpec: 45101 */
         dev->mocs.internal = 3 << 1;
         dev->mocs.external = 3 << 1;
      } else if (dev->info->is_dg1) {
         /* L3CC=WB */
         dev->mocs.internal = 5 << 1;
         /* Displayables on DG1 are free to cache in L3 since L3 is transient
          * and flushed at bottom of each submission.
          */
         dev->mocs.external = 5 << 1;
      } else {
         /* TC=1/LLC Only, LeCC=1/UC, LRUM=0, L3CC=3/WB */
         dev->mocs.external = 61 << 1;
         /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */
         dev->mocs.internal = 2 << 1;

         /* L1 - HDC:L1 + L3 + LLC */
         dev->mocs.l1_hdc_l3_llc = 48 << 1;
      }
   } else if (dev->info->ver >= 9) {
      /* TC=LLC/eLLC, LeCC=PTE, LRUM=3, L3CC=WB */
      dev->mocs.external = 1 << 1;
      /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */
      dev->mocs.internal = 2 << 1;
   } else if (dev->info->ver >= 8) {
      /* MEMORY_OBJECT_CONTROL_STATE:
       * .MemoryTypeLLCeLLCCacheabilityControl = UCwithFenceifcoherentcycle,
       * .TargetCache = L3DefertoPATforLLCeLLCselection,
       * .AgeforQUADLRU = 0
       */
      dev->mocs.external = 0x18;
      /* MEMORY_OBJECT_CONTROL_STATE:
       * .MemoryTypeLLCeLLCCacheabilityControl = WB,
       * .TargetCache = L3DefertoPATforLLCeLLCselection,
       * .AgeforQUADLRU = 0
       */
      dev->mocs.internal = 0x78;
   } else if (dev->info->ver >= 7) {
      if (dev->info->is_haswell) {
         /* MEMORY_OBJECT_CONTROL_STATE:
          * .LLCeLLCCacheabilityControlLLCCC             = 0,
          * .L3CacheabilityControlL3CC                   = 1,
          */
         dev->mocs.internal = 1;
         dev->mocs.external = 1;
      } else {
         /* MEMORY_OBJECT_CONTROL_STATE:
          * .GraphicsDataTypeGFDT                        = 0,
          * .LLCCacheabilityControlLLCCC                 = 0,
          * .L3CacheabilityControlL3CC                   = 1,
          */
         dev->mocs.internal = 1;
         dev->mocs.external = 1;
      }
   } else {
      dev->mocs.internal = 0;
      dev->mocs.external = 0;
   }
}

/**
 * Return an appropriate MOCS entry for the given usage flags.
 */
uint32_t
isl_mocs(const struct isl_device *dev, isl_surf_usage_flags_t usage,
         bool external)
{
   if (external)
      return dev->mocs.external;

   if (dev->info->ver >= 12 && !dev->info->is_dg1) {
      if (usage & ISL_SURF_USAGE_STAGING_BIT)
         return dev->mocs.internal;

      /* Using L1:HDC for storage buffers breaks Vulkan memory model
       * tests that use shader atomics.  This isn't likely to work out,
       * and we can't know a priori whether they'll be used.  So just
       * continue with ordinary internal MOCS for now.
       */
      if (usage & ISL_SURF_USAGE_STORAGE_BIT)
         return dev->mocs.internal;

      if (usage & (ISL_SURF_USAGE_CONSTANT_BUFFER_BIT |
                   ISL_SURF_USAGE_RENDER_TARGET_BIT |
                   ISL_SURF_USAGE_TEXTURE_BIT))
         return dev->mocs.l1_hdc_l3_llc;
   }

   return dev->mocs.internal;
}

void
isl_device_init(struct isl_device *dev,
                const struct intel_device_info *info)
{
   /* Gfx8+ don't have bit6 swizzling, ensure callsite is not confused. */
   assert(!(info->has_bit6_swizzle && info->ver >= 8));

   dev->info = info;
   dev->use_separate_stencil = ISL_GFX_VER(dev) >= 6;
   dev->has_bit6_swizzling = info->has_bit6_swizzle;

   /* The ISL_DEV macros may be defined in the CFLAGS, thus hardcoding some
    * device properties at buildtime. Verify that the macros with the device
    * properties chosen during runtime.
    */
   ISL_GFX_VER_SANITIZE(dev);
   ISL_DEV_USE_SEPARATE_STENCIL_SANITIZE(dev);

   /* Did we break hiz or stencil? */
   if (ISL_DEV_USE_SEPARATE_STENCIL(dev))
      assert(info->has_hiz_and_separate_stencil);
   if (info->must_use_separate_stencil)
      assert(ISL_DEV_USE_SEPARATE_STENCIL(dev));

   dev->ss.size = RENDER_SURFACE_STATE_length(info) * 4;
   dev->ss.align = isl_align(dev->ss.size, 32);

   dev->ss.clear_color_state_size =
      isl_align(CLEAR_COLOR_length(info) * 4, 64);
   dev->ss.clear_color_state_offset =
      RENDER_SURFACE_STATE_ClearValueAddress_start(info) / 32 * 4;

   dev->ss.clear_value_size =
      isl_align(RENDER_SURFACE_STATE_RedClearColor_bits(info) +
                RENDER_SURFACE_STATE_GreenClearColor_bits(info) +
                RENDER_SURFACE_STATE_BlueClearColor_bits(info) +
                RENDER_SURFACE_STATE_AlphaClearColor_bits(info), 32) / 8;

   dev->ss.clear_value_offset =
      RENDER_SURFACE_STATE_RedClearColor_start(info) / 32 * 4;

   assert(RENDER_SURFACE_STATE_SurfaceBaseAddress_start(info) % 8 == 0);
   dev->ss.addr_offset =
      RENDER_SURFACE_STATE_SurfaceBaseAddress_start(info) / 8;

   /* The "Auxiliary Surface Base Address" field starts a bit higher up
    * because the bottom 12 bits are used for other things.  Round down to
    * the nearest dword before.
    */
   dev->ss.aux_addr_offset =
      (RENDER_SURFACE_STATE_AuxiliarySurfaceBaseAddress_start(info) & ~31) / 8;

   dev->ds.size = _3DSTATE_DEPTH_BUFFER_length(info) * 4;
   assert(_3DSTATE_DEPTH_BUFFER_SurfaceBaseAddress_start(info) % 8 == 0);
   dev->ds.depth_offset =
      _3DSTATE_DEPTH_BUFFER_SurfaceBaseAddress_start(info) / 8;

   if (dev->use_separate_stencil) {
      dev->ds.size += _3DSTATE_STENCIL_BUFFER_length(info) * 4 +
                      _3DSTATE_HIER_DEPTH_BUFFER_length(info) * 4 +
                      _3DSTATE_CLEAR_PARAMS_length(info) * 4;

      assert(_3DSTATE_STENCIL_BUFFER_SurfaceBaseAddress_start(info) % 8 == 0);
      dev->ds.stencil_offset =
         _3DSTATE_DEPTH_BUFFER_length(info) * 4 +
         _3DSTATE_STENCIL_BUFFER_SurfaceBaseAddress_start(info) / 8;

      assert(_3DSTATE_HIER_DEPTH_BUFFER_SurfaceBaseAddress_start(info) % 8 == 0);
      dev->ds.hiz_offset =
         _3DSTATE_DEPTH_BUFFER_length(info) * 4 +
         _3DSTATE_STENCIL_BUFFER_length(info) * 4 +
         _3DSTATE_HIER_DEPTH_BUFFER_SurfaceBaseAddress_start(info) / 8;
   } else {
      dev->ds.stencil_offset = 0;
      dev->ds.hiz_offset = 0;
   }

   if (ISL_GFX_VER(dev) >= 7) {
      /* From the IVB PRM, SURFACE_STATE::Height,
       *
       *    For typed buffer and structured buffer surfaces, the number
       *    of entries in the buffer ranges from 1 to 2^27. For raw buffer
       *    surfaces, the number of entries in the buffer is the number of bytes
       *    which can range from 1 to 2^30.
       *
       * This limit is only concerned with raw buffers.
       */
      dev->max_buffer_size = 1ull << 30;
   } else {
      dev->max_buffer_size = 1ull << 27;
   }

   isl_device_setup_mocs(dev);
}

/**
 * @brief Query the set of multisamples supported by the device.
 *
 * This function always returns non-zero, as ISL_SAMPLE_COUNT_1_BIT is always
 * supported.
 */
isl_sample_count_mask_t ATTRIBUTE_CONST
isl_device_get_sample_counts(struct isl_device *dev)
{
   if (ISL_GFX_VER(dev) >= 9) {
      return ISL_SAMPLE_COUNT_1_BIT |
             ISL_SAMPLE_COUNT_2_BIT |
             ISL_SAMPLE_COUNT_4_BIT |
             ISL_SAMPLE_COUNT_8_BIT |
             ISL_SAMPLE_COUNT_16_BIT;
   } else if (ISL_GFX_VER(dev) >= 8) {
      return ISL_SAMPLE_COUNT_1_BIT |
             ISL_SAMPLE_COUNT_2_BIT |
             ISL_SAMPLE_COUNT_4_BIT |
             ISL_SAMPLE_COUNT_8_BIT;
   } else if (ISL_GFX_VER(dev) >= 7) {
      return ISL_SAMPLE_COUNT_1_BIT |
             ISL_SAMPLE_COUNT_4_BIT |
             ISL_SAMPLE_COUNT_8_BIT;
   } else if (ISL_GFX_VER(dev) >= 6) {
      return ISL_SAMPLE_COUNT_1_BIT |
             ISL_SAMPLE_COUNT_4_BIT;
   } else {
      return ISL_SAMPLE_COUNT_1_BIT;
   }
}

/**
 * Returns an isl_tile_info representation of the given isl_tiling when
 * combined when used in the given configuration.
 *
 * @param[in]  tiling      The tiling format to introspect
 * @param[in]  dim         The dimensionality of the surface being tiled
 * @param[in]  msaa_layout The layout of samples in the surface being tiled
 * @param[in]  format_bpb  The number of bits per surface element (block) for
 *                         the surface being tiled
 * @param[in]  samples     The samples in the surface being tiled
 * @param[out] tile_info   Return parameter for the tiling information
 */
void
isl_tiling_get_info(enum isl_tiling tiling,
                    enum isl_surf_dim dim,
                    enum isl_msaa_layout msaa_layout,
                    uint32_t format_bpb,
                    uint32_t samples,
                    struct isl_tile_info *tile_info)
{
   const uint32_t bs = format_bpb / 8;
   struct isl_extent4d logical_el;
   struct isl_extent2d phys_B;

   if (tiling != ISL_TILING_LINEAR && !isl_is_pow2(format_bpb)) {
      /* It is possible to have non-power-of-two formats in a tiled buffer.
       * The easiest way to handle this is to treat the tile as if it is three
       * times as wide.  This way no pixel will ever cross a tile boundary.
       * This really only works on a subset of tiling formats.
       */
      assert(tiling == ISL_TILING_X || tiling == ISL_TILING_Y0 ||
             tiling == ISL_TILING_4);
      assert(bs % 3 == 0 && isl_is_pow2(format_bpb / 3));
      isl_tiling_get_info(tiling, dim, msaa_layout, format_bpb / 3, samples,
                          tile_info);
      return;
   }

   switch (tiling) {
   case ISL_TILING_LINEAR:
      assert(bs > 0);
      logical_el = isl_extent4d(1, 1, 1, 1);
      phys_B = isl_extent2d(bs, 1);
      break;

   case ISL_TILING_X:
      assert(bs > 0);
      logical_el = isl_extent4d(512 / bs, 8, 1, 1);
      phys_B = isl_extent2d(512, 8);
      break;

   case ISL_TILING_Y0:
   case ISL_TILING_4:
      assert(bs > 0);
      logical_el = isl_extent4d(128 / bs, 32, 1, 1);
      phys_B = isl_extent2d(128, 32);
      break;

   case ISL_TILING_W:
      assert(bs == 1);
      logical_el = isl_extent4d(64, 64, 1, 1);
      /* From the Broadwell PRM Vol 2d, RENDER_SURFACE_STATE::SurfacePitch:
       *
       *    "If the surface is a stencil buffer (and thus has Tile Mode set
       *    to TILEMODE_WMAJOR), the pitch must be set to 2x the value
       *    computed based on width, as the stencil buffer is stored with two
       *    rows interleaved."
       *
       * This, together with the fact that stencil buffers are referred to as
       * being Y-tiled in the PRMs for older hardware implies that the
       * physical size of a W-tile is actually the same as for a Y-tile.
       */
      phys_B = isl_extent2d(128, 32);
      break;

   case ISL_TILING_Yf:
   case ISL_TILING_Ys: {
      bool is_Ys = tiling == ISL_TILING_Ys;

      assert(bs > 0);
      unsigned width = 1 << (6 + (ffs(bs) / 2) + (2 * is_Ys));
      unsigned height = 1 << (6 - (ffs(bs) / 2) + (2 * is_Ys));

      logical_el = isl_extent4d(width / bs, height, 1, 1);
      phys_B = isl_extent2d(width, height);
      break;
   }
   case ISL_TILING_64:
      /* The tables below are taken from the "2D Surfaces" page in the Bspec
       * which are formulated in terms of the Cv and Cu constants. This is
       * different from the tables in the "Tile64 Format" page which should be
       * equivalent but are usually in terms of pixels. Also note that Cv and
       * Cu are HxW order to match the Bspec table, not WxH order like you
       * might expect.
       *
       * From the Bspec's "Tile64 Format" page:
       *
       *    MSAA Depth/Stencil surface use IMS (Interleaved Multi Samples)
       *    which means:
       *
       *    - Use the 1X MSAA (non-MSRT) version of the Tile64 equations and
       *      let the client unit do the swizzling internally
       *
       * Surfaces using the IMS layout will use the mapping for 1x MSAA.
       */
#define tile_extent(bs, cv, cu, a) \
      isl_extent4d((1 << cu) / bs, 1 << cv, 1, a)

      /* Only 2D surfaces are handled. */
      assert(dim == ISL_SURF_DIM_2D);

      if (samples == 1 || msaa_layout == ISL_MSAA_LAYOUT_INTERLEAVED) {
         switch (format_bpb) {
         case 128: logical_el = tile_extent(bs, 6, 10, 1); break;
         case  64: logical_el = tile_extent(bs, 6, 10, 1); break;
         case  32: logical_el = tile_extent(bs, 7,  9, 1); break;
         case  16: logical_el = tile_extent(bs, 7,  9, 1); break;
         case   8: logical_el = tile_extent(bs, 8,  8, 1); break;
         default: unreachable("Unsupported format size.");
         }
      } else if (samples == 2) {
         switch (format_bpb) {
         case 128: logical_el = tile_extent(bs, 6,  9, 2); break;
         case  64: logical_el = tile_extent(bs, 6,  9, 2); break;
         case  32: logical_el = tile_extent(bs, 7,  8, 2); break;
         case  16: logical_el = tile_extent(bs, 7,  8, 2); break;
         case   8: logical_el = tile_extent(bs, 8,  7, 2); break;
         default: unreachable("Unsupported format size.");
         }
      } else {
         switch (format_bpb) {
         case 128: logical_el = tile_extent(bs, 5,  9, 4); break;
         case  64: logical_el = tile_extent(bs, 5,  9, 4); break;
         case  32: logical_el = tile_extent(bs, 6,  8, 4); break;
         case  16: logical_el = tile_extent(bs, 6,  8, 4); break;
         case   8: logical_el = tile_extent(bs, 7,  7, 4); break;
         default: unreachable("Unsupported format size.");
         }
      }

#undef tile_extent

      phys_B.w = logical_el.w * bs;
      phys_B.h = 64 * 1024 / phys_B.w;
      break;

   case ISL_TILING_HIZ:
      /* HiZ buffers are required to have ISL_FORMAT_HIZ which is an 8x4
       * 128bpb format.  The tiling has the same physical dimensions as
       * Y-tiling but actually has two HiZ columns per Y-tiled column.
       */
      assert(bs == 16);
      logical_el = isl_extent4d(16, 16, 1, 1);
      phys_B = isl_extent2d(128, 32);
      break;

   case ISL_TILING_CCS:
      /* CCS surfaces are required to have one of the GENX_CCS_* formats which
       * have a block size of 1 or 2 bits per block and each CCS element
       * corresponds to one cache-line pair in the main surface.  From the Sky
       * Lake PRM Vol. 12 in the section on planes:
       *
       *    "The Color Control Surface (CCS) contains the compression status
       *    of the cache-line pairs. The compression state of the cache-line
       *    pair is specified by 2 bits in the CCS.  Each CCS cache-line
       *    represents an area on the main surface of 16x16 sets of 128 byte
       *    Y-tiled cache-line-pairs. CCS is always Y tiled."
       *
       * The CCS being Y-tiled implies that it's an 8x8 grid of cache-lines.
       * Since each cache line corresponds to a 16x16 set of cache-line pairs,
       * that yields total tile area of 128x128 cache-line pairs or CCS
       * elements.  On older hardware, each CCS element is 1 bit and the tile
       * is 128x256 elements.
       */
      assert(format_bpb == 1 || format_bpb == 2);
      logical_el = isl_extent4d(128, 256 / format_bpb, 1, 1);
      phys_B = isl_extent2d(128, 32);
      break;

   case ISL_TILING_GFX12_CCS:
      /* From the Bspec, Gen Graphics > Gfx12 > Memory Data Formats > Memory
       * Compression > Memory Compression - Gfx12:
       *
       *    4 bits of auxiliary plane data are required for 2 cachelines of
       *    main surface data. This results in a single cacheline of auxiliary
       *    plane data mapping to 4 4K pages of main surface data for the 4K
       *    pages (tile Y ) and 1 64K Tile Ys page.
       *
       * The Y-tiled pairing bit of 9 shown in the table below that Bspec
       * section expresses that the 2 cachelines of main surface data are
       * horizontally adjacent.
       *
       * TODO: Handle Ys, Yf and their pairing bits.
       *
       * Therefore, each CCS cacheline represents a 512Bx32 row area and each
       * element represents a 32Bx4 row area.
       */
      assert(format_bpb == 4);
      logical_el = isl_extent4d(16, 8, 1, 1);
      phys_B = isl_extent2d(64, 1);
      break;

   default:
      unreachable("not reached");
   } /* end switch */

   *tile_info = (struct isl_tile_info) {
      .tiling = tiling,
      .format_bpb = format_bpb,
      .logical_extent_el = logical_el,
      .phys_extent_B = phys_B,
   };
}

bool
isl_color_value_is_zero(union isl_color_value value,
                        enum isl_format format)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(format);

#define RETURN_FALSE_IF_NOT_0(c, i) \
   if (fmtl->channels.c.bits && value.u32[i] != 0) \
      return false

   RETURN_FALSE_IF_NOT_0(r, 0);
   RETURN_FALSE_IF_NOT_0(g, 1);
   RETURN_FALSE_IF_NOT_0(b, 2);
   RETURN_FALSE_IF_NOT_0(a, 3);

#undef RETURN_FALSE_IF_NOT_0

   return true;
}

bool
isl_color_value_is_zero_one(union isl_color_value value,
                            enum isl_format format)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(format);

#define RETURN_FALSE_IF_NOT_0_1(c, i, field) \
   if (fmtl->channels.c.bits && value.field[i] != 0 && value.field[i] != 1) \
      return false

   if (isl_format_has_int_channel(format)) {
      RETURN_FALSE_IF_NOT_0_1(r, 0, u32);
      RETURN_FALSE_IF_NOT_0_1(g, 1, u32);
      RETURN_FALSE_IF_NOT_0_1(b, 2, u32);
      RETURN_FALSE_IF_NOT_0_1(a, 3, u32);
   } else {
      RETURN_FALSE_IF_NOT_0_1(r, 0, f32);
      RETURN_FALSE_IF_NOT_0_1(g, 1, f32);
      RETURN_FALSE_IF_NOT_0_1(b, 2, f32);
      RETURN_FALSE_IF_NOT_0_1(a, 3, f32);
   }

#undef RETURN_FALSE_IF_NOT_0_1

   return true;
}

/**
 * @param[out] tiling is set only on success
 */
static bool
isl_surf_choose_tiling(const struct isl_device *dev,
                       const struct isl_surf_init_info *restrict info,
                       enum isl_tiling *tiling)
{
   isl_tiling_flags_t tiling_flags = info->tiling_flags;

   /* HiZ surfaces always use the HiZ tiling */
   if (info->usage & ISL_SURF_USAGE_HIZ_BIT) {
      assert(info->format == ISL_FORMAT_HIZ);
      assert(tiling_flags == ISL_TILING_HIZ_BIT);
      *tiling = isl_tiling_flag_to_enum(tiling_flags);
      return true;
   }

   /* CCS surfaces always use the CCS tiling */
   if (info->usage & ISL_SURF_USAGE_CCS_BIT) {
      assert(isl_format_get_layout(info->format)->txc == ISL_TXC_CCS);
      UNUSED bool ivb_ccs = ISL_GFX_VER(dev) < 12 &&
                            tiling_flags == ISL_TILING_CCS_BIT;
      UNUSED bool tgl_ccs = ISL_GFX_VER(dev) >= 12 &&
                            tiling_flags == ISL_TILING_GFX12_CCS_BIT;
      assert(ivb_ccs != tgl_ccs);
      *tiling = isl_tiling_flag_to_enum(tiling_flags);
      return true;
   }

   if (ISL_GFX_VERX10(dev) >= 125) {
      isl_gfx125_filter_tiling(dev, info, &tiling_flags);
   } else if (ISL_GFX_VER(dev) >= 6) {
      isl_gfx6_filter_tiling(dev, info, &tiling_flags);
   } else {
      isl_gfx4_filter_tiling(dev, info, &tiling_flags);
   }

   #define CHOOSE(__tiling) \
      do { \
         if (tiling_flags & (1u << (__tiling))) { \
            *tiling = (__tiling); \
            return true; \
          } \
      } while (0)

   /* Of the tiling modes remaining, choose the one that offers the best
    * performance.
    */

   if (info->dim == ISL_SURF_DIM_1D) {
      /* Prefer linear for 1D surfaces because they do not benefit from
       * tiling. To the contrary, tiling leads to wasted memory and poor
       * memory locality due to the swizzling and alignment restrictions
       * required in tiled surfaces.
       */
      CHOOSE(ISL_TILING_LINEAR);
   }

   CHOOSE(ISL_TILING_4);
   CHOOSE(ISL_TILING_64);
   CHOOSE(ISL_TILING_Ys);
   CHOOSE(ISL_TILING_Yf);
   CHOOSE(ISL_TILING_Y0);
   CHOOSE(ISL_TILING_X);
   CHOOSE(ISL_TILING_W);
   CHOOSE(ISL_TILING_LINEAR);

   #undef CHOOSE

   /* No tiling mode accomodates the inputs. */
   return false;
}

static bool
isl_choose_msaa_layout(const struct isl_device *dev,
                 const struct isl_surf_init_info *info,
                 enum isl_tiling tiling,
                 enum isl_msaa_layout *msaa_layout)
{
   if (ISL_GFX_VER(dev) >= 8) {
      return isl_gfx8_choose_msaa_layout(dev, info, tiling, msaa_layout);
   } else if (ISL_GFX_VER(dev) >= 7) {
      return isl_gfx7_choose_msaa_layout(dev, info, tiling, msaa_layout);
   } else if (ISL_GFX_VER(dev) >= 6) {
      return isl_gfx6_choose_msaa_layout(dev, info, tiling, msaa_layout);
   } else {
      return isl_gfx4_choose_msaa_layout(dev, info, tiling, msaa_layout);
   }
}

struct isl_extent2d
isl_get_interleaved_msaa_px_size_sa(uint32_t samples)
{
   assert(isl_is_pow2(samples));

   /* From the Broadwell PRM >> Volume 5: Memory Views >> Computing Mip Level
    * Sizes (p133):
    *
    *    If the surface is multisampled and it is a depth or stencil surface
    *    or Multisampled Surface StorageFormat in SURFACE_STATE is
    *    MSFMT_DEPTH_STENCIL, W_L and H_L must be adjusted as follows before
    *    proceeding: [...]
    */
   return (struct isl_extent2d) {
      .width = 1 << ((ffs(samples) - 0) / 2),
      .height = 1 << ((ffs(samples) - 1) / 2),
   };
}

static void
isl_msaa_interleaved_scale_px_to_sa(uint32_t samples,
                                    uint32_t *width, uint32_t *height)
{
   const struct isl_extent2d px_size_sa =
      isl_get_interleaved_msaa_px_size_sa(samples);

   if (width)
      *width = isl_align(*width, 2) * px_size_sa.width;
   if (height)
      *height = isl_align(*height, 2) * px_size_sa.height;
}

static enum isl_array_pitch_span
isl_choose_array_pitch_span(const struct isl_device *dev,
                            const struct isl_surf_init_info *restrict info,
                            enum isl_dim_layout dim_layout,
                            const struct isl_extent4d *phys_level0_sa)
{
   switch (dim_layout) {
   case ISL_DIM_LAYOUT_GFX9_1D:
   case ISL_DIM_LAYOUT_GFX4_2D:
      if (ISL_GFX_VER(dev) >= 8) {
         /* QPitch becomes programmable in Broadwell. So choose the
          * most compact QPitch possible in order to conserve memory.
          *
          * From the Broadwell PRM >> Volume 2d: Command Reference: Structures
          * >> RENDER_SURFACE_STATE Surface QPitch (p325):
          *
          *    - Software must ensure that this field is set to a value
          *      sufficiently large such that the array slices in the surface
          *      do not overlap. Refer to the Memory Data Formats section for
          *      information on how surfaces are stored in memory.
          *
          *    - This field specifies the distance in rows between array
          *      slices.  It is used only in the following cases:
          *
          *          - Surface Array is enabled OR
          *          - Number of Mulitsamples is not NUMSAMPLES_1 and
          *            Multisampled Surface Storage Format set to MSFMT_MSS OR
          *          - Surface Type is SURFTYPE_CUBE
          */
         return ISL_ARRAY_PITCH_SPAN_COMPACT;
      } else if (ISL_GFX_VER(dev) >= 7) {
         /* Note that Ivybridge introduces
          * RENDER_SURFACE_STATE.SurfaceArraySpacing, which provides the
          * driver more control over the QPitch.
          */

         if (phys_level0_sa->array_len == 1) {
            /* The hardware will never use the QPitch. So choose the most
             * compact QPitch possible in order to conserve memory.
             */
            return ISL_ARRAY_PITCH_SPAN_COMPACT;
         }

         if (isl_surf_usage_is_depth_or_stencil(info->usage) ||
             (info->usage & ISL_SURF_USAGE_HIZ_BIT)) {
            /* From the Ivybridge PRM >> Volume 1 Part 1: Graphics Core >>
             * Section 6.18.4.7: Surface Arrays (p112):
             *
             *    If Surface Array Spacing is set to ARYSPC_FULL (note that
             *    the depth buffer and stencil buffer have an implied value of
             *    ARYSPC_FULL):
             */
            return ISL_ARRAY_PITCH_SPAN_FULL;
         }

         if (info->levels == 1) {
            /* We are able to set RENDER_SURFACE_STATE.SurfaceArraySpacing
             * to ARYSPC_LOD0.
             */
            return ISL_ARRAY_PITCH_SPAN_COMPACT;
         }

         return ISL_ARRAY_PITCH_SPAN_FULL;
      } else if ((ISL_GFX_VER(dev) == 5 || ISL_GFX_VER(dev) == 6) &&
                 ISL_DEV_USE_SEPARATE_STENCIL(dev) &&
                 isl_surf_usage_is_stencil(info->usage)) {
         /* [ILK-SNB] Errata from the Sandy Bridge PRM >> Volume 4 Part 1:
          * Graphics Core >> Section 7.18.3.7: Surface Arrays:
          *
          *    The separate stencil buffer does not support mip mapping, thus
          *    the storage for LODs other than LOD 0 is not needed.
          */
         assert(info->levels == 1);
         return ISL_ARRAY_PITCH_SPAN_COMPACT;
      } else {
         if ((ISL_GFX_VER(dev) == 5 || ISL_GFX_VER(dev) == 6) &&
             ISL_DEV_USE_SEPARATE_STENCIL(dev) &&
             isl_surf_usage_is_stencil(info->usage)) {
            /* [ILK-SNB] Errata from the Sandy Bridge PRM >> Volume 4 Part 1:
             * Graphics Core >> Section 7.18.3.7: Surface Arrays:
             *
             *    The separate stencil buffer does not support mip mapping,
             *    thus the storage for LODs other than LOD 0 is not needed.
             */
            assert(info->levels == 1);
            assert(phys_level0_sa->array_len == 1);
            return ISL_ARRAY_PITCH_SPAN_COMPACT;
         }

         if (phys_level0_sa->array_len == 1) {
            /* The hardware will never use the QPitch. So choose the most
             * compact QPitch possible in order to conserve memory.
             */
            return ISL_ARRAY_PITCH_SPAN_COMPACT;
         }

         return ISL_ARRAY_PITCH_SPAN_FULL;
      }

   case ISL_DIM_LAYOUT_GFX4_3D:
      /* The hardware will never use the QPitch. So choose the most
       * compact QPitch possible in order to conserve memory.
       */
      return ISL_ARRAY_PITCH_SPAN_COMPACT;

   case ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ:
      /* Each array image in the gfx6 stencil of HiZ surface is compact in the
       * sense that every LOD is a compact array of the same size as LOD0.
       */
      return ISL_ARRAY_PITCH_SPAN_COMPACT;
   }

   unreachable("bad isl_dim_layout");
   return ISL_ARRAY_PITCH_SPAN_FULL;
}

static void
isl_choose_image_alignment_el(const struct isl_device *dev,
                              const struct isl_surf_init_info *restrict info,
                              enum isl_tiling tiling,
                              enum isl_dim_layout dim_layout,
                              enum isl_msaa_layout msaa_layout,
                              struct isl_extent3d *image_align_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);
   if (fmtl->txc == ISL_TXC_MCS) {
      assert(tiling == ISL_TILING_Y0);

      /*
       * IvyBrigde PRM Vol 2, Part 1, "11.7 MCS Buffer for Render Target(s)":
       *
       * Height, width, and layout of MCS buffer in this case must match with
       * Render Target height, width, and layout. MCS buffer is tiledY.
       *
       * To avoid wasting memory, choose the smallest alignment possible:
       * HALIGN_4 and VALIGN_4.
       */
      *image_align_el = isl_extent3d(4, 4, 1);
      return;
   } else if (info->format == ISL_FORMAT_HIZ) {
      assert(ISL_GFX_VER(dev) >= 6);
      if (ISL_GFX_VER(dev) == 6) {
         /* HiZ surfaces on Sandy Bridge are packed tightly. */
         *image_align_el = isl_extent3d(1, 1, 1);
      } else if (ISL_GFX_VER(dev) < 12) {
         /* On gfx7+, HiZ surfaces are always aligned to 16x8 pixels in the
          * primary surface which works out to 2x2 HiZ elments.
          */
         *image_align_el = isl_extent3d(2, 2, 1);
      } else {
         /* On gfx12+, HiZ surfaces are always aligned to 16x16 pixels in the
          * primary surface which works out to 2x4 HiZ elments.
          * TODO: Verify
          */
         *image_align_el = isl_extent3d(2, 4, 1);
      }
      return;
   }

   if (ISL_GFX_VERX10(dev) >= 125) {
      isl_gfx125_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                           msaa_layout, image_align_el);
   } else if (ISL_GFX_VER(dev) >= 12) {
      isl_gfx12_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                          msaa_layout, image_align_el);
   } else if (ISL_GFX_VER(dev) >= 9) {
      isl_gfx9_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                         msaa_layout, image_align_el);
   } else if (ISL_GFX_VER(dev) >= 8) {
      isl_gfx8_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                         msaa_layout, image_align_el);
   } else if (ISL_GFX_VER(dev) >= 7) {
      isl_gfx7_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                          msaa_layout, image_align_el);
   } else if (ISL_GFX_VER(dev) >= 6) {
      isl_gfx6_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                         msaa_layout, image_align_el);
   } else {
      isl_gfx4_choose_image_alignment_el(dev, info, tiling, dim_layout,
                                         msaa_layout, image_align_el);
   }
}

static enum isl_dim_layout
isl_surf_choose_dim_layout(const struct isl_device *dev,
                           enum isl_surf_dim logical_dim,
                           enum isl_tiling tiling,
                           isl_surf_usage_flags_t usage)
{
   /* Sandy bridge needs a special layout for HiZ and stencil. */
   if (ISL_GFX_VER(dev) == 6 &&
       (tiling == ISL_TILING_W || tiling == ISL_TILING_HIZ))
      return ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ;

   if (ISL_GFX_VER(dev) >= 9) {
      switch (logical_dim) {
      case ISL_SURF_DIM_1D:
         /* From the Sky Lake PRM Vol. 5, "1D Surfaces":
          *
          *    One-dimensional surfaces use a tiling mode of linear.
          *    Technically, they are not tiled resources, but the Tiled
          *    Resource Mode field in RENDER_SURFACE_STATE is still used to
          *    indicate the alignment requirements for this linear surface
          *    (See 1D Alignment requirements for how 4K and 64KB Tiled
          *    Resource Modes impact alignment). Alternatively, a 1D surface
          *    can be defined as a 2D tiled surface (e.g. TileY or TileX) with
          *    a height of 0.
          *
          * In other words, ISL_DIM_LAYOUT_GFX9_1D is only used for linear
          * surfaces and, for tiled surfaces, ISL_DIM_LAYOUT_GFX4_2D is used.
          */
         if (tiling == ISL_TILING_LINEAR)
            return ISL_DIM_LAYOUT_GFX9_1D;
         else
            return ISL_DIM_LAYOUT_GFX4_2D;
      case ISL_SURF_DIM_2D:
      case ISL_SURF_DIM_3D:
         return ISL_DIM_LAYOUT_GFX4_2D;
      }
   } else {
      switch (logical_dim) {
      case ISL_SURF_DIM_1D:
      case ISL_SURF_DIM_2D:
         /* From the G45 PRM Vol. 1a, "6.17.4.1 Hardware Cube Map Layout":
          *
          * The cube face textures are stored in the same way as 3D surfaces
          * are stored (see section 6.17.5 for details).  For cube surfaces,
          * however, the depth is equal to the number of faces (always 6) and 
          * is not reduced for each MIP.
          */
         if (ISL_GFX_VER(dev) == 4 && (usage & ISL_SURF_USAGE_CUBE_BIT))
            return ISL_DIM_LAYOUT_GFX4_3D;

         return ISL_DIM_LAYOUT_GFX4_2D;
      case ISL_SURF_DIM_3D:
         return ISL_DIM_LAYOUT_GFX4_3D;
      }
   }

   unreachable("bad isl_surf_dim");
   return ISL_DIM_LAYOUT_GFX4_2D;
}

/**
 * Calculate the physical extent of the surface's first level, in units of
 * surface samples.
 */
static void
isl_calc_phys_level0_extent_sa(const struct isl_device *dev,
                               const struct isl_surf_init_info *restrict info,
                               enum isl_dim_layout dim_layout,
                               enum isl_tiling tiling,
                               enum isl_msaa_layout msaa_layout,
                               struct isl_extent4d *phys_level0_sa)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   if (isl_format_is_planar(info->format))
      unreachable("Planar formats unsupported");

   switch (info->dim) {
   case ISL_SURF_DIM_1D:
      assert(info->height == 1);
      assert(info->depth == 1);
      assert(info->samples == 1);

      switch (dim_layout) {
      case ISL_DIM_LAYOUT_GFX4_3D:
         unreachable("bad isl_dim_layout");

      case ISL_DIM_LAYOUT_GFX9_1D:
      case ISL_DIM_LAYOUT_GFX4_2D:
      case ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ:
         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = 1,
            .d = 1,
            .a = info->array_len,
         };
         break;
      }
      break;

   case ISL_SURF_DIM_2D:
      if (ISL_GFX_VER(dev) == 4 && (info->usage & ISL_SURF_USAGE_CUBE_BIT))
         assert(dim_layout == ISL_DIM_LAYOUT_GFX4_3D);
      else
         assert(dim_layout == ISL_DIM_LAYOUT_GFX4_2D ||
                dim_layout == ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ);

      if (tiling == ISL_TILING_Ys && info->samples > 1)
         isl_finishme("%s:%s: multisample TileYs layout", __FILE__, __func__);

      switch (msaa_layout) {
      case ISL_MSAA_LAYOUT_NONE:
         assert(info->depth == 1);
         assert(info->samples == 1);

         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = info->height,
            .d = 1,
            .a = info->array_len,
         };
         break;

      case ISL_MSAA_LAYOUT_ARRAY:
         assert(info->depth == 1);
         assert(info->levels == 1);
         assert(isl_format_supports_multisampling(dev->info, info->format));
         assert(fmtl->bw == 1 && fmtl->bh == 1);

         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = info->height,
            .d = 1,
            .a = info->array_len * info->samples,
         };
         break;

      case ISL_MSAA_LAYOUT_INTERLEAVED:
         assert(info->depth == 1);
         assert(info->levels == 1);
         assert(isl_format_supports_multisampling(dev->info, info->format));

         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = info->height,
            .d = 1,
            .a = info->array_len,
         };

         isl_msaa_interleaved_scale_px_to_sa(info->samples,
                                             &phys_level0_sa->w,
                                             &phys_level0_sa->h);
         break;
      }
      break;

   case ISL_SURF_DIM_3D:
      assert(info->array_len == 1);
      assert(info->samples == 1);

      if (fmtl->bd > 1) {
         isl_finishme("%s:%s: compression block with depth > 1",
                      __FILE__, __func__);
      }

      switch (dim_layout) {
      case ISL_DIM_LAYOUT_GFX9_1D:
      case ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ:
         unreachable("bad isl_dim_layout");

      case ISL_DIM_LAYOUT_GFX4_2D:
         assert(ISL_GFX_VER(dev) >= 9);

         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = info->height,
            .d = 1,
            .a = info->depth,
         };
         break;

      case ISL_DIM_LAYOUT_GFX4_3D:
         assert(ISL_GFX_VER(dev) < 9);
         *phys_level0_sa = (struct isl_extent4d) {
            .w = info->width,
            .h = info->height,
            .d = info->depth,
            .a = 1,
         };
         break;
      }
      break;
   }
}

/**
 * Calculate the pitch between physical array slices, in units of rows of
 * surface elements.
 */
static uint32_t
isl_calc_array_pitch_el_rows_gfx4_2d(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      const struct isl_tile_info *tile_info,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      enum isl_array_pitch_span array_pitch_span,
      const struct isl_extent2d *phys_slice0_sa)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);
   uint32_t pitch_sa_rows = 0;

   switch (array_pitch_span) {
   case ISL_ARRAY_PITCH_SPAN_COMPACT:
      pitch_sa_rows = isl_align_npot(phys_slice0_sa->h, image_align_sa->h);
      break;
   case ISL_ARRAY_PITCH_SPAN_FULL: {
      /* The QPitch equation is found in the Broadwell PRM >> Volume 5:
       * Memory Views >> Common Surface Formats >> Surface Layout >> 2D
       * Surfaces >> Surface Arrays.
       */
      uint32_t H0_sa = phys_level0_sa->h;
      uint32_t H1_sa = isl_minify(H0_sa, 1);

      uint32_t h0_sa = isl_align_npot(H0_sa, image_align_sa->h);
      uint32_t h1_sa = isl_align_npot(H1_sa, image_align_sa->h);

      uint32_t m;
      if (ISL_GFX_VER(dev) >= 7) {
         /* The QPitch equation changed slightly in Ivybridge. */
         m = 12;
      } else {
         m = 11;
      }

      pitch_sa_rows = h0_sa + h1_sa + (m * image_align_sa->h);

      if (ISL_GFX_VER(dev) == 6 && info->samples > 1 &&
          (info->height % 4 == 1)) {
         /* [SNB] Errata from the Sandy Bridge PRM >> Volume 4 Part 1:
          * Graphics Core >> Section 7.18.3.7: Surface Arrays:
          *
          *    [SNB] Errata: Sampler MSAA Qpitch will be 4 greater than
          *    the value calculated in the equation above , for every
          *    other odd Surface Height starting from 1 i.e. 1,5,9,13.
          *
          * XXX(chadv): Is the errata natural corollary of the physical
          * layout of interleaved samples?
          */
         pitch_sa_rows += 4;
      }

      pitch_sa_rows = isl_align_npot(pitch_sa_rows, fmtl->bh);
      } /* end case */
      break;
   }

   assert(pitch_sa_rows % fmtl->bh == 0);
   uint32_t pitch_el_rows = pitch_sa_rows / fmtl->bh;

   if (ISL_GFX_VER(dev) >= 9 && ISL_GFX_VER(dev) <= 11 &&
       fmtl->txc == ISL_TXC_CCS) {
      /*
       * From the Sky Lake PRM Vol 7, "MCS Buffer for Render Target(s)" (p. 632):
       *
       *    "Mip-mapped and arrayed surfaces are supported with MCS buffer
       *    layout with these alignments in the RT space: Horizontal
       *    Alignment = 128 and Vertical Alignment = 64."
       *
       * From the Sky Lake PRM Vol. 2d, "RENDER_SURFACE_STATE" (p. 435):
       *
       *    "For non-multisampled render target's CCS auxiliary surface,
       *    QPitch must be computed with Horizontal Alignment = 128 and
       *    Surface Vertical Alignment = 256. These alignments are only for
       *    CCS buffer and not for associated render target."
       *
       * The first restriction is already handled by isl_choose_image_alignment_el
       * but the second restriction, which is an extension of the first, only
       * applies to qpitch and must be applied here.
       *
       * The second restriction disappears on Gfx12.
       */
      assert(fmtl->bh == 4);
      pitch_el_rows = isl_align(pitch_el_rows, 256 / 4);
   }

   if (ISL_GFX_VER(dev) >= 9 &&
       info->dim == ISL_SURF_DIM_3D &&
       tile_info->tiling != ISL_TILING_LINEAR) {
      /* From the Skylake BSpec >> RENDER_SURFACE_STATE >> Surface QPitch:
       *
       *    Tile Mode != Linear: This field must be set to an integer multiple
       *    of the tile height
       */
      pitch_el_rows = isl_align(pitch_el_rows, tile_info->logical_extent_el.height);
   }

   return pitch_el_rows;
}

/**
 * A variant of isl_calc_phys_slice0_extent_sa() specific to
 * ISL_DIM_LAYOUT_GFX4_2D.
 */
static void
isl_calc_phys_slice0_extent_sa_gfx4_2d(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      enum isl_msaa_layout msaa_layout,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      struct isl_extent2d *phys_slice0_sa)
{
   assert(phys_level0_sa->depth == 1);

   if (info->levels == 1) {
      /* Do not pad the surface to the image alignment.
       *
       * For tiled surfaces, using a reduced alignment here avoids wasting CPU
       * cycles on the below mipmap layout caluclations. Reducing the
       * alignment here is safe because we later align the row pitch and array
       * pitch to the tile boundary. It is safe even for
       * ISL_MSAA_LAYOUT_INTERLEAVED, because phys_level0_sa is already scaled
       * to accomodate the interleaved samples.
       *
       * For linear surfaces, reducing the alignment here permits us to later
       * choose an arbitrary, non-aligned row pitch. If the surface backs
       * a VkBuffer, then an arbitrary pitch may be needed to accomodate
       * VkBufferImageCopy::bufferRowLength.
       */
      *phys_slice0_sa = (struct isl_extent2d) {
         .w = phys_level0_sa->w,
         .h = phys_level0_sa->h,
      };
      return;
   }

   uint32_t slice_top_w = 0;
   uint32_t slice_bottom_w = 0;
   uint32_t slice_left_h = 0;
   uint32_t slice_right_h = 0;

   uint32_t W0 = phys_level0_sa->w;
   uint32_t H0 = phys_level0_sa->h;

   for (uint32_t l = 0; l < info->levels; ++l) {
      uint32_t W = isl_minify(W0, l);
      uint32_t H = isl_minify(H0, l);

      uint32_t w = isl_align_npot(W, image_align_sa->w);
      uint32_t h = isl_align_npot(H, image_align_sa->h);

      if (l == 0) {
         slice_top_w = w;
         slice_left_h = h;
         slice_right_h = h;
      } else if (l == 1) {
         slice_bottom_w = w;
         slice_left_h += h;
      } else if (l == 2) {
         slice_bottom_w += w;
         slice_right_h += h;
      } else {
         slice_right_h += h;
      }
   }

   *phys_slice0_sa = (struct isl_extent2d) {
      .w = MAX(slice_top_w, slice_bottom_w),
      .h = MAX(slice_left_h, slice_right_h),
   };
}

static void
isl_calc_phys_total_extent_el_gfx4_2d(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      const struct isl_tile_info *tile_info,
      enum isl_msaa_layout msaa_layout,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      enum isl_array_pitch_span array_pitch_span,
      uint32_t *array_pitch_el_rows,
      struct isl_extent4d *phys_total_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   struct isl_extent2d phys_slice0_sa;
   isl_calc_phys_slice0_extent_sa_gfx4_2d(dev, info, msaa_layout,
                                          image_align_sa, phys_level0_sa,
                                          &phys_slice0_sa);
   *array_pitch_el_rows =
      isl_calc_array_pitch_el_rows_gfx4_2d(dev, info, tile_info,
                                           image_align_sa, phys_level0_sa,
                                           array_pitch_span,
                                           &phys_slice0_sa);

   if (tile_info->tiling == ISL_TILING_64) {
      *phys_total_el = (struct isl_extent4d) {
         .w = isl_align_div_npot(phys_slice0_sa.w, fmtl->bw),
         .h = isl_align_div_npot(phys_slice0_sa.h, fmtl->bh),
         .d = isl_align_div_npot(phys_level0_sa->d, fmtl->bd),
         .a = phys_level0_sa->array_len,
      };
   } else {
      *phys_total_el = (struct isl_extent4d) {
         .w = isl_align_div_npot(phys_slice0_sa.w, fmtl->bw),
         .h = *array_pitch_el_rows * (phys_level0_sa->array_len - 1) +
              isl_align_div_npot(phys_slice0_sa.h, fmtl->bh),
         .d = 1,
         .a = 1,
      };
   }
}

/**
 * A variant of isl_calc_phys_slice0_extent_sa() specific to
 * ISL_DIM_LAYOUT_GFX4_3D.
 */
static void
isl_calc_phys_total_extent_el_gfx4_3d(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      uint32_t *array_pitch_el_rows,
      struct isl_extent4d *phys_total_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   assert(info->samples == 1);

   if (info->dim != ISL_SURF_DIM_3D) {
      /* From the G45 PRM Vol. 1a, "6.17.4.1 Hardware Cube Map Layout":
       *
       * The cube face textures are stored in the same way as 3D surfaces
       * are stored (see section 6.17.5 for details).  For cube surfaces,
       * however, the depth is equal to the number of faces (always 6) and
       * is not reduced for each MIP.
       */
      assert(ISL_GFX_VER(dev) == 4);
      assert(info->usage & ISL_SURF_USAGE_CUBE_BIT);
      assert(phys_level0_sa->array_len == 6);
   } else {
      assert(phys_level0_sa->array_len == 1);
   }

   uint32_t total_w = 0;
   uint32_t total_h = 0;

   uint32_t W0 = phys_level0_sa->w;
   uint32_t H0 = phys_level0_sa->h;
   uint32_t D0 = phys_level0_sa->d;
   uint32_t A0 = phys_level0_sa->a;

   for (uint32_t l = 0; l < info->levels; ++l) {
      uint32_t level_w = isl_align_npot(isl_minify(W0, l), image_align_sa->w);
      uint32_t level_h = isl_align_npot(isl_minify(H0, l), image_align_sa->h);
      uint32_t level_d = info->dim == ISL_SURF_DIM_3D ? isl_minify(D0, l) : A0;

      uint32_t max_layers_horiz = MIN(level_d, 1u << l);
      uint32_t max_layers_vert = isl_align(level_d, 1u << l) / (1u << l);

      total_w = MAX(total_w, level_w * max_layers_horiz);
      total_h += level_h * max_layers_vert;
   }

   /* GFX4_3D layouts don't really have an array pitch since each LOD has a
    * different number of horizontal and vertical layers.  We have to set it
    * to something, so at least make it true for LOD0.
    */
   *array_pitch_el_rows =
      isl_align_npot(phys_level0_sa->h, image_align_sa->h) / fmtl->bw;
   *phys_total_el = (struct isl_extent4d) {
      .w = isl_assert_div(total_w, fmtl->bw),
      .h = isl_assert_div(total_h, fmtl->bh),
      .d = 1,
      .a = 1,
   };
}

/**
 * A variant of isl_calc_phys_slice0_extent_sa() specific to
 * ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ.
 */
static void
isl_calc_phys_total_extent_el_gfx6_stencil_hiz(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      const struct isl_tile_info *tile_info,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      uint32_t *array_pitch_el_rows,
      struct isl_extent4d *phys_total_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   const struct isl_extent2d tile_extent_sa = {
      .w = tile_info->logical_extent_el.w * fmtl->bw,
      .h = tile_info->logical_extent_el.h * fmtl->bh,
   };
   /* Tile size is a multiple of image alignment */
   assert(tile_extent_sa.w % image_align_sa->w == 0);
   assert(tile_extent_sa.h % image_align_sa->h == 0);

   const uint32_t W0 = phys_level0_sa->w;
   const uint32_t H0 = phys_level0_sa->h;

   /* Each image has the same height as LOD0 because the hardware thinks
    * everything is LOD0
    */
   const uint32_t H = isl_align(H0, image_align_sa->h) * phys_level0_sa->a;

   uint32_t total_top_w = 0;
   uint32_t total_bottom_w = 0;
   uint32_t total_h = 0;

   for (uint32_t l = 0; l < info->levels; ++l) {
      const uint32_t W = isl_minify(W0, l);

      const uint32_t w = isl_align(W, tile_extent_sa.w);
      const uint32_t h = isl_align(H, tile_extent_sa.h);

      if (l == 0) {
         total_top_w = w;
         total_h = h;
      } else if (l == 1) {
         total_bottom_w = w;
         total_h += h;
      } else {
         total_bottom_w += w;
      }
   }

   *array_pitch_el_rows =
      isl_assert_div(isl_align(H0, image_align_sa->h), fmtl->bh);
   *phys_total_el = (struct isl_extent4d) {
      .w = isl_assert_div(MAX(total_top_w, total_bottom_w), fmtl->bw),
      .h = isl_assert_div(total_h, fmtl->bh),
      .d = 1,
      .a = 1,
   };
}

/**
 * A variant of isl_calc_phys_slice0_extent_sa() specific to
 * ISL_DIM_LAYOUT_GFX9_1D.
 */
static void
isl_calc_phys_total_extent_el_gfx9_1d(
      const struct isl_device *dev,
      const struct isl_surf_init_info *restrict info,
      const struct isl_extent3d *image_align_sa,
      const struct isl_extent4d *phys_level0_sa,
      uint32_t *array_pitch_el_rows,
      struct isl_extent4d *phys_total_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   assert(phys_level0_sa->height == 1);
   assert(phys_level0_sa->depth == 1);
   assert(info->samples == 1);
   assert(image_align_sa->w >= fmtl->bw);

   uint32_t slice_w = 0;
   const uint32_t W0 = phys_level0_sa->w;

   for (uint32_t l = 0; l < info->levels; ++l) {
      uint32_t W = isl_minify(W0, l);
      uint32_t w = isl_align_npot(W, image_align_sa->w);

      slice_w += w;
   }

   *array_pitch_el_rows = 1;
   *phys_total_el = (struct isl_extent4d) {
      .w = isl_assert_div(slice_w, fmtl->bw),
      .h = phys_level0_sa->array_len,
      .d = 1,
      .a = 1,
   };
}

/**
 * Calculate the two-dimensional total physical extent of the surface, in
 * units of surface elements.
 */
static void
isl_calc_phys_total_extent_el(const struct isl_device *dev,
                              const struct isl_surf_init_info *restrict info,
                              const struct isl_tile_info *tile_info,
                              enum isl_dim_layout dim_layout,
                              enum isl_msaa_layout msaa_layout,
                              const struct isl_extent3d *image_align_sa,
                              const struct isl_extent4d *phys_level0_sa,
                              enum isl_array_pitch_span array_pitch_span,
                              uint32_t *array_pitch_el_rows,
                              struct isl_extent4d *phys_total_el)
{
   switch (dim_layout) {
   case ISL_DIM_LAYOUT_GFX9_1D:
      assert(array_pitch_span == ISL_ARRAY_PITCH_SPAN_COMPACT);
      isl_calc_phys_total_extent_el_gfx9_1d(dev, info,
                                            image_align_sa, phys_level0_sa,
                                            array_pitch_el_rows,
                                            phys_total_el);
      return;
   case ISL_DIM_LAYOUT_GFX4_2D:
      isl_calc_phys_total_extent_el_gfx4_2d(dev, info, tile_info, msaa_layout,
                                            image_align_sa, phys_level0_sa,
                                            array_pitch_span,
                                            array_pitch_el_rows,
                                            phys_total_el);
      return;
   case ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ:
      assert(array_pitch_span == ISL_ARRAY_PITCH_SPAN_COMPACT);
      isl_calc_phys_total_extent_el_gfx6_stencil_hiz(dev, info, tile_info,
                                                     image_align_sa,
                                                     phys_level0_sa,
                                                     array_pitch_el_rows,
                                                     phys_total_el);
      return;
   case ISL_DIM_LAYOUT_GFX4_3D:
      assert(array_pitch_span == ISL_ARRAY_PITCH_SPAN_COMPACT);
      isl_calc_phys_total_extent_el_gfx4_3d(dev, info,
                                            image_align_sa, phys_level0_sa,
                                            array_pitch_el_rows,
                                            phys_total_el);
      return;
   }

   unreachable("invalid value for dim_layout");
}

static uint32_t
isl_calc_row_pitch_alignment(const struct isl_device *dev,
                             const struct isl_surf_init_info *surf_info,
                             const struct isl_tile_info *tile_info)
{
   if (tile_info->tiling != ISL_TILING_LINEAR) {
      /* According to BSpec: 44930, Gfx12's CCS-compressed surface pitches must
       * be 512B-aligned. CCS is only support on Y tilings.
       *
       * Only consider 512B alignment when :
       *    - AUX is not explicitly disabled
       *    - the caller has specified no pitch
       *
       * isl_surf_get_ccs_surf() will check that the main surface alignment
       * matches CCS expectations.
       */
      if (ISL_GFX_VER(dev) >= 12 &&
          isl_format_supports_ccs_e(dev->info, surf_info->format) &&
          tile_info->tiling != ISL_TILING_X &&
          !(surf_info->usage & ISL_SURF_USAGE_DISABLE_AUX_BIT) &&
          surf_info->row_pitch_B == 0) {
         return isl_align(tile_info->phys_extent_B.width, 512);
      }

      return tile_info->phys_extent_B.width;
   }

   /* From the Broadwel PRM >> Volume 2d: Command Reference: Structures >>
    * RENDER_SURFACE_STATE Surface Pitch (p349):
    *
    *    - For linear render target surfaces and surfaces accessed with the
    *      typed data port messages, the pitch must be a multiple of the
    *      element size for non-YUV surface formats.  Pitch must be
    *      a multiple of 2 * element size for YUV surface formats.
    *
    *    - [Requirements for SURFTYPE_BUFFER and SURFTYPE_STRBUF, which we
    *      ignore because isl doesn't do buffers.]
    *
    *    - For other linear surfaces, the pitch can be any multiple of
    *      bytes.
    */
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf_info->format);
   const uint32_t bs = fmtl->bpb / 8;
   uint32_t alignment;

   if (surf_info->usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) {
      if (isl_format_is_yuv(surf_info->format)) {
         alignment = 2 * bs;
      } else  {
         alignment = bs;
      }
   } else {
      alignment = 1;
   }

   /* From the Broadwell PRM >> Volume 2c: Command Reference: Registers >>
    * PRI_STRIDE Stride (p1254):
    *
    *    "When using linear memory, this must be at least 64 byte aligned."
    *
    * However, when displaying on NVIDIA and recent AMD GPUs via PRIME,
    * we need a larger pitch of 256 bytes.
    *
    * If the ISL caller didn't specify a row_pitch_B, then we should assume
    * the NVIDIA/AMD requirements. Otherwise, if we have a specified
    * row_pitch_B, this is probably because the caller is trying to import a
    * buffer. In that case we limit the minimum row pitch to the Intel HW
    * requirement.
    */
   if (surf_info->usage & ISL_SURF_USAGE_DISPLAY_BIT) {
      if (surf_info->row_pitch_B == 0)
         alignment = isl_align(alignment, 256);
      else
         alignment = isl_align(alignment, 64);
   }

   return alignment;
}

static uint32_t
isl_calc_linear_min_row_pitch(const struct isl_device *dev,
                              const struct isl_surf_init_info *info,
                              const struct isl_extent4d *phys_total_el,
                              uint32_t alignment_B)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);
   const uint32_t bs = fmtl->bpb / 8;

   return isl_align_npot(bs * phys_total_el->w, alignment_B);
}

static uint32_t
isl_calc_tiled_min_row_pitch(const struct isl_device *dev,
                             const struct isl_surf_init_info *surf_info,
                             const struct isl_tile_info *tile_info,
                             const struct isl_extent4d *phys_total_el,
                             uint32_t alignment_B)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf_info->format);

   assert(fmtl->bpb % tile_info->format_bpb == 0);

   const uint32_t tile_el_scale = fmtl->bpb / tile_info->format_bpb;
   const uint32_t total_w_tl =
      isl_align_div(phys_total_el->w * tile_el_scale,
                    tile_info->logical_extent_el.width);

   /* In some cases the alignment of the pitch might be > to the tile size
    * (for example Gfx12 CCS requires 512B alignment while the tile's width
    * can be 128B), so align the row pitch to the alignment.
    */
   assert(alignment_B >= tile_info->phys_extent_B.width);
   return isl_align(total_w_tl * tile_info->phys_extent_B.width, alignment_B);
}

static uint32_t
isl_calc_min_row_pitch(const struct isl_device *dev,
                       const struct isl_surf_init_info *surf_info,
                       const struct isl_tile_info *tile_info,
                       const struct isl_extent4d *phys_total_el,
                       uint32_t alignment_B)
{
   if (tile_info->tiling == ISL_TILING_LINEAR) {
      return isl_calc_linear_min_row_pitch(dev, surf_info, phys_total_el,
                                           alignment_B);
   } else {
      return isl_calc_tiled_min_row_pitch(dev, surf_info, tile_info,
                                          phys_total_el, alignment_B);
   }
}

/**
 * Is `pitch` in the valid range for a hardware bitfield, if the bitfield's
 * size is `bits` bits?
 *
 * Hardware pitch fields are offset by 1. For example, if the size of
 * RENDER_SURFACE_STATE::SurfacePitch is B bits, then the range of valid
 * pitches is [1, 2^b] inclusive.  If the surface pitch is N, then
 * RENDER_SURFACE_STATE::SurfacePitch must be set to N-1.
 */
static bool
pitch_in_range(uint32_t n, uint32_t bits)
{
   assert(n != 0);
   return likely(bits != 0 && 1 <= n && n <= (1 << bits));
}

static bool
isl_calc_row_pitch(const struct isl_device *dev,
                   const struct isl_surf_init_info *surf_info,
                   const struct isl_tile_info *tile_info,
                   enum isl_dim_layout dim_layout,
                   const struct isl_extent4d *phys_total_el,
                   uint32_t *out_row_pitch_B)
{
   uint32_t alignment_B =
      isl_calc_row_pitch_alignment(dev, surf_info, tile_info);

   const uint32_t min_row_pitch_B =
      isl_calc_min_row_pitch(dev, surf_info, tile_info, phys_total_el,
                             alignment_B);

   if (surf_info->row_pitch_B != 0) {
      if (surf_info->row_pitch_B < min_row_pitch_B)
         return false;

      if (surf_info->row_pitch_B % alignment_B != 0)
         return false;
   }

   const uint32_t row_pitch_B =
      surf_info->row_pitch_B != 0 ? surf_info->row_pitch_B : min_row_pitch_B;

   const uint32_t row_pitch_tl = row_pitch_B / tile_info->phys_extent_B.width;

   if (row_pitch_B == 0)
      return false;

   if (dim_layout == ISL_DIM_LAYOUT_GFX9_1D) {
      /* SurfacePitch is ignored for this layout. */
      goto done;
   }

   if ((surf_info->usage & (ISL_SURF_USAGE_RENDER_TARGET_BIT |
                            ISL_SURF_USAGE_TEXTURE_BIT |
                            ISL_SURF_USAGE_STORAGE_BIT)) &&
       !pitch_in_range(row_pitch_B, RENDER_SURFACE_STATE_SurfacePitch_bits(dev->info)))
      return false;

   if ((surf_info->usage & (ISL_SURF_USAGE_CCS_BIT |
                            ISL_SURF_USAGE_MCS_BIT)) &&
       !pitch_in_range(row_pitch_tl, RENDER_SURFACE_STATE_AuxiliarySurfacePitch_bits(dev->info)))
      return false;

   if ((surf_info->usage & ISL_SURF_USAGE_DEPTH_BIT) &&
       !pitch_in_range(row_pitch_B, _3DSTATE_DEPTH_BUFFER_SurfacePitch_bits(dev->info)))
      return false;

   if ((surf_info->usage & ISL_SURF_USAGE_HIZ_BIT) &&
       !pitch_in_range(row_pitch_B, _3DSTATE_HIER_DEPTH_BUFFER_SurfacePitch_bits(dev->info)))
      return false;

   const uint32_t stencil_pitch_bits = dev->use_separate_stencil ?
      _3DSTATE_STENCIL_BUFFER_SurfacePitch_bits(dev->info) :
      _3DSTATE_DEPTH_BUFFER_SurfacePitch_bits(dev->info);

   if ((surf_info->usage & ISL_SURF_USAGE_STENCIL_BIT) &&
       !pitch_in_range(row_pitch_B, stencil_pitch_bits))
      return false;

 done:
   *out_row_pitch_B = row_pitch_B;
   return true;
}

bool
isl_surf_init_s(const struct isl_device *dev,
                struct isl_surf *surf,
                const struct isl_surf_init_info *restrict info)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(info->format);

   const struct isl_extent4d logical_level0_px = {
      .w = info->width,
      .h = info->height,
      .d = info->depth,
      .a = info->array_len,
   };

   enum isl_tiling tiling;
   if (!isl_surf_choose_tiling(dev, info, &tiling))
      return false;

   const enum isl_dim_layout dim_layout =
      isl_surf_choose_dim_layout(dev, info->dim, tiling, info->usage);

   enum isl_msaa_layout msaa_layout;
   if (!isl_choose_msaa_layout(dev, info, tiling, &msaa_layout))
       return false;

   struct isl_tile_info tile_info;
   isl_tiling_get_info(tiling, info->dim, msaa_layout, fmtl->bpb,
                       info->samples, &tile_info);

   struct isl_extent3d image_align_el;
   isl_choose_image_alignment_el(dev, info, tiling, dim_layout, msaa_layout,
                                 &image_align_el);

   struct isl_extent3d image_align_sa =
      isl_extent3d_el_to_sa(info->format, image_align_el);

   struct isl_extent4d phys_level0_sa;
   isl_calc_phys_level0_extent_sa(dev, info, dim_layout, tiling, msaa_layout,
                                  &phys_level0_sa);

   enum isl_array_pitch_span array_pitch_span =
      isl_choose_array_pitch_span(dev, info, dim_layout, &phys_level0_sa);

   uint32_t array_pitch_el_rows;
   struct isl_extent4d phys_total_el;
   isl_calc_phys_total_extent_el(dev, info, &tile_info,
                                 dim_layout, msaa_layout,
                                 &image_align_sa, &phys_level0_sa,
                                 array_pitch_span, &array_pitch_el_rows,
                                 &phys_total_el);

   uint32_t row_pitch_B;
   if (!isl_calc_row_pitch(dev, info, &tile_info, dim_layout,
                           &phys_total_el, &row_pitch_B))
      return false;

   uint32_t base_alignment_B;
   uint64_t size_B;
   if (tiling == ISL_TILING_LINEAR) {
      /* LINEAR tiling has no concept of intra-tile arrays */
      assert(phys_total_el.d == 1 && phys_total_el.a == 1);

      size_B = (uint64_t) row_pitch_B * phys_total_el.h;

      /* From the Broadwell PRM Vol 2d, RENDER_SURFACE_STATE::SurfaceBaseAddress:
       *
       *    "The Base Address for linear render target surfaces and surfaces
       *    accessed with the typed surface read/write data port messages must
       *    be element-size aligned, for non-YUV surface formats, or a
       *    multiple of 2 element-sizes for YUV surface formats. Other linear
       *    surfaces have no alignment requirements (byte alignment is
       *    sufficient.)"
       */
      base_alignment_B = MAX(1, info->min_alignment_B);
      if (info->usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) {
         if (isl_format_is_yuv(info->format)) {
            base_alignment_B = MAX(base_alignment_B, fmtl->bpb / 4);
         } else {
            base_alignment_B = MAX(base_alignment_B, fmtl->bpb / 8);
         }
      }
      base_alignment_B = isl_round_up_to_power_of_two(base_alignment_B);

      /* From the Skylake PRM Vol 2c, PLANE_STRIDE::Stride:
       *
       *     "For Linear memory, this field specifies the stride in chunks of
       *     64 bytes (1 cache line)."
       */
      if (isl_surf_usage_is_display(info->usage))
         base_alignment_B = MAX(base_alignment_B, 64);
   } else {
      /* Pitches must make sense with the tiling */
      assert(row_pitch_B % tile_info.phys_extent_B.width == 0);

      uint32_t array_slices, array_pitch_tl_rows;
      if (phys_total_el.d > 1) {
         assert(phys_total_el.a == 1);
         array_pitch_tl_rows = isl_assert_div(array_pitch_el_rows,
                                              tile_info.logical_extent_el.h);
         array_slices = isl_align_div(phys_total_el.d,
                                      tile_info.logical_extent_el.d);
      } else if (phys_total_el.a > 1) {
         assert(phys_total_el.d == 1);
         array_pitch_tl_rows = isl_assert_div(array_pitch_el_rows,
                                              tile_info.logical_extent_el.h);
         array_slices = isl_align_div(phys_total_el.a,
                                      tile_info.logical_extent_el.a);
      } else {
         assert(phys_total_el.d == 1 && phys_total_el.a == 1);
         array_pitch_tl_rows = 0;
         array_slices = 1;
      }

      const uint32_t total_h_tl =
         (array_slices - 1) * array_pitch_tl_rows +
         isl_align_div(phys_total_el.h, tile_info.logical_extent_el.height);

      size_B = (uint64_t) total_h_tl * tile_info.phys_extent_B.height * row_pitch_B;

      const uint32_t tile_size_B = tile_info.phys_extent_B.width *
                                   tile_info.phys_extent_B.height;
      assert(isl_is_pow2(info->min_alignment_B) && isl_is_pow2(tile_size_B));
      base_alignment_B = MAX(info->min_alignment_B, tile_size_B);

      /* The diagram in the Bspec section Memory Compression - Gfx12, shows
       * that the CCS is indexed in 256B chunks. However, the
       * PLANE_AUX_DIST::Auxiliary Surface Distance field is in units of 4K
       * pages. We currently don't assign the usage field like we do for main
       * surfaces, so just use 4K for now.
       */
      if (tiling == ISL_TILING_GFX12_CCS)
         base_alignment_B = MAX(base_alignment_B, 4096);

      /* Gfx12+ requires that images be 64K-aligned if they're going to used
       * with CCS.  This is because the Aux translation table maps main
       * surface addresses to aux addresses at a 64K (in the main surface)
       * granularity.  Because we don't know for sure in ISL if a surface will
       * use CCS, we have to guess based on the DISABLE_AUX usage bit.  The
       * one thing we do know is that we haven't enable CCS on linear images
       * yet so we can avoid the extra alignment there.
       */
      if (ISL_GFX_VER(dev) >= 12 &&
          !(info->usage & ISL_SURF_USAGE_DISABLE_AUX_BIT)) {
         base_alignment_B = MAX(base_alignment_B, 64 * 1024);
      }
   }

   if (ISL_GFX_VER(dev) < 9) {
      /* From the Broadwell PRM Vol 5, Surface Layout:
       *
       *    "In addition to restrictions on maximum height, width, and depth,
       *     surfaces are also restricted to a maximum size in bytes. This
       *     maximum is 2 GB for all products and all surface types."
       *
       * This comment is applicable to all Pre-gfx9 platforms.
       */
      if (size_B > (uint64_t) 1 << 31)
         return false;
   } else if (ISL_GFX_VER(dev) < 11) {
      /* From the Skylake PRM Vol 5, Maximum Surface Size in Bytes:
       *    "In addition to restrictions on maximum height, width, and depth,
       *     surfaces are also restricted to a maximum size of 2^38 bytes.
       *     All pixels within the surface must be contained within 2^38 bytes
       *     of the base address."
       */
      if (size_B > (uint64_t) 1 << 38)
         return false;
   } else {
      /* gfx11+ platforms raised this limit to 2^44 bytes. */
      if (size_B > (uint64_t) 1 << 44)
         return false;
   }

   *surf = (struct isl_surf) {
      .dim = info->dim,
      .dim_layout = dim_layout,
      .msaa_layout = msaa_layout,
      .tiling = tiling,
      .format = info->format,

      .levels = info->levels,
      .samples = info->samples,

      .image_alignment_el = image_align_el,
      .logical_level0_px = logical_level0_px,
      .phys_level0_sa = phys_level0_sa,

      .size_B = size_B,
      .alignment_B = base_alignment_B,
      .row_pitch_B = row_pitch_B,
      .array_pitch_el_rows = array_pitch_el_rows,
      .array_pitch_span = array_pitch_span,

      .usage = info->usage,
   };

   return true;
}

void
isl_surf_get_tile_info(const struct isl_surf *surf,
                       struct isl_tile_info *tile_info)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);
   isl_tiling_get_info(surf->tiling, surf->dim, surf->msaa_layout, fmtl->bpb,
                       surf->samples, tile_info);
}

bool
isl_surf_get_hiz_surf(const struct isl_device *dev,
                      const struct isl_surf *surf,
                      struct isl_surf *hiz_surf)
{
   assert(ISL_GFX_VER(dev) >= 5 && ISL_DEV_USE_SEPARATE_STENCIL(dev));

   if (!isl_surf_usage_is_depth(surf->usage))
      return false;

   /* HiZ only works with Y-tiled depth buffers */
   if (!isl_tiling_is_any_y(surf->tiling))
      return false;

   /* On SNB+, compressed depth buffers cannot be interleaved with stencil. */
   switch (surf->format) {
   case ISL_FORMAT_R24_UNORM_X8_TYPELESS:
      if (isl_surf_usage_is_depth_and_stencil(surf->usage)) {
         assert(ISL_GFX_VER(dev) == 5);
         unreachable("This should work, but is untested");
      }
      FALLTHROUGH;
   case ISL_FORMAT_R16_UNORM:
   case ISL_FORMAT_R32_FLOAT:
      break;
   case ISL_FORMAT_R32_FLOAT_X8X24_TYPELESS:
      if (ISL_GFX_VER(dev) == 5) {
         assert(isl_surf_usage_is_depth_and_stencil(surf->usage));
         unreachable("This should work, but is untested");
      }
      FALLTHROUGH;
   default:
      return false;
   }

   /* Multisampled depth is always interleaved */
   assert(surf->msaa_layout == ISL_MSAA_LAYOUT_NONE ||
          surf->msaa_layout == ISL_MSAA_LAYOUT_INTERLEAVED);

   /* From the Broadwell PRM Vol. 7, "Hierarchical Depth Buffer":
    *
    *    "The Surface Type, Height, Width, Depth, Minimum Array Element, Render
    *    Target View Extent, and Depth Coordinate Offset X/Y of the
    *    hierarchical depth buffer are inherited from the depth buffer. The
    *    height and width of the hierarchical depth buffer that must be
    *    allocated are computed by the following formulas, where HZ is the
    *    hierarchical depth buffer and Z is the depth buffer. The Z_Height,
    *    Z_Width, and Z_Depth values given in these formulas are those present
    *    in 3DSTATE_DEPTH_BUFFER incremented by one.
    *
    *    "The value of Z_Height and Z_Width must each be multiplied by 2 before
    *    being applied to the table below if Number of Multisamples is set to
    *    NUMSAMPLES_4. The value of Z_Height must be multiplied by 2 and
    *    Z_Width must be multiplied by 4 before being applied to the table
    *    below if Number of Multisamples is set to NUMSAMPLES_8."
    *
    * In the Sky Lake PRM, the second paragraph is replaced with this:
    *
    *    "The Z_Height and Z_Width values must equal those present in
    *    3DSTATE_DEPTH_BUFFER incremented by one."
    *
    * In other words, on Sandy Bridge through Broadwell, each 128-bit HiZ
    * block corresponds to a region of 8x4 samples in the primary depth
    * surface.  On Sky Lake, on the other hand, each HiZ block corresponds to
    * a region of 8x4 pixels in the primary depth surface regardless of the
    * number of samples.  The dimensions of a HiZ block in both pixels and
    * samples are given in the table below:
    *
    *                    | SNB - BDW |     SKL+
    *              ------+-----------+-------------
    *                1x  |  8 x 4 sa |   8 x 4 sa
    *               MSAA |  8 x 4 px |   8 x 4 px
    *              ------+-----------+-------------
    *                2x  |  8 x 4 sa |  16 x 4 sa
    *               MSAA |  4 x 4 px |   8 x 4 px
    *              ------+-----------+-------------
    *                4x  |  8 x 4 sa |  16 x 8 sa
    *               MSAA |  4 x 2 px |   8 x 4 px
    *              ------+-----------+-------------
    *                8x  |  8 x 4 sa |  32 x 8 sa
    *               MSAA |  2 x 2 px |   8 x 4 px
    *              ------+-----------+-------------
    *               16x  |    N/A    | 32 x 16 sa
    *               MSAA |    N/A    |  8 x  4 px
    *              ------+-----------+-------------
    *
    * There are a number of different ways that this discrepency could be
    * handled.  The way we have chosen is to simply make MSAA HiZ have the
    * same number of samples as the parent surface pre-Sky Lake and always be
    * single-sampled on Sky Lake and above.  Since the block sizes of
    * compressed formats are given in samples, this neatly handles everything
    * without the need for additional HiZ formats with different block sizes
    * on SKL+.
    */
   const unsigned samples = ISL_GFX_VER(dev) >= 9 ? 1 : surf->samples;

   return isl_surf_init(dev, hiz_surf,
                        .dim = surf->dim,
                        .format = ISL_FORMAT_HIZ,
                        .width = surf->logical_level0_px.width,
                        .height = surf->logical_level0_px.height,
                        .depth = surf->logical_level0_px.depth,
                        .levels = surf->levels,
                        .array_len = surf->logical_level0_px.array_len,
                        .samples = samples,
                        .usage = ISL_SURF_USAGE_HIZ_BIT,
                        .tiling_flags = ISL_TILING_HIZ_BIT);
}

bool
isl_surf_get_mcs_surf(const struct isl_device *dev,
                      const struct isl_surf *surf,
                      struct isl_surf *mcs_surf)
{
   /* It must be multisampled with an array layout */
   if (surf->msaa_layout != ISL_MSAA_LAYOUT_ARRAY)
      return false;

   if (mcs_surf->size_B > 0)
      return false;

   /* The following are true of all multisampled surfaces */
   assert(surf->samples > 1);
   assert(surf->dim == ISL_SURF_DIM_2D);
   assert(surf->levels == 1);
   assert(surf->logical_level0_px.depth == 1);

   /* From the Ivy Bridge PRM, Vol4 Part1 p77 ("MCS Enable"):
    *
    *   This field must be set to 0 for all SINT MSRTs when all RT channels
    *   are not written
    *
    * In practice this means that we have to disable MCS for all signed
    * integer MSAA buffers.  The alternative, to disable MCS only when one
    * of the render target channels is disabled, is impractical because it
    * would require converting between CMS and UMS MSAA layouts on the fly,
    * which is expensive.
    */
   if (ISL_GFX_VER(dev) == 7 && isl_format_has_sint_channel(surf->format))
      return false;

   /* The "Auxiliary Surface Pitch" field in RENDER_SURFACE_STATE is only 9
    * bits which means the maximum pitch of a compression surface is 512
    * tiles or 64KB (since MCS is always Y-tiled).  Since a 16x MCS buffer is
    * 64bpp, this gives us a maximum width of 8192 pixels.  We can create
    * larger multisampled surfaces, we just can't compress them.   For 2x, 4x,
    * and 8x, we have enough room for the full 16k supported by the hardware.
    */
   if (surf->samples == 16 && surf->logical_level0_px.width > 8192)
      return false;

   enum isl_format mcs_format;
   switch (surf->samples) {
   case 2:  mcs_format = ISL_FORMAT_MCS_2X;  break;
   case 4:  mcs_format = ISL_FORMAT_MCS_4X;  break;
   case 8:  mcs_format = ISL_FORMAT_MCS_8X;  break;
   case 16: mcs_format = ISL_FORMAT_MCS_16X; break;
   default:
      unreachable("Invalid sample count");
   }

   return isl_surf_init(dev, mcs_surf,
                        .dim = ISL_SURF_DIM_2D,
                        .format = mcs_format,
                        .width = surf->logical_level0_px.width,
                        .height = surf->logical_level0_px.height,
                        .depth = 1,
                        .levels = 1,
                        .array_len = surf->logical_level0_px.array_len,
                        .samples = 1, /* MCS surfaces are really single-sampled */
                        .usage = ISL_SURF_USAGE_MCS_BIT,
                        .tiling_flags = ISL_TILING_Y0_BIT);
}

bool
isl_surf_supports_ccs(const struct isl_device *dev,
                      const struct isl_surf *surf,
                      const struct isl_surf *hiz_or_mcs_surf)
{
   /* CCS support does not exist prior to Gfx7 */
   if (ISL_GFX_VER(dev) <= 6)
      return false;

   /* Wa_22011186057: Disable compression on ADL-P A0 */
   if (dev->info->is_alderlake && dev->info->gt == 2 &&
       dev->info->revision == 0)
      return false;

   if (surf->usage & ISL_SURF_USAGE_DISABLE_AUX_BIT)
      return false;

   if (isl_format_is_compressed(surf->format))
      return false;

   if (!isl_is_pow2(isl_format_get_layout(surf->format)->bpb))
      return false;

   /* From the Ivy Bridge PRM, Vol2 Part1 11.7 "MCS Buffer for Render
    * Target(s)", beneath the "Fast Color Clear" bullet (p326):
    *
    *     - Support is limited to tiled render targets.
    *
    * From the Skylake documentation, it is made clear that X-tiling is no
    * longer supported:
    *
    *     - MCS and Lossless compression is supported for
    *       TiledY/TileYs/TileYf non-MSRTs only.
    *
    * From the BSpec (44930) for Gfx12:
    *
    *    Linear CCS is only allowed for Untyped Buffers but only via HDC
    *    Data-Port messages.
    *
    * We never use untyped messages on surfaces created by ISL on Gfx9+ so
    * this means linear is out on Gfx12+ as well.
    */
   if (surf->tiling == ISL_TILING_LINEAR)
      return false;

   if (ISL_GFX_VER(dev) >= 12) {
      if (isl_surf_usage_is_stencil(surf->usage)) {
         /* HiZ and MCS aren't allowed with stencil */
         assert(hiz_or_mcs_surf == NULL || hiz_or_mcs_surf->size_B == 0);

         /* Multi-sampled stencil cannot have CCS */
         if (surf->samples > 1)
            return false;
      } else if (isl_surf_usage_is_depth(surf->usage)) {
         const struct isl_surf *hiz_surf = hiz_or_mcs_surf;

         /* With depth surfaces, HIZ is required for CCS. */
         if (hiz_surf == NULL || hiz_surf->size_B == 0)
            return false;

         assert(hiz_surf->usage & ISL_SURF_USAGE_HIZ_BIT);
         assert(hiz_surf->tiling == ISL_TILING_HIZ);
         assert(hiz_surf->format == ISL_FORMAT_HIZ);
      } else if (surf->samples > 1) {
         const struct isl_surf *mcs_surf = hiz_or_mcs_surf;

         /* With multisampled color, CCS requires MCS */
         if (mcs_surf == NULL || mcs_surf->size_B == 0)
            return false;

         assert(mcs_surf->usage & ISL_SURF_USAGE_MCS_BIT);
         assert(isl_tiling_is_any_y(mcs_surf->tiling));
         assert(isl_format_is_mcs(mcs_surf->format));
      } else {
         /* Single-sampled color can't have MCS or HiZ */
         assert(hiz_or_mcs_surf == NULL || hiz_or_mcs_surf->size_B == 0);
      }

      /* On Gfx12, all CCS-compressed surface pitches must be multiples of
       * 512B.
       */
      if (surf->row_pitch_B % 512 != 0)
         return false;

      /* According to Wa_1406738321, 3D textures need a blit to a new
       * surface in order to perform a resolve. For now, just disable CCS.
       */
      if (surf->dim == ISL_SURF_DIM_3D) {
         isl_finishme("%s:%s: CCS for 3D textures is disabled, but a workaround"
                      " is available.", __FILE__, __func__);
         return false;
      }

      /* Wa_1207137018
       *
       * TODO: implement following workaround currently covered by the
       * restriction above. If following conditions are met:
       *
       *    - RENDER_SURFACE_STATE.Surface Type == 3D
       *    - RENDER_SURFACE_STATE.Auxiliary Surface Mode != AUX_NONE
       *    - RENDER_SURFACE_STATE.Tiled ResourceMode is TYF or TYS
       *
       * Set the value of RENDER_SURFACE_STATE.Mip Tail Start LOD to a mip
       * that larger than those present in the surface (i.e. 15)
       */

      /* TODO: Handle the other tiling formats */
      if (surf->tiling != ISL_TILING_Y0)
         return false;
   } else {
      /* ISL_GFX_VER(dev) < 12 */
      if (surf->samples > 1)
         return false;

      /* CCS is only for color images on Gfx7-11 */
      if (isl_surf_usage_is_depth_or_stencil(surf->usage))
         return false;

      /* We're single-sampled color so having HiZ or MCS makes no sense */
      assert(hiz_or_mcs_surf == NULL || hiz_or_mcs_surf->size_B == 0);

      /* The PRM doesn't say this explicitly, but fast-clears don't appear to
       * work for 3D textures until gfx9 where the layout of 3D textures
       * changes to match 2D array textures.
       */
      if (ISL_GFX_VER(dev) <= 8 && surf->dim != ISL_SURF_DIM_2D)
         return false;

      /* From the HSW PRM Volume 7: 3D-Media-GPGPU, page 652 (Color Clear of
       * Non-MultiSampler Render Target Restrictions):
       *
       *    "Support is for non-mip-mapped and non-array surface types only."
       *
       * This restriction is lifted on gfx8+.  Technically, it may be possible
       * to create a CCS for an arrayed or mipmapped image and only enable
       * CCS_D when rendering to the base slice.  However, there is no
       * documentation tell us what the hardware would do in that case or what
       * it does if you walk off the bases slice.  (Does it ignore CCS or does
       * it start scribbling over random memory?)  We play it safe and just
       * follow the docs and don't allow CCS_D for arrayed or mip-mapped
       * surfaces.
       */
      if (ISL_GFX_VER(dev) <= 7 &&
          (surf->levels > 1 || surf->logical_level0_px.array_len > 1))
         return false;

      /* From the Ivy Bridge PRM, Vol2 Part1 11.7 "MCS Buffer for Render
       * Target(s)", beneath the "Fast Color Clear" bullet (p326):
       *
       *     - MCS buffer for non-MSRT is supported only for RT formats 32bpp,
       *       64bpp, and 128bpp.
       */
      if (isl_format_get_layout(surf->format)->bpb < 32)
         return false;

      /* From the Skylake documentation, it is made clear that X-tiling is no
       * longer supported:
       *
       *     - MCS and Lossless compression is supported for
       *     TiledY/TileYs/TileYf non-MSRTs only.
       */
      if (ISL_GFX_VER(dev) >= 9 && !isl_tiling_is_any_y(surf->tiling))
         return false;
   }

   return true;
}

bool
isl_surf_get_ccs_surf(const struct isl_device *dev,
                      const struct isl_surf *surf,
                      const struct isl_surf *hiz_or_mcs_surf,
                      struct isl_surf *ccs_surf,
                      uint32_t row_pitch_B)
{
   if (!isl_surf_supports_ccs(dev, surf, hiz_or_mcs_surf))
      return false;

   if (ISL_GFX_VER(dev) >= 12) {
      enum isl_format ccs_format;
      switch (isl_format_get_layout(surf->format)->bpb) {
      case 8:     ccs_format = ISL_FORMAT_GFX12_CCS_8BPP_Y0;    break;
      case 16:    ccs_format = ISL_FORMAT_GFX12_CCS_16BPP_Y0;   break;
      case 32:    ccs_format = ISL_FORMAT_GFX12_CCS_32BPP_Y0;   break;
      case 64:    ccs_format = ISL_FORMAT_GFX12_CCS_64BPP_Y0;   break;
      case 128:   ccs_format = ISL_FORMAT_GFX12_CCS_128BPP_Y0;  break;
      default:
         return false;
      }

      /* On Gfx12, the CCS is a scaled-down version of the main surface. We
       * model this as the CCS compressing a 2D-view of the entire surface.
       */
      const bool ok =
         isl_surf_init(dev, ccs_surf,
                       .dim = ISL_SURF_DIM_2D,
                       .format = ccs_format,
                       .width = isl_surf_get_row_pitch_el(surf),
                       .height = surf->size_B / surf->row_pitch_B,
                       .depth = 1,
                       .levels = 1,
                       .array_len = 1,
                       .samples = 1,
                       .row_pitch_B = row_pitch_B,
                       .usage = ISL_SURF_USAGE_CCS_BIT,
                       .tiling_flags = ISL_TILING_GFX12_CCS_BIT);
      assert(!ok || ccs_surf->size_B == surf->size_B / 256);
      return ok;
   } else {
      enum isl_format ccs_format;
      if (ISL_GFX_VER(dev) >= 9) {
         switch (isl_format_get_layout(surf->format)->bpb) {
         case 32:    ccs_format = ISL_FORMAT_GFX9_CCS_32BPP;   break;
         case 64:    ccs_format = ISL_FORMAT_GFX9_CCS_64BPP;   break;
         case 128:   ccs_format = ISL_FORMAT_GFX9_CCS_128BPP;  break;
         default:    unreachable("Unsupported CCS format");
            return false;
         }
      } else if (surf->tiling == ISL_TILING_Y0) {
         switch (isl_format_get_layout(surf->format)->bpb) {
         case 32:    ccs_format = ISL_FORMAT_GFX7_CCS_32BPP_Y;    break;
         case 64:    ccs_format = ISL_FORMAT_GFX7_CCS_64BPP_Y;    break;
         case 128:   ccs_format = ISL_FORMAT_GFX7_CCS_128BPP_Y;   break;
         default:    unreachable("Unsupported CCS format");
         }
      } else if (surf->tiling == ISL_TILING_X) {
         switch (isl_format_get_layout(surf->format)->bpb) {
         case 32:    ccs_format = ISL_FORMAT_GFX7_CCS_32BPP_X;    break;
         case 64:    ccs_format = ISL_FORMAT_GFX7_CCS_64BPP_X;    break;
         case 128:   ccs_format = ISL_FORMAT_GFX7_CCS_128BPP_X;   break;
         default:    unreachable("Unsupported CCS format");
         }
      } else {
         unreachable("Invalid tiling format");
      }

      return isl_surf_init(dev, ccs_surf,
                           .dim = surf->dim,
                           .format = ccs_format,
                           .width = surf->logical_level0_px.width,
                           .height = surf->logical_level0_px.height,
                           .depth = surf->logical_level0_px.depth,
                           .levels = surf->levels,
                           .array_len = surf->logical_level0_px.array_len,
                           .samples = 1,
                           .row_pitch_B = row_pitch_B,
                           .usage = ISL_SURF_USAGE_CCS_BIT,
                           .tiling_flags = ISL_TILING_CCS_BIT);
   }
}

#define isl_genX_call(dev, func, ...)              \
   switch (ISL_GFX_VERX10(dev)) {                  \
   case 40:                                        \
      isl_gfx4_##func(__VA_ARGS__);                \
      break;                                       \
   case 45:                                        \
      /* G45 surface state is the same as gfx5 */  \
   case 50:                                        \
      isl_gfx5_##func(__VA_ARGS__);                \
      break;                                       \
   case 60:                                        \
      isl_gfx6_##func(__VA_ARGS__);                \
      break;                                       \
   case 70:                                        \
      isl_gfx7_##func(__VA_ARGS__);                \
      break;                                       \
   case 75:                                        \
      isl_gfx75_##func(__VA_ARGS__);               \
      break;                                       \
   case 80:                                        \
      isl_gfx8_##func(__VA_ARGS__);                \
      break;                                       \
   case 90:                                        \
      isl_gfx9_##func(__VA_ARGS__);                \
      break;                                       \
   case 110:                                       \
      isl_gfx11_##func(__VA_ARGS__);               \
      break;                                       \
   case 120:                                       \
      isl_gfx12_##func(__VA_ARGS__);               \
      break;                                       \
   case 125:                                       \
      isl_gfx125_##func(__VA_ARGS__);              \
      break;                                       \
   default:                                        \
      assert(!"Unknown hardware generation");      \
   }

void
isl_surf_fill_state_s(const struct isl_device *dev, void *state,
                      const struct isl_surf_fill_state_info *restrict info)
{
#ifndef NDEBUG
   isl_surf_usage_flags_t _base_usage =
      info->view->usage & (ISL_SURF_USAGE_RENDER_TARGET_BIT |
                           ISL_SURF_USAGE_TEXTURE_BIT |
                           ISL_SURF_USAGE_STORAGE_BIT);
   /* They may only specify one of the above bits at a time */
   assert(__builtin_popcount(_base_usage) == 1);
   /* The only other allowed bit is ISL_SURF_USAGE_CUBE_BIT */
   assert((info->view->usage & ~ISL_SURF_USAGE_CUBE_BIT) == _base_usage);
#endif

   if (info->surf->dim == ISL_SURF_DIM_3D) {
      assert(info->view->base_array_layer + info->view->array_len <=
             info->surf->logical_level0_px.depth);
   } else {
      assert(info->view->base_array_layer + info->view->array_len <=
             info->surf->logical_level0_px.array_len);
   }

   isl_genX_call(dev, surf_fill_state_s, dev, state, info);
}

void
isl_buffer_fill_state_s(const struct isl_device *dev, void *state,
                        const struct isl_buffer_fill_state_info *restrict info)
{
   isl_genX_call(dev, buffer_fill_state_s, dev, state, info);
}

void
isl_null_fill_state_s(const struct isl_device *dev, void *state,
                      const struct isl_null_fill_state_info *restrict info)
{
   isl_genX_call(dev, null_fill_state, dev, state, info);
}

void
isl_emit_depth_stencil_hiz_s(const struct isl_device *dev, void *batch,
                             const struct isl_depth_stencil_hiz_emit_info *restrict info)
{
   if (info->depth_surf && info->stencil_surf) {
      if (!dev->info->has_hiz_and_separate_stencil) {
         assert(info->depth_surf == info->stencil_surf);
         assert(info->depth_address == info->stencil_address);
      }
      assert(info->depth_surf->dim == info->stencil_surf->dim);
   }

   if (info->depth_surf) {
      assert((info->depth_surf->usage & ISL_SURF_USAGE_DEPTH_BIT));
      if (info->depth_surf->dim == ISL_SURF_DIM_3D) {
         assert(info->view->base_array_layer + info->view->array_len <=
                info->depth_surf->logical_level0_px.depth);
      } else {
         assert(info->view->base_array_layer + info->view->array_len <=
                info->depth_surf->logical_level0_px.array_len);
      }
   }

   if (info->stencil_surf) {
      assert((info->stencil_surf->usage & ISL_SURF_USAGE_STENCIL_BIT));
      if (info->stencil_surf->dim == ISL_SURF_DIM_3D) {
         assert(info->view->base_array_layer + info->view->array_len <=
                info->stencil_surf->logical_level0_px.depth);
      } else {
         assert(info->view->base_array_layer + info->view->array_len <=
                info->stencil_surf->logical_level0_px.array_len);
      }
   }

   isl_genX_call(dev, emit_depth_stencil_hiz_s, dev, batch, info);
}

/**
 * A variant of isl_surf_get_image_offset_sa() specific to
 * ISL_DIM_LAYOUT_GFX4_2D.
 */
static void
get_image_offset_sa_gfx4_2d(const struct isl_surf *surf,
                            uint32_t level, uint32_t logical_array_layer,
                            uint32_t *x_offset_sa,
                            uint32_t *y_offset_sa)
{
   assert(level < surf->levels);
   if (surf->dim == ISL_SURF_DIM_3D)
      assert(logical_array_layer < surf->logical_level0_px.depth);
   else
      assert(logical_array_layer < surf->logical_level0_px.array_len);

   const struct isl_extent3d image_align_sa =
      isl_surf_get_image_alignment_sa(surf);

   const uint32_t W0 = surf->phys_level0_sa.width;
   const uint32_t H0 = surf->phys_level0_sa.height;

   const uint32_t phys_layer = logical_array_layer *
      (surf->msaa_layout == ISL_MSAA_LAYOUT_ARRAY ? surf->samples : 1);

   uint32_t x = 0;
   uint32_t y = phys_layer * isl_surf_get_array_pitch_sa_rows(surf);

   for (uint32_t l = 0; l < level; ++l) {
      if (l == 1) {
         uint32_t W = isl_minify(W0, l);
         x += isl_align_npot(W, image_align_sa.w);
      } else {
         uint32_t H = isl_minify(H0, l);
         y += isl_align_npot(H, image_align_sa.h);
      }
   }

   *x_offset_sa = x;
   *y_offset_sa = y;
}

/**
 * A variant of isl_surf_get_image_offset_sa() specific to
 * ISL_DIM_LAYOUT_GFX4_3D.
 */
static void
get_image_offset_sa_gfx4_3d(const struct isl_surf *surf,
                            uint32_t level, uint32_t logical_z_offset_px,
                            uint32_t *x_offset_sa,
                            uint32_t *y_offset_sa)
{
   assert(level < surf->levels);
   if (surf->dim == ISL_SURF_DIM_3D) {
      assert(surf->phys_level0_sa.array_len == 1);
      assert(logical_z_offset_px < isl_minify(surf->phys_level0_sa.depth, level));
   } else {
      assert(surf->dim == ISL_SURF_DIM_2D);
      assert(surf->usage & ISL_SURF_USAGE_CUBE_BIT);
      assert(surf->phys_level0_sa.array_len == 6);
      assert(logical_z_offset_px < surf->phys_level0_sa.array_len);
   }

   const struct isl_extent3d image_align_sa =
      isl_surf_get_image_alignment_sa(surf);

   const uint32_t W0 = surf->phys_level0_sa.width;
   const uint32_t H0 = surf->phys_level0_sa.height;
   const uint32_t D0 = surf->phys_level0_sa.depth;
   const uint32_t AL = surf->phys_level0_sa.array_len;

   uint32_t x = 0;
   uint32_t y = 0;

   for (uint32_t l = 0; l < level; ++l) {
      const uint32_t level_h = isl_align_npot(isl_minify(H0, l), image_align_sa.h);
      const uint32_t level_d =
         isl_align_npot(surf->dim == ISL_SURF_DIM_3D ? isl_minify(D0, l) : AL,
                        image_align_sa.d);
      const uint32_t max_layers_vert = isl_align(level_d, 1u << l) / (1u << l);

      y += level_h * max_layers_vert;
   }

   const uint32_t level_w = isl_align_npot(isl_minify(W0, level), image_align_sa.w);
   const uint32_t level_h = isl_align_npot(isl_minify(H0, level), image_align_sa.h);
   const uint32_t level_d =
      isl_align_npot(surf->dim == ISL_SURF_DIM_3D ? isl_minify(D0, level) : AL,
                     image_align_sa.d);

   const uint32_t max_layers_horiz = MIN(level_d, 1u << level);

   x += level_w * (logical_z_offset_px % max_layers_horiz);
   y += level_h * (logical_z_offset_px / max_layers_horiz);

   *x_offset_sa = x;
   *y_offset_sa = y;
}

static void
get_image_offset_sa_gfx6_stencil_hiz(const struct isl_surf *surf,
                                     uint32_t level,
                                     uint32_t logical_array_layer,
                                     uint32_t *x_offset_sa,
                                     uint32_t *y_offset_sa)
{
   assert(level < surf->levels);
   assert(surf->logical_level0_px.depth == 1);
   assert(logical_array_layer < surf->logical_level0_px.array_len);

   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);

   const struct isl_extent3d image_align_sa =
      isl_surf_get_image_alignment_sa(surf);

   struct isl_tile_info tile_info;
   isl_surf_get_tile_info(surf, &tile_info);
   const struct isl_extent2d tile_extent_sa = {
      .w = tile_info.logical_extent_el.w * fmtl->bw,
      .h = tile_info.logical_extent_el.h * fmtl->bh,
   };
   /* Tile size is a multiple of image alignment */
   assert(tile_extent_sa.w % image_align_sa.w == 0);
   assert(tile_extent_sa.h % image_align_sa.h == 0);

   const uint32_t W0 = surf->phys_level0_sa.w;
   const uint32_t H0 = surf->phys_level0_sa.h;

   /* Each image has the same height as LOD0 because the hardware thinks
    * everything is LOD0
    */
   const uint32_t H = isl_align(H0, image_align_sa.h);

   /* Quick sanity check for consistency */
   if (surf->phys_level0_sa.array_len > 1)
      assert(surf->array_pitch_el_rows == isl_assert_div(H, fmtl->bh));

   uint32_t x = 0, y = 0;
   for (uint32_t l = 0; l < level; ++l) {
      const uint32_t W = isl_minify(W0, l);

      const uint32_t w = isl_align(W, tile_extent_sa.w);
      const uint32_t h = isl_align(H * surf->phys_level0_sa.a,
                                   tile_extent_sa.h);

      if (l == 0) {
         y += h;
      } else {
         x += w;
      }
   }

   y += H * logical_array_layer;

   *x_offset_sa = x;
   *y_offset_sa = y;
}

/**
 * A variant of isl_surf_get_image_offset_sa() specific to
 * ISL_DIM_LAYOUT_GFX9_1D.
 */
static void
get_image_offset_sa_gfx9_1d(const struct isl_surf *surf,
                            uint32_t level, uint32_t layer,
                            uint32_t *x_offset_sa,
                            uint32_t *y_offset_sa)
{
   assert(level < surf->levels);
   assert(layer < surf->phys_level0_sa.array_len);
   assert(surf->phys_level0_sa.height == 1);
   assert(surf->phys_level0_sa.depth == 1);
   assert(surf->samples == 1);

   const uint32_t W0 = surf->phys_level0_sa.width;
   const struct isl_extent3d image_align_sa =
      isl_surf_get_image_alignment_sa(surf);

   uint32_t x = 0;

   for (uint32_t l = 0; l < level; ++l) {
      uint32_t W = isl_minify(W0, l);
      uint32_t w = isl_align_npot(W, image_align_sa.w);

      x += w;
   }

   *x_offset_sa = x;
   *y_offset_sa = layer * isl_surf_get_array_pitch_sa_rows(surf);
}

/**
 * Calculate the offset, in units of surface samples, to a subimage in the
 * surface.
 *
 * @invariant level < surface levels
 * @invariant logical_array_layer < logical array length of surface
 * @invariant logical_z_offset_px < logical depth of surface at level
 */
void
isl_surf_get_image_offset_sa(const struct isl_surf *surf,
                             uint32_t level,
                             uint32_t logical_array_layer,
                             uint32_t logical_z_offset_px,
                             uint32_t *x_offset_sa,
                             uint32_t *y_offset_sa,
                             uint32_t *z_offset_sa,
                             uint32_t *array_offset)
{
   assert(level < surf->levels);
   assert(logical_array_layer < surf->logical_level0_px.array_len);
   assert(logical_z_offset_px
          < isl_minify(surf->logical_level0_px.depth, level));

   switch (surf->dim_layout) {
   case ISL_DIM_LAYOUT_GFX9_1D:
      get_image_offset_sa_gfx9_1d(surf, level, logical_array_layer,
                                  x_offset_sa, y_offset_sa);
      *z_offset_sa = 0;
      *array_offset = 0;
      break;
   case ISL_DIM_LAYOUT_GFX4_2D:
      get_image_offset_sa_gfx4_2d(surf, level, logical_array_layer
                                  + logical_z_offset_px,
                                  x_offset_sa, y_offset_sa);
      *z_offset_sa = 0;
      *array_offset = 0;
      break;
   case ISL_DIM_LAYOUT_GFX4_3D:
      get_image_offset_sa_gfx4_3d(surf, level, logical_array_layer +
                                  logical_z_offset_px,
                                  x_offset_sa, y_offset_sa);
      *z_offset_sa = 0;
      *array_offset = 0;
      break;
   case ISL_DIM_LAYOUT_GFX6_STENCIL_HIZ:
      get_image_offset_sa_gfx6_stencil_hiz(surf, level, logical_array_layer +
                                           logical_z_offset_px,
                                           x_offset_sa, y_offset_sa);
      *z_offset_sa = 0;
      *array_offset = 0;
      break;

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

void
isl_surf_get_image_offset_el(const struct isl_surf *surf,
                             uint32_t level,
                             uint32_t logical_array_layer,
                             uint32_t logical_z_offset_px,
                             uint32_t *x_offset_el,
                             uint32_t *y_offset_el,
                             uint32_t *z_offset_el,
                             uint32_t *array_offset)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);

   assert(level < surf->levels);
   assert(logical_array_layer < surf->logical_level0_px.array_len);
   assert(logical_z_offset_px
          < isl_minify(surf->logical_level0_px.depth, level));

   uint32_t x_offset_sa, y_offset_sa, z_offset_sa;
   isl_surf_get_image_offset_sa(surf, level,
                                logical_array_layer,
                                logical_z_offset_px,
                                &x_offset_sa,
                                &y_offset_sa,
                                &z_offset_sa,
                                array_offset);

   *x_offset_el = x_offset_sa / fmtl->bw;
   *y_offset_el = y_offset_sa / fmtl->bh;
   *z_offset_el = z_offset_sa / fmtl->bd;
}

void
isl_surf_get_image_offset_B_tile_sa(const struct isl_surf *surf,
                                    uint32_t level,
                                    uint32_t logical_array_layer,
                                    uint32_t logical_z_offset_px,
                                    uint64_t *offset_B,
                                    uint32_t *x_offset_sa,
                                    uint32_t *y_offset_sa)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);

   uint32_t x_offset_el, y_offset_el;
   isl_surf_get_image_offset_B_tile_el(surf, level,
                                       logical_array_layer,
                                       logical_z_offset_px,
                                       offset_B,
                                       &x_offset_el,
                                       &y_offset_el);

   if (x_offset_sa) {
      *x_offset_sa = x_offset_el * fmtl->bw;
   } else {
      assert(x_offset_el == 0);
   }

   if (y_offset_sa) {
      *y_offset_sa = y_offset_el * fmtl->bh;
   } else {
      assert(y_offset_el == 0);
   }
}

void
isl_surf_get_image_offset_B_tile_el(const struct isl_surf *surf,
                                    uint32_t level,
                                    uint32_t logical_array_layer,
                                    uint32_t logical_z_offset_px,
                                    uint64_t *offset_B,
                                    uint32_t *x_offset_el,
                                    uint32_t *y_offset_el)
{
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);

   uint32_t total_x_offset_el, total_y_offset_el;
   uint32_t total_z_offset_el, total_array_offset;
   isl_surf_get_image_offset_el(surf, level, logical_array_layer,
                                logical_z_offset_px,
                                &total_x_offset_el,
                                &total_y_offset_el,
                                &total_z_offset_el,
                                &total_array_offset);

   uint32_t z_offset_el, array_offset;
   isl_tiling_get_intratile_offset_el(surf->tiling, surf->dim,
                                      surf->msaa_layout, fmtl->bpb,
                                      surf->samples,
                                      surf->row_pitch_B,
                                      surf->array_pitch_el_rows,
                                      total_x_offset_el,
                                      total_y_offset_el,
                                      total_z_offset_el,
                                      total_array_offset,
                                      offset_B,
                                      x_offset_el,
                                      y_offset_el,
                                      &z_offset_el,
                                      &array_offset);
   assert(z_offset_el == 0);
   assert(array_offset == 0);
}

void
isl_surf_get_image_range_B_tile(const struct isl_surf *surf,
                                uint32_t level,
                                uint32_t logical_array_layer,
                                uint32_t logical_z_offset_px,
                                uint64_t *start_tile_B,
                                uint64_t *end_tile_B)
{
   uint32_t start_x_offset_el, start_y_offset_el;
   uint32_t start_z_offset_el, start_array_slice;
   isl_surf_get_image_offset_el(surf, level, logical_array_layer,
                                logical_z_offset_px,
                                &start_x_offset_el,
                                &start_y_offset_el,
                                &start_z_offset_el,
                                &start_array_slice);

   /* Compute the size of the subimage in surface elements */
   const uint32_t subimage_w_sa = isl_minify(surf->phys_level0_sa.w, level);
   const uint32_t subimage_h_sa = isl_minify(surf->phys_level0_sa.h, level);
   const struct isl_format_layout *fmtl = isl_format_get_layout(surf->format);
   const uint32_t subimage_w_el = isl_align_div_npot(subimage_w_sa, fmtl->bw);
   const uint32_t subimage_h_el = isl_align_div_npot(subimage_h_sa, fmtl->bh);

   /* Find the last pixel */
   uint32_t end_x_offset_el = start_x_offset_el + subimage_w_el - 1;
   uint32_t end_y_offset_el = start_y_offset_el + subimage_h_el - 1;

   /* We only consider one Z or array slice */
   const uint32_t end_z_offset_el = start_z_offset_el;
   const uint32_t end_array_slice = start_array_slice;

   UNUSED uint32_t x_offset_el, y_offset_el, z_offset_el, array_slice;
   isl_tiling_get_intratile_offset_el(surf->tiling, surf->dim,
                                      surf->msaa_layout, fmtl->bpb,
                                      surf->samples,
                                      surf->row_pitch_B,
                                      surf->array_pitch_el_rows,
                                      start_x_offset_el,
                                      start_y_offset_el,
                                      start_z_offset_el,
                                      start_array_slice,
                                      start_tile_B,
                                      &x_offset_el,
                                      &y_offset_el,
                                      &z_offset_el,
                                      &array_slice);

   isl_tiling_get_intratile_offset_el(surf->tiling, surf->dim,
                                      surf->msaa_layout, fmtl->bpb,
                                      surf->samples,
                                      surf->row_pitch_B,
                                      surf->array_pitch_el_rows,
                                      end_x_offset_el,
                                      end_y_offset_el,
                                      end_z_offset_el,
                                      end_array_slice,
                                      end_tile_B,
                                      &x_offset_el,
                                      &y_offset_el,
                                      &z_offset_el,
                                      &array_slice);

   /* We want the range we return to be exclusive but the tile containing the
    * last pixel (what we just calculated) is inclusive.  Add one.
    */
   (*end_tile_B)++;

   assert(*end_tile_B <= surf->size_B);
}

void
isl_surf_get_image_surf(const struct isl_device *dev,
                        const struct isl_surf *surf,
                        uint32_t level,
                        uint32_t logical_array_layer,
                        uint32_t logical_z_offset_px,
                        struct isl_surf *image_surf,
                        uint64_t *offset_B,
                        uint32_t *x_offset_sa,
                        uint32_t *y_offset_sa)
{
   isl_surf_get_image_offset_B_tile_sa(surf,
                                       level,
                                       logical_array_layer,
                                       logical_z_offset_px,
                                       offset_B,
                                       x_offset_sa,
                                       y_offset_sa);

   /* Even for cube maps there will be only single face, therefore drop the
    * corresponding flag if present.
    */
   const isl_surf_usage_flags_t usage =
      surf->usage & (~ISL_SURF_USAGE_CUBE_BIT);

   bool ok UNUSED;
   ok = isl_surf_init(dev, image_surf,
                      .dim = ISL_SURF_DIM_2D,
                      .format = surf->format,
                      .width = isl_minify(surf->logical_level0_px.w, level),
                      .height = isl_minify(surf->logical_level0_px.h, level),
                      .depth = 1,
                      .levels = 1,
                      .array_len = 1,
                      .samples = surf->samples,
                      .row_pitch_B = surf->row_pitch_B,
                      .usage = usage,
                      .tiling_flags = (1 << surf->tiling));
   assert(ok);
}

bool
isl_surf_get_uncompressed_surf(const struct isl_device *dev,
                               const struct isl_surf *surf,
                               const struct isl_view *view,
                               struct isl_surf *ucompr_surf,
                               struct isl_view *ucompr_view,
                               uint64_t *offset_B,
                               uint32_t *x_offset_el,
                               uint32_t *y_offset_el)
{
   const struct isl_format_layout *fmtl =
      isl_format_get_layout(surf->format);
   const enum isl_format view_format = view->format;

   assert(fmtl->bw > 1 || fmtl->bh > 1 || fmtl->bd > 1);
   assert(isl_format_is_compressed(surf->format));
   assert(!isl_format_is_compressed(view->format));
   assert(isl_format_get_layout(view->format)->bpb == fmtl->bpb);
   assert(view->levels == 1);

   const uint32_t view_width_px =
      isl_minify(surf->logical_level0_px.width, view->base_level);
   const uint32_t view_height_px =
      isl_minify(surf->logical_level0_px.height, view->base_level);

   assert(surf->samples == 1);
   const uint32_t view_width_el = isl_align_div_npot(view_width_px, fmtl->bw);
   const uint32_t view_height_el = isl_align_div_npot(view_height_px, fmtl->bh);

   /* If we ever enable 3D block formats, we'll need to re-think this */
   assert(fmtl->bd == 1);

   if (view->array_len > 1) {
      /* The Skylake PRM Vol. 2d, "RENDER_SURFACE_STATE::X Offset" says:
       *
       *    "If Surface Array is enabled, this field must be zero."
       *
       * The PRMs for other hardware have similar text.  This is also tricky
       * to handle with things like BLORP's SW offsetting because the
       * increased surface size required for the offset may result in an image
       * height greater than qpitch.
       */
      if (view->base_level > 0)
         return false;

      /* On Haswell and earlier, RENDER_SURFACE_STATE doesn't have a QPitch
       * field; it only has "array pitch span" which means the QPitch is
       * automatically calculated.  Since we're smashing the surface format
       * (block formats are subtly different) and the number of miplevels,
       * that calculation will get thrown off.  This means we can't do arrays
       * even at LOD0
       *
       * On Broadwell, we do have a QPitch field which we can control.
       * However, HALIGN and VALIGN are specified in pixels and are
       * hard-coded to align to exactly the block size of the compressed
       * texture.  This means that, when reinterpreted as a non-compressed
       * the QPitch may be anything but the HW requires it to be properly
       * aligned.
       */
      if (ISL_GFX_VER(dev) < 9)
         return false;

      *ucompr_surf = *surf;
      ucompr_surf->levels = 1;
      ucompr_surf->format = view_format;

      /* We're making an uncompressed view here.  The image dimensions
       * need to be scaled down by the block size.
       */
      assert(ucompr_surf->logical_level0_px.width == view_width_px);
      assert(ucompr_surf->logical_level0_px.height == view_height_px);
      ucompr_surf->logical_level0_px.width = view_width_el;
      ucompr_surf->logical_level0_px.height = view_height_el;
      ucompr_surf->phys_level0_sa = isl_surf_get_phys_level0_el(surf);

      /* The surface mostly stays as-is; there is no offset */
      *offset_B = 0;
      *x_offset_el = 0;
      *y_offset_el = 0;

      /* The view remains the same */
      *ucompr_view = *view;
   } else {
      /* If only one array slice is requested, directly offset to that slice.
       * We could, in theory, still use arrays in some cases but BLORP isn't
       * prepared for this and everyone who calls this function should be
       * prepared to handle an X/Y offset.
       */
      isl_surf_get_image_offset_B_tile_el(surf,
                                          view->base_level,
                                          surf->dim == ISL_SURF_DIM_3D ?
                                             0 : view->base_array_layer,
                                          surf->dim == ISL_SURF_DIM_3D ?
                                             view->base_array_layer : 0,
                                          offset_B,
                                          x_offset_el,
                                          y_offset_el);

      /* Even for cube maps there will be only single face, therefore drop the
       * corresponding flag if present.
       */
      const isl_surf_usage_flags_t usage =
         surf->usage & (~ISL_SURF_USAGE_CUBE_BIT);

      bool ok UNUSED;
      ok = isl_surf_init(dev, ucompr_surf,
                         .dim = ISL_SURF_DIM_2D,
                         .format = view_format,
                         .width = view_width_el,
                         .height = view_height_el,
                         .depth = 1,
                         .levels = 1,
                         .array_len = 1,
                         .samples = 1,
                         .row_pitch_B = surf->row_pitch_B,
                         .usage = usage,
                         .tiling_flags = (1 << surf->tiling));
      assert(ok);

      /* The newly created image represents the one subimage we're
       * referencing with this view so it only has one array slice and
       * miplevel.
       */
      *ucompr_view = *view;
      ucompr_view->base_array_layer = 0;
      ucompr_view->base_level = 0;
   }

   return true;
}

void
isl_tiling_get_intratile_offset_el(enum isl_tiling tiling,
                                   enum isl_surf_dim dim,
                                   enum isl_msaa_layout msaa_layout,
                                   uint32_t bpb,
                                   uint32_t samples,
                                   uint32_t row_pitch_B,
                                   uint32_t array_pitch_el_rows,
                                   uint32_t total_x_offset_el,
                                   uint32_t total_y_offset_el,
                                   uint32_t total_z_offset_el,
                                   uint32_t total_array_offset,
                                   uint64_t *tile_offset_B,
                                   uint32_t *x_offset_el,
                                   uint32_t *y_offset_el,
                                   uint32_t *z_offset_el,
                                   uint32_t *array_offset)
{
   if (tiling == ISL_TILING_LINEAR) {
      assert(bpb % 8 == 0);
      assert(samples == 1);
      assert(total_z_offset_el == 0 && total_array_offset == 0);
      *tile_offset_B = (uint64_t)total_y_offset_el * row_pitch_B +
                       (uint64_t)total_x_offset_el * (bpb / 8);
      *x_offset_el = 0;
      *y_offset_el = 0;
      *z_offset_el = 0;
      *array_offset = 0;
      return;
   }

   struct isl_tile_info tile_info;
   isl_tiling_get_info(tiling, dim, msaa_layout, bpb, samples, &tile_info);

   /* Pitches must make sense with the tiling */
   assert(row_pitch_B % tile_info.phys_extent_B.width == 0);
   if (tile_info.logical_extent_el.d > 1 || tile_info.logical_extent_el.a > 1)
      assert(array_pitch_el_rows % tile_info.logical_extent_el.h == 0);

   /* For non-power-of-two formats, we need the address to be both tile and
    * element-aligned.  The easiest way to achieve this is to work with a tile
    * that is three times as wide as the regular tile.
    *
    * The tile info returned by get_tile_info has a logical size that is an
    * integer number of tile_info.format_bpb size elements.  To scale the
    * tile, we scale up the physical width and then treat the logical tile
    * size as if it has bpb size elements.
    */
   const uint32_t tile_el_scale = bpb / tile_info.format_bpb;
   tile_info.phys_extent_B.width *= tile_el_scale;

   /* Compute the offset into the tile */
   *x_offset_el = total_x_offset_el % tile_info.logical_extent_el.w;
   *y_offset_el = total_y_offset_el % tile_info.logical_extent_el.h;
   *z_offset_el = total_z_offset_el % tile_info.logical_extent_el.d;
   *array_offset = total_array_offset % tile_info.logical_extent_el.a;

   /* Compute the offset of the tile in units of whole tiles */
   uint32_t x_offset_tl = total_x_offset_el / tile_info.logical_extent_el.w;
   uint32_t y_offset_tl = total_y_offset_el / tile_info.logical_extent_el.h;
   uint32_t z_offset_tl = total_z_offset_el / tile_info.logical_extent_el.d;
   uint32_t a_offset_tl = total_array_offset / tile_info.logical_extent_el.a;

   /* Compute an array pitch in number of tiles */
   uint32_t array_pitch_tl_rows =
      array_pitch_el_rows / tile_info.logical_extent_el.h;

   /* Add the Z and array offset to the Y offset to get a 2D offset */
   y_offset_tl += (z_offset_tl + a_offset_tl) * array_pitch_tl_rows;

   *tile_offset_B =
      (uint64_t)y_offset_tl * tile_info.phys_extent_B.h * row_pitch_B +
      (uint64_t)x_offset_tl * tile_info.phys_extent_B.h * tile_info.phys_extent_B.w;
}

uint32_t
isl_surf_get_depth_format(const struct isl_device *dev,
                          const struct isl_surf *surf)
{
   /* Support for separate stencil buffers began in gfx5. Support for
    * interleaved depthstencil buffers ceased in gfx7. The intermediate gens,
    * those that supported separate and interleaved stencil, were gfx5 and
    * gfx6.
    *
    * For a list of all available formats, see the Sandybridge PRM >> Volume
    * 2 Part 1: 3D/Media - 3D Pipeline >> 3DSTATE_DEPTH_BUFFER >> Surface
    * Format (p321).
    */

   bool has_stencil = surf->usage & ISL_SURF_USAGE_STENCIL_BIT;

   assert(surf->usage & ISL_SURF_USAGE_DEPTH_BIT);

   if (has_stencil)
      assert(ISL_GFX_VER(dev) < 7);

   switch (surf->format) {
   default:
      unreachable("bad isl depth format");
   case ISL_FORMAT_R32_FLOAT_X8X24_TYPELESS:
      assert(ISL_GFX_VER(dev) < 7);
      return 0; /* D32_FLOAT_S8X24_UINT */
   case ISL_FORMAT_R32_FLOAT:
      assert(!has_stencil);
      return 1; /* D32_FLOAT */
   case ISL_FORMAT_R24_UNORM_X8_TYPELESS:
      if (has_stencil) {
         assert(ISL_GFX_VER(dev) < 7);
         return 2; /* D24_UNORM_S8_UINT */
      } else {
         assert(ISL_GFX_VER(dev) >= 5);
         return 3; /* D24_UNORM_X8_UINT */
      }
   case ISL_FORMAT_R16_UNORM:
      assert(!has_stencil);
      return 5; /* D16_UNORM */
   }
}

bool
isl_swizzle_supports_rendering(const struct intel_device_info *devinfo,
                               struct isl_swizzle swizzle)
{
   if (devinfo->is_haswell) {
      /* From the Haswell PRM,
       * RENDER_SURFACE_STATE::Shader Channel Select Red
       *
       *    "The Shader channel selects also define which shader channels are
       *    written to which surface channel. If the Shader channel select is
       *    SCS_ZERO or SCS_ONE then it is not written to the surface. If the
       *    shader channel select is SCS_RED it is written to the surface red
       *    channel and so on. If more than one shader channel select is set
       *    to the same surface channel only the first shader channel in RGBA
       *    order will be written."
       */
      return true;
   } else if (devinfo->ver <= 7) {
      /* Ivy Bridge and early doesn't have any swizzling */
      return isl_swizzle_is_identity(swizzle);
   } else {
      /* From the Sky Lake PRM Vol. 2d,
       * RENDER_SURFACE_STATE::Shader Channel Select Red
       *
       *    "For Render Target, Red, Green and Blue Shader Channel Selects
       *    MUST be such that only valid components can be swapped i.e. only
       *    change the order of components in the pixel. Any other values for
       *    these Shader Channel Select fields are not valid for Render
       *    Targets. This also means that there MUST not be multiple shader
       *    channels mapped to the same RT channel."
       *
       * From the Sky Lake PRM Vol. 2d,
       * RENDER_SURFACE_STATE::Shader Channel Select Alpha
       *
       *    "For Render Target, this field MUST be programmed to
       *    value = SCS_ALPHA."
       */
      return (swizzle.r == ISL_CHANNEL_SELECT_RED ||
              swizzle.r == ISL_CHANNEL_SELECT_GREEN ||
              swizzle.r == ISL_CHANNEL_SELECT_BLUE) &&
             (swizzle.g == ISL_CHANNEL_SELECT_RED ||
              swizzle.g == ISL_CHANNEL_SELECT_GREEN ||
              swizzle.g == ISL_CHANNEL_SELECT_BLUE) &&
             (swizzle.b == ISL_CHANNEL_SELECT_RED ||
              swizzle.b == ISL_CHANNEL_SELECT_GREEN ||
              swizzle.b == ISL_CHANNEL_SELECT_BLUE) &&
             swizzle.r != swizzle.g &&
             swizzle.r != swizzle.b &&
             swizzle.g != swizzle.b &&
             swizzle.a == ISL_CHANNEL_SELECT_ALPHA;
   }
}

static enum isl_channel_select
swizzle_select(enum isl_channel_select chan, struct isl_swizzle swizzle)
{
   switch (chan) {
   case ISL_CHANNEL_SELECT_ZERO:
   case ISL_CHANNEL_SELECT_ONE:
      return chan;
   case ISL_CHANNEL_SELECT_RED:
      return swizzle.r;
   case ISL_CHANNEL_SELECT_GREEN:
      return swizzle.g;
   case ISL_CHANNEL_SELECT_BLUE:
      return swizzle.b;
   case ISL_CHANNEL_SELECT_ALPHA:
      return swizzle.a;
   default:
      unreachable("Invalid swizzle component");
   }
}

/**
 * Returns the single swizzle that is equivalent to applying the two given
 * swizzles in sequence.
 */
struct isl_swizzle
isl_swizzle_compose(struct isl_swizzle first, struct isl_swizzle second)
{
   return (struct isl_swizzle) {
      .r = swizzle_select(first.r, second),
      .g = swizzle_select(first.g, second),
      .b = swizzle_select(first.b, second),
      .a = swizzle_select(first.a, second),
   };
}

/**
 * Returns a swizzle that is the pseudo-inverse of this swizzle.
 */
struct isl_swizzle
isl_swizzle_invert(struct isl_swizzle swizzle)
{
   /* Default to zero for channels which do not show up in the swizzle */
   enum isl_channel_select chans[4] = {
      ISL_CHANNEL_SELECT_ZERO,
      ISL_CHANNEL_SELECT_ZERO,
      ISL_CHANNEL_SELECT_ZERO,
      ISL_CHANNEL_SELECT_ZERO,
   };

   /* We go in ABGR order so that, if there are any duplicates, the first one
    * is taken if you look at it in RGBA order.  This is what Haswell hardware
    * does for render target swizzles.
    */
   if ((unsigned)(swizzle.a - ISL_CHANNEL_SELECT_RED) < 4)
      chans[swizzle.a - ISL_CHANNEL_SELECT_RED] = ISL_CHANNEL_SELECT_ALPHA;
   if ((unsigned)(swizzle.b - ISL_CHANNEL_SELECT_RED) < 4)
      chans[swizzle.b - ISL_CHANNEL_SELECT_RED] = ISL_CHANNEL_SELECT_BLUE;
   if ((unsigned)(swizzle.g - ISL_CHANNEL_SELECT_RED) < 4)
      chans[swizzle.g - ISL_CHANNEL_SELECT_RED] = ISL_CHANNEL_SELECT_GREEN;
   if ((unsigned)(swizzle.r - ISL_CHANNEL_SELECT_RED) < 4)
      chans[swizzle.r - ISL_CHANNEL_SELECT_RED] = ISL_CHANNEL_SELECT_RED;

   return (struct isl_swizzle) { chans[0], chans[1], chans[2], chans[3] };
}

/** Applies an inverse swizzle to a color value */
union isl_color_value
isl_color_value_swizzle_inv(union isl_color_value src,
                            struct isl_swizzle swizzle)
{
   union isl_color_value dst = { .u32 = { 0, } };

   /* We assign colors in ABGR order so that the first one will be taken in
    * RGBA precedence order.  According to the PRM docs for shader channel
    * select, this matches Haswell hardware behavior.
    */
   if ((unsigned)(swizzle.a - ISL_CHANNEL_SELECT_RED) < 4)
      dst.u32[swizzle.a - ISL_CHANNEL_SELECT_RED] = src.u32[3];
   if ((unsigned)(swizzle.b - ISL_CHANNEL_SELECT_RED) < 4)
      dst.u32[swizzle.b - ISL_CHANNEL_SELECT_RED] = src.u32[2];
   if ((unsigned)(swizzle.g - ISL_CHANNEL_SELECT_RED) < 4)
      dst.u32[swizzle.g - ISL_CHANNEL_SELECT_RED] = src.u32[1];
   if ((unsigned)(swizzle.r - ISL_CHANNEL_SELECT_RED) < 4)
      dst.u32[swizzle.r - ISL_CHANNEL_SELECT_RED] = src.u32[0];

   return dst;
}

uint8_t
isl_format_get_aux_map_encoding(enum isl_format format)
{
   switch(format) {
   case ISL_FORMAT_R32G32B32A32_FLOAT: return 0x11;
   case ISL_FORMAT_R32G32B32X32_FLOAT: return 0x11;
   case ISL_FORMAT_R32G32B32A32_SINT: return 0x12;
   case ISL_FORMAT_R32G32B32A32_UINT: return 0x13;
   case ISL_FORMAT_R16G16B16A16_UNORM: return 0x14;
   case ISL_FORMAT_R16G16B16A16_SNORM: return 0x15;
   case ISL_FORMAT_R16G16B16A16_SINT: return 0x16;
   case ISL_FORMAT_R16G16B16A16_UINT: return 0x17;
   case ISL_FORMAT_R16G16B16A16_FLOAT: return 0x10;
   case ISL_FORMAT_R16G16B16X16_FLOAT: return 0x10;
   case ISL_FORMAT_R32G32_FLOAT: return 0x11;
   case ISL_FORMAT_R32G32_SINT: return 0x12;
   case ISL_FORMAT_R32G32_UINT: return 0x13;
   case ISL_FORMAT_B8G8R8A8_UNORM: return 0xA;
   case ISL_FORMAT_B8G8R8X8_UNORM: return 0xA;
   case ISL_FORMAT_B8G8R8A8_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_B8G8R8X8_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_R10G10B10A2_UNORM: return 0x18;
   case ISL_FORMAT_R10G10B10A2_UNORM_SRGB: return 0x18;
   case ISL_FORMAT_R10G10B10_FLOAT_A2_UNORM: return 0x19;
   case ISL_FORMAT_R10G10B10A2_UINT: return 0x1A;
   case ISL_FORMAT_R8G8B8A8_UNORM: return 0xA;
   case ISL_FORMAT_R8G8B8A8_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_R8G8B8A8_SNORM: return 0x1B;
   case ISL_FORMAT_R8G8B8A8_SINT: return 0x1C;
   case ISL_FORMAT_R8G8B8A8_UINT: return 0x1D;
   case ISL_FORMAT_R16G16_UNORM: return 0x14;
   case ISL_FORMAT_R16G16_SNORM: return 0x15;
   case ISL_FORMAT_R16G16_SINT: return 0x16;
   case ISL_FORMAT_R16G16_UINT: return 0x17;
   case ISL_FORMAT_R16G16_FLOAT: return 0x10;
   case ISL_FORMAT_B10G10R10A2_UNORM: return 0x18;
   case ISL_FORMAT_B10G10R10A2_UNORM_SRGB: return 0x18;
   case ISL_FORMAT_R11G11B10_FLOAT: return 0x1E;
   case ISL_FORMAT_R32_SINT: return 0x12;
   case ISL_FORMAT_R32_UINT: return 0x13;
   case ISL_FORMAT_R32_FLOAT: return 0x11;
   case ISL_FORMAT_R24_UNORM_X8_TYPELESS: return 0x13;
   case ISL_FORMAT_B5G6R5_UNORM: return 0xA;
   case ISL_FORMAT_B5G6R5_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_B5G5R5A1_UNORM: return 0xA;
   case ISL_FORMAT_B5G5R5A1_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_B4G4R4A4_UNORM: return 0xA;
   case ISL_FORMAT_B4G4R4A4_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_R8G8_UNORM: return 0xA;
   case ISL_FORMAT_R8G8_SNORM: return 0x1B;
   case ISL_FORMAT_R8G8_SINT: return 0x1C;
   case ISL_FORMAT_R8G8_UINT: return 0x1D;
   case ISL_FORMAT_R16_UNORM: return 0x14;
   case ISL_FORMAT_R16_SNORM: return 0x15;
   case ISL_FORMAT_R16_SINT: return 0x16;
   case ISL_FORMAT_R16_UINT: return 0x17;
   case ISL_FORMAT_R16_FLOAT: return 0x10;
   case ISL_FORMAT_B5G5R5X1_UNORM: return 0xA;
   case ISL_FORMAT_B5G5R5X1_UNORM_SRGB: return 0xA;
   case ISL_FORMAT_A1B5G5R5_UNORM: return 0xA;
   case ISL_FORMAT_A4B4G4R4_UNORM: return 0xA;
   case ISL_FORMAT_R8_UNORM: return 0xA;
   case ISL_FORMAT_R8_SNORM: return 0x1B;
   case ISL_FORMAT_R8_SINT: return 0x1C;
   case ISL_FORMAT_R8_UINT: return 0x1D;
   case ISL_FORMAT_A8_UNORM: return 0xA;
   case ISL_FORMAT_PLANAR_420_8: return 0xF;
   case ISL_FORMAT_PLANAR_420_10: return 0x7;
   case ISL_FORMAT_PLANAR_420_12: return 0x8;
   case ISL_FORMAT_PLANAR_420_16: return 0x8;
   case ISL_FORMAT_YCRCB_NORMAL: return 0x3;
   case ISL_FORMAT_YCRCB_SWAPY: return 0xB;
   default:
      unreachable("Unsupported aux-map format!");
      return 0;
   }
}

/*
 * Returns compression format encoding for Unified Lossless Compression
 */
uint8_t
isl_get_render_compression_format(enum isl_format format)
{
   /* From the Bspec, Enumeration_RenderCompressionFormat section (53726): */
   switch(format) {
   case ISL_FORMAT_R32G32B32A32_FLOAT:
   case ISL_FORMAT_R32G32B32X32_FLOAT:
   case ISL_FORMAT_R32G32B32A32_SINT:
      return 0x0;
   case ISL_FORMAT_R32G32B32A32_UINT:
      return 0x1;
   case ISL_FORMAT_R32G32_FLOAT:
   case ISL_FORMAT_R32G32_SINT:
      return 0x2;
   case ISL_FORMAT_R32G32_UINT:
      return 0x3;
   case ISL_FORMAT_R16G16B16A16_UNORM:
   case ISL_FORMAT_R16G16B16X16_UNORM:
   case ISL_FORMAT_R16G16B16A16_UINT:
      return 0x4;
   case ISL_FORMAT_R16G16B16A16_SNORM:
   case ISL_FORMAT_R16G16B16A16_SINT:
   case ISL_FORMAT_R16G16B16A16_FLOAT:
   case ISL_FORMAT_R16G16B16X16_FLOAT:
      return 0x5;
   case ISL_FORMAT_R16G16_UNORM:
   case ISL_FORMAT_R16G16_UINT:
      return 0x6;
   case ISL_FORMAT_R16G16_SNORM:
   case ISL_FORMAT_R16G16_SINT:
   case ISL_FORMAT_R16G16_FLOAT:
      return 0x7;
   case ISL_FORMAT_B8G8R8A8_UNORM:
   case ISL_FORMAT_B8G8R8X8_UNORM:
   case ISL_FORMAT_B8G8R8A8_UNORM_SRGB:
   case ISL_FORMAT_B8G8R8X8_UNORM_SRGB:
   case ISL_FORMAT_R8G8B8A8_UNORM:
   case ISL_FORMAT_R8G8B8X8_UNORM:
   case ISL_FORMAT_R8G8B8A8_UNORM_SRGB:
   case ISL_FORMAT_R8G8B8X8_UNORM_SRGB:
   case ISL_FORMAT_R8G8B8A8_UINT:
      return 0x8;
   case ISL_FORMAT_R8G8B8A8_SNORM:
   case ISL_FORMAT_R8G8B8A8_SINT:
      return 0x9;
   case ISL_FORMAT_B5G6R5_UNORM:
   case ISL_FORMAT_B5G6R5_UNORM_SRGB:
   case ISL_FORMAT_B5G5R5A1_UNORM:
   case ISL_FORMAT_B5G5R5A1_UNORM_SRGB:
   case ISL_FORMAT_B4G4R4A4_UNORM:
   case ISL_FORMAT_B4G4R4A4_UNORM_SRGB:
   case ISL_FORMAT_B5G5R5X1_UNORM:
   case ISL_FORMAT_B5G5R5X1_UNORM_SRGB:
   case ISL_FORMAT_A1B5G5R5_UNORM:
   case ISL_FORMAT_A4B4G4R4_UNORM:
   case ISL_FORMAT_R8G8_UNORM:
   case ISL_FORMAT_R8G8_UINT:
      return 0xA;
   case ISL_FORMAT_R8G8_SNORM:
   case ISL_FORMAT_R8G8_SINT:
      return 0xB;
   case ISL_FORMAT_R10G10B10A2_UNORM:
   case ISL_FORMAT_R10G10B10A2_UNORM_SRGB:
   case ISL_FORMAT_R10G10B10_FLOAT_A2_UNORM:
   case ISL_FORMAT_R10G10B10A2_UINT:
   case ISL_FORMAT_B10G10R10A2_UNORM:
   case ISL_FORMAT_B10G10R10X2_UNORM:
   case ISL_FORMAT_B10G10R10A2_UNORM_SRGB:
      return 0xC;
   case ISL_FORMAT_R11G11B10_FLOAT:
      return 0xD;
   case ISL_FORMAT_R32_SINT:
   case ISL_FORMAT_R32_FLOAT:
      return 0x10;
   case ISL_FORMAT_R32_UINT:
   case ISL_FORMAT_R24_UNORM_X8_TYPELESS:
      return 0x11;
   case ISL_FORMAT_R16_UNORM:
   case ISL_FORMAT_R16_UINT:
      return 0x14;
   case ISL_FORMAT_R16_SNORM:
   case ISL_FORMAT_R16_SINT:
   case ISL_FORMAT_R16_FLOAT:
      return 0x15;
   case ISL_FORMAT_R8_UNORM:
   case ISL_FORMAT_R8_UINT:
   case ISL_FORMAT_A8_UNORM:
      return 0x18;
   case ISL_FORMAT_R8_SNORM:
   case ISL_FORMAT_R8_SINT:
      return 0x19;
   default:
      unreachable("Unsupported render compression format!");
      return 0;
   }
}