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
// SPDX-License-Identifier: MIT
/*
 * Copyright © 2021-2024 Intel Corporation
 */

#include <linux/types.h>

#include <drm/drm_managed.h>
#include <drm/drm_print.h>

#include "abi/guc_actions_abi.h"
#include "abi/guc_capture_abi.h"
#include "abi/guc_log_abi.h"
#include "regs/xe_engine_regs.h"
#include "regs/xe_gt_regs.h"

#include "xe_bo_types.h"
#include "xe_device.h"
#include "xe_exec_queue_types.h"
#include "xe_gt.h"
#include "xe_gt_mcr.h"
#include "xe_gt_printk.h"
#include "xe_guc.h"
#include "xe_guc_capture.h"
#include "xe_guc_capture_types.h"
#include "xe_guc_ct.h"
#include "xe_guc_exec_queue_types.h"
#include "xe_guc_log.h"
#include "xe_guc_submit_types.h"
#include "xe_guc_submit.h"
#include "xe_hw_engine_types.h"
#include "xe_hw_engine.h"
#include "xe_lrc.h"
#include "xe_macros.h"
#include "xe_map.h"
#include "xe_mmio.h"
#include "xe_sched_job.h"

/*
 * struct __guc_capture_bufstate
 *
 * Book-keeping structure used to track read and write pointers
 * as we extract error capture data from the GuC-log-buffer's
 * error-capture region as a stream of dwords.
 */
struct __guc_capture_bufstate {
	u32 size;
	u32 data_offset;
	u32 rd;
	u32 wr;
};

/*
 * struct __guc_capture_parsed_output - extracted error capture node
 *
 * A single unit of extracted error-capture output data grouped together
 * at an engine-instance level. We keep these nodes in a linked list.
 * See cachelist and outlist below.
 */
struct __guc_capture_parsed_output {
	/*
	 * A single set of 3 capture lists: a global-list
	 * an engine-class-list and an engine-instance list.
	 * outlist in __guc_capture_parsed_output will keep
	 * a linked list of these nodes that will eventually
	 * be detached from outlist and attached into to
	 * xe_codedump in response to a context reset
	 */
	struct list_head link;
	bool is_partial;
	u32 eng_class;
	u32 eng_inst;
	u32 guc_id;
	u32 lrca;
	u32 type;
	bool locked;
	enum xe_hw_engine_snapshot_source_id source;
	struct gcap_reg_list_info {
		u32 vfid;
		u32 num_regs;
		struct guc_mmio_reg *regs;
	} reginfo[GUC_STATE_CAPTURE_TYPE_MAX];
#define GCAP_PARSED_REGLIST_INDEX_GLOBAL   BIT(GUC_STATE_CAPTURE_TYPE_GLOBAL)
#define GCAP_PARSED_REGLIST_INDEX_ENGCLASS BIT(GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS)
};

/*
 * Define all device tables of GuC error capture register lists
 * NOTE:
 *     For engine-registers, GuC only needs the register offsets
 *     from the engine-mmio-base
 *
 *     64 bit registers need 2 entries for low 32 bit register and high 32 bit
 *     register, for example:
 *       Register           data_type       flags   mask    Register name
 *     { XXX_REG_LO(0),  REG_64BIT_LOW_DW,    0,      0,      NULL},
 *     { XXX_REG_HI(0),  REG_64BIT_HI_DW,,    0,      0,      "XXX_REG"},
 *     1. data_type: Indicate is hi/low 32 bit for a 64 bit register
 *                   A 64 bit register define requires 2 consecutive entries,
 *                   with low dword first and hi dword the second.
 *     2. Register name: null for incompleted define
 *     3. Incorrect order will trigger XE_WARN.
 */
#define COMMON_XELP_BASE_GLOBAL \
	{ FORCEWAKE_GT,			REG_32BIT,	0,	0,	0,	"FORCEWAKE_GT"}

#define COMMON_BASE_ENGINE_INSTANCE \
	{ RING_HWSTAM(0),		REG_32BIT,	0,	0,	0,	"HWSTAM"}, \
	{ RING_HWS_PGA(0),		REG_32BIT,	0,	0,	0,	"RING_HWS_PGA"}, \
	{ RING_HEAD(0),			REG_32BIT,	0,	0,	0,	"RING_HEAD"}, \
	{ RING_TAIL(0),			REG_32BIT,	0,	0,	0,	"RING_TAIL"}, \
	{ RING_CTL(0),			REG_32BIT,	0,	0,	0,	"RING_CTL"}, \
	{ RING_MI_MODE(0),		REG_32BIT,	0,	0,	0,	"RING_MI_MODE"}, \
	{ GFX_MODE(0),			REG_32BIT,	0,	0,	0,	"GFX_MODE"}, \
	{ RING_ESR(0),			REG_32BIT,	0,	0,	0,	"RING_ESR"}, \
	{ RING_EMR(0),			REG_32BIT,	0,	0,	0,	"RING_EMR"}, \
	{ RING_EIR(0),			REG_32BIT,	0,	0,	0,	"RING_EIR"}, \
	{ RING_IMR(0),			REG_32BIT,	0,	0,	0,	"RING_IMR"}, \
	{ RING_IPEHR(0),		REG_32BIT,	0,	0,	0,	"IPEHR"}, \
	{ RING_INSTDONE(0),		REG_32BIT,	0,	0,	0,	"RING_INSTDONE"}, \
	{ INDIRECT_RING_STATE(0),	REG_32BIT,	0,	0,	0,	"INDIRECT_RING_STATE"}, \
	{ RING_CURRENT_LRCA(0),		REG_32BIT,	0,	0,	0,	"CURRENT_LRCA"}, \
	{ RING_ACTHD(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_ACTHD_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"ACTHD"}, \
	{ RING_BBADDR(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_BBADDR_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_BBADDR"}, \
	{ RING_START(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_START_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_START"}, \
	{ RING_DMA_FADD(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_DMA_FADD_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_DMA_FADD"}, \
	{ RING_EXECLIST_STATUS_LO(0),	REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_EXECLIST_STATUS_HI(0),	REG_64BIT_HI_DW, 0,	0,	0,	"RING_EXECLIST_STATUS"}, \
	{ RING_EXECLIST_SQ_CONTENTS_LO(0), REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
	{ RING_EXECLIST_SQ_CONTENTS_HI(0), REG_64BIT_HI_DW, 0,	0,	0,	"RING_EXECLIST_SQ_CONTENTS"}

#define COMMON_XELP_RC_CLASS \
	{ RCU_MODE,			REG_32BIT,	0,	0,	0,	"RCU_MODE"}

#define COMMON_XELP_RC_CLASS_INSTDONE \
	{ SC_INSTDONE,			REG_32BIT,	0,	0,	0,	"SC_INSTDONE"}, \
	{ SC_INSTDONE_EXTRA,		REG_32BIT,	0,	0,	0,	"SC_INSTDONE_EXTRA"}, \
	{ SC_INSTDONE_EXTRA2,		REG_32BIT,	0,	0,	0,	"SC_INSTDONE_EXTRA2"}

#define XELP_VEC_CLASS_REGS \
	{ SFC_DONE(0),			0,	0,	0,	0,	"SFC_DONE[0]"}, \
	{ SFC_DONE(1),			0,	0,	0,	0,	"SFC_DONE[1]"}, \
	{ SFC_DONE(2),			0,	0,	0,	0,	"SFC_DONE[2]"}, \
	{ SFC_DONE(3),			0,	0,	0,	0,	"SFC_DONE[3]"}

#define XE3P_BASE_ENGINE_INSTANCE \
	{ RING_CSMQDEBUG(0),		REG_32BIT,	0,	0,	0,	"CSMQDEBUG"}

/* XE_LP Global */
static const struct __guc_mmio_reg_descr xe_lp_global_regs[] = {
	COMMON_XELP_BASE_GLOBAL,
};

/* Render / Compute Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe_rc_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
};

/* Render / Compute Engine-Class */
static const struct __guc_mmio_reg_descr xe_rc_class_regs[] = {
	COMMON_XELP_RC_CLASS,
	COMMON_XELP_RC_CLASS_INSTDONE,
};

/* Render / Compute Engine-Class for xehpg */
static const struct __guc_mmio_reg_descr xe_hpg_rc_class_regs[] = {
	COMMON_XELP_RC_CLASS,
};

/* Media Decode/Encode Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe_vd_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
};

/* Video Enhancement Engine-Class */
static const struct __guc_mmio_reg_descr xe_vec_class_regs[] = {
	XELP_VEC_CLASS_REGS,
};

/* Video Enhancement Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe_vec_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
};

/* Blitter Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe_blt_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
};

/* XE_LP - GSC Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe_lp_gsc_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
};

/* Render / Compute Per-Engine-Instance */
static const struct __guc_mmio_reg_descr xe3p_rc_inst_regs[] = {
	COMMON_BASE_ENGINE_INSTANCE,
	XE3P_BASE_ENGINE_INSTANCE,
};

/*
 * Empty list to prevent warnings about unknown class/instance types
 * as not all class/instance types have entries on all platforms.
 */
static const struct __guc_mmio_reg_descr empty_regs_list[] = {
};

#define TO_GCAP_DEF_OWNER(x) (GUC_CAPTURE_LIST_INDEX_##x)
#define TO_GCAP_DEF_TYPE(x) (GUC_STATE_CAPTURE_TYPE_##x)
#define MAKE_REGLIST(regslist, regsowner, regstype, class) \
	{ \
		regslist, \
		ARRAY_SIZE(regslist), \
		TO_GCAP_DEF_OWNER(regsowner), \
		TO_GCAP_DEF_TYPE(regstype), \
		class \
	}

/* List of lists for legacy graphic product version < 1255 */
static const struct __guc_mmio_reg_descr_group xe_lp_lists[] = {
	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
	MAKE_REGLIST(xe_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(xe_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	{}
};

 /* List of lists for graphic product version >= 1255 */
static const struct __guc_mmio_reg_descr_group xe_hpg_lists[] = {
	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
	MAKE_REGLIST(xe_hpg_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(xe_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_PAGING),
	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_PAGING),
	{}
};

 /* List of lists for Xe3p and beyond */
static const struct __guc_mmio_reg_descr_group xe3p_lists[] = {
	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
	MAKE_REGLIST(xe_hpg_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(xe3p_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_PAGING),
	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_PAGING),
	{}
};
static const char * const capture_list_type_names[] = {
	"Global",
	"Class",
	"Instance",
};

static const char * const capture_engine_class_names[] = {
	"Render/Compute",
	"Video",
	"VideoEnhance",
	"Blitter",
	"GSC-Other",
	"Paging",
};

struct __guc_capture_ads_cache {
	bool is_valid;
	void *ptr;
	size_t size;
	int status;
};

struct xe_guc_state_capture {
	const struct __guc_mmio_reg_descr_group *reglists;
	/**
	 * NOTE: steered registers have multiple instances depending on the HW configuration
	 * (slices or dual-sub-slices) and thus depends on HW fuses discovered
	 */
	struct __guc_mmio_reg_descr_group *extlists;
	struct __guc_capture_ads_cache ads_cache[GUC_CAPTURE_LIST_INDEX_MAX]
						[GUC_STATE_CAPTURE_TYPE_MAX]
						[GUC_CAPTURE_LIST_CLASS_MAX];
	void *ads_null_cache;
	struct list_head cachelist;
#define PREALLOC_NODES_MAX_COUNT (3 * GUC_MAX_ENGINE_CLASSES * GUC_MAX_INSTANCES_PER_CLASS)
#define PREALLOC_NODES_DEFAULT_NUMREGS 64

	int max_mmio_per_node;
	struct list_head outlist;
};

static void
guc_capture_remove_stale_matches_from_list(struct xe_guc_state_capture *gc,
					   struct __guc_capture_parsed_output *node);

static const struct __guc_mmio_reg_descr_group *
guc_capture_get_device_reglist(struct xe_device *xe)
{
	if (GRAPHICS_VER(xe) >= 35)
		return xe3p_lists;
	else if (GRAPHICS_VERx100(xe) >= 1255)
		return xe_hpg_lists;
	else
		return xe_lp_lists;
}

static const struct __guc_mmio_reg_descr_group *
guc_capture_get_one_list(const struct __guc_mmio_reg_descr_group *reglists,
			 u32 owner, u32 type, enum guc_capture_list_class_type capture_class)
{
	int i;

	if (!reglists)
		return NULL;

	for (i = 0; reglists[i].list; ++i) {
		if (reglists[i].owner == owner && reglists[i].type == type &&
		    (reglists[i].engine == capture_class ||
		     reglists[i].type == GUC_STATE_CAPTURE_TYPE_GLOBAL))
			return &reglists[i];
	}

	return NULL;
}

const struct __guc_mmio_reg_descr_group *
xe_guc_capture_get_reg_desc_list(struct xe_gt *gt, u32 owner, u32 type,
				 enum guc_capture_list_class_type capture_class, bool is_ext)
{
	const struct __guc_mmio_reg_descr_group *reglists;

	if (is_ext) {
		struct xe_guc *guc = &gt->uc.guc;

		reglists = guc->capture->extlists;
	} else {
		reglists = guc_capture_get_device_reglist(gt_to_xe(gt));
	}
	return guc_capture_get_one_list(reglists, owner, type, capture_class);
}

struct __ext_steer_reg {
	const char *name;
	struct xe_reg_mcr reg;
};

static const struct __ext_steer_reg xe_extregs[] = {
	{"SAMPLER_INSTDONE",		SAMPLER_INSTDONE},
	{"ROW_INSTDONE",		ROW_INSTDONE}
};

static const struct __ext_steer_reg xehpg_extregs[] = {
	{"SC_INSTDONE",			XEHPG_SC_INSTDONE},
	{"SC_INSTDONE_EXTRA",		XEHPG_SC_INSTDONE_EXTRA},
	{"SC_INSTDONE_EXTRA2",		XEHPG_SC_INSTDONE_EXTRA2},
	{"INSTDONE_GEOM_SVGUNIT",	XEHPG_INSTDONE_GEOM_SVGUNIT}
};

static void __fill_ext_reg(struct __guc_mmio_reg_descr *ext,
			   const struct __ext_steer_reg *extlist,
			   u32 dss_id, u16 slice_id, u16 subslice_id)
{
	if (!ext || !extlist)
		return;

	ext->reg = XE_REG(extlist->reg.__reg.addr);
	ext->flags = FIELD_PREP(GUC_REGSET_STEERING_NEEDED, 1);
	ext->flags |= FIELD_PREP(GUC_REGSET_STEERING_GROUP, slice_id);
	ext->flags |= FIELD_PREP(GUC_REGSET_STEERING_INSTANCE, subslice_id);
	ext->dss_id = dss_id;
	ext->regname = extlist->name;
}

static int
__alloc_ext_regs(struct drm_device *drm, struct __guc_mmio_reg_descr_group *newlist,
		 const struct __guc_mmio_reg_descr_group *rootlist, int num_regs)
{
	struct __guc_mmio_reg_descr *list;

	list = drmm_kzalloc(drm, num_regs * sizeof(struct __guc_mmio_reg_descr), GFP_KERNEL);
	if (!list)
		return -ENOMEM;

	newlist->list = list;
	newlist->num_regs = num_regs;
	newlist->owner = rootlist->owner;
	newlist->engine = rootlist->engine;
	newlist->type = rootlist->type;

	return 0;
}

static int guc_capture_get_steer_reg_num(struct xe_device *xe)
{
	int num = ARRAY_SIZE(xe_extregs);

	if (GRAPHICS_VERx100(xe) >= 1255)
		num += ARRAY_SIZE(xehpg_extregs);

	return num;
}

static void guc_capture_alloc_steered_lists(struct xe_guc *guc)
{
	struct xe_gt *gt = guc_to_gt(guc);
	u16 slice, subslice;
	int dss, i, total = 0;
	const struct __guc_mmio_reg_descr_group *lists = guc->capture->reglists;
	const struct __guc_mmio_reg_descr_group *list;
	struct __guc_mmio_reg_descr_group *extlists;
	struct __guc_mmio_reg_descr *extarray;
	bool has_xehpg_extregs = GRAPHICS_VERx100(gt_to_xe(gt)) >= 1255;
	struct drm_device *drm = &gt_to_xe(gt)->drm;
	bool has_rcs_ccs = false;
	struct xe_hw_engine *hwe;
	enum xe_hw_engine_id id;

	/*
	 * If GT has no rcs/ccs, no need to alloc steered list.
	 * Currently, only rcs/ccs has steering register, if in the future,
	 * other engine types has steering register, this condition check need
	 * to be extended
	 */
	for_each_hw_engine(hwe, gt, id) {
		if (xe_hwe_to_guc_capture_class(hwe) ==
		    GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
			has_rcs_ccs = true;
			break;
		}
	}

	if (!has_rcs_ccs)
		return;

	/* steered registers currently only exist for the render-class */
	list = guc_capture_get_one_list(lists, GUC_CAPTURE_LIST_INDEX_PF,
					GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
					GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE);
	/*
	 * Skip if this platform has no engine class registers or if extlists
	 * was previously allocated
	 */
	if (!list || guc->capture->extlists)
		return;

	{
		xe_dss_mask_t all_dss;

		total = bitmap_weighted_or(all_dss, gt->fuse_topo.g_dss_mask,
					   gt->fuse_topo.c_dss_mask,
					   XE_MAX_DSS_FUSE_BITS) *
			guc_capture_get_steer_reg_num(guc_to_xe(guc));
	}

	if (!total)
		return;

	/* allocate an extra for an end marker */
	extlists = drmm_kzalloc(drm, 2 * sizeof(struct __guc_mmio_reg_descr_group), GFP_KERNEL);
	if (!extlists)
		return;

	if (__alloc_ext_regs(drm, &extlists[0], list, total)) {
		drmm_kfree(drm, extlists);
		return;
	}

	/* For steering registers, the list is generated at run-time */
	extarray = (struct __guc_mmio_reg_descr *)extlists[0].list;
	for_each_dss_steering(dss, gt, slice, subslice) {
		for (i = 0; i < ARRAY_SIZE(xe_extregs); ++i) {
			__fill_ext_reg(extarray, &xe_extregs[i], dss, slice, subslice);
			++extarray;
		}

		if (has_xehpg_extregs)
			for (i = 0; i < ARRAY_SIZE(xehpg_extregs); ++i) {
				__fill_ext_reg(extarray, &xehpg_extregs[i], dss, slice, subslice);
				++extarray;
			}
	}

	extlists[0].num_regs = total;

	xe_gt_dbg(guc_to_gt(guc), "capture found %d ext-regs.\n", total);
	guc->capture->extlists = extlists;
}

static int
guc_capture_list_init(struct xe_guc *guc, u32 owner, u32 type,
		      enum guc_capture_list_class_type capture_class, struct guc_mmio_reg *ptr,
		      u16 num_entries)
{
	u32 ptr_idx = 0, list_idx = 0;
	const struct __guc_mmio_reg_descr_group *reglists = guc->capture->reglists;
	struct __guc_mmio_reg_descr_group *extlists = guc->capture->extlists;
	const struct __guc_mmio_reg_descr_group *match;
	u32 list_num;

	if (!reglists)
		return -ENODEV;

	match = guc_capture_get_one_list(reglists, owner, type, capture_class);
	if (!match)
		return -ENODATA;

	list_num = match->num_regs;
	for (list_idx = 0; ptr_idx < num_entries && list_idx < list_num; ++list_idx, ++ptr_idx) {
		ptr[ptr_idx].offset = match->list[list_idx].reg.addr;
		ptr[ptr_idx].value = 0xDEADF00D;
		ptr[ptr_idx].flags = match->list[list_idx].flags;
		ptr[ptr_idx].mask = match->list[list_idx].mask;
	}

	match = guc_capture_get_one_list(extlists, owner, type, capture_class);
	if (match)
		for (ptr_idx = list_num, list_idx = 0;
		     ptr_idx < num_entries && list_idx < match->num_regs;
		     ++ptr_idx, ++list_idx) {
			ptr[ptr_idx].offset = match->list[list_idx].reg.addr;
			ptr[ptr_idx].value = 0xDEADF00D;
			ptr[ptr_idx].flags = match->list[list_idx].flags;
			ptr[ptr_idx].mask = match->list[list_idx].mask;
		}

	if (ptr_idx < num_entries)
		xe_gt_dbg(guc_to_gt(guc), "Got short capture reglist init: %d out-of %d.\n",
			  ptr_idx, num_entries);

	return 0;
}

static int
guc_cap_list_num_regs(struct xe_guc *guc, u32 owner, u32 type,
		      enum guc_capture_list_class_type capture_class)
{
	const struct __guc_mmio_reg_descr_group *match;
	int num_regs = 0;

	match = guc_capture_get_one_list(guc->capture->reglists, owner, type, capture_class);
	if (match)
		num_regs = match->num_regs;

	match = guc_capture_get_one_list(guc->capture->extlists, owner, type, capture_class);
	if (match)
		num_regs += match->num_regs;
	else
		/*
		 * If a caller wants the full register dump size but we have
		 * not yet got the hw-config, which is before max_mmio_per_node
		 * is initialized, then provide a worst-case number for
		 * extlists based on max dss fuse bits, but only ever for
		 * render/compute
		 */
		if (owner == GUC_CAPTURE_LIST_INDEX_PF &&
		    type == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
		    capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE &&
		    !guc->capture->max_mmio_per_node)
			num_regs += guc_capture_get_steer_reg_num(guc_to_xe(guc)) *
				    XE_MAX_DSS_FUSE_BITS;

	return num_regs;
}

static int
guc_capture_getlistsize(struct xe_guc *guc, u32 owner, u32 type,
			enum guc_capture_list_class_type capture_class,
			size_t *size, bool is_purpose_est)
{
	struct xe_guc_state_capture *gc = guc->capture;
	struct xe_gt *gt = guc_to_gt(guc);
	struct __guc_capture_ads_cache *cache;
	int num_regs;

	xe_gt_assert(gt, type < GUC_STATE_CAPTURE_TYPE_MAX);
	xe_gt_assert(gt, capture_class < GUC_CAPTURE_LIST_CLASS_MAX);

	cache = &gc->ads_cache[owner][type][capture_class];
	if (!gc->reglists) {
		xe_gt_warn(gt, "No capture reglist for this device\n");
		return -ENODEV;
	}

	if (cache->is_valid) {
		*size = cache->size;
		return cache->status;
	}

	if (!is_purpose_est && owner == GUC_CAPTURE_LIST_INDEX_PF &&
	    !guc_capture_get_one_list(gc->reglists, owner, type, capture_class)) {
		if (type == GUC_STATE_CAPTURE_TYPE_GLOBAL)
			xe_gt_warn(gt, "Missing capture reglist: global!\n");
		else
			xe_gt_warn(gt, "Missing capture reglist: %s(%u):%s(%u)!\n",
				   capture_list_type_names[type], type,
				   capture_engine_class_names[capture_class], capture_class);
		return -ENODEV;
	}

	num_regs = guc_cap_list_num_regs(guc, owner, type, capture_class);
	/* intentional empty lists can exist depending on hw config */
	if (!num_regs)
		return -ENODATA;

	if (size)
		*size = PAGE_ALIGN((sizeof(struct guc_debug_capture_list)) +
				   (num_regs * sizeof(struct guc_mmio_reg)));

	return 0;
}

/**
 * xe_guc_capture_getlistsize - Get list size for owner/type/class combination
 * @guc: The GuC object
 * @owner: PF/VF owner
 * @type: GuC capture register type
 * @capture_class: GuC capture engine class id
 * @size: Point to the size
 *
 * This function will get the list for the owner/type/class combination, and
 * return the page aligned list size.
 *
 * Returns: 0 on success or a negative error code on failure.
 */
int
xe_guc_capture_getlistsize(struct xe_guc *guc, u32 owner, u32 type,
			   enum guc_capture_list_class_type capture_class, size_t *size)
{
	return guc_capture_getlistsize(guc, owner, type, capture_class, size, false);
}

/**
 * xe_guc_capture_getlist - Get register capture list for owner/type/class
 * combination
 * @guc:	The GuC object
 * @owner:	PF/VF owner
 * @type:	GuC capture register type
 * @capture_class:	GuC capture engine class id
 * @outptr:	Point to cached register capture list
 *
 * This function will get the register capture list for the owner/type/class
 * combination.
 *
 * Returns: 0 on success or a negative error code on failure.
 */
int
xe_guc_capture_getlist(struct xe_guc *guc, u32 owner, u32 type,
		       enum guc_capture_list_class_type capture_class, void **outptr)
{
	struct xe_guc_state_capture *gc = guc->capture;
	struct __guc_capture_ads_cache *cache = &gc->ads_cache[owner][type][capture_class];
	struct guc_debug_capture_list *listnode;
	int ret, num_regs;
	u8 *caplist, *tmp;
	size_t size = 0;

	if (!gc->reglists)
		return -ENODEV;

	if (cache->is_valid) {
		*outptr = cache->ptr;
		return cache->status;
	}

	ret = xe_guc_capture_getlistsize(guc, owner, type, capture_class, &size);
	if (ret) {
		cache->is_valid = true;
		cache->ptr = NULL;
		cache->size = 0;
		cache->status = ret;
		return ret;
	}

	caplist = drmm_kzalloc(guc_to_drm(guc), size, GFP_KERNEL);
	if (!caplist)
		return -ENOMEM;

	/* populate capture list header */
	tmp = caplist;
	num_regs = guc_cap_list_num_regs(guc, owner, type, capture_class);
	listnode = (struct guc_debug_capture_list *)tmp;
	listnode->header.info = FIELD_PREP(GUC_CAPTURELISTHDR_NUMDESCR, (u32)num_regs);

	/* populate list of register descriptor */
	tmp += sizeof(struct guc_debug_capture_list);
	guc_capture_list_init(guc, owner, type, capture_class,
			      (struct guc_mmio_reg *)tmp, num_regs);

	/* cache this list */
	cache->is_valid = true;
	cache->ptr = caplist;
	cache->size = size;
	cache->status = 0;

	*outptr = caplist;

	return 0;
}

/**
 * xe_guc_capture_getnullheader - Get a null list for register capture
 * @guc:	The GuC object
 * @outptr:	Point to cached register capture list
 * @size:	Point to the size
 *
 * This function will alloc for a null list for register capture.
 *
 * Returns: 0 on success or a negative error code on failure.
 */
int
xe_guc_capture_getnullheader(struct xe_guc *guc, void **outptr, size_t *size)
{
	struct xe_guc_state_capture *gc = guc->capture;
	int tmp = sizeof(u32) * 4;
	void *null_header;

	if (gc->ads_null_cache) {
		*outptr = gc->ads_null_cache;
		*size = tmp;
		return 0;
	}

	null_header = drmm_kzalloc(guc_to_drm(guc), tmp, GFP_KERNEL);
	if (!null_header)
		return -ENOMEM;

	gc->ads_null_cache = null_header;
	*outptr = null_header;
	*size = tmp;

	return 0;
}

/**
 * xe_guc_capture_ads_input_worst_size - Calculate the worst size for GuC register capture
 * @guc: point to xe_guc structure
 *
 * Calculate the worst size for GuC register capture by including all possible engines classes.
 *
 * Returns: Calculated size
 */
size_t xe_guc_capture_ads_input_worst_size(struct xe_guc *guc)
{
	size_t total_size, class_size, instance_size, global_size;
	int i, j;

	/*
	 * This function calculates the worst case register lists size by
	 * including all possible engines classes. It is called during the
	 * first of a two-phase GuC (and ADS-population) initialization
	 * sequence, that is, during the pre-hwconfig phase before we have
	 * the exact engine fusing info.
	 */
	total_size = PAGE_SIZE;	/* Pad a page in front for empty lists */
	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; i++) {
		for (j = 0; j < GUC_CAPTURE_LIST_CLASS_MAX; j++) {
			if (!xe_guc_has_paging_engine(guc) &&
			    j == GUC_CAPTURE_LIST_CLASS_PAGING)
				continue;

			if (xe_guc_capture_getlistsize(guc, i,
						       GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
						       j, &class_size) < 0)
				class_size = 0;
			if (xe_guc_capture_getlistsize(guc, i,
						       GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE,
						       j, &instance_size) < 0)
				instance_size = 0;
			total_size += class_size + instance_size;
		}
		if (xe_guc_capture_getlistsize(guc, i,
					       GUC_STATE_CAPTURE_TYPE_GLOBAL,
					       0, &global_size) < 0)
			global_size = 0;
		total_size += global_size;
	}

	return PAGE_ALIGN(total_size);
}

static int guc_capture_output_size_est(struct xe_guc *guc)
{
	struct xe_gt *gt = guc_to_gt(guc);
	struct xe_hw_engine *hwe;
	enum xe_hw_engine_id id;

	int capture_size = 0;
	size_t tmp = 0;

	if (!guc->capture)
		return -ENODEV;

	/*
	 * If every single engine-instance suffered a failure in quick succession but
	 * were all unrelated, then a burst of multiple error-capture events would dump
	 * registers for every one engine instance, one at a time. In this case, GuC
	 * would even dump the global-registers repeatedly.
	 *
	 * For each engine instance, there would be 1 x guc_state_capture_group_t output
	 * followed by 3 x guc_state_capture_t lists. The latter is how the register
	 * dumps are split across different register types (where the '3' are global vs class
	 * vs instance).
	 */
	for_each_hw_engine(hwe, gt, id) {
		enum guc_capture_list_class_type capture_class;

		capture_class = xe_hwe_to_guc_capture_class(hwe);
		capture_size += sizeof(struct guc_state_capture_group_header_t) +
					 (3 * sizeof(struct guc_state_capture_header_t));

		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_GLOBAL,
					     0, &tmp, true))
			capture_size += tmp;
		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
					     capture_class, &tmp, true))
			capture_size += tmp;
		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE,
					     capture_class, &tmp, true))
			capture_size += tmp;
	}

	return capture_size;
}

/*
 * Add on a 3x multiplier to allow for multiple back-to-back captures occurring
 * before the Xe can read the data out and process it
 */
#define GUC_CAPTURE_OVERBUFFER_MULTIPLIER 3

static void check_guc_capture_size(struct xe_guc *guc)
{
	int capture_size = guc_capture_output_size_est(guc);
	int spare_size = capture_size * GUC_CAPTURE_OVERBUFFER_MULTIPLIER;
	u32 buffer_size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE;

	/*
	 * NOTE: capture_size is much smaller than the capture region
	 * allocation (DG2: <80K vs 1MB).
	 * Additionally, its based on space needed to fit all engines getting
	 * reset at once within the same G2H handler task slot. This is very
	 * unlikely. However, if GuC really does run out of space for whatever
	 * reason, we will see an separate warning message when processing the
	 * G2H event capture-notification, search for:
	 * xe_guc_STATE_CAPTURE_EVENT_STATUS_NOSPACE.
	 */
	if (capture_size < 0)
		xe_gt_dbg(guc_to_gt(guc),
			  "Failed to calculate error state capture buffer minimum size: %d!\n",
			  capture_size);
	if (capture_size > buffer_size)
		xe_gt_dbg(guc_to_gt(guc), "Error state capture buffer maybe small: %d < %d\n",
			  buffer_size, capture_size);
	else if (spare_size > buffer_size)
		xe_gt_dbg(guc_to_gt(guc),
			  "Error state capture buffer lacks spare size: %d < %d (min = %d)\n",
			  buffer_size, spare_size, capture_size);
}

static void
guc_capture_add_node_to_list(struct __guc_capture_parsed_output *node,
			     struct list_head *list)
{
	list_add(&node->link, list);
}

static void
guc_capture_add_node_to_outlist(struct xe_guc_state_capture *gc,
				struct __guc_capture_parsed_output *node)
{
	guc_capture_remove_stale_matches_from_list(gc, node);
	guc_capture_add_node_to_list(node, &gc->outlist);
}

static void
guc_capture_add_node_to_cachelist(struct xe_guc_state_capture *gc,
				  struct __guc_capture_parsed_output *node)
{
	guc_capture_add_node_to_list(node, &gc->cachelist);
}

static void
guc_capture_free_outlist_node(struct xe_guc_state_capture *gc,
			      struct __guc_capture_parsed_output *n)
{
	if (n) {
		n->locked = 0;
		list_del(&n->link);
		/* put node back to cache list */
		guc_capture_add_node_to_cachelist(gc, n);
	}
}

static void
guc_capture_remove_stale_matches_from_list(struct xe_guc_state_capture *gc,
					   struct __guc_capture_parsed_output *node)
{
	struct __guc_capture_parsed_output *n, *ntmp;
	int guc_id = node->guc_id;

	list_for_each_entry_safe(n, ntmp, &gc->outlist, link) {
		if (n != node && !n->locked && n->guc_id == guc_id)
			guc_capture_free_outlist_node(gc, n);
	}
}

static void
guc_capture_init_node(struct xe_guc *guc, struct __guc_capture_parsed_output *node)
{
	struct guc_mmio_reg *tmp[GUC_STATE_CAPTURE_TYPE_MAX];
	int i;

	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
		tmp[i] = node->reginfo[i].regs;
		memset(tmp[i], 0, sizeof(struct guc_mmio_reg) *
		       guc->capture->max_mmio_per_node);
	}
	memset(node, 0, sizeof(*node));
	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i)
		node->reginfo[i].regs = tmp[i];

	INIT_LIST_HEAD(&node->link);
}

/**
 * DOC: Init, G2H-event and reporting flows for GuC-error-capture
 *
 * KMD Init time flows:
 * --------------------
 *     --> alloc A: GuC input capture regs lists (registered to GuC via ADS).
 *                  xe_guc_ads acquires the register lists by calling
 *                  xe_guc_capture_getlistsize and xe_guc_capture_getlist 'n' times,
 *                  where n = 1 for global-reg-list +
 *                            num_engine_classes for class-reg-list +
 *                            num_engine_classes for instance-reg-list
 *                               (since all instances of the same engine-class type
 *                                have an identical engine-instance register-list).
 *                  ADS module also calls separately for PF vs VF.
 *
 *     --> alloc B: GuC output capture buf (registered via guc_init_params(log_param))
 *                  Size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE (warns if on too-small)
 *                  Note2: 'x 3' to hold multiple capture groups
 *
 * GUC Runtime notify capture:
 * --------------------------
 *     --> G2H STATE_CAPTURE_NOTIFICATION
 *                   L--> xe_guc_capture_process
 *                           L--> Loop through B (head..tail) and for each engine instance's
 *                                err-state-captured register-list we find, we alloc 'C':
 *      --> alloc C: A capture-output-node structure that includes misc capture info along
 *                   with 3 register list dumps (global, engine-class and engine-instance)
 *                   This node is created from a pre-allocated list of blank nodes in
 *                   guc->capture->cachelist and populated with the error-capture
 *                   data from GuC and then it's added into guc->capture->outlist linked
 *                   list. This list is used for matchup and printout by xe_devcoredump_read
 *                   and xe_engine_snapshot_print, (when user invokes the devcoredump sysfs).
 *
 * GUC --> notify context reset:
 * -----------------------------
 *     --> guc_exec_queue_timedout_job
 *                   L--> xe_devcoredump
 *                          L--> devcoredump_snapshot
 *                               --> xe_hw_engine_snapshot_capture
 *                               --> xe_engine_manual_capture(For manual capture)
 *
 * User Sysfs / Debugfs
 * --------------------
 *      --> xe_devcoredump_read->
 *             L--> xxx_snapshot_print
 *                    L--> xe_engine_snapshot_print
 *                         Print register lists values saved at
 *                         guc->capture->outlist
 *
 */

static int guc_capture_buf_cnt(struct __guc_capture_bufstate *buf)
{
	if (buf->wr >= buf->rd)
		return (buf->wr - buf->rd);
	return (buf->size - buf->rd) + buf->wr;
}

static int guc_capture_buf_cnt_to_end(struct __guc_capture_bufstate *buf)
{
	if (buf->rd > buf->wr)
		return (buf->size - buf->rd);
	return (buf->wr - buf->rd);
}

/*
 * GuC's error-capture output is a ring buffer populated in a byte-stream fashion:
 *
 * The GuC Log buffer region for error-capture is managed like a ring buffer.
 * The GuC firmware dumps error capture logs into this ring in a byte-stream flow.
 * Additionally, as per the current and foreseeable future, all packed error-
 * capture output structures are dword aligned.
 *
 * That said, if the GuC firmware is in the midst of writing a structure that is larger
 * than one dword but the tail end of the err-capture buffer-region has lesser space left,
 * we would need to extract that structure one dword at a time straddled across the end,
 * onto the start of the ring.
 *
 * Below function, guc_capture_log_remove_bytes is a helper for that. All callers of this
 * function would typically do a straight-up memcpy from the ring contents and will only
 * call this helper if their structure-extraction is straddling across the end of the
 * ring. GuC firmware does not add any padding. The reason for the no-padding is to ease
 * scalability for future expansion of output data types without requiring a redesign
 * of the flow controls.
 */
static int
guc_capture_log_remove_bytes(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
			     void *out, int bytes_needed)
{
#define GUC_CAPTURE_LOG_BUF_COPY_RETRY_MAX	3

	int fill_size = 0, tries = GUC_CAPTURE_LOG_BUF_COPY_RETRY_MAX;
	int copy_size, avail;

	xe_assert(guc_to_xe(guc), bytes_needed % sizeof(u32) == 0);

	if (bytes_needed > guc_capture_buf_cnt(buf))
		return -1;

	while (bytes_needed > 0 && tries--) {
		int misaligned;

		avail = guc_capture_buf_cnt_to_end(buf);
		misaligned = avail % sizeof(u32);
		/* wrap if at end */
		if (!avail) {
			/* output stream clipped */
			if (!buf->rd)
				return fill_size;
			buf->rd = 0;
			continue;
		}

		/* Only copy to u32 aligned data */
		copy_size = avail < bytes_needed ? avail - misaligned : bytes_needed;
		xe_map_memcpy_from(guc_to_xe(guc), out + fill_size, &guc->log.bo->vmap,
				   buf->data_offset + buf->rd, copy_size);
		buf->rd += copy_size;
		fill_size += copy_size;
		bytes_needed -= copy_size;

		if (misaligned)
			xe_gt_warn(guc_to_gt(guc),
				   "Bytes extraction not dword aligned, clipping.\n");
	}

	return fill_size;
}

static int
guc_capture_log_get_group_hdr(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
			      struct guc_state_capture_group_header_t *ghdr)
{
	int fullsize = sizeof(struct guc_state_capture_group_header_t);

	if (guc_capture_log_remove_bytes(guc, buf, ghdr, fullsize) != fullsize)
		return -1;
	return 0;
}

static int
guc_capture_log_get_data_hdr(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
			     struct guc_state_capture_header_t *hdr)
{
	int fullsize = sizeof(struct guc_state_capture_header_t);

	if (guc_capture_log_remove_bytes(guc, buf, hdr, fullsize) != fullsize)
		return -1;
	return 0;
}

static int
guc_capture_log_get_register(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
			     struct guc_mmio_reg *reg)
{
	int fullsize = sizeof(struct guc_mmio_reg);

	if (guc_capture_log_remove_bytes(guc, buf, reg, fullsize) != fullsize)
		return -1;
	return 0;
}

static struct __guc_capture_parsed_output *
guc_capture_get_prealloc_node(struct xe_guc *guc)
{
	struct __guc_capture_parsed_output *found = NULL;

	if (!list_empty(&guc->capture->cachelist)) {
		struct __guc_capture_parsed_output *n, *ntmp;

		/* get first avail node from the cache list */
		list_for_each_entry_safe(n, ntmp, &guc->capture->cachelist, link) {
			found = n;
			break;
		}
	} else {
		struct __guc_capture_parsed_output *n, *ntmp;

		/*
		 * traverse reversed and steal back the oldest node already
		 * allocated
		 */
		list_for_each_entry_safe_reverse(n, ntmp, &guc->capture->outlist, link) {
			if (!n->locked)
				found = n;
		}
	}
	if (found) {
		list_del(&found->link);
		guc_capture_init_node(guc, found);
	}

	return found;
}

static struct __guc_capture_parsed_output *
guc_capture_clone_node(struct xe_guc *guc, struct __guc_capture_parsed_output *original,
		       u32 keep_reglist_mask)
{
	struct __guc_capture_parsed_output *new;
	int i;

	new = guc_capture_get_prealloc_node(guc);
	if (!new)
		return NULL;
	if (!original)
		return new;

	new->is_partial = original->is_partial;

	/* copy reg-lists that we want to clone */
	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
		if (keep_reglist_mask & BIT(i)) {
			XE_WARN_ON(original->reginfo[i].num_regs  >
				   guc->capture->max_mmio_per_node);

			memcpy(new->reginfo[i].regs, original->reginfo[i].regs,
			       original->reginfo[i].num_regs * sizeof(struct guc_mmio_reg));

			new->reginfo[i].num_regs = original->reginfo[i].num_regs;
			new->reginfo[i].vfid  = original->reginfo[i].vfid;

			if (i == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS) {
				new->eng_class = original->eng_class;
			} else if (i == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
				new->eng_inst = original->eng_inst;
				new->guc_id = original->guc_id;
				new->lrca = original->lrca;
			}
		}
	}

	return new;
}

static int
guc_capture_extract_reglists(struct xe_guc *guc, struct __guc_capture_bufstate *buf)
{
	struct xe_gt *gt = guc_to_gt(guc);
	struct guc_state_capture_group_header_t ghdr = {0};
	struct guc_state_capture_header_t hdr = {0};
	struct __guc_capture_parsed_output *node = NULL;
	struct guc_mmio_reg *regs = NULL;
	int i, numlists, numregs, ret = 0;
	enum guc_state_capture_type datatype;
	struct guc_mmio_reg tmp;
	bool is_partial = false;

	i = guc_capture_buf_cnt(buf);
	if (!i)
		return -ENODATA;

	if (i % sizeof(u32)) {
		xe_gt_warn(gt, "Got mis-aligned register capture entries\n");
		ret = -EIO;
		goto bailout;
	}

	/* first get the capture group header */
	if (guc_capture_log_get_group_hdr(guc, buf, &ghdr)) {
		ret = -EIO;
		goto bailout;
	}
	/*
	 * we would typically expect a layout as below where n would be expected to be
	 * anywhere between 3 to n where n > 3 if we are seeing multiple dependent engine
	 * instances being reset together.
	 * ____________________________________________
	 * | Capture Group                            |
	 * | ________________________________________ |
	 * | | Capture Group Header:                | |
	 * | |  - num_captures = 5                  | |
	 * | |______________________________________| |
	 * | ________________________________________ |
	 * | | Capture1:                            | |
	 * | |  Hdr: GLOBAL, numregs=a              | |
	 * | | ____________________________________ | |
	 * | | | Reglist                          | | |
	 * | | | - reg1, reg2, ... rega           | | |
	 * | | |__________________________________| | |
	 * | |______________________________________| |
	 * | ________________________________________ |
	 * | | Capture2:                            | |
	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=b| |
	 * | | ____________________________________ | |
	 * | | | Reglist                          | | |
	 * | | | - reg1, reg2, ... regb           | | |
	 * | | |__________________________________| | |
	 * | |______________________________________| |
	 * | ________________________________________ |
	 * | | Capture3:                            | |
	 * | |  Hdr: INSTANCE=RCS, numregs=c        | |
	 * | | ____________________________________ | |
	 * | | | Reglist                          | | |
	 * | | | - reg1, reg2, ... regc           | | |
	 * | | |__________________________________| | |
	 * | |______________________________________| |
	 * | ________________________________________ |
	 * | | Capture4:                            | |
	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=d| |
	 * | | ____________________________________ | |
	 * | | | Reglist                          | | |
	 * | | | - reg1, reg2, ... regd           | | |
	 * | | |__________________________________| | |
	 * | |______________________________________| |
	 * | ________________________________________ |
	 * | | Capture5:                            | |
	 * | |  Hdr: INSTANCE=CCS0, numregs=e       | |
	 * | | ____________________________________ | |
	 * | | | Reglist                          | | |
	 * | | | - reg1, reg2, ... rege           | | |
	 * | | |__________________________________| | |
	 * | |______________________________________| |
	 * |__________________________________________|
	 */
	is_partial = FIELD_GET(GUC_STATE_CAPTURE_GROUP_HEADER_CAPTURE_GROUP_TYPE, ghdr.info);
	numlists = FIELD_GET(GUC_STATE_CAPTURE_GROUP_HEADER_NUM_CAPTURES, ghdr.info);

	while (numlists--) {
		if (guc_capture_log_get_data_hdr(guc, buf, &hdr)) {
			ret = -EIO;
			break;
		}

		datatype = FIELD_GET(GUC_STATE_CAPTURE_HEADER_CAPTURE_TYPE, hdr.info);
		if (datatype > GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
			/* unknown capture type - skip over to next capture set */
			numregs = FIELD_GET(GUC_STATE_CAPTURE_HEADER_NUM_MMIO_ENTRIES,
					    hdr.num_mmio_entries);
			while (numregs--) {
				if (guc_capture_log_get_register(guc, buf, &tmp)) {
					ret = -EIO;
					break;
				}
			}
			continue;
		} else if (node) {
			/*
			 * Based on the current capture type and what we have so far,
			 * decide if we should add the current node into the internal
			 * linked list for match-up when xe_devcoredump calls later
			 * (and alloc a blank node for the next set of reglists)
			 * or continue with the same node or clone the current node
			 * but only retain the global or class registers (such as the
			 * case of dependent engine resets).
			 */
			if (datatype == GUC_STATE_CAPTURE_TYPE_GLOBAL) {
				guc_capture_add_node_to_outlist(guc->capture, node);
				node = NULL;
			} else if (datatype == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
				   node->reginfo[GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS].num_regs) {
				/* Add to list, clone node and duplicate global list */
				guc_capture_add_node_to_outlist(guc->capture, node);
				node = guc_capture_clone_node(guc, node,
							      GCAP_PARSED_REGLIST_INDEX_GLOBAL);
			} else if (datatype == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE &&
				   node->reginfo[GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE].num_regs) {
				/* Add to list, clone node and duplicate global + class lists */
				guc_capture_add_node_to_outlist(guc->capture, node);
				node = guc_capture_clone_node(guc, node,
							      (GCAP_PARSED_REGLIST_INDEX_GLOBAL |
							      GCAP_PARSED_REGLIST_INDEX_ENGCLASS));
			}
		}

		if (!node) {
			node = guc_capture_get_prealloc_node(guc);
			if (!node) {
				ret = -ENOMEM;
				break;
			}
			if (datatype != GUC_STATE_CAPTURE_TYPE_GLOBAL)
				xe_gt_dbg(gt, "Register capture missing global dump: %08x!\n",
					  datatype);
		}
		node->is_partial = is_partial;
		node->reginfo[datatype].vfid = FIELD_GET(GUC_STATE_CAPTURE_HEADER_VFID, hdr.owner);
		node->source = XE_ENGINE_CAPTURE_SOURCE_GUC;
		node->type = datatype;

		switch (datatype) {
		case GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE:
			node->eng_class = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_CLASS,
						    hdr.info);
			node->eng_inst = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_INSTANCE,
						   hdr.info);
			node->lrca = hdr.lrca;
			node->guc_id = hdr.guc_id;
			break;
		case GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS:
			node->eng_class = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_CLASS,
						    hdr.info);
			break;
		default:
			break;
		}

		numregs = FIELD_GET(GUC_STATE_CAPTURE_HEADER_NUM_MMIO_ENTRIES,
				    hdr.num_mmio_entries);
		if (numregs > guc->capture->max_mmio_per_node) {
			xe_gt_dbg(gt, "Register capture list extraction clipped by prealloc!\n");
			numregs = guc->capture->max_mmio_per_node;
		}
		node->reginfo[datatype].num_regs = numregs;
		regs = node->reginfo[datatype].regs;
		i = 0;
		while (numregs--) {
			if (guc_capture_log_get_register(guc, buf, &regs[i++])) {
				ret = -EIO;
				break;
			}
		}
	}

bailout:
	if (node) {
		/* If we have data, add to linked list for match-up when xe_devcoredump calls */
		for (i = GUC_STATE_CAPTURE_TYPE_GLOBAL; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
			if (node->reginfo[i].regs) {
				guc_capture_add_node_to_outlist(guc->capture, node);
				node = NULL;
				break;
			}
		}
		if (node) /* else return it back to cache list */
			guc_capture_add_node_to_cachelist(guc->capture, node);
	}
	return ret;
}

static int __guc_capture_flushlog_complete(struct xe_guc *guc)
{
	u32 action[] = {
		XE_GUC_ACTION_LOG_BUFFER_FILE_FLUSH_COMPLETE,
		GUC_LOG_TYPE_STATE_CAPTURE
	};

	return xe_guc_ct_send_g2h_handler(&guc->ct, action, ARRAY_SIZE(action));
}

static void __guc_capture_process_output(struct xe_guc *guc)
{
	unsigned int buffer_size, read_offset, write_offset, full_count;
	struct xe_uc *uc = container_of(guc, typeof(*uc), guc);
	struct guc_log_buffer_state log_buf_state_local;
	struct __guc_capture_bufstate buf;
	bool new_overflow;
	int ret, tmp;
	u32 log_buf_state_offset;
	u32 src_data_offset;

	log_buf_state_offset = sizeof(struct guc_log_buffer_state) * GUC_LOG_TYPE_STATE_CAPTURE;
	src_data_offset = XE_GUC_LOG_STATE_CAPTURE_OFFSET;

	/*
	 * Make a copy of the state structure, inside GuC log buffer
	 * (which is uncached mapped), on the stack to avoid reading
	 * from it multiple times.
	 */
	xe_map_memcpy_from(guc_to_xe(guc), &log_buf_state_local, &guc->log.bo->vmap,
			   log_buf_state_offset, sizeof(struct guc_log_buffer_state));

	buffer_size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE;
	read_offset = log_buf_state_local.read_ptr;
	write_offset = log_buf_state_local.sampled_write_ptr;
	full_count = FIELD_GET(GUC_LOG_BUFFER_STATE_BUFFER_FULL_CNT, log_buf_state_local.flags);

	/* Bookkeeping stuff */
	tmp = FIELD_GET(GUC_LOG_BUFFER_STATE_FLUSH_TO_FILE, log_buf_state_local.flags);
	guc->log.stats[GUC_LOG_TYPE_STATE_CAPTURE].flush += tmp;
	new_overflow = xe_guc_check_log_buf_overflow(&guc->log, GUC_LOG_TYPE_STATE_CAPTURE,
						     full_count);

	/* Now copy the actual logs. */
	if (unlikely(new_overflow)) {
		/* copy the whole buffer in case of overflow */
		read_offset = 0;
		write_offset = buffer_size;
	} else if (unlikely((read_offset > buffer_size) ||
			(write_offset > buffer_size))) {
		xe_gt_err(guc_to_gt(guc),
			  "Register capture buffer in invalid state: read = 0x%X, size = 0x%X!\n",
			  read_offset, buffer_size);
		/* copy whole buffer as offsets are unreliable */
		read_offset = 0;
		write_offset = buffer_size;
	}

	buf.size = buffer_size;
	buf.rd = read_offset;
	buf.wr = write_offset;
	buf.data_offset = src_data_offset;

	if (!xe_guc_read_stopped(guc)) {
		do {
			ret = guc_capture_extract_reglists(guc, &buf);
			if (ret && ret != -ENODATA)
				xe_gt_dbg(guc_to_gt(guc), "Capture extraction failed:%d\n", ret);
		} while (ret >= 0);
	}

	/* Update the state of log buffer err-cap state */
	xe_map_wr(guc_to_xe(guc), &guc->log.bo->vmap,
		  log_buf_state_offset + offsetof(struct guc_log_buffer_state, read_ptr), u32,
		  write_offset);

	/*
	 * Clear the flush_to_file from local first, the local was loaded by above
	 * xe_map_memcpy_from, then write out the "updated local" through
	 * xe_map_wr()
	 */
	log_buf_state_local.flags &= ~GUC_LOG_BUFFER_STATE_FLUSH_TO_FILE;
	xe_map_wr(guc_to_xe(guc), &guc->log.bo->vmap,
		  log_buf_state_offset + offsetof(struct guc_log_buffer_state, flags), u32,
		  log_buf_state_local.flags);
	__guc_capture_flushlog_complete(guc);
}

/*
 * xe_guc_capture_process - Process GuC register captured data
 * @guc: The GuC object
 *
 * When GuC captured data is ready, GuC will send message
 * XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION to host, this function will be
 * called to process the data comes with the message.
 *
 * Returns: None
 */
void xe_guc_capture_process(struct xe_guc *guc)
{
	if (guc->capture)
		__guc_capture_process_output(guc);
}

static struct __guc_capture_parsed_output *
guc_capture_alloc_one_node(struct xe_guc *guc)
{
	struct drm_device *drm = guc_to_drm(guc);
	struct __guc_capture_parsed_output *new;
	int i;

	new = drmm_kzalloc(drm, sizeof(*new), GFP_KERNEL);
	if (!new)
		return NULL;

	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
		new->reginfo[i].regs = drmm_kzalloc(drm, guc->capture->max_mmio_per_node *
						    sizeof(struct guc_mmio_reg), GFP_KERNEL);
		if (!new->reginfo[i].regs) {
			while (i)
				drmm_kfree(drm, new->reginfo[--i].regs);
			drmm_kfree(drm, new);
			return NULL;
		}
	}
	guc_capture_init_node(guc, new);

	return new;
}

static void
__guc_capture_create_prealloc_nodes(struct xe_guc *guc)
{
	struct __guc_capture_parsed_output *node = NULL;
	int i;

	for (i = 0; i < PREALLOC_NODES_MAX_COUNT; ++i) {
		node = guc_capture_alloc_one_node(guc);
		if (!node) {
			xe_gt_warn(guc_to_gt(guc), "Register capture pre-alloc-cache failure\n");
			/* dont free the priors, use what we got and cleanup at shutdown */
			return;
		}
		guc_capture_add_node_to_cachelist(guc->capture, node);
	}
}

static int
guc_get_max_reglist_count(struct xe_guc *guc)
{
	int i, j, k, tmp, maxregcount = 0;

	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; ++i) {
		for (j = 0; j < GUC_STATE_CAPTURE_TYPE_MAX; ++j) {
			for (k = 0; k < GUC_CAPTURE_LIST_CLASS_MAX; ++k) {
				const struct __guc_mmio_reg_descr_group *match;

				if (j == GUC_STATE_CAPTURE_TYPE_GLOBAL && k > 0)
					continue;

				tmp = 0;
				match = guc_capture_get_one_list(guc->capture->reglists, i, j, k);
				if (match)
					tmp = match->num_regs;

				match = guc_capture_get_one_list(guc->capture->extlists, i, j, k);
				if (match)
					tmp += match->num_regs;

				if (tmp > maxregcount)
					maxregcount = tmp;
			}
		}
	}
	if (!maxregcount)
		maxregcount = PREALLOC_NODES_DEFAULT_NUMREGS;

	return maxregcount;
}

static void
guc_capture_create_prealloc_nodes(struct xe_guc *guc)
{
	/* skip if we've already done the pre-alloc */
	if (guc->capture->max_mmio_per_node)
		return;

	guc->capture->max_mmio_per_node = guc_get_max_reglist_count(guc);
	__guc_capture_create_prealloc_nodes(guc);
}

static void
read_reg_to_node(struct xe_hw_engine *hwe, const struct __guc_mmio_reg_descr_group *list,
		 struct guc_mmio_reg *regs)
{
	int i;

	if (!list || !list->list || list->num_regs == 0)
		return;

	if (!regs)
		return;

	for (i = 0; i < list->num_regs; i++) {
		struct __guc_mmio_reg_descr desc = list->list[i];
		u32 value;

		if (list->type == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
			value = xe_hw_engine_mmio_read32(hwe, desc.reg);
		} else {
			if (list->type == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
			    FIELD_GET(GUC_REGSET_STEERING_NEEDED, desc.flags)) {
				int group, instance;

				group = FIELD_GET(GUC_REGSET_STEERING_GROUP, desc.flags);
				instance = FIELD_GET(GUC_REGSET_STEERING_INSTANCE, desc.flags);
				value = xe_gt_mcr_unicast_read(hwe->gt, XE_REG_MCR(desc.reg.addr),
							       group, instance);
			} else {
				value = xe_mmio_read32(&hwe->gt->mmio, desc.reg);
			}
		}

		regs[i].value = value;
		regs[i].offset = desc.reg.addr;
		regs[i].flags = desc.flags;
		regs[i].mask = desc.mask;
	}
}

/**
 * xe_engine_manual_capture - Take a manual engine snapshot from engine.
 * @hwe: Xe HW Engine.
 * @snapshot: The engine snapshot
 *
 * Take engine snapshot from engine read.
 *
 * Returns: None
 */
void
xe_engine_manual_capture(struct xe_hw_engine *hwe, struct xe_hw_engine_snapshot *snapshot)
{
	struct xe_gt *gt = hwe->gt;
	struct xe_device *xe = gt_to_xe(gt);
	struct xe_guc *guc = &gt->uc.guc;
	struct xe_devcoredump *devcoredump = &xe->devcoredump;
	enum guc_capture_list_class_type capture_class;
	const struct __guc_mmio_reg_descr_group *list;
	struct __guc_capture_parsed_output *new;
	enum guc_state_capture_type type;
	u16 guc_id = 0;
	u32 lrca = 0;

	if (IS_SRIOV_VF(xe))
		return;

	new = guc_capture_get_prealloc_node(guc);
	if (!new)
		return;

	capture_class = xe_hwe_to_guc_capture_class(hwe);
	for (type = GUC_STATE_CAPTURE_TYPE_GLOBAL; type < GUC_STATE_CAPTURE_TYPE_MAX; type++) {
		struct gcap_reg_list_info *reginfo = &new->reginfo[type];
		/*
		 * regsinfo->regs is allocated based on guc->capture->max_mmio_per_node
		 * which is based on the descriptor list driving the population so
		 * should not overflow
		 */

		/* Get register list for the type/class */
		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF, type,
							capture_class, false);
		if (!list) {
			xe_gt_dbg(gt, "Empty GuC capture register descriptor for %s",
				  hwe->name);
			continue;
		}

		read_reg_to_node(hwe, list, reginfo->regs);
		reginfo->num_regs = list->num_regs;

		/* Capture steering registers for rcs/ccs */
		if (capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
			list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF,
								type, capture_class, true);
			if (list) {
				read_reg_to_node(hwe, list, &reginfo->regs[reginfo->num_regs]);
				reginfo->num_regs += list->num_regs;
			}
		}
	}

	if (devcoredump && devcoredump->captured) {
		struct xe_guc_submit_exec_queue_snapshot *ge = devcoredump->snapshot.ge;

		if (ge) {
			guc_id = ge->guc.id;
			if (ge->lrc[0])
				lrca = ge->lrc[0]->context_desc;
		}
	}

	new->eng_class = xe_hwe_to_guc_class(hwe);
	new->eng_inst = hwe->instance;
	new->guc_id = guc_id;
	new->lrca = lrca;
	new->is_partial = 0;
	new->locked = 1;
	new->source = XE_ENGINE_CAPTURE_SOURCE_MANUAL;

	guc_capture_add_node_to_outlist(guc->capture, new);
	devcoredump->snapshot.matched_node = new;
}

static struct guc_mmio_reg *
guc_capture_find_reg(struct gcap_reg_list_info *reginfo, u32 addr, u32 flags)
{
	int i;

	if (reginfo && reginfo->num_regs > 0) {
		struct guc_mmio_reg *regs = reginfo->regs;

		if (regs)
			for (i = 0; i < reginfo->num_regs; i++)
				if (regs[i].offset == addr && regs[i].flags == flags)
					return &regs[i];
	}

	return NULL;
}

static void
snapshot_print_by_list_order(struct xe_hw_engine_snapshot *snapshot, struct drm_printer *p,
			     u32 type, const struct __guc_mmio_reg_descr_group *list)
{
	struct xe_gt *gt = snapshot->hwe->gt;
	struct xe_device *xe = gt_to_xe(gt);
	struct xe_devcoredump *devcoredump = &xe->devcoredump;
	struct xe_devcoredump_snapshot *devcore_snapshot = &devcoredump->snapshot;
	struct gcap_reg_list_info *reginfo = NULL;
	u32 i, last_value = 0;
	bool low32_ready = false;

	if (!list || !list->list || list->num_regs == 0)
		return;
	XE_WARN_ON(!devcore_snapshot->matched_node);

	reginfo = &devcore_snapshot->matched_node->reginfo[type];

	/*
	 * loop through descriptor first and find the register in the node
	 * this is more scalable for developer maintenance as it will ensure
	 * the printout matched the ordering of the static descriptor
	 * table-of-lists
	 */
	for (i = 0; i < list->num_regs; i++) {
		const struct __guc_mmio_reg_descr *reg_desc = &list->list[i];
		struct guc_mmio_reg *reg;
		u32 value;

		reg = guc_capture_find_reg(reginfo, reg_desc->reg.addr, reg_desc->flags);
		if (!reg)
			continue;

		value = reg->value;
		switch (reg_desc->data_type) {
		case REG_64BIT_LOW_DW:
			last_value = value;

			/*
			 * A 64 bit register define requires 2 consecutive
			 * entries in register list, with low dword first
			 * and hi dword the second, like:
			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
			 *  { XXX_REG_HI(0), REG_64BIT_HI_DW,  0, 0, "XXX_REG"},
			 *
			 * Incorrect order will trigger XE_WARN.
			 *
			 * Possible double low here, for example:
			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
			 */
			XE_WARN_ON(low32_ready);
			low32_ready = true;
			/* Low 32 bit dword saved, continue for high 32 bit */
			break;

		case REG_64BIT_HI_DW: {
			u64 value_qw = ((u64)value << 32) | last_value;

			/*
			 * Incorrect 64bit register order. Possible missing low.
			 * for example:
			 *  { XXX_REG(0), REG_32BIT, 0, 0, NULL},
			 *  { XXX_REG_HI(0), REG_64BIT_HI_DW, 0, 0, NULL},
			 */
			XE_WARN_ON(!low32_ready);
			low32_ready = false;

			drm_printf(p, "\t%s: 0x%016llx\n", reg_desc->regname, value_qw);
			break;
		}

		case REG_32BIT:
			/*
			 * Incorrect 64bit register order. Possible missing high.
			 * for example:
			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
			 *  { XXX_REG(0), REG_32BIT, 0, 0, "XXX_REG"},
			 */
			XE_WARN_ON(low32_ready);

			if (FIELD_GET(GUC_REGSET_STEERING_NEEDED, reg_desc->flags))
				drm_printf(p, "\t%s[%u]: 0x%08x\n", reg_desc->regname,
					   reg_desc->dss_id, value);
			else
				drm_printf(p, "\t%s: 0x%08x\n", reg_desc->regname, value);

			break;
		}
	}

	/*
	 * Incorrect 64bit register order. Possible missing high.
	 * for example:
	 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
	 *  } // <- Register list end
	 */
	XE_WARN_ON(low32_ready);
}

/**
 * xe_engine_snapshot_print - Print out a given Xe HW Engine snapshot.
 * @snapshot: Xe HW Engine snapshot object.
 * @p: drm_printer where it will be printed out.
 *
 * This function prints out a given Xe HW Engine snapshot object.
 */
void xe_engine_snapshot_print(struct xe_hw_engine_snapshot *snapshot, struct drm_printer *p)
{
	const char *grptype[GUC_STATE_CAPTURE_GROUP_TYPE_MAX] = {
		"full-capture",
		"partial-capture"
	};
	int type;
	const struct __guc_mmio_reg_descr_group *list;
	enum guc_capture_list_class_type capture_class;

	struct xe_gt *gt;
	struct xe_device *xe;
	struct xe_devcoredump *devcoredump;
	struct xe_devcoredump_snapshot *devcore_snapshot;

	if (!snapshot)
		return;

	gt = snapshot->hwe->gt;
	xe = gt_to_xe(gt);
	devcoredump = &xe->devcoredump;
	devcore_snapshot = &devcoredump->snapshot;

	if (!devcore_snapshot->matched_node)
		return;

	xe_gt_assert(gt, snapshot->hwe);

	capture_class = xe_hwe_to_guc_capture_class(snapshot->hwe);

	drm_printf(p, "%s (physical), logical instance=%d\n",
		   snapshot->name ? snapshot->name : "",
		   snapshot->logical_instance);
	drm_printf(p, "\tCapture_source: %s\n",
		   devcore_snapshot->matched_node->source == XE_ENGINE_CAPTURE_SOURCE_GUC ?
		   "GuC" : "Manual");
	drm_printf(p, "\tCoverage: %s\n", grptype[devcore_snapshot->matched_node->is_partial]);
	drm_printf(p, "\tForcewake: domain 0x%x, ref %d\n",
		   snapshot->forcewake.domain, snapshot->forcewake.ref);
	drm_printf(p, "\tReserved: %s\n",
		   str_yes_no(snapshot->kernel_reserved));

	for (type = GUC_STATE_CAPTURE_TYPE_GLOBAL; type < GUC_STATE_CAPTURE_TYPE_MAX; type++) {
		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF, type,
							capture_class, false);
		snapshot_print_by_list_order(snapshot, p, type, list);
	}

	if (capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF,
							GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
							capture_class, true);
		snapshot_print_by_list_order(snapshot, p, GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
					     list);
	}

	drm_puts(p, "\n");
}

/**
 * xe_guc_capture_get_matching_and_lock - Matching GuC capture for the queue.
 * @q: The exec queue object
 *
 * Search within the capture outlist for the queue, could be used for check if
 * GuC capture is ready for the queue.
 * If found, the locked boolean of the node will be flagged.
 *
 * Returns: found guc-capture node ptr else NULL
 */
struct __guc_capture_parsed_output *
xe_guc_capture_get_matching_and_lock(struct xe_exec_queue *q)
{
	struct xe_hw_engine *hwe;
	enum xe_hw_engine_id id;
	struct xe_device *xe;
	u16 guc_class = GUC_LAST_ENGINE_CLASS + 1;
	struct xe_devcoredump_snapshot *ss;

	if (!q || !q->gt)
		return NULL;

	xe = gt_to_xe(q->gt);

	if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET)
		return NULL;

	if (!xe_device_uc_enabled(xe))
		return NULL;

	if (IS_SRIOV_VF(xe))
		return NULL;

	ss = &xe->devcoredump.snapshot;
	if (ss->matched_node && ss->matched_node->source == XE_ENGINE_CAPTURE_SOURCE_GUC)
		return ss->matched_node;

	/* Find hwe for the queue */
	for_each_hw_engine(hwe, q->gt, id) {
		if (hwe != q->hwe)
			continue;
		guc_class = xe_hwe_to_guc_class(hwe);
		break;
	}

	if (guc_class <= GUC_LAST_ENGINE_CLASS) {
		struct __guc_capture_parsed_output *n, *ntmp;
		struct xe_guc *guc =  &q->gt->uc.guc;
		u16 guc_id = q->guc->id;
		u32 lrca = xe_lrc_ggtt_addr(q->lrc[0]);

		/*
		 * Look for a matching GuC reported error capture node from
		 * the internal output link-list based on engine, guc id and
		 * lrca info.
		 */
		list_for_each_entry_safe(n, ntmp, &guc->capture->outlist, link) {
			if (n->eng_class == guc_class && n->eng_inst == hwe->instance &&
			    n->guc_id == guc_id && n->lrca == lrca &&
			    n->source == XE_ENGINE_CAPTURE_SOURCE_GUC) {
				n->locked = 1;
				return n;
			}
		}
	}
	return NULL;
}

/**
 * xe_engine_snapshot_capture_for_queue - Take snapshot of associated engine
 * @q: The exec queue object
 *
 * Take snapshot of associated HW Engine
 *
 * Returns: None.
 */
void
xe_engine_snapshot_capture_for_queue(struct xe_exec_queue *q)
{
	struct xe_device *xe = gt_to_xe(q->gt);
	struct xe_devcoredump *coredump = &xe->devcoredump;
	struct xe_hw_engine *hwe;
	enum xe_hw_engine_id id;
	u32 adj_logical_mask = q->logical_mask;

	if (IS_SRIOV_VF(xe))
		return;

	for_each_hw_engine(hwe, q->gt, id) {
		if (hwe->class != q->hwe->class ||
		    !(BIT(hwe->logical_instance) & adj_logical_mask)) {
			coredump->snapshot.hwe[id] = NULL;
			continue;
		}

		if (!coredump->snapshot.hwe[id]) {
			coredump->snapshot.hwe[id] =
				xe_hw_engine_snapshot_capture(hwe, q);
		} else {
			struct __guc_capture_parsed_output *new;

			new = xe_guc_capture_get_matching_and_lock(q);
			if (new) {
				struct xe_guc *guc =  &q->gt->uc.guc;

				/*
				 * If we are in here, it means we found a fresh
				 * GuC-err-capture node for this engine after
				 * previously failing to find a match in the
				 * early part of guc_exec_queue_timedout_job.
				 * Thus we must free the manually captured node
				 */
				guc_capture_free_outlist_node(guc->capture,
							      coredump->snapshot.matched_node);
				coredump->snapshot.matched_node = new;
			}
		}

		break;
	}
}

/*
 * xe_guc_capture_put_matched_nodes - Cleanup matched nodes
 * @guc: The GuC object
 *
 * Free matched node and all nodes with the equal guc_id from
 * GuC captured outlist
 */
void xe_guc_capture_put_matched_nodes(struct xe_guc *guc)
{
	struct xe_device *xe = guc_to_xe(guc);
	struct xe_devcoredump *devcoredump = &xe->devcoredump;
	struct __guc_capture_parsed_output *n = devcoredump->snapshot.matched_node;

	if (n) {
		guc_capture_remove_stale_matches_from_list(guc->capture, n);
		guc_capture_free_outlist_node(guc->capture, n);
		devcoredump->snapshot.matched_node = NULL;
	}
}

/*
 * xe_guc_capture_steered_list_init - Init steering register list
 * @guc: The GuC object
 *
 * Init steering register list for GuC register capture, create pre-alloc node
 */
void xe_guc_capture_steered_list_init(struct xe_guc *guc)
{
	/*
	 * For certain engine classes, there are slice and subslice
	 * level registers requiring steering. We allocate and populate
	 * these based on hw config and add it as an extension list at
	 * the end of the pre-populated render list.
	 */
	guc_capture_alloc_steered_lists(guc);
	check_guc_capture_size(guc);
	guc_capture_create_prealloc_nodes(guc);
}

/*
 * xe_guc_capture_init - Init for GuC register capture
 * @guc: The GuC object
 *
 * Init for GuC register capture, alloc memory for capture data structure.
 *
 * Returns: 0 if success.
 *	    -ENOMEM if out of memory
 */
int xe_guc_capture_init(struct xe_guc *guc)
{
	guc->capture = drmm_kzalloc(guc_to_drm(guc), sizeof(*guc->capture), GFP_KERNEL);
	if (!guc->capture)
		return -ENOMEM;

	guc->capture->reglists = guc_capture_get_device_reglist(guc_to_xe(guc));

	INIT_LIST_HEAD(&guc->capture->outlist);
	INIT_LIST_HEAD(&guc->capture->cachelist);

	return 0;
}