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
/*
 * Copyright 2020 Advanced Micro Devices, Inc.
 *
 * 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 shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
 */

#define SWSMU_CODE_LAYER_L4

#include "amdgpu.h"
#include "amdgpu_smu.h"
#include "smu_cmn.h"
#include "soc15_common.h"

/*
 * DO NOT use these for err/warn/info/debug messages.
 * Use dev_err, dev_warn, dev_info and dev_dbg instead.
 * They are more MGPU friendly.
 */
#undef pr_err
#undef pr_warn
#undef pr_info
#undef pr_debug

#define MP1_C2PMSG_90__CONTENT_MASK                                                                    0xFFFFFFFFL

const int link_speed[] = {25, 50, 80, 160, 320, 640};

#undef __SMU_DUMMY_MAP
#define __SMU_DUMMY_MAP(type)	#type
static const char * const __smu_message_names[] = {
	SMU_MESSAGE_TYPES
};

#define smu_cmn_call_asic_func(intf, smu, args...)                             \
	((smu)->ppt_funcs ? ((smu)->ppt_funcs->intf ?                          \
				     (smu)->ppt_funcs->intf(smu, ##args) :     \
				     -ENOTSUPP) :                              \
			    -EINVAL)

#define SMU_MSG_V1_DEFAULT_RATELIMIT_INTERVAL (5 * HZ)
#define SMU_MSG_V1_DEFAULT_RATELIMIT_BURST 10

static const char *smu_get_message_name(struct smu_context *smu,
					enum smu_message_type type)
{
	if (type >= SMU_MSG_MAX_COUNT)
		return "unknown smu message";

	return __smu_message_names[type];
}

/* Redefine the SMU error codes here.
 *
 * Note that these definitions are redundant and should be removed
 * when the SMU has exported a unified header file containing these
 * macros, which header file we can just include and use the SMU's
 * macros. At the moment, these error codes are defined by the SMU
 * per-ASIC unfortunately, yet we're a one driver for all ASICs.
 */
#define SMU_RESP_NONE           0
#define SMU_RESP_OK             1
#define SMU_RESP_CMD_FAIL       0xFF
#define SMU_RESP_CMD_UNKNOWN    0xFE
#define SMU_RESP_CMD_BAD_PREREQ 0xFD
#define SMU_RESP_BUSY_OTHER     0xFC
#define SMU_RESP_DEBUG_END      0xFB

#define SMU_RESP_UNEXP (~0U)

static int smu_msg_v1_send_debug_msg(struct smu_msg_ctl *ctl, u32 msg, u32 param)
{
	struct amdgpu_device *adev = ctl->smu->adev;
	struct smu_msg_config *cfg = &ctl->config;

	if (!(ctl->flags & SMU_MSG_CTL_DEBUG_MAILBOX))
		return -EOPNOTSUPP;

	mutex_lock(&ctl->lock);

	WREG32(cfg->debug_param_reg, param);
	WREG32(cfg->debug_msg_reg, msg);
	WREG32(cfg->debug_resp_reg, 0);

	mutex_unlock(&ctl->lock);

	return 0;
}

static int __smu_cmn_send_debug_msg(struct smu_msg_ctl *ctl,
				    u32 msg,
				    u32 param)
{
	if (!ctl->ops || !ctl->ops->send_debug_msg)
		return -EOPNOTSUPP;

	return ctl->ops->send_debug_msg(ctl, msg, param);
}

/**
 * smu_cmn_wait_for_response -- wait for response from the SMU
 * @smu: pointer to an SMU context
 *
 * Wait for status from the SMU.
 *
 * Return 0 on success, -errno on error, indicating the execution
 * status and result of the message being waited for. See
 * smu_msg_v1_decode_response() for details of the -errno.
 */
int smu_cmn_wait_for_response(struct smu_context *smu)
{
	return smu_msg_wait_response(&smu->msg_ctl, 0);
}

/**
 * smu_cmn_send_smc_msg_with_params_ext - send an SMU message with 0..N args
 * @smu: pointer to an SMU context
 * @msg: message to send
 * @params: optional input argument array
 * @num_params: number of input arguments in @params
 * @read_args: optional output argument array
 * @num_read_args: number of output arguments to read back
 * @flags: message flags (SMU_MSG_FLAG_*)
 * @timeout: per-message timeout in us (0 = use default)
 *
 * This helper keeps the raw protocol semantics of struct smu_msg_args while
 * hiding the per-call boilerplate. It is intended for true multi-parameter
 * messages. Legacy wrappers such as smu_cmn_send_smc_msg() retain their
 * existing single-zero-parameter behavior for compatibility.
 *
 * Return: 0 on success, -errno on failure.
 */
int smu_cmn_send_smc_msg_with_params_ext(struct smu_context *smu,
					 enum smu_message_type msg,
					 const uint32_t *params,
					 size_t num_params,
					 uint32_t *read_args,
					 size_t num_read_args,
					 uint32_t flags,
					 uint32_t timeout)
{
	struct smu_msg_ctl *ctl = &smu->msg_ctl;
	struct smu_msg_args args = {
		.msg = msg,
		.num_args = num_params,
		.num_out_args = num_read_args,
		.flags = flags,
		.timeout = timeout,
	};
	int ret;

	if ((num_params && !params) || (num_read_args && !read_args))
		return -EINVAL;

	if (num_params > SMU_MSG_MAX_ARGS || num_read_args > SMU_MSG_MAX_ARGS)
		return -EINVAL;

	if (num_params)
		memcpy(args.args, params, num_params * sizeof(*params));

	ret = ctl->ops->send_msg(ctl, &args);

	if (num_read_args)
		memcpy(read_args, args.out_args,
		       num_read_args * sizeof(*read_args));

	return ret;
}

/**
 * smu_cmn_send_smc_msg_with_param -- send a message with parameter
 * @smu: pointer to an SMU context
 * @msg: message to send
 * @param: parameter to send to the SMU
 * @read_arg: pointer to u32 to return a value from the SMU back
 *            to the caller
 *
 * Send the message @msg with parameter @param to the SMU, wait for
 * completion of the command, and return back a value from the SMU in
 * @read_arg pointer.
 *
 * Return 0 on success, -errno when a problem is encountered sending
 * message or receiving reply. If there is a PCI bus recovery or
 * the destination is a virtual GPU which does not allow this message
 * type, the message is simply dropped and success is also returned.
 * See smu_msg_v1_decode_response() for details of the -errno.
 *
 * If we weren't able to send the message to the SMU, we also print
 * the error to the standard log.
 *
 * Command completion status is printed only if the -errno is
 * -EREMOTEIO, indicating that the SMU returned back an
 * undefined/unknown/unspecified result. All other cases are
 * well-defined, not printed, but instead given back to the client to
 * decide what further to do.
 *
 * The return value, @read_arg is read back regardless, to give back
 * more information to the client, which on error would most likely be
 * @param, but we can't assume that. This also eliminates more
 * conditionals.
 */
int smu_cmn_send_smc_msg_with_param(struct smu_context *smu,
				    enum smu_message_type msg,
				    uint32_t param,
				    uint32_t *read_arg)
{
	return smu_cmn_send_smc_msg_with_params(smu, msg,
						&param, 1,
						read_arg, read_arg ? 1 : 0);
}

int smu_cmn_send_smc_msg(struct smu_context *smu,
			 enum smu_message_type msg,
			 uint32_t *read_arg)
{
	return smu_cmn_send_smc_msg_with_param(smu,
					       msg,
					       0,
					       read_arg);
}

int smu_cmn_send_debug_smc_msg(struct smu_context *smu,
			 uint32_t msg)
{
	return __smu_cmn_send_debug_msg(&smu->msg_ctl, msg, 0);
}

int smu_cmn_send_debug_smc_msg_with_param(struct smu_context *smu,
			 uint32_t msg, uint32_t param)
{
	return __smu_cmn_send_debug_msg(&smu->msg_ctl, msg, param);
}

static int smu_msg_v1_decode_response(u32 resp)
{
	int res;

	switch (resp) {
	case SMU_RESP_NONE:
		/* The SMU is busy--still executing your command.
		 */
		res = -ETIME;
		break;
	case SMU_RESP_OK:
		res = 0;
		break;
	case SMU_RESP_CMD_FAIL:
		/* Command completed successfully, but the command
		 * status was failure.
		 */
		res = -EIO;
		break;
	case SMU_RESP_CMD_UNKNOWN:
		/* Unknown command--ignored by the SMU.
		 */
		res = -EOPNOTSUPP;
		break;
	case SMU_RESP_CMD_BAD_PREREQ:
		/* Valid command--bad prerequisites.
		 */
		res = -EINVAL;
		break;
	case SMU_RESP_BUSY_OTHER:
		/* The SMU is busy with other commands. The client
		 * should retry in 10 us.
		 */
		res = -EBUSY;
		break;
	default:
		/* Unknown or debug response from the SMU.
		 */
		res = -EREMOTEIO;
		break;
	}

	return res;
}

static u32 __smu_msg_v1_poll_stat(struct smu_msg_ctl *ctl, u32 timeout_us)
{
	struct amdgpu_device *adev = ctl->smu->adev;
	struct smu_msg_config *cfg = &ctl->config;
	u32 timeout = timeout_us ? timeout_us : ctl->default_timeout;
	u32 reg;

	for (; timeout > 0; timeout--) {
		reg = RREG32(cfg->resp_reg);
		if ((reg & MP1_C2PMSG_90__CONTENT_MASK) != 0)
			break;
		udelay(1);
	}

	return reg;
}

static void __smu_msg_v1_send(struct smu_msg_ctl *ctl, u16 index,
			      struct smu_msg_args *args)
{
	struct amdgpu_device *adev = ctl->smu->adev;
	struct smu_msg_config *cfg = &ctl->config;
	u32 arg;
	int i;

	WREG32(cfg->resp_reg, 0);
	for (i = 0; i < cfg->num_arg_regs; i++) {
		/* NOTE: Clear unused argument registers to avoid stale values. */
		arg = i < args->num_args ? args->args[i] : 0;
		WREG32(cfg->arg_regs[i], arg);
	}
	WREG32(cfg->msg_reg, index);
}

static void __smu_msg_v1_read_out_args(struct smu_msg_ctl *ctl,
				       struct smu_msg_args *args)
{
	struct amdgpu_device *adev = ctl->smu->adev;
	int i;

	for (i = 0; i < args->num_out_args; i++)
		args->out_args[i] = RREG32(ctl->config.arg_regs[i]);
}

static void __smu_msg_v1_print_err_limited(struct smu_msg_ctl *ctl,
					   struct smu_msg_args *args,
					   char *err_msg)
{
	static DEFINE_RATELIMIT_STATE(_rs,
				      SMU_MSG_V1_DEFAULT_RATELIMIT_INTERVAL,
				      SMU_MSG_V1_DEFAULT_RATELIMIT_BURST);
	struct smu_context *smu = ctl->smu;
	struct amdgpu_device *adev = smu->adev;

	if (__ratelimit(&_rs)) {
		u32 in[SMU_MSG_MAX_ARGS];
		int i;

		dev_err(adev->dev, "%s msg_reg: %x resp_reg: %x", err_msg,
			RREG32(ctl->config.msg_reg),
			RREG32(ctl->config.resp_reg));
		if (args->num_args > 0) {
			for (i = 0; i < args->num_args; i++)
				in[i] = RREG32(ctl->config.arg_regs[i]);
			print_hex_dump(KERN_ERR, "in params:", DUMP_PREFIX_NONE,
				       16, 4, in, args->num_args * sizeof(u32),
				       false);
		}
	}
}

static void __smu_msg_v1_print_error(struct smu_msg_ctl *ctl,
				     u32 resp,
				     struct smu_msg_args *args)
{
	struct smu_context *smu = ctl->smu;
	struct amdgpu_device *adev = smu->adev;
	int index = ctl->message_map[args->msg].map_to;

	switch (resp) {
	case SMU_RESP_NONE:
		__smu_msg_v1_print_err_limited(ctl, args, "SMU: No response");
		break;
	case SMU_RESP_OK:
		break;
	case SMU_RESP_CMD_FAIL:
		break;
	case SMU_RESP_CMD_UNKNOWN:
		__smu_msg_v1_print_err_limited(ctl, args,
					       "SMU: unknown command");
		break;
	case SMU_RESP_CMD_BAD_PREREQ:
		__smu_msg_v1_print_err_limited(
			ctl, args, "SMU: valid command, bad prerequisites");
		break;
	case SMU_RESP_BUSY_OTHER:
		if (args->msg != SMU_MSG_GetBadPageCount)
			__smu_msg_v1_print_err_limited(ctl, args,
						       "SMU: I'm very busy");
		break;
	case SMU_RESP_DEBUG_END:
		__smu_msg_v1_print_err_limited(ctl, args, "SMU: Debug Err");
		break;
	case SMU_RESP_UNEXP:
		if (amdgpu_device_bus_status_check(adev)) {
			dev_err(adev->dev,
				"SMU: bus error for message: %s(%d) response:0x%08X ",
				smu_get_message_name(smu, args->msg), index,
				resp);
			if (args->num_args > 0)
				print_hex_dump(KERN_ERR,
					       "in params:", DUMP_PREFIX_NONE,
					       16, 4, args->args,
					       args->num_args * sizeof(u32),
					       false);
		}
		break;
	default:
		__smu_msg_v1_print_err_limited(ctl, args,
					       "SMU: unknown response");
		break;
	}
}

static int __smu_msg_v1_ras_filter(struct smu_msg_ctl *ctl,
				   enum smu_message_type msg, u32 msg_flags,
				   bool *skip_pre_poll)
{
	struct smu_context *smu = ctl->smu;
	struct amdgpu_device *adev = smu->adev;
	bool fed_status;
	u32 reg;

	if (!(smu->smc_fw_caps & SMU_FW_CAP_RAS_PRI))
		return 0;

	fed_status = amdgpu_ras_get_fed_status(adev);

	/* Block non-RAS-priority messages during RAS error */
	if (fed_status && !(msg_flags & SMU_MSG_RAS_PRI)) {
		dev_dbg(adev->dev, "RAS error detected, skip sending %s",
			smu_get_message_name(smu, msg));
		return -EACCES;
	}

	/* Skip pre-poll for priority messages or during RAS error */
	if ((msg_flags & SMU_MSG_NO_PRECHECK) || fed_status) {
		reg = RREG32(ctl->config.resp_reg);
		dev_dbg(adev->dev,
			"Sending priority message %s response status: %x",
			smu_get_message_name(smu, msg), reg);
		if (reg == 0)
			*skip_pre_poll = true;
	}

	return 0;
}

/**
 * smu_msg_v1_send_msg - Complete V1 protocol with all filtering
 * @ctl: Message control block
 * @args: Message arguments
 *
 * Return: 0 on success, negative errno on failure
 */
static int smu_msg_v1_send_msg(struct smu_msg_ctl *ctl,
			       struct smu_msg_args *args)
{
	struct smu_context *smu = ctl->smu;
	struct amdgpu_device *adev = smu->adev;
	const struct cmn2asic_msg_mapping *mapping;
	u32 reg, msg_flags;
	int ret, index;
	bool skip_pre_poll = false;
	bool lock_held = args->flags & SMU_MSG_FLAG_LOCK_HELD;

	/* Early exit if no HW access */
	if (adev->no_hw_access)
		return 0;

	/* Message index translation */
	if (args->msg >= SMU_MSG_MAX_COUNT || !ctl->message_map)
		return -EINVAL;

	if (args->num_args > ctl->config.num_arg_regs ||
	    args->num_out_args > ctl->config.num_arg_regs)
		return -EINVAL;

	mapping = &ctl->message_map[args->msg];
	if (!mapping->valid_mapping)
		return -EINVAL;

	msg_flags = mapping->flags;
	index = mapping->map_to;

	/* VF filter - skip messages not valid for VF */
	if (amdgpu_sriov_vf(adev) && !(msg_flags & SMU_MSG_VF_FLAG))
		return 0;

	if (!lock_held)
		mutex_lock(&ctl->lock);

	/* RAS priority filter */
	ret = __smu_msg_v1_ras_filter(ctl, args->msg, msg_flags,
				      &skip_pre_poll);
	if (ret)
		goto out;

	/* FW state checks */
	if (smu->smc_fw_state == SMU_FW_HANG) {
		dev_err(adev->dev,
			"SMU is in hanged state, failed to send smu message!\n");
		ret = -EREMOTEIO;
		goto out;
	} else if (smu->smc_fw_state == SMU_FW_INIT) {
		skip_pre_poll = true;
		smu->smc_fw_state = SMU_FW_RUNTIME;
	}

	/* Pre-poll: ensure previous message completed */
	if (!skip_pre_poll) {
		reg = __smu_msg_v1_poll_stat(ctl, args->timeout);
		ret = smu_msg_v1_decode_response(reg);
		if (reg == SMU_RESP_NONE || ret == -EREMOTEIO) {
			__smu_msg_v1_print_error(ctl, reg, args);
			goto out;
		}
	}

	/* Send message */
	__smu_msg_v1_send(ctl, (u16)index, args);

	/* Post-poll (skip if ASYNC) */
	if (args->flags & SMU_MSG_FLAG_ASYNC) {
		ret = 0;
		goto out;
	}

	reg = __smu_msg_v1_poll_stat(ctl, args->timeout);
	ret = smu_msg_v1_decode_response(reg);

	/* FW state update on fatal error */
	if (ret == -EREMOTEIO) {
		smu->smc_fw_state = SMU_FW_HANG;
		__smu_msg_v1_print_error(ctl, reg, args);
	} else if (ret != 0) {
		__smu_msg_v1_print_error(ctl, reg, args);
	}

	/* Read output args */
	if ((ret == 0 || (args->flags & SMU_MSG_FLAG_FORCE_READ_ARG)) &&
	    args->num_out_args > 0) {
		__smu_msg_v1_read_out_args(ctl, args);
		dev_dbg(adev->dev, "smu send message: %s(%d) resp : 0x%08x",
			smu_get_message_name(smu, args->msg), index, reg);
		if (args->num_args > 0)
			print_hex_dump_debug("in params:", DUMP_PREFIX_NONE, 16,
					     4, args->args,
					     args->num_args * sizeof(u32),
					     false);
		print_hex_dump_debug("out params:", DUMP_PREFIX_NONE, 16, 4,
				     args->out_args,
				     args->num_out_args * sizeof(u32), false);
	} else {
		dev_dbg(adev->dev, "smu send message: %s(%d), resp: 0x%08x\n",
			smu_get_message_name(smu, args->msg), index, reg);
		if (args->num_args > 0)
			print_hex_dump_debug("in params:", DUMP_PREFIX_NONE, 16,
					     4, args->args,
					     args->num_args * sizeof(u32),
					     false);
	}

out:
	/* Debug halt on error */
	if (unlikely(adev->pm.smu_debug_mask & SMU_DEBUG_HALT_ON_ERROR) &&
	    ret) {
		amdgpu_device_halt(adev);
		WARN_ON(1);
	}

	if (!lock_held)
		mutex_unlock(&ctl->lock);
	return ret;
}

static int smu_msg_v1_wait_response(struct smu_msg_ctl *ctl, u32 timeout_us)
{
	struct smu_context *smu = ctl->smu;
	struct amdgpu_device *adev = smu->adev;
	u32 reg;
	int ret;

	reg = __smu_msg_v1_poll_stat(ctl, timeout_us);
	ret = smu_msg_v1_decode_response(reg);

	if (ret == -EREMOTEIO)
		smu->smc_fw_state = SMU_FW_HANG;

	if (unlikely(adev->pm.smu_debug_mask & SMU_DEBUG_HALT_ON_ERROR) &&
	    ret && (ret != -ETIME)) {
		amdgpu_device_halt(adev);
		WARN_ON(1);
	}

	return ret;
}

const struct smu_msg_ops smu_msg_v1_ops = {
	.send_msg = smu_msg_v1_send_msg,
	.wait_response = smu_msg_v1_wait_response,
	.decode_response = smu_msg_v1_decode_response,
	.send_debug_msg = smu_msg_v1_send_debug_msg,
};

int smu_msg_wait_response(struct smu_msg_ctl *ctl, u32 timeout_us)
{
	return ctl->ops->wait_response(ctl, timeout_us);
}

/**
 * smu_msg_send_async_locked - Send message asynchronously, caller holds lock
 * @ctl: Message control block
 * @msg: Message type
 * @param: Message parameter
 *
 * Send an SMU message without waiting for response. Caller must hold ctl->lock
 * and call smu_msg_wait_response() later to get the result.
 *
 * Return: 0 on success, negative errno on failure
 */
int smu_msg_send_async_locked(struct smu_msg_ctl *ctl,
			      enum smu_message_type msg, u32 param)
{
	struct smu_msg_args args = {
		.msg = msg,
		.args[0] = param,
		.num_args = 1,
		.num_out_args = 0,
		.flags = SMU_MSG_FLAG_ASYNC | SMU_MSG_FLAG_LOCK_HELD,
		.timeout = 0,
	};

	return ctl->ops->send_msg(ctl, &args);
}

int smu_cmn_to_asic_specific_index(struct smu_context *smu,
				   enum smu_cmn2asic_mapping_type type,
				   uint32_t index)
{
	struct cmn2asic_msg_mapping msg_mapping;
	struct cmn2asic_mapping mapping;

	switch (type) {
	case CMN2ASIC_MAPPING_MSG:
		if (index >= SMU_MSG_MAX_COUNT ||
		    !smu->msg_ctl.message_map)
			return -EINVAL;

		msg_mapping = smu->msg_ctl.message_map[index];
		if (!msg_mapping.valid_mapping)
			return -EINVAL;

		if (amdgpu_sriov_vf(smu->adev) &&
		    !(msg_mapping.flags & SMU_MSG_VF_FLAG))
			return -EACCES;

		return msg_mapping.map_to;

	case CMN2ASIC_MAPPING_CLK:
		if (index >= SMU_CLK_COUNT ||
		    !smu->clock_map)
			return -EINVAL;

		mapping = smu->clock_map[index];
		if (!mapping.valid_mapping)
			return -EINVAL;

		return mapping.map_to;

	case CMN2ASIC_MAPPING_FEATURE:
		if (index >= SMU_FEATURE_COUNT ||
		    !smu->feature_map)
			return -EINVAL;

		mapping = smu->feature_map[index];
		if (!mapping.valid_mapping)
			return -EINVAL;

		return mapping.map_to;

	case CMN2ASIC_MAPPING_TABLE:
		if (index >= SMU_TABLE_COUNT ||
		    !smu->table_map)
			return -EINVAL;

		mapping = smu->table_map[index];
		if (!mapping.valid_mapping)
			return -EINVAL;

		return mapping.map_to;

	case CMN2ASIC_MAPPING_PWR:
		if (index >= SMU_POWER_SOURCE_COUNT ||
		    !smu->pwr_src_map)
			return -EINVAL;

		mapping = smu->pwr_src_map[index];
		if (!mapping.valid_mapping)
			return -EINVAL;

		return mapping.map_to;

	case CMN2ASIC_MAPPING_WORKLOAD:
		if (index >= PP_SMC_POWER_PROFILE_COUNT ||
		    !smu->workload_map)
			return -EINVAL;

		mapping = smu->workload_map[index];
		if (!mapping.valid_mapping)
			return -ENOTSUPP;

		return mapping.map_to;

	default:
		return -EINVAL;
	}
}

int smu_cmn_feature_is_supported(struct smu_context *smu,
				 enum smu_feature_mask mask)
{
	int feature_id;

	feature_id = smu_cmn_to_asic_specific_index(smu,
						    CMN2ASIC_MAPPING_FEATURE,
						    mask);
	if (feature_id < 0)
		return 0;

	return smu_feature_list_is_set(smu, SMU_FEATURE_LIST_SUPPORTED,
				       feature_id);
}

static int __smu_get_enabled_features(struct smu_context *smu,
				      struct smu_feature_bits *enabled_features)
{
	return smu_cmn_call_asic_func(get_enabled_mask, smu, enabled_features);
}

int smu_cmn_feature_is_enabled(struct smu_context *smu,
			       enum smu_feature_mask mask)
{
	struct amdgpu_device *adev = smu->adev;
	struct smu_feature_bits enabled_features;
	int feature_id;

	if (__smu_get_enabled_features(smu, &enabled_features)) {
		dev_err(adev->dev, "Failed to retrieve enabled ppfeatures!\n");
		return 0;
	}

	/*
	 * For Renoir and Cyan Skillfish, they are assumed to have all features
	 * enabled. Also considering they have no feature_map available, the
	 * check here can avoid unwanted feature_map check below.
	 */
	if (smu_feature_bits_full(&enabled_features,
				  smu->smu_feature.feature_num))
		return 1;

	feature_id = smu_cmn_to_asic_specific_index(smu,
						    CMN2ASIC_MAPPING_FEATURE,
						    mask);
	if (feature_id < 0)
		return 0;

	return smu_feature_bits_is_set(&enabled_features, feature_id);
}

bool smu_cmn_clk_dpm_is_enabled(struct smu_context *smu,
				enum smu_clk_type clk_type)
{
	enum smu_feature_mask feature_id = 0;

	switch (clk_type) {
	case SMU_MCLK:
	case SMU_UCLK:
		feature_id = SMU_FEATURE_DPM_UCLK_BIT;
		break;
	case SMU_GFXCLK:
	case SMU_SCLK:
		feature_id = SMU_FEATURE_DPM_GFXCLK_BIT;
		break;
	case SMU_SOCCLK:
		feature_id = SMU_FEATURE_DPM_SOCCLK_BIT;
		break;
	case SMU_VCLK:
	case SMU_VCLK1:
		feature_id = SMU_FEATURE_DPM_VCLK_BIT;
		break;
	case SMU_DCLK:
	case SMU_DCLK1:
		feature_id = SMU_FEATURE_DPM_DCLK_BIT;
		break;
	case SMU_FCLK:
		feature_id = SMU_FEATURE_DPM_FCLK_BIT;
		break;
	default:
		return true;
	}

	if (!smu_cmn_feature_is_enabled(smu, feature_id))
		return false;

	return true;
}

int smu_cmn_get_enabled_mask(struct smu_context *smu,
			     struct smu_feature_bits *feature_mask)
{
	uint32_t features[2];
	int ret = 0, index = 0;

	if (!feature_mask)
		return -EINVAL;

	index = smu_cmn_to_asic_specific_index(smu,
						CMN2ASIC_MAPPING_MSG,
						SMU_MSG_GetEnabledSmuFeatures);
	if (index > 0) {
		ret = smu_cmn_send_smc_msg_with_param(
			smu, SMU_MSG_GetEnabledSmuFeatures, 0, &features[0]);
		if (ret)
			return ret;

		ret = smu_cmn_send_smc_msg_with_param(
			smu, SMU_MSG_GetEnabledSmuFeatures, 1, &features[1]);
	} else {
		ret = smu_cmn_send_smc_msg(
			smu, SMU_MSG_GetEnabledSmuFeaturesHigh, &features[1]);
		if (ret)
			return ret;

		ret = smu_cmn_send_smc_msg(
			smu, SMU_MSG_GetEnabledSmuFeaturesLow, &features[0]);
	}

	if (!ret)
		smu_feature_bits_from_arr32(feature_mask, features,
					    SMU_FEATURE_NUM_DEFAULT);

	return ret;
}

uint64_t smu_cmn_get_indep_throttler_status(
					const unsigned long dep_status,
					const uint8_t *throttler_map)
{
	uint64_t indep_status = 0;
	uint8_t dep_bit = 0;

	for_each_set_bit(dep_bit, &dep_status, 32)
		indep_status |= 1ULL << throttler_map[dep_bit];

	return indep_status;
}

int smu_cmn_feature_update_enable_state(struct smu_context *smu,
					uint64_t feature_mask,
					bool enabled)
{
	int ret = 0;

	if (enabled) {
		ret = smu_cmn_send_smc_msg_with_param(smu,
						  SMU_MSG_EnableSmuFeaturesLow,
						  lower_32_bits(feature_mask),
						  NULL);
		if (ret)
			return ret;
		ret = smu_cmn_send_smc_msg_with_param(smu,
						  SMU_MSG_EnableSmuFeaturesHigh,
						  upper_32_bits(feature_mask),
						  NULL);
	} else {
		ret = smu_cmn_send_smc_msg_with_param(smu,
						  SMU_MSG_DisableSmuFeaturesLow,
						  lower_32_bits(feature_mask),
						  NULL);
		if (ret)
			return ret;
		ret = smu_cmn_send_smc_msg_with_param(smu,
						  SMU_MSG_DisableSmuFeaturesHigh,
						  upper_32_bits(feature_mask),
						  NULL);
	}

	return ret;
}

int smu_cmn_feature_set_enabled(struct smu_context *smu,
				enum smu_feature_mask mask,
				bool enable)
{
	int feature_id;

	feature_id = smu_cmn_to_asic_specific_index(smu,
						    CMN2ASIC_MAPPING_FEATURE,
						    mask);
	if (feature_id < 0)
		return -EINVAL;

	return smu_cmn_feature_update_enable_state(smu,
					       1ULL << feature_id,
					       enable);
}

#undef __SMU_DUMMY_MAP
#define __SMU_DUMMY_MAP(fea)	#fea
static const char *__smu_feature_names[] = {
	SMU_FEATURE_MASKS
};

static const char *smu_get_feature_name(struct smu_context *smu,
					enum smu_feature_mask feature)
{
	if (feature >= SMU_FEATURE_COUNT)
		return "unknown smu feature";
	return __smu_feature_names[feature];
}

size_t smu_cmn_get_pp_feature_mask(struct smu_context *smu,
				   char *buf)
{
	int16_t sort_feature[MAX(SMU_FEATURE_COUNT, SMU_FEATURE_MAX)];
	struct smu_feature_bits feature_mask;
	uint32_t features[2];
	int i, feature_index;
	uint32_t count = 0;
	size_t size = 0;

	if (__smu_get_enabled_features(smu, &feature_mask))
		return 0;

	/* TBD: Need to handle for > 64 bits */
	smu_feature_bits_to_arr32(&feature_mask, features, 64);
	size = sysfs_emit_at(buf, size, "features high: 0x%08x low: 0x%08x\n",
			     features[1], features[0]);

	memset(sort_feature, -1, sizeof(sort_feature));

	for (i = 0; i < SMU_FEATURE_COUNT; i++) {
		feature_index = smu_cmn_to_asic_specific_index(smu,
							       CMN2ASIC_MAPPING_FEATURE,
							       i);
		if (feature_index < 0)
			continue;

		sort_feature[feature_index] = i;
	}

	size += sysfs_emit_at(buf, size, "%-2s. %-20s  %-3s : %-s\n",
			"No", "Feature", "Bit", "State");

	for (feature_index = 0; feature_index < smu->smu_feature.feature_num;
	     feature_index++) {
		if (sort_feature[feature_index] < 0)
			continue;

		size += sysfs_emit_at(
			buf, size, "%02d. %-20s (%2d) : %s\n", count++,
			smu_get_feature_name(smu, sort_feature[feature_index]),
			feature_index,
			smu_feature_bits_is_set(&feature_mask, feature_index) ?
				"enabled" :
				"disabled");
	}

	return size;
}

int smu_cmn_set_pp_feature_mask(struct smu_context *smu,
				uint64_t new_mask)
{
	int ret = 0;
	struct smu_feature_bits feature_mask;
	uint64_t feature_mask_u64;
	uint64_t feature_2_enabled = 0;
	uint64_t feature_2_disabled = 0;

	ret = __smu_get_enabled_features(smu, &feature_mask);
	if (ret)
		return ret;

	feature_mask_u64 = *(uint64_t *)feature_mask.bits;
	feature_2_enabled = ~feature_mask_u64 & new_mask;
	feature_2_disabled = feature_mask_u64 & ~new_mask;

	if (feature_2_enabled) {
		ret = smu_cmn_feature_update_enable_state(smu,
							  feature_2_enabled,
							  true);
		if (ret)
			return ret;
	}
	if (feature_2_disabled) {
		ret = smu_cmn_feature_update_enable_state(smu,
							  feature_2_disabled,
							  false);
		if (ret)
			return ret;
	}

	return ret;
}

/**
 * smu_cmn_disable_all_features_with_exception - disable all dpm features
 *                                               except this specified by
 *                                               @mask
 *
 * @smu:               smu_context pointer
 * @mask:              the dpm feature which should not be disabled
 *                     SMU_FEATURE_COUNT: no exception, all dpm features
 *                     to disable
 *
 * Returns:
 * 0 on success or a negative error code on failure.
 */
int smu_cmn_disable_all_features_with_exception(struct smu_context *smu,
						enum smu_feature_mask mask)
{
	uint64_t features_to_disable = U64_MAX;
	int skipped_feature_id;

	if (mask != SMU_FEATURE_COUNT) {
		skipped_feature_id = smu_cmn_to_asic_specific_index(smu,
								    CMN2ASIC_MAPPING_FEATURE,
								    mask);
		if (skipped_feature_id < 0)
			return -EINVAL;

		features_to_disable &= ~(1ULL << skipped_feature_id);
	}

	return smu_cmn_feature_update_enable_state(smu,
						   features_to_disable,
						   0);
}

int smu_cmn_get_smc_version(struct smu_context *smu,
			    uint32_t *if_version,
			    uint32_t *smu_version)
{
	int ret = 0;

	if (!if_version && !smu_version)
		return -EINVAL;

	if (smu->smc_fw_if_version && smu->smc_fw_version)
	{
		if (if_version)
			*if_version = smu->smc_fw_if_version;

		if (smu_version)
			*smu_version = smu->smc_fw_version;

		return 0;
	}

	if (if_version) {
		ret = smu_cmn_send_smc_msg(smu, SMU_MSG_GetDriverIfVersion, if_version);
		if (ret)
			return ret;

		smu->smc_fw_if_version = *if_version;
	}

	if (smu_version) {
		ret = smu_cmn_send_smc_msg(smu, SMU_MSG_GetSmuVersion, smu_version);
		if (ret)
			return ret;

		smu->smc_fw_version = *smu_version;
	}

	return ret;
}

int smu_cmn_check_fw_version(struct smu_context *smu)
{
	struct amdgpu_device *adev = smu->adev;
	uint32_t if_version = 0xff, smu_version = 0xff;
	uint8_t smu_program, smu_major, smu_minor, smu_debug;
	int ret;

	ret = smu_cmn_get_smc_version(smu, &if_version, &smu_version);
	if (ret)
		return ret;

	smu_program = (smu_version >> 24) & 0xff;
	smu_major = (smu_version >> 16) & 0xff;
	smu_minor = (smu_version >> 8) & 0xff;
	smu_debug = (smu_version >> 0) & 0xff;
	adev->pm.fw_version = smu_version;

	dev_info_once(adev->dev, "smu driver if version = 0x%08x, smu fw if version = 0x%08x, "
		      "smu fw program = %d, smu fw version = 0x%08x (%d.%d.%d)\n",
		      smu->smc_driver_if_version, if_version,
		      smu_program, smu_version, smu_major, smu_minor, smu_debug);

	return 0;
}

int smu_cmn_update_table_read_arg(struct smu_context *smu,
				    enum smu_table_id table_index,
				    int argument,
				    void *table_data,
				    uint32_t *read_arg,
				    bool drv2smu)
{
	struct amdgpu_device *adev = smu->adev;
	struct smu_table_context *smu_table = &smu->smu_table;
	struct smu_table *table = &smu_table->driver_table;
	int table_id = smu_cmn_to_asic_specific_index(smu,
						      CMN2ASIC_MAPPING_TABLE,
						      table_index);
	uint32_t table_size;
	int ret = 0;
	uint32_t param;

	if (!table_data || table_index >= SMU_TABLE_COUNT || table_id < 0)
		return -EINVAL;

	table_size = smu_table->tables[table_index].size;

	if (drv2smu) {
		memcpy(table->cpu_addr, table_data, table_size);
		/*
		 * Flush hdp cache: to guard the content seen by
		 * GPU is consitent with CPU.
		 */
		amdgpu_hdp_flush(adev, NULL);
	}

	param = ((argument & 0xFFFF) << 16) | (table_id & 0xffff);

	ret = smu_cmn_send_smc_msg_with_params_ext(
		smu,
		drv2smu ? SMU_MSG_TransferTableDram2Smu :
			  SMU_MSG_TransferTableSmu2Dram,
		&param, 1, read_arg, read_arg ? 1 : 0,
		read_arg ? SMU_MSG_FLAG_FORCE_READ_ARG : 0, 0);

	if (ret)
		return ret;

	if (!drv2smu) {
		amdgpu_hdp_invalidate(adev, NULL);
		memcpy(table_data, table->cpu_addr, table_size);
	}

	return 0;
}

int smu_cmn_vram_cpy(struct smu_context *smu, void *dst, const void *src,
		     size_t len)
{
	memcpy(dst, src, len);

	/* Don't trust the copy operation if RAS fatal error happened. */
	if (amdgpu_ras_get_fed_status(smu->adev))
		return -EHWPOISON;

	return 0;
}

int smu_cmn_write_watermarks_table(struct smu_context *smu)
{
	void *watermarks_table = smu->smu_table.watermarks_table;

	if (!watermarks_table)
		return -EINVAL;

	return smu_cmn_update_table(smu,
				    SMU_TABLE_WATERMARKS,
				    0,
				    watermarks_table,
				    true);
}

int smu_cmn_write_pptable(struct smu_context *smu)
{
	void *pptable = smu->smu_table.driver_pptable;

	return smu_cmn_update_table(smu,
				    SMU_TABLE_PPTABLE,
				    0,
				    pptable,
				    true);
}

int smu_cmn_get_metrics_table(struct smu_context *smu,
			      void *metrics_table,
			      bool bypass_cache)
{
	struct smu_table_context *smu_table = &smu->smu_table;
	uint32_t table_size =
		smu_table->tables[SMU_TABLE_SMU_METRICS].size;
	int ret = 0;

	if (bypass_cache ||
	    !smu_table->metrics_time ||
	    time_after(jiffies, smu_table->metrics_time + msecs_to_jiffies(1))) {
		ret = smu_cmn_update_table(smu,
				       SMU_TABLE_SMU_METRICS,
				       0,
				       smu_table->metrics_table,
				       false);
		if (ret) {
			dev_info(smu->adev->dev, "Failed to export SMU metrics table!\n");
			return ret;
		}
		smu_table->metrics_time = jiffies;
	}

	if (metrics_table)
		memcpy(metrics_table, smu_table->metrics_table, table_size);

	return 0;
}

int smu_cmn_get_combo_pptable(struct smu_context *smu)
{
	void *pptable = smu->smu_table.combo_pptable;

	return smu_cmn_update_table(smu,
				    SMU_TABLE_COMBO_PPTABLE,
				    0,
				    pptable,
				    false);
}

int smu_cmn_set_mp1_state(struct smu_context *smu,
			  enum pp_mp1_state mp1_state)
{
	enum smu_message_type msg;
	int ret;

	switch (mp1_state) {
	case PP_MP1_STATE_SHUTDOWN:
		msg = SMU_MSG_PrepareMp1ForShutdown;
		break;
	case PP_MP1_STATE_UNLOAD:
		msg = SMU_MSG_PrepareMp1ForUnload;
		break;
	case PP_MP1_STATE_RESET:
		msg = SMU_MSG_PrepareMp1ForReset;
		break;
	case PP_MP1_STATE_NONE:
	default:
		return 0;
	}

	ret = smu_cmn_send_smc_msg(smu, msg, NULL);
	if (ret)
		dev_err(smu->adev->dev, "[PrepareMp1] Failed!\n");

	return ret;
}

bool smu_cmn_is_audio_func_enabled(struct amdgpu_device *adev)
{
	struct pci_dev *p = NULL;
	bool snd_driver_loaded;

	/*
	 * If the ASIC comes with no audio function, we always assume
	 * it is "enabled".
	 */
	p = pci_get_domain_bus_and_slot(pci_domain_nr(adev->pdev->bus),
			adev->pdev->bus->number, 1);
	if (!p)
		return true;

	snd_driver_loaded = pci_is_enabled(p) ? true : false;

	pci_dev_put(p);

	return snd_driver_loaded;
}

static char *smu_soc_policy_get_desc(struct smu_dpm_policy *policy, int level)
{
	if (level < 0 || !(policy->level_mask & BIT(level)))
		return "Invalid";

	switch (level) {
	case SOC_PSTATE_DEFAULT:
		return "soc_pstate_default";
	case SOC_PSTATE_0:
		return "soc_pstate_0";
	case SOC_PSTATE_1:
		return "soc_pstate_1";
	case SOC_PSTATE_2:
		return "soc_pstate_2";
	}

	return "Invalid";
}

static struct smu_dpm_policy_desc pstate_policy_desc = {
	.name = STR_SOC_PSTATE_POLICY,
	.get_desc = smu_soc_policy_get_desc,
};

void smu_cmn_generic_soc_policy_desc(struct smu_dpm_policy *policy)
{
	policy->desc = &pstate_policy_desc;
}

static char *smu_xgmi_plpd_policy_get_desc(struct smu_dpm_policy *policy,
					   int level)
{
	if (level < 0 || !(policy->level_mask & BIT(level)))
		return "Invalid";

	switch (level) {
	case XGMI_PLPD_DISALLOW:
		return "plpd_disallow";
	case XGMI_PLPD_DEFAULT:
		return "plpd_default";
	case XGMI_PLPD_OPTIMIZED:
		return "plpd_optimized";
	}

	return "Invalid";
}

static struct smu_dpm_policy_desc xgmi_plpd_policy_desc = {
	.name = STR_XGMI_PLPD_POLICY,
	.get_desc = smu_xgmi_plpd_policy_get_desc,
};

void smu_cmn_generic_plpd_policy_desc(struct smu_dpm_policy *policy)
{
	policy->desc = &xgmi_plpd_policy_desc;
}

void smu_cmn_get_backend_workload_mask(struct smu_context *smu,
				       u32 workload_mask,
				       u32 *backend_workload_mask)
{
	int workload_type;
	u32 profile_mode;

	*backend_workload_mask = 0;

	for (profile_mode = 0; profile_mode < PP_SMC_POWER_PROFILE_COUNT; profile_mode++) {
		if (!(workload_mask & (1 << profile_mode)))
			continue;

		/* conv PP_SMC_POWER_PROFILE* to WORKLOAD_PPLIB_*_BIT */
		workload_type = smu_cmn_to_asic_specific_index(smu,
							       CMN2ASIC_MAPPING_WORKLOAD,
							       profile_mode);

		if (workload_type < 0)
			continue;

		*backend_workload_mask |= 1 << workload_type;
	}
}

void smu_cmn_reset_custom_level(struct smu_context *smu)
{
	struct smu_umd_pstate_table *pstate_table = &smu->pstate_table;

	pstate_table->gfxclk_pstate.custom.min = 0;
	pstate_table->gfxclk_pstate.custom.max = 0;
	pstate_table->uclk_pstate.custom.min = 0;
	pstate_table->uclk_pstate.custom.max = 0;
}

static inline bool smu_cmn_freqs_match(uint32_t freq1, uint32_t freq2)
{
	/* Frequencies within 25 MHz are considered equal */
	return (abs((int)freq1 - (int)freq2) <= 25);
}

int smu_cmn_print_dpm_clk_levels(struct smu_context *smu,
				 struct smu_dpm_table *dpm_table,
				 uint32_t cur_clk, char *buf, int *offset)
{
	uint32_t min_clk, max_clk, level_index, count;
	uint32_t freq_values[3];
	int size, lvl, i;
	bool is_fine_grained;
	bool is_deep_sleep;
	bool freq_match;

	if (!dpm_table || !buf)
		return -EINVAL;

	level_index = 0;
	size = *offset;
	count = dpm_table->count;
	is_fine_grained = dpm_table->flags & SMU_DPM_TABLE_FINE_GRAINED;
	min_clk = SMU_DPM_TABLE_MIN(dpm_table);
	max_clk = SMU_DPM_TABLE_MAX(dpm_table);

	/* Deep sleep - current clock < min_clock/2, TBD: cur_clk = 0 as GFXOFF */
	is_deep_sleep = cur_clk < min_clk / 2;
	if (is_deep_sleep) {
		size += sysfs_emit_at(buf, size, "S: %uMhz *\n", cur_clk);
		level_index = 1;
	}

	if (!is_fine_grained || count == 1) {
		for (i = 0; i < count; i++) {
			freq_match = !is_deep_sleep &&
				     smu_cmn_freqs_match(
					     cur_clk,
					     dpm_table->dpm_levels[i].value);
			size += sysfs_emit_at(buf, size, "%d: %uMhz %s\n",
					      level_index + i,
					      dpm_table->dpm_levels[i].value,
					      freq_match ? "*" : "");
		}
	} else {
		count = 2;
		freq_values[0] = min_clk;
		freq_values[1] = max_clk;

		if (!is_deep_sleep) {
			if (smu_cmn_freqs_match(cur_clk, min_clk)) {
				lvl = 0;
			} else if (smu_cmn_freqs_match(cur_clk, max_clk)) {
				lvl = 1;
			} else {
				/* NOTE: use index '1' to show current clock value */
				lvl = 1;
				count = 3;
				freq_values[1] = cur_clk;
				freq_values[2] = max_clk;
			}
		}

		for (i = 0; i < count; i++) {
			size += sysfs_emit_at(
				buf, size, "%d: %uMhz %s\n", level_index + i,
				freq_values[i],
				(!is_deep_sleep && i == lvl) ? "*" : "");
		}
	}

	*offset = size;

	return 0;
}

int smu_cmn_print_pcie_levels(struct smu_context *smu,
			      struct smu_pcie_table *pcie_table,
			      uint32_t cur_gen, uint32_t cur_lane, char *buf,
			      int *offset)
{
	int size, i;

	if (!pcie_table || !buf)
		return -EINVAL;

	size = *offset;

	for (i = 0; i < pcie_table->lclk_levels; i++) {
		size += sysfs_emit_at(
			buf, size, "%d: %s %s %dMhz %s\n", i,
			(pcie_table->pcie_gen[i] == 0) ? "2.5GT/s," :
			(pcie_table->pcie_gen[i] == 1) ? "5.0GT/s," :
			(pcie_table->pcie_gen[i] == 2) ? "8.0GT/s," :
			(pcie_table->pcie_gen[i] == 3) ? "16.0GT/s," :
			(pcie_table->pcie_gen[i] == 4) ? "32.0GT/s," :
			(pcie_table->pcie_gen[i] == 5) ? "64.0GT/s," :
							 "",
			(pcie_table->pcie_lane[i] == 1) ? "x1" :
			(pcie_table->pcie_lane[i] == 2) ? "x2" :
			(pcie_table->pcie_lane[i] == 3) ? "x4" :
			(pcie_table->pcie_lane[i] == 4) ? "x8" :
			(pcie_table->pcie_lane[i] == 5) ? "x12" :
			(pcie_table->pcie_lane[i] == 6) ? "x16" :
			(pcie_table->pcie_lane[i] == 7) ? "x32" :
							  "",
			pcie_table->lclk_freq[i],
			(cur_gen == pcie_table->pcie_gen[i]) &&
					(cur_lane == pcie_table->pcie_lane[i]) ?
				"*" :
				"");
	}

	*offset = size;

	return 0;
}

int smu_cmn_dpm_pcie_gen_idx(int gen)
{
	int ret;

	switch (gen) {
	case 1 ... 5:
		ret = gen - 1;
		break;
	default:
		ret = -1;
		break;
	}

	return ret;
}

int smu_cmn_dpm_pcie_width_idx(int width)
{
	int ret;

	switch (width) {
	case 1:
		ret = 1;
		break;
	case 2:
		ret = 2;
		break;
	case 4:
		ret = 3;
		break;
	case 8:
		ret = 4;
		break;
	case 12:
		ret = 5;
		break;
	case 16:
		ret = 6;
		break;
	case 32:
		ret = 7;
		break;
	default:
		ret = -1;
		break;
	}

	return ret;
}

static int smu_cmn_get_pptable_v2_0(struct smu_context *smu, void **table, uint32_t *size)
{
	const struct smc_firmware_header_v2_0 *v2;
	struct amdgpu_device *adev = smu->adev;
	size_t fw_size = adev->pm.fw->size;
	uint32_t ppt_offset_bytes;
	uint32_t ppt_size_bytes;

	if (fw_size < sizeof(*v2)) {
		dev_err(adev->dev,
			"SMC firmware too small for v2.0 header: %zu < %zu\n",
			fw_size, sizeof(*v2));
		return -EINVAL;
	}

	v2 = (const struct smc_firmware_header_v2_0 *)adev->pm.fw->data;

	ppt_offset_bytes = le32_to_cpu(v2->ppt_offset_bytes);
	ppt_size_bytes   = le32_to_cpu(v2->ppt_size_bytes);

	if (ppt_offset_bytes > fw_size ||
	    ppt_size_bytes > fw_size - ppt_offset_bytes) {
		dev_err(adev->dev,
			"pptable v2.0 exceeds firmware binary: offset %u + size %u > %zu\n",
			ppt_offset_bytes, ppt_size_bytes, fw_size);
		return -EINVAL;
	}

	*size  = ppt_size_bytes;
	*table = (uint8_t *)v2 + ppt_offset_bytes;

	return 0;
}

static int smu_cmn_get_pptable_v2_1(struct smu_context *smu, void **table,
				     uint32_t *size, uint32_t pptable_id)
{
	const struct smc_firmware_header_v2_1 *v2_1;
	struct amdgpu_device *adev = smu->adev;
	struct smc_soft_pptable_entry *entries;
	size_t fw_size = adev->pm.fw->size;
	uint32_t pptable_entry_offset;
	uint32_t ppt_offset_bytes;
	uint32_t ppt_size_bytes;
	uint32_t pptable_count;
	int i;

	if (fw_size < sizeof(*v2_1)) {
		dev_err(adev->dev,
			"SMC firmware too small for v2.1 header: %zu < %zu\n",
			fw_size, sizeof(*v2_1));
		return -EINVAL;
	}

	v2_1 = (const struct smc_firmware_header_v2_1 *)adev->pm.fw->data;

	pptable_entry_offset = le32_to_cpu(v2_1->pptable_entry_offset);
	pptable_count        = le32_to_cpu(v2_1->pptable_count);

	if (pptable_entry_offset > fw_size ||
	    pptable_count > (fw_size - pptable_entry_offset) / sizeof(*entries)) {
		dev_err(adev->dev,
			"pptable v2.1 entry array exceeds firmware binary: offset %u, count %u\n",
			pptable_entry_offset, pptable_count);
		return -EINVAL;
	}

	entries = (struct smc_soft_pptable_entry *)
		((uint8_t *)v2_1 + pptable_entry_offset);

	for (i = 0; i < pptable_count; i++) {
		if (le32_to_cpu(entries[i].id) != pptable_id)
			continue;

		ppt_offset_bytes = le32_to_cpu(entries[i].ppt_offset_bytes);
		ppt_size_bytes   = le32_to_cpu(entries[i].ppt_size_bytes);

		if (ppt_offset_bytes > fw_size ||
		    ppt_size_bytes > fw_size - ppt_offset_bytes) {
			dev_err(adev->dev,
				"pptable entry %d exceeds firmware binary: offset %u + size %u > %zu\n",
				i, ppt_offset_bytes, ppt_size_bytes, fw_size);
			return -EINVAL;
		}

		*table = (uint8_t *)v2_1 + ppt_offset_bytes;
		*size  = ppt_size_bytes;
		return 0;
	}

	return -EINVAL;
}

/**
 * smu_cmn_get_pptable_from_firmware - locate the soft pptable embedded in the
 *                                     SMC firmware binary.
 * @smu:        SMU context
 * @table:      on success, set to the start of the pptable within the firmware
 *              blob
 * @size:       on success, set to the pptable size in bytes
 * @pptable_id: the entry ID to search for (used only for v2.1 binaries)
 *
 * Reads the firmware header version and dispatches to the appropriate v2.x
 * parser.  Only major version 2 is supported; minor version selects between
 * the single-entry (v2.0) and multi-entry directory (v2.1) layouts.
 *
 * Return: 0 on success, -EINVAL for an unsupported version or if the
 *         requested pptable cannot be found or exceeds the binary bounds.
 */
int smu_cmn_get_pptable_from_firmware(struct smu_context *smu, void **table,
				      uint32_t *size, uint32_t pptable_id)
{
	const struct smc_firmware_header_v1_0 *hdr;
	struct amdgpu_device *adev = smu->adev;
	uint16_t version_major, version_minor;

	hdr = (const struct smc_firmware_header_v1_0 *)adev->pm.fw->data;
	if (!hdr)
		return -EINVAL;

	dev_info(adev->dev, "use driver provided pptable %d\n", pptable_id);

	version_major = le16_to_cpu(hdr->header.header_version_major);
	version_minor = le16_to_cpu(hdr->header.header_version_minor);
	if (version_major != 2) {
		dev_err(adev->dev, "Unsupported smu firmware version %d.%d\n",
			version_major, version_minor);
		return -EINVAL;
	}

	switch (version_minor) {
	case 0:
		return smu_cmn_get_pptable_v2_0(smu, table, size);
	case 1:
		return smu_cmn_get_pptable_v2_1(smu, table, size, pptable_id);
	default:
		return -EINVAL;
	}
}