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
// SPDX-License-Identifier: GPL-2.0
/*
 *  Copyright (c) 2017-2018, The Linux Foundation. All rights reserved.
 *  Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

/* Disable MMIO tracing to prevent excessive logging of unwanted MMIO traces */
#define __DISABLE_TRACE_MMIO__

#define CREATE_TRACE_POINTS
#include <trace/events/qcom_geni_se.h>

EXPORT_TRACEPOINT_SYMBOL_GPL(geni_se_regs);

#include <linux/acpi.h>
#include <linux/bitfield.h>
#include <linux/clk.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/pinctrl/consumer.h>
#include <linux/platform_device.h>
#include <linux/pm_domain.h>
#include <linux/pm_opp.h>
#include <linux/soc/qcom/geni-se.h>

/**
 * DOC: Overview
 *
 * Generic Interface (GENI) Serial Engine (SE) Wrapper driver is introduced
 * to manage GENI firmware based Qualcomm Universal Peripheral (QUP) Wrapper
 * controller. QUP Wrapper is designed to support various serial bus protocols
 * like UART, SPI, I2C, I3C, etc.
 */

/**
 * DOC: Hardware description
 *
 * GENI based QUP is a highly-flexible and programmable module for supporting
 * a wide range of serial interfaces like UART, SPI, I2C, I3C, etc. A single
 * QUP module can provide upto 8 serial interfaces, using its internal
 * serial engines. The actual configuration is determined by the target
 * platform configuration. The protocol supported by each interface is
 * determined by the firmware loaded to the serial engine. Each SE consists
 * of a DMA Engine and GENI sub modules which enable serial engines to
 * support FIFO and DMA modes of operation.
 *
 *
 *                      +-----------------------------------------+
 *                      |QUP Wrapper                              |
 *                      |         +----------------------------+  |
 *   --QUP & SE Clocks-->         | Serial Engine N            |  +-IO------>
 *                      |         | ...                        |  | Interface
 *   <---Clock Perf.----+    +----+-----------------------+    |  |
 *     State Interface  |    | Serial Engine 1            |    |  |
 *                      |    |                            |    |  |
 *                      |    |                            |    |  |
 *   <--------AHB------->    |                            |    |  |
 *                      |    |                            +----+  |
 *                      |    |                            |       |
 *                      |    |                            |       |
 *   <------SE IRQ------+    +----------------------------+       |
 *                      |                                         |
 *                      +-----------------------------------------+
 *
 *                         Figure 1: GENI based QUP Wrapper
 *
 * The GENI submodules include primary and secondary sequencers which are
 * used to drive TX & RX operations. On serial interfaces that operate using
 * master-slave model, primary sequencer drives both TX & RX operations. On
 * serial interfaces that operate using peer-to-peer model, primary sequencer
 * drives TX operation and secondary sequencer drives RX operation.
 */

/**
 * DOC: Software description
 *
 * GENI SE Wrapper driver is structured into 2 parts:
 *
 * geni_wrapper represents QUP Wrapper controller. This part of the driver
 * manages QUP Wrapper information such as hardware version, clock
 * performance table that is common to all the internal serial engines.
 *
 * geni_se represents serial engine. This part of the driver manages serial
 * engine information such as clocks, containing QUP Wrapper, etc. This part
 * of driver also supports operations (eg. initialize the concerned serial
 * engine, select between FIFO and DMA mode of operation etc.) that are
 * common to all the serial engines and are independent of serial interfaces.
 */

#define MAX_CLK_PERF_LEVEL 32
#define MAX_CLKS 2

/**
 * struct geni_wrapper - Data structure to represent the QUP Wrapper Core
 * @dev:		Device pointer of the QUP wrapper core
 * @base:		Base address of this instance of QUP wrapper core
 * @clks:		Handle to the primary & optional secondary AHB clocks
 * @num_clks:		Count of clocks
 */
struct geni_wrapper {
	struct device *dev;
	void __iomem *base;
	struct clk_bulk_data clks[MAX_CLKS];
	unsigned int num_clks;
};

/**
 * struct geni_se_desc - Data structure to represent the QUP Wrapper resources
 * @clks:		Name of the primary & optional secondary AHB clocks
 * @num_clks:		Count of clock names
 */
struct geni_se_desc {
	unsigned int num_clks;
	const char * const *clks;
};

static const char * const icc_path_names[] = {"qup-core", "qup-config",
						"qup-memory"};

static const char * const protocol_name[] = { "None", "SPI", "UART", "I2C", "I3C", "SPI SLAVE" };

/**
 * struct se_fw_hdr - Serial Engine firmware configuration header
 *
 * This structure defines the SE firmware header, which together with the
 * firmware payload is stored in individual ELF segments.
 *
 * @magic: Set to 'SEFW'.
 * @version: Structure version number.
 * @core_version: QUPV3 hardware version.
 * @serial_protocol: Encoded in GENI_FW_REVISION.
 * @fw_version: Firmware version, from GENI_FW_REVISION.
 * @cfg_version: Configuration version, from GENI_INIT_CFG_REVISION.
 * @fw_size_in_items: Number of 32-bit words in GENI_FW_RAM.
 * @fw_offset: Byte offset to GENI_FW_RAM array.
 * @cfg_size_in_items: Number of GENI_FW_CFG index/value pairs.
 * @cfg_idx_offset: Byte offset to GENI_FW_CFG index array.
 * @cfg_val_offset: Byte offset to GENI_FW_CFG values array.
 */
struct se_fw_hdr {
	__le32 magic;
	__le32 version;
	__le32 core_version;
	__le16 serial_protocol;
	__le16 fw_version;
	__le16 cfg_version;
	__le16 fw_size_in_items;
	__le16 fw_offset;
	__le16 cfg_size_in_items;
	__le16 cfg_idx_offset;
	__le16 cfg_val_offset;
};

/*Magic numbers*/
#define SE_MAGIC_NUM			0x57464553

#define MI_PBT_NON_PAGED_SEGMENT	0x0
#define MI_PBT_HASH_SEGMENT		0x2
#define MI_PBT_NOTUSED_SEGMENT		0x3
#define MI_PBT_SHARED_SEGMENT		0x4

#define MI_PBT_FLAG_PAGE_MODE		BIT(20)
#define MI_PBT_FLAG_SEGMENT_TYPE	GENMASK(26, 24)
#define MI_PBT_FLAG_ACCESS_TYPE		GENMASK(23, 21)

#define MI_PBT_PAGE_MODE_VALUE(x) FIELD_GET(MI_PBT_FLAG_PAGE_MODE, x)

#define MI_PBT_SEGMENT_TYPE_VALUE(x) FIELD_GET(MI_PBT_FLAG_SEGMENT_TYPE, x)

#define MI_PBT_ACCESS_TYPE_VALUE(x) FIELD_GET(MI_PBT_FLAG_ACCESS_TYPE, x)

#define M_COMMON_GENI_M_IRQ_EN	(GENMASK(6, 1) | \
				M_IO_DATA_DEASSERT_EN | \
				M_IO_DATA_ASSERT_EN | M_RX_FIFO_RD_ERR_EN | \
				M_RX_FIFO_WR_ERR_EN | M_TX_FIFO_RD_ERR_EN | \
				M_TX_FIFO_WR_ERR_EN)

/* Common QUPV3 registers */
#define QUPV3_HW_VER_REG		0x4
#define QUPV3_SE_AHB_M_CFG		0x118
#define QUPV3_COMMON_CFG		0x120
#define QUPV3_COMMON_CGC_CTRL		0x21c

/* QUPV3_COMMON_CFG fields */
#define FAST_SWITCH_TO_HIGH_DISABLE	BIT(0)

/* QUPV3_SE_AHB_M_CFG fields */
#define AHB_M_CLK_CGC_ON		BIT(0)

/* QUPV3_COMMON_CGC_CTRL fields */
#define COMMON_CSR_SLV_CLK_CGC_ON	BIT(0)

/* Common SE registers */
#define SE_GENI_INIT_CFG_REVISION	0x0
#define SE_GENI_S_INIT_CFG_REVISION	0x4
#define SE_GENI_CGC_CTRL		0x28
#define SE_GENI_CLK_CTRL_RO		0x60
#define SE_GENI_FW_S_REVISION_RO	0x6c
#define SE_GENI_CFG_REG0		0x100
#define SE_GENI_BYTE_GRAN		0x254
#define SE_GENI_TX_PACKING_CFG0		0x260
#define SE_GENI_TX_PACKING_CFG1		0x264
#define SE_GENI_RX_PACKING_CFG0		0x284
#define SE_GENI_RX_PACKING_CFG1		0x288
#define SE_GENI_S_IRQ_ENABLE		0x644
#define SE_DMA_TX_PTR_L			0xc30
#define SE_DMA_TX_PTR_H			0xc34
#define SE_DMA_TX_ATTR			0xc38
#define SE_DMA_TX_LEN			0xc3c
#define SE_DMA_TX_IRQ_EN		0xc48
#define SE_DMA_TX_IRQ_EN_SET		0xc4c
#define SE_DMA_TX_IRQ_EN_CLR		0xc50
#define SE_DMA_TX_LEN_IN		0xc54
#define SE_DMA_TX_MAX_BURST		0xc5c
#define SE_DMA_RX_PTR_L			0xd30
#define SE_DMA_RX_PTR_H			0xd34
#define SE_DMA_RX_ATTR			0xd38
#define SE_DMA_RX_LEN			0xd3c
#define SE_DMA_RX_IRQ_EN		0xd48
#define SE_DMA_RX_IRQ_EN_SET		0xd4c
#define SE_DMA_RX_IRQ_EN_CLR		0xd50
#define SE_DMA_RX_MAX_BURST		0xd5c
#define SE_DMA_RX_FLUSH			0xd60
#define SE_GSI_EVENT_EN			0xe18
#define SE_IRQ_EN			0xe1c
#define SE_DMA_GENERAL_CFG		0xe30
#define SE_GENI_FW_REVISION		0x1000
#define SE_GENI_S_FW_REVISION		0x1004
#define SE_GENI_CFG_RAMN		0x1010
#define SE_GENI_CLK_CTRL		0x2000
#define SE_DMA_IF_EN			0x2004
#define SE_FIFO_IF_DISABLE		0x2008

/* GENI_FW_REVISION_RO fields */
#define FW_REV_VERSION_MSK		GENMASK(7, 0)

/* GENI_OUTPUT_CTRL fields */
#define DEFAULT_IO_OUTPUT_CTRL_MSK	GENMASK(6, 0)

/* GENI_CGC_CTRL fields */
#define CFG_AHB_CLK_CGC_ON		BIT(0)
#define CFG_AHB_WR_ACLK_CGC_ON		BIT(1)
#define DATA_AHB_CLK_CGC_ON		BIT(2)
#define SCLK_CGC_ON			BIT(3)
#define TX_CLK_CGC_ON			BIT(4)
#define RX_CLK_CGC_ON			BIT(5)
#define EXT_CLK_CGC_ON			BIT(6)
#define PROG_RAM_HCLK_OFF		BIT(8)
#define PROG_RAM_SCLK_OFF		BIT(9)
#define DEFAULT_CGC_EN			GENMASK(6, 0)

/* SE_GSI_EVENT_EN fields */
#define DMA_RX_EVENT_EN			BIT(0)
#define DMA_TX_EVENT_EN			BIT(1)
#define GENI_M_EVENT_EN			BIT(2)
#define GENI_S_EVENT_EN			BIT(3)

/* SE_IRQ_EN fields */
#define DMA_RX_IRQ_EN			BIT(0)
#define DMA_TX_IRQ_EN			BIT(1)
#define GENI_M_IRQ_EN			BIT(2)
#define GENI_S_IRQ_EN			BIT(3)

/* SE_DMA_GENERAL_CFG */
#define DMA_RX_CLK_CGC_ON		BIT(0)
#define DMA_TX_CLK_CGC_ON		BIT(1)
#define DMA_AHB_SLV_CLK_CGC_ON		BIT(2)
#define AHB_SEC_SLV_CLK_CGC_ON		BIT(3)
#define DUMMY_RX_NON_BUFFERABLE		BIT(4)
#define RX_DMA_ZERO_PADDING_EN		BIT(5)
#define RX_DMA_IRQ_DELAY_MSK		GENMASK(8, 6)
#define RX_DMA_IRQ_DELAY_SHFT		6

/* GENI_CLK_CTRL fields */
#define SER_CLK_SEL			BIT(0)

/* GENI_DMA_IF_EN fields */
#define DMA_IF_EN			BIT(0)

#define geni_setbits32(_addr, _v) writel(readl(_addr) |  (_v), _addr)
#define geni_clrbits32(_addr, _v) writel(readl(_addr) & ~(_v), _addr)

enum domain_idx {
	DOMAIN_IDX_POWER,
	DOMAIN_IDX_PERF,
	DOMAIN_IDX_MAX
};

/**
 * geni_se_get_qup_hw_version() - Read the QUP wrapper Hardware version
 * @se:	Pointer to the corresponding serial engine.
 *
 * Return: Hardware Version of the wrapper.
 */
u32 geni_se_get_qup_hw_version(struct geni_se *se)
{
	struct geni_wrapper *wrapper = se->wrapper;

	return readl_relaxed(wrapper->base + QUPV3_HW_VER_REG);
}
EXPORT_SYMBOL_GPL(geni_se_get_qup_hw_version);

static void geni_se_io_set_mode(void __iomem *base)
{
	u32 val;

	val = readl_relaxed(base + SE_IRQ_EN);
	val |= GENI_M_IRQ_EN | GENI_S_IRQ_EN;
	val |= DMA_TX_IRQ_EN | DMA_RX_IRQ_EN;
	writel_relaxed(val, base + SE_IRQ_EN);

	val = readl_relaxed(base + SE_GENI_DMA_MODE_EN);
	val &= ~GENI_DMA_MODE_EN;
	writel_relaxed(val, base + SE_GENI_DMA_MODE_EN);

	writel_relaxed(0, base + SE_GSI_EVENT_EN);
}

static void geni_se_io_init(void __iomem *base)
{
	u32 val;

	val = readl_relaxed(base + SE_GENI_CGC_CTRL);
	val |= DEFAULT_CGC_EN;
	writel_relaxed(val, base + SE_GENI_CGC_CTRL);

	val = readl_relaxed(base + SE_DMA_GENERAL_CFG);
	val |= AHB_SEC_SLV_CLK_CGC_ON | DMA_AHB_SLV_CLK_CGC_ON;
	val |= DMA_TX_CLK_CGC_ON | DMA_RX_CLK_CGC_ON;
	writel_relaxed(val, base + SE_DMA_GENERAL_CFG);

	writel_relaxed(DEFAULT_IO_OUTPUT_CTRL_MSK, base + GENI_OUTPUT_CTRL);
	writel_relaxed(FORCE_DEFAULT, base + GENI_FORCE_DEFAULT_REG);
}

static void geni_se_irq_clear(struct geni_se *se)
{
	writel_relaxed(0, se->base + SE_GSI_EVENT_EN);
	writel_relaxed(0xffffffff, se->base + SE_GENI_M_IRQ_CLEAR);
	writel_relaxed(0xffffffff, se->base + SE_GENI_S_IRQ_CLEAR);
	writel_relaxed(0xffffffff, se->base + SE_DMA_TX_IRQ_CLR);
	writel_relaxed(0xffffffff, se->base + SE_DMA_RX_IRQ_CLR);
	writel_relaxed(0xffffffff, se->base + SE_IRQ_EN);
}

/**
 * geni_se_init() - Initialize the GENI serial engine
 * @se:		Pointer to the concerned serial engine.
 * @rx_wm:	Receive watermark, in units of FIFO words.
 * @rx_rfr:	Ready-for-receive watermark, in units of FIFO words.
 *
 * This function is used to initialize the GENI serial engine, configure
 * receive watermark and ready-for-receive watermarks.
 */
void geni_se_init(struct geni_se *se, u32 rx_wm, u32 rx_rfr)
{
	u32 val;

	geni_se_irq_clear(se);
	geni_se_io_init(se->base);
	geni_se_io_set_mode(se->base);

	writel_relaxed(rx_wm, se->base + SE_GENI_RX_WATERMARK_REG);
	writel_relaxed(rx_rfr, se->base + SE_GENI_RX_RFR_WATERMARK_REG);

	val = readl_relaxed(se->base + SE_GENI_M_IRQ_EN);
	val |= M_COMMON_GENI_M_IRQ_EN;
	writel_relaxed(val, se->base + SE_GENI_M_IRQ_EN);

	val = readl_relaxed(se->base + SE_GENI_S_IRQ_EN);
	val |= S_COMMON_GENI_S_IRQ_EN;
	writel_relaxed(val, se->base + SE_GENI_S_IRQ_EN);
}
EXPORT_SYMBOL_GPL(geni_se_init);

static void geni_se_select_fifo_mode(struct geni_se *se)
{
	u32 proto = geni_se_read_proto(se);
	u32 val, val_old;

	geni_se_irq_clear(se);

	/* UART driver manages enabling / disabling interrupts internally */
	if (proto != GENI_SE_UART) {
		/* Non-UART use only primary sequencer so dont bother about S_IRQ */
		val_old = val = readl_relaxed(se->base + SE_GENI_M_IRQ_EN);
		val |= M_CMD_DONE_EN | M_TX_FIFO_WATERMARK_EN;
		val |= M_RX_FIFO_WATERMARK_EN | M_RX_FIFO_LAST_EN;
		if (val != val_old)
			writel_relaxed(val, se->base + SE_GENI_M_IRQ_EN);
	}

	val_old = val = readl_relaxed(se->base + SE_GENI_DMA_MODE_EN);
	val &= ~GENI_DMA_MODE_EN;
	if (val != val_old)
		writel_relaxed(val, se->base + SE_GENI_DMA_MODE_EN);
}

static void geni_se_select_dma_mode(struct geni_se *se)
{
	u32 proto = geni_se_read_proto(se);
	u32 val, val_old;

	geni_se_irq_clear(se);

	/* UART driver manages enabling / disabling interrupts internally */
	if (proto != GENI_SE_UART) {
		/* Non-UART use only primary sequencer so dont bother about S_IRQ */
		val_old = val = readl_relaxed(se->base + SE_GENI_M_IRQ_EN);
		val &= ~(M_CMD_DONE_EN | M_TX_FIFO_WATERMARK_EN);
		val &= ~(M_RX_FIFO_WATERMARK_EN | M_RX_FIFO_LAST_EN);
		if (val != val_old)
			writel_relaxed(val, se->base + SE_GENI_M_IRQ_EN);
	}

	val_old = val = readl_relaxed(se->base + SE_GENI_DMA_MODE_EN);
	val |= GENI_DMA_MODE_EN;
	if (val != val_old)
		writel_relaxed(val, se->base + SE_GENI_DMA_MODE_EN);
}

static void geni_se_select_gpi_mode(struct geni_se *se)
{
	u32 val;

	geni_se_irq_clear(se);

	writel(0, se->base + SE_IRQ_EN);

	val = readl(se->base + SE_GENI_M_IRQ_EN);
	val &= ~(M_CMD_DONE_EN | M_TX_FIFO_WATERMARK_EN |
		 M_RX_FIFO_WATERMARK_EN | M_RX_FIFO_LAST_EN);
	writel(val, se->base + SE_GENI_M_IRQ_EN);

	writel(GENI_DMA_MODE_EN, se->base + SE_GENI_DMA_MODE_EN);

	val = readl(se->base + SE_GSI_EVENT_EN);
	val |= (DMA_RX_EVENT_EN | DMA_TX_EVENT_EN | GENI_M_EVENT_EN | GENI_S_EVENT_EN);
	writel(val, se->base + SE_GSI_EVENT_EN);
}

/**
 * geni_se_select_mode() - Select the serial engine transfer mode
 * @se:		Pointer to the concerned serial engine.
 * @mode:	Transfer mode to be selected.
 */
void geni_se_select_mode(struct geni_se *se, enum geni_se_xfer_mode mode)
{
	WARN_ON(mode != GENI_SE_FIFO && mode != GENI_SE_DMA && mode != GENI_GPI_DMA);

	switch (mode) {
	case GENI_SE_FIFO:
		geni_se_select_fifo_mode(se);
		break;
	case GENI_SE_DMA:
		geni_se_select_dma_mode(se);
		break;
	case GENI_GPI_DMA:
		geni_se_select_gpi_mode(se);
		break;
	case GENI_SE_INVALID:
	default:
		break;
	}
}
EXPORT_SYMBOL_GPL(geni_se_select_mode);

/**
 * DOC: Overview
 *
 * GENI FIFO packing is highly configurable. TX/RX packing/unpacking consist
 * of up to 4 operations, each operation represented by 4 configuration vectors
 * of 10 bits programmed in GENI_TX_PACKING_CFG0 and GENI_TX_PACKING_CFG1 for
 * TX FIFO and in GENI_RX_PACKING_CFG0 and GENI_RX_PACKING_CFG1 for RX FIFO.
 * Refer to below examples for detailed bit-field description.
 *
 * Example 1: word_size = 7, packing_mode = 4 x 8, msb_to_lsb = 1
 *
 *        +-----------+-------+-------+-------+-------+
 *        |           | vec_0 | vec_1 | vec_2 | vec_3 |
 *        +-----------+-------+-------+-------+-------+
 *        | start     | 0x6   | 0xe   | 0x16  | 0x1e  |
 *        | direction | 1     | 1     | 1     | 1     |
 *        | length    | 6     | 6     | 6     | 6     |
 *        | stop      | 0     | 0     | 0     | 1     |
 *        +-----------+-------+-------+-------+-------+
 *
 * Example 2: word_size = 15, packing_mode = 2 x 16, msb_to_lsb = 0
 *
 *        +-----------+-------+-------+-------+-------+
 *        |           | vec_0 | vec_1 | vec_2 | vec_3 |
 *        +-----------+-------+-------+-------+-------+
 *        | start     | 0x0   | 0x8   | 0x10  | 0x18  |
 *        | direction | 0     | 0     | 0     | 0     |
 *        | length    | 7     | 6     | 7     | 6     |
 *        | stop      | 0     | 0     | 0     | 1     |
 *        +-----------+-------+-------+-------+-------+
 *
 * Example 3: word_size = 23, packing_mode = 1 x 32, msb_to_lsb = 1
 *
 *        +-----------+-------+-------+-------+-------+
 *        |           | vec_0 | vec_1 | vec_2 | vec_3 |
 *        +-----------+-------+-------+-------+-------+
 *        | start     | 0x16  | 0xe   | 0x6   | 0x0   |
 *        | direction | 1     | 1     | 1     | 1     |
 *        | length    | 7     | 7     | 6     | 0     |
 *        | stop      | 0     | 0     | 1     | 0     |
 *        +-----------+-------+-------+-------+-------+
 *
 */

#define NUM_PACKING_VECTORS 4
#define PACKING_START_SHIFT 5
#define PACKING_DIR_SHIFT 4
#define PACKING_LEN_SHIFT 1
#define PACKING_STOP_BIT BIT(0)
#define PACKING_VECTOR_SHIFT 10
/**
 * geni_se_config_packing() - Packing configuration of the serial engine
 * @se:		Pointer to the concerned serial engine
 * @bpw:	Bits of data per transfer word.
 * @pack_words:	Number of words per fifo element.
 * @msb_to_lsb:	Transfer from MSB to LSB or vice-versa.
 * @tx_cfg:	Flag to configure the TX Packing.
 * @rx_cfg:	Flag to configure the RX Packing.
 *
 * This function is used to configure the packing rules for the current
 * transfer.
 */
void geni_se_config_packing(struct geni_se *se, int bpw, int pack_words,
			    bool msb_to_lsb, bool tx_cfg, bool rx_cfg)
{
	u32 cfg0, cfg1, cfg[NUM_PACKING_VECTORS] = {0};
	int len;
	int temp_bpw = bpw;
	int idx_start = msb_to_lsb ? bpw - 1 : 0;
	int idx = idx_start;
	int idx_delta = msb_to_lsb ? -BITS_PER_BYTE : BITS_PER_BYTE;
	int ceil_bpw = ALIGN(bpw, BITS_PER_BYTE);
	int iter = (ceil_bpw * pack_words) / BITS_PER_BYTE;
	int i;

	if (iter <= 0 || iter > NUM_PACKING_VECTORS)
		return;

	for (i = 0; i < iter; i++) {
		len = min_t(int, temp_bpw, BITS_PER_BYTE) - 1;
		cfg[i] = idx << PACKING_START_SHIFT;
		cfg[i] |= msb_to_lsb << PACKING_DIR_SHIFT;
		cfg[i] |= len << PACKING_LEN_SHIFT;

		if (temp_bpw <= BITS_PER_BYTE) {
			idx = ((i + 1) * BITS_PER_BYTE) + idx_start;
			temp_bpw = bpw;
		} else {
			idx = idx + idx_delta;
			temp_bpw = temp_bpw - BITS_PER_BYTE;
		}
	}
	cfg[iter - 1] |= PACKING_STOP_BIT;
	cfg0 = cfg[0] | (cfg[1] << PACKING_VECTOR_SHIFT);
	cfg1 = cfg[2] | (cfg[3] << PACKING_VECTOR_SHIFT);

	if (tx_cfg) {
		writel_relaxed(cfg0, se->base + SE_GENI_TX_PACKING_CFG0);
		writel_relaxed(cfg1, se->base + SE_GENI_TX_PACKING_CFG1);
	}
	if (rx_cfg) {
		writel_relaxed(cfg0, se->base + SE_GENI_RX_PACKING_CFG0);
		writel_relaxed(cfg1, se->base + SE_GENI_RX_PACKING_CFG1);
	}

	/*
	 * Number of protocol words in each FIFO entry
	 * 0 - 4x8, four words in each entry, max word size of 8 bits
	 * 1 - 2x16, two words in each entry, max word size of 16 bits
	 * 2 - 1x32, one word in each entry, max word size of 32 bits
	 * 3 - undefined
	 */
	if (pack_words || bpw == 32)
		writel_relaxed(bpw / 16, se->base + SE_GENI_BYTE_GRAN);
}
EXPORT_SYMBOL_GPL(geni_se_config_packing);

static void geni_se_clks_off(struct geni_se *se)
{
	struct geni_wrapper *wrapper = se->wrapper;

	clk_disable_unprepare(se->clk);
	clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks);
	clk_disable_unprepare(se->core_clk);
}

/**
 * geni_se_resources_off() - Turn off resources associated with the serial
 *                           engine
 * @se:	Pointer to the concerned serial engine.
 *
 * Return: 0 on success, standard Linux error codes on failure/error.
 */
int geni_se_resources_off(struct geni_se *se)
{
	int ret;

	if (has_acpi_companion(se->dev))
		return 0;

	ret = pinctrl_pm_select_sleep_state(se->dev);
	if (ret)
		return ret;

	geni_se_clks_off(se);
	return 0;
}
EXPORT_SYMBOL_GPL(geni_se_resources_off);

static int geni_se_clks_on(struct geni_se *se)
{
	int ret;
	struct geni_wrapper *wrapper = se->wrapper;

	ret = clk_bulk_prepare_enable(wrapper->num_clks, wrapper->clks);
	if (ret)
		return ret;

	ret = clk_prepare_enable(se->clk);
	if (ret)
		goto err_bulk_clks;

	ret = clk_prepare_enable(se->core_clk);
	if (ret)
		goto err_se_clk;

	return 0;

err_se_clk:
	clk_disable_unprepare(se->clk);
err_bulk_clks:
	clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks);
	return ret;
}

/**
 * geni_se_resources_on() - Turn on resources associated with the serial
 *                          engine
 * @se:	Pointer to the concerned serial engine.
 *
 * Return: 0 on success, standard Linux error codes on failure/error.
 */
int geni_se_resources_on(struct geni_se *se)
{
	int ret;

	if (has_acpi_companion(se->dev))
		return 0;

	ret = geni_se_clks_on(se);
	if (ret)
		return ret;

	ret = pinctrl_pm_select_default_state(se->dev);
	if (ret)
		geni_se_clks_off(se);

	return ret;
}
EXPORT_SYMBOL_GPL(geni_se_resources_on);

/**
 * geni_se_clk_tbl_get() - Get the clock table to program DFS
 * @se:		Pointer to the concerned serial engine.
 * @tbl:	Table in which the output is returned.
 *
 * This function is called by the protocol drivers to determine the different
 * clock frequencies supported by serial engine core clock. The protocol
 * drivers use the output to determine the clock frequency index to be
 * programmed into DFS.
 *
 * Return: number of valid performance levels in the table on success,
 *	   standard Linux error codes on failure.
 */
int geni_se_clk_tbl_get(struct geni_se *se, unsigned long **tbl)
{
	long freq = 0;
	int i;

	if (se->clk_perf_tbl) {
		*tbl = se->clk_perf_tbl;
		return se->num_clk_levels;
	}

	se->clk_perf_tbl = devm_kcalloc(se->dev, MAX_CLK_PERF_LEVEL,
					sizeof(*se->clk_perf_tbl),
					GFP_KERNEL);
	if (!se->clk_perf_tbl)
		return -ENOMEM;

	for (i = 0; i < MAX_CLK_PERF_LEVEL; i++) {
		freq = clk_round_rate(se->clk, freq + 1);
		if (freq <= 0 ||
		    (i > 0 && freq == se->clk_perf_tbl[i - 1]))
			break;
		se->clk_perf_tbl[i] = freq;
	}
	se->num_clk_levels = i;
	*tbl = se->clk_perf_tbl;
	return se->num_clk_levels;
}
EXPORT_SYMBOL_GPL(geni_se_clk_tbl_get);

/**
 * geni_se_clk_freq_match() - Get the matching or closest SE clock frequency
 * @se:		Pointer to the concerned serial engine.
 * @req_freq:	Requested clock frequency.
 * @index:	Index of the resultant frequency in the table.
 * @res_freq:	Resultant frequency of the source clock.
 * @exact:	Flag to indicate exact multiple requirement of the requested
 *		frequency.
 *
 * This function is called by the protocol drivers to determine the best match
 * of the requested frequency as provided by the serial engine clock in order
 * to meet the performance requirements.
 *
 * If we return success:
 * - if @exact is true  then @res_freq / <an_integer> == @req_freq
 * - if @exact is false then @res_freq / <an_integer> <= @req_freq
 *
 * Return: 0 on success, standard Linux error codes on failure.
 */
int geni_se_clk_freq_match(struct geni_se *se, unsigned long req_freq,
			   unsigned int *index, unsigned long *res_freq,
			   bool exact)
{
	unsigned long *tbl;
	int num_clk_levels;
	int i;
	unsigned long best_delta;
	unsigned long new_delta;
	unsigned int divider;

	num_clk_levels = geni_se_clk_tbl_get(se, &tbl);
	if (num_clk_levels < 0)
		return num_clk_levels;

	if (num_clk_levels == 0)
		return -EINVAL;

	best_delta = ULONG_MAX;
	for (i = 0; i < num_clk_levels; i++) {
		divider = DIV_ROUND_UP(tbl[i], req_freq);
		new_delta = req_freq - tbl[i] / divider;
		if (new_delta < best_delta) {
			/* We have a new best! */
			*index = i;
			*res_freq = tbl[i];

			/* If the new best is exact then we're done */
			if (new_delta == 0)
				return 0;

			/* Record how close we got */
			best_delta = new_delta;
		}
	}

	if (exact)
		return -EINVAL;

	return 0;
}
EXPORT_SYMBOL_GPL(geni_se_clk_freq_match);

#define GENI_SE_DMA_DONE_EN		BIT(0)
#define GENI_SE_DMA_EOT_EN		BIT(1)
#define GENI_SE_DMA_AHB_ERR_EN		BIT(2)
#define GENI_SE_DMA_RESET_DONE_EN	BIT(3)
#define GENI_SE_DMA_FLUSH_DONE		BIT(4)

#define GENI_SE_DMA_EOT_BUF BIT(0)

/**
 * geni_se_tx_init_dma() - Initiate TX DMA transfer on the serial engine
 * @se:			Pointer to the concerned serial engine.
 * @iova:		Mapped DMA address.
 * @len:		Length of the TX buffer.
 *
 * This function is used to initiate DMA TX transfer.
 */
void geni_se_tx_init_dma(struct geni_se *se, dma_addr_t iova, size_t len)
{
	u32 val;

	val = GENI_SE_DMA_DONE_EN;
	val |= GENI_SE_DMA_EOT_EN;
	val |= GENI_SE_DMA_AHB_ERR_EN;
	writel_relaxed(val, se->base + SE_DMA_TX_IRQ_EN_SET);
	writel_relaxed(lower_32_bits(iova), se->base + SE_DMA_TX_PTR_L);
	writel_relaxed(upper_32_bits(iova), se->base + SE_DMA_TX_PTR_H);
	writel_relaxed(GENI_SE_DMA_EOT_BUF, se->base + SE_DMA_TX_ATTR);
	writel(len, se->base + SE_DMA_TX_LEN);
}
EXPORT_SYMBOL_GPL(geni_se_tx_init_dma);

/**
 * geni_se_tx_dma_prep() - Prepare the serial engine for TX DMA transfer
 * @se:			Pointer to the concerned serial engine.
 * @buf:		Pointer to the TX buffer.
 * @len:		Length of the TX buffer.
 * @iova:		Pointer to store the mapped DMA address.
 *
 * This function is used to prepare the buffers for DMA TX.
 *
 * Return: 0 on success, standard Linux error codes on failure.
 */
int geni_se_tx_dma_prep(struct geni_se *se, void *buf, size_t len,
			dma_addr_t *iova)
{
	struct geni_wrapper *wrapper = se->wrapper;

	if (!wrapper)
		return -EINVAL;

	*iova = dma_map_single(wrapper->dev, buf, len, DMA_TO_DEVICE);
	if (dma_mapping_error(wrapper->dev, *iova))
		return -EIO;

	geni_se_tx_init_dma(se, *iova, len);
	return 0;
}
EXPORT_SYMBOL_GPL(geni_se_tx_dma_prep);

/**
 * geni_se_rx_init_dma() - Initiate RX DMA transfer on the serial engine
 * @se:			Pointer to the concerned serial engine.
 * @iova:		Mapped DMA address.
 * @len:		Length of the RX buffer.
 *
 * This function is used to initiate DMA RX transfer.
 */
void geni_se_rx_init_dma(struct geni_se *se, dma_addr_t iova, size_t len)
{
	u32 val;

	val = GENI_SE_DMA_DONE_EN;
	val |= GENI_SE_DMA_EOT_EN;
	val |= GENI_SE_DMA_AHB_ERR_EN;
	writel_relaxed(val, se->base + SE_DMA_RX_IRQ_EN_SET);
	writel_relaxed(lower_32_bits(iova), se->base + SE_DMA_RX_PTR_L);
	writel_relaxed(upper_32_bits(iova), se->base + SE_DMA_RX_PTR_H);
	/* RX does not have EOT buffer type bit. So just reset RX_ATTR */
	writel_relaxed(0, se->base + SE_DMA_RX_ATTR);
	writel(len, se->base + SE_DMA_RX_LEN);
}
EXPORT_SYMBOL_GPL(geni_se_rx_init_dma);

/**
 * geni_se_rx_dma_prep() - Prepare the serial engine for RX DMA transfer
 * @se:			Pointer to the concerned serial engine.
 * @buf:		Pointer to the RX buffer.
 * @len:		Length of the RX buffer.
 * @iova:		Pointer to store the mapped DMA address.
 *
 * This function is used to prepare the buffers for DMA RX.
 *
 * Return: 0 on success, standard Linux error codes on failure.
 */
int geni_se_rx_dma_prep(struct geni_se *se, void *buf, size_t len,
			dma_addr_t *iova)
{
	struct geni_wrapper *wrapper = se->wrapper;

	if (!wrapper)
		return -EINVAL;

	*iova = dma_map_single(wrapper->dev, buf, len, DMA_FROM_DEVICE);
	if (dma_mapping_error(wrapper->dev, *iova))
		return -EIO;

	geni_se_rx_init_dma(se, *iova, len);
	return 0;
}
EXPORT_SYMBOL_GPL(geni_se_rx_dma_prep);

/**
 * geni_se_tx_dma_unprep() - Unprepare the serial engine after TX DMA transfer
 * @se:			Pointer to the concerned serial engine.
 * @iova:		DMA address of the TX buffer.
 * @len:		Length of the TX buffer.
 *
 * This function is used to unprepare the DMA buffers after DMA TX.
 */
void geni_se_tx_dma_unprep(struct geni_se *se, dma_addr_t iova, size_t len)
{
	struct geni_wrapper *wrapper = se->wrapper;

	if (!dma_mapping_error(wrapper->dev, iova))
		dma_unmap_single(wrapper->dev, iova, len, DMA_TO_DEVICE);
}
EXPORT_SYMBOL_GPL(geni_se_tx_dma_unprep);

/**
 * geni_se_rx_dma_unprep() - Unprepare the serial engine after RX DMA transfer
 * @se:			Pointer to the concerned serial engine.
 * @iova:		DMA address of the RX buffer.
 * @len:		Length of the RX buffer.
 *
 * This function is used to unprepare the DMA buffers after DMA RX.
 */
void geni_se_rx_dma_unprep(struct geni_se *se, dma_addr_t iova, size_t len)
{
	struct geni_wrapper *wrapper = se->wrapper;

	if (!dma_mapping_error(wrapper->dev, iova))
		dma_unmap_single(wrapper->dev, iova, len, DMA_FROM_DEVICE);
}
EXPORT_SYMBOL_GPL(geni_se_rx_dma_unprep);

int geni_icc_get(struct geni_se *se, const char *icc_ddr)
{
	struct geni_icc_path *icc_paths = se->icc_paths;

	if (has_acpi_companion(se->dev))
		return 0;

	icc_paths[GENI_TO_CORE].path = devm_of_icc_get(se->dev, "qup-core");
	if (IS_ERR(icc_paths[GENI_TO_CORE].path))
		return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_CORE].path),
				     "Failed to get 'qup-core' ICC path\n");

	icc_paths[CPU_TO_GENI].path = devm_of_icc_get(se->dev, "qup-config");
	if (IS_ERR(icc_paths[CPU_TO_GENI].path))
		return dev_err_probe(se->dev, PTR_ERR(icc_paths[CPU_TO_GENI].path),
				     "Failed to get 'qup-config' ICC path\n");

	/* The DDR path is optional, depending on protocol and hw capabilities */
	icc_paths[GENI_TO_DDR].path = devm_of_icc_get(se->dev, "qup-memory");
	if (IS_ERR(icc_paths[GENI_TO_DDR].path)) {
		if (PTR_ERR(icc_paths[GENI_TO_DDR].path) == -ENODATA)
			icc_paths[GENI_TO_DDR].path = NULL;
		else
			return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_DDR].path),
					     "Failed to get 'qup-memory' ICC path\n");
	}

	return 0;
}
EXPORT_SYMBOL_GPL(geni_icc_get);

int geni_icc_set_bw(struct geni_se *se)
{
	int i, ret;

	for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++) {
		ret = icc_set_bw(se->icc_paths[i].path,
			se->icc_paths[i].avg_bw, se->icc_paths[i].avg_bw);
		if (ret) {
			dev_err_ratelimited(se->dev, "ICC BW voting failed on path '%s': %d\n",
					icc_path_names[i], ret);
			return ret;
		}
	}

	return 0;
}
EXPORT_SYMBOL_GPL(geni_icc_set_bw);

/**
 * geni_icc_set_bw_ab() - Set average bandwidth for all ICC paths and apply
 * @se:		Pointer to the concerned serial engine.
 * @core_ab:	Average bandwidth in kBps for GENI_TO_CORE path.
 * @cfg_ab:	Average bandwidth in kBps for CPU_TO_GENI path.
 * @ddr_ab:	Average bandwidth in kBps for GENI_TO_DDR path.
 *
 * Sets bandwidth values for all ICC paths and applies them. DDR path is
 * optional and only set if it exists.
 *
 * Return: 0 on success, negative error code on failure.
 */
int geni_icc_set_bw_ab(struct geni_se *se, u32 core_ab, u32 cfg_ab, u32 ddr_ab)
{
	se->icc_paths[GENI_TO_CORE].avg_bw = core_ab;
	se->icc_paths[CPU_TO_GENI].avg_bw = cfg_ab;
	se->icc_paths[GENI_TO_DDR].avg_bw = ddr_ab;

	return geni_icc_set_bw(se);
}
EXPORT_SYMBOL_GPL(geni_icc_set_bw_ab);

void geni_icc_set_tag(struct geni_se *se, u32 tag)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++)
		icc_set_tag(se->icc_paths[i].path, tag);
}
EXPORT_SYMBOL_GPL(geni_icc_set_tag);

/* To do: Replace this by icc_bulk_enable once it's implemented in ICC core */
int geni_icc_enable(struct geni_se *se)
{
	int i, ret;

	for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++) {
		ret = icc_enable(se->icc_paths[i].path);
		if (ret) {
			dev_err_ratelimited(se->dev, "ICC enable failed on path '%s': %d\n",
					icc_path_names[i], ret);
			return ret;
		}
	}

	return 0;
}
EXPORT_SYMBOL_GPL(geni_icc_enable);

int geni_icc_disable(struct geni_se *se)
{
	int i, ret;

	for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++) {
		ret = icc_disable(se->icc_paths[i].path);
		if (ret) {
			dev_err_ratelimited(se->dev, "ICC disable failed on path '%s': %d\n",
					icc_path_names[i], ret);
			return ret;
		}
	}

	return 0;
}
EXPORT_SYMBOL_GPL(geni_icc_disable);

/**
 * geni_se_resources_deactivate() - Deactivate GENI SE device resources
 * @se: Pointer to the geni_se structure
 *
 * Deactivates device resources for power saving: OPP rate to 0, pin control
 * to sleep state, turns off clocks, and disables interconnect. Skips ACPI devices.
 *
 * Return: 0 on success, negative error code on failure
 */
int geni_se_resources_deactivate(struct geni_se *se)
{
	int ret;

	if (has_acpi_companion(se->dev))
		return 0;

	if (se->has_opp)
		dev_pm_opp_set_rate(se->dev, 0);

	ret = pinctrl_pm_select_sleep_state(se->dev);
	if (ret)
		return ret;

	geni_se_clks_off(se);

	return geni_icc_disable(se);
}
EXPORT_SYMBOL_GPL(geni_se_resources_deactivate);

/**
 * geni_se_resources_activate() - Activate GENI SE device resources
 * @se: Pointer to the geni_se structure
 *
 * Activates device resources for operation: enables interconnect, prepares clocks,
 * and sets pin control to default state. Includes error cleanup. Skips ACPI devices.
 *
 * Unlike geni_se_resources_deactivate(), this function doesn't alter the
 * connected genpds' performance states, which must be additionally handled.
 *
 * Return: 0 on success, negative error code on failure
 */
int geni_se_resources_activate(struct geni_se *se)
{
	int ret;

	if (has_acpi_companion(se->dev))
		return 0;

	ret = geni_icc_enable(se);
	if (ret)
		return ret;

	ret = geni_se_clks_on(se);
	if (ret)
		goto out_icc_disable;

	ret = pinctrl_pm_select_default_state(se->dev);
	if (ret) {
		geni_se_clks_off(se);
		goto out_icc_disable;
	}

	return 0;

out_icc_disable:
	geni_icc_disable(se);
	return ret;
}
EXPORT_SYMBOL_GPL(geni_se_resources_activate);

/**
 * geni_se_set_perf_level() - Set performance level for GENI SE.
 * @se: Pointer to the struct geni_se instance.
 * @level: The desired performance level.
 *
 * Sets the performance level by directly calling dev_pm_opp_set_level
 * on the performance device associated with the SE.
 *
 * Return: 0 on success, or a negative error code on failure.
 */
int geni_se_set_perf_level(struct geni_se *se, unsigned long level)
{
	return dev_pm_opp_set_level(se->pd_list->pd_devs[DOMAIN_IDX_PERF], level);
}
EXPORT_SYMBOL_GPL(geni_se_set_perf_level);

/**
 * geni_se_set_perf_opp() - Set performance OPP for GENI SE by frequency.
 * @se: Pointer to the struct geni_se instance.
 * @clk_freq: The requested clock frequency.
 *
 * Finds the nearest operating performance point (OPP) for the given
 * clock frequency and applies it to the SE's performance device.
 *
 * Return: 0 on success, or a negative error code on failure.
 */
int geni_se_set_perf_opp(struct geni_se *se, unsigned long clk_freq)
{
	struct device *perf_dev = se->pd_list->pd_devs[DOMAIN_IDX_PERF];
	struct dev_pm_opp *opp;
	int ret;

	opp = dev_pm_opp_find_freq_floor(perf_dev, &clk_freq);
	if (IS_ERR(opp)) {
		dev_err(se->dev, "failed to find opp for freq %lu\n", clk_freq);
		return PTR_ERR(opp);
	}

	ret = dev_pm_opp_set_opp(perf_dev, opp);
	dev_pm_opp_put(opp);
	return ret;
}
EXPORT_SYMBOL_GPL(geni_se_set_perf_opp);

/**
 * geni_se_domain_attach() - Attach power domains to a GENI SE device.
 * @se: Pointer to the geni_se structure representing the GENI SE device.
 *
 * This function attaches the power domains ("power" and "perf") required
 * in the SCMI auto-VM environment to the GENI Serial Engine device. It
 * initializes se->pd_list with the attached domains.
 *
 * Return: 0 on success, or a negative error code on failure.
 */
int geni_se_domain_attach(struct geni_se *se)
{
	struct dev_pm_domain_attach_data pd_data = {
		.pd_flags = PD_FLAG_DEV_LINK_ON,
		.pd_names = (const char*[]) { "power", "perf" },
		.num_pd_names = 2,
	};
	int ret;

	ret = devm_pm_domain_attach_list(se->dev,
					 &pd_data, &se->pd_list);
	if (ret == 0)
		return -ENODEV;
	else if (ret < 0)
		return ret;

	return 0;
}
EXPORT_SYMBOL_GPL(geni_se_domain_attach);

/**
 * geni_se_resources_init() - Initialize resources for a GENI SE device.
 * @se: Pointer to the geni_se structure representing the GENI SE device.
 *
 * This function initializes various resources required by the GENI Serial Engine
 * (SE) device, including clock resources (core and SE clocks), interconnect
 * paths for communication.
 * It retrieves optional and mandatory clock resources, adds an OF-based
 * operating performance point (OPP) table, and sets up interconnect paths
 * with default bandwidths. The function also sets a flag (`has_opp`) to
 * indicate whether OPP support is available for the device.
 *
 * Return: 0 on success, or a negative errno on failure.
 */
int geni_se_resources_init(struct geni_se *se)
{
	int ret;

	se->core_clk = devm_clk_get_optional(se->dev, "core");
	if (IS_ERR(se->core_clk))
		return dev_err_probe(se->dev, PTR_ERR(se->core_clk),
				     "Failed to get optional core clk\n");

	se->clk = devm_clk_get(se->dev, "se");
	if (IS_ERR(se->clk) && !has_acpi_companion(se->dev))
		return dev_err_probe(se->dev, PTR_ERR(se->clk),
				     "Failed to get SE clk\n");

	ret = devm_pm_opp_set_clkname(se->dev, "se");
	if (ret)
		return ret;

	ret = devm_pm_opp_of_add_table(se->dev);
	if (ret && ret != -ENODEV)
		return dev_err_probe(se->dev, ret, "Failed to add OPP table\n");

	se->has_opp = (ret == 0);

	ret = geni_icc_get(se, "qup-memory");
	if (ret)
		return ret;

	return geni_icc_set_bw_ab(se, GENI_DEFAULT_BW, GENI_DEFAULT_BW, GENI_DEFAULT_BW);
}
EXPORT_SYMBOL_GPL(geni_se_resources_init);

/**
 * geni_find_protocol_fw() - Locate and validate SE firmware for a protocol.
 * @se: Pointer to the serial engine structure.
 * @fw: Pointer to the firmware image.
 * @protocol: Expected serial engine protocol type.
 *
 * Identifies the appropriate firmware image or configuration required for a
 * specific communication protocol instance running on a Qualcomm GENI
 * controller. Validates the firmware size against the hardware PROG_RAM_DEPTH
 * read from SE_HW_PARAM_2.
 *
 * Return: pointer to a valid 'struct se_fw_hdr' if found, or NULL otherwise.
 */
static struct se_fw_hdr *geni_find_protocol_fw(struct geni_se *se, const struct firmware *fw,
					       enum geni_se_protocol_type protocol)
{
	struct device *dev = se->dev;
	const struct elf32_hdr *ehdr;
	const struct elf32_phdr *phdrs;
	const struct elf32_phdr	*phdr;
	struct se_fw_hdr *sefw;
	u32 fw_end, cfg_idx_end, cfg_val_end;
	u32 prog_ram_depth;
	u16 fw_size;
	int i;

	if (!fw || fw->size < sizeof(struct elf32_hdr))
		return NULL;

	ehdr = (const struct elf32_hdr *)fw->data;
	phdrs = (const struct elf32_phdr *)(fw->data + ehdr->e_phoff);

	/*
	 * The firmware is expected to have at least two program headers (segments).
	 * One for metadata and the other for the actual protocol-specific firmware.
	 */
	if (ehdr->e_phnum < 2) {
		dev_err(dev, "Invalid firmware: less than 2 program headers\n");
		return NULL;
	}

	for (i = 0; i < ehdr->e_phnum; i++) {
		phdr = &phdrs[i];

		if (fw->size < phdr->p_offset + phdr->p_filesz) {
			dev_err(dev, "Firmware size (%zu) < expected offset (%u) + size (%u)\n",
				fw->size, phdr->p_offset, phdr->p_filesz);
			return NULL;
		}

		if (phdr->p_type != PT_LOAD || !phdr->p_memsz)
			continue;

		if (MI_PBT_PAGE_MODE_VALUE(phdr->p_flags) != MI_PBT_NON_PAGED_SEGMENT ||
		    MI_PBT_SEGMENT_TYPE_VALUE(phdr->p_flags) == MI_PBT_HASH_SEGMENT ||
		    MI_PBT_ACCESS_TYPE_VALUE(phdr->p_flags) == MI_PBT_NOTUSED_SEGMENT ||
		    MI_PBT_ACCESS_TYPE_VALUE(phdr->p_flags) == MI_PBT_SHARED_SEGMENT)
			continue;

		if (phdr->p_filesz < sizeof(struct se_fw_hdr))
			continue;

		sefw = (struct se_fw_hdr *)(fw->data + phdr->p_offset);
		fw_size = le16_to_cpu(sefw->fw_size_in_items);
		fw_end = le16_to_cpu(sefw->fw_offset) + fw_size * sizeof(u32);
		cfg_idx_end = le16_to_cpu(sefw->cfg_idx_offset) +
			      le16_to_cpu(sefw->cfg_size_in_items) * sizeof(u8);
		cfg_val_end = le16_to_cpu(sefw->cfg_val_offset) +
			      le16_to_cpu(sefw->cfg_size_in_items) * sizeof(u32);

		if (le32_to_cpu(sefw->magic) != SE_MAGIC_NUM || le32_to_cpu(sefw->version) != 1)
			continue;

		if (le32_to_cpu(sefw->serial_protocol) != protocol)
			continue;

		if (fw_size % 2 != 0) {
			fw_size++;
			sefw->fw_size_in_items = cpu_to_le16(fw_size);
		}

		prog_ram_depth = FIELD_GET(PROG_RAM_DEPTH_MSK,
					   readl_relaxed(se->base + SE_HW_PARAM_2));
		if (fw_size >= prog_ram_depth) {
			dev_err(dev, "Firmware size (%u) exceeds RAM size (%u)\n",
				fw_size, prog_ram_depth);
			continue;
		}

		if (fw_end > phdr->p_filesz || cfg_idx_end > phdr->p_filesz ||
		    cfg_val_end > phdr->p_filesz) {
			dev_err(dev, "Truncated or corrupt SE FW segment found at index %d\n", i);
			continue;
		}

		return sefw;
	}

	dev_err(dev, "Failed to get %s protocol firmware\n", protocol_name[protocol]);
	return NULL;
}

/**
 * geni_configure_xfer_mode() - Set the transfer mode.
 * @se: Pointer to the concerned serial engine.
 * @mode: SE data transfer mode.
 *
 * Set the transfer mode to either FIFO or DMA according to the mode specified
 * by the protocol driver.
 *
 * Return: 0 if successful, otherwise return an error value.
 */
static int geni_configure_xfer_mode(struct geni_se *se, enum geni_se_xfer_mode mode)
{
	/* Configure SE FIFO, DMA or GSI mode. */
	switch (mode) {
	case GENI_GPI_DMA:
		geni_setbits32(se->base + SE_GENI_DMA_MODE_EN, GENI_DMA_MODE_EN);
		writel(0x0, se->base + SE_IRQ_EN);
		writel(DMA_RX_EVENT_EN | DMA_TX_EVENT_EN | GENI_M_EVENT_EN | GENI_S_EVENT_EN,
		       se->base + SE_GSI_EVENT_EN);
		break;

	case GENI_SE_FIFO:
		geni_clrbits32(se->base + SE_GENI_DMA_MODE_EN, GENI_DMA_MODE_EN);
		writel(DMA_RX_IRQ_EN | DMA_TX_IRQ_EN | GENI_M_IRQ_EN | GENI_S_IRQ_EN,
		       se->base + SE_IRQ_EN);
		writel(0x0, se->base + SE_GSI_EVENT_EN);
		break;

	case GENI_SE_DMA:
		geni_setbits32(se->base + SE_GENI_DMA_MODE_EN, GENI_DMA_MODE_EN);
		writel(DMA_RX_IRQ_EN | DMA_TX_IRQ_EN | GENI_M_IRQ_EN | GENI_S_IRQ_EN,
		       se->base + SE_IRQ_EN);
		writel(0x0, se->base + SE_GSI_EVENT_EN);
		break;

	default:
		dev_err(se->dev, "Invalid geni-se transfer mode: %d\n", mode);
		return -EINVAL;
	}
	return 0;
}

/**
 * geni_enable_interrupts() - Enable interrupts.
 * @se: Pointer to the concerned serial engine.
 *
 * Enable the required interrupts during the firmware load process.
 */
static void geni_enable_interrupts(struct geni_se *se)
{
	u32 val;

	/* Enable required interrupts. */
	writel(M_COMMON_GENI_M_IRQ_EN, se->base + SE_GENI_M_IRQ_EN);

	val = S_CMD_OVERRUN_EN | S_ILLEGAL_CMD_EN | S_CMD_CANCEL_EN | S_CMD_ABORT_EN |
	      S_GP_IRQ_0_EN | S_GP_IRQ_1_EN | S_GP_IRQ_2_EN | S_GP_IRQ_3_EN |
	      S_RX_FIFO_WR_ERR_EN | S_RX_FIFO_RD_ERR_EN;
	writel(val, se->base + SE_GENI_S_IRQ_ENABLE);

	/* DMA mode configuration. */
	val = GENI_SE_DMA_RESET_DONE_EN | GENI_SE_DMA_AHB_ERR_EN | GENI_SE_DMA_DONE_EN;
	writel(val, se->base + SE_DMA_TX_IRQ_EN_SET);
	val = GENI_SE_DMA_FLUSH_DONE | GENI_SE_DMA_RESET_DONE_EN | GENI_SE_DMA_AHB_ERR_EN |
	      GENI_SE_DMA_DONE_EN;
	writel(val, se->base + SE_DMA_RX_IRQ_EN_SET);
}

/**
 * geni_write_fw_revision() - Write the firmware revision.
 * @se: Pointer to the concerned serial engine.
 * @serial_protocol: serial protocol type.
 * @fw_version: QUP firmware version.
 *
 * Write the firmware revision and protocol into the respective register.
 */
static void geni_write_fw_revision(struct geni_se *se, u16 serial_protocol, u16 fw_version)
{
	u32 reg;

	reg = FIELD_PREP(FW_REV_PROTOCOL_MSK, serial_protocol);
	reg |= FIELD_PREP(FW_REV_VERSION_MSK, fw_version);

	writel(reg, se->base + SE_GENI_FW_REVISION);
	writel(reg, se->base + SE_GENI_S_FW_REVISION);
}

/**
 * geni_load_se_fw() - Load Serial Engine specific firmware.
 * @se: Pointer to the concerned serial engine.
 * @fw: Pointer to the firmware structure.
 * @mode: SE data transfer mode.
 * @protocol: Protocol type to be used with the SE (e.g., UART, SPI, I2C).
 *
 * Load the protocol firmware into the IRAM of the Serial Engine.
 *
 * Return: 0 if successful, otherwise return an error value.
 */
static int geni_load_se_fw(struct geni_se *se, const struct firmware *fw,
			   enum geni_se_xfer_mode mode, enum geni_se_protocol_type protocol)
{
	const u32 *fw_data, *cfg_val_arr;
	const u8 *cfg_idx_arr;
	u32 i, reg_value;
	int ret;
	struct se_fw_hdr *hdr;

	hdr = geni_find_protocol_fw(se, fw, protocol);
	if (!hdr)
		return -EINVAL;

	fw_data = (const u32 *)((u8 *)hdr + le16_to_cpu(hdr->fw_offset));
	cfg_idx_arr = (const u8 *)hdr + le16_to_cpu(hdr->cfg_idx_offset);
	cfg_val_arr = (const u32 *)((u8 *)hdr + le16_to_cpu(hdr->cfg_val_offset));

	ret = geni_icc_set_bw(se);
	if (ret)
		return ret;

	ret = geni_icc_enable(se);
	if (ret)
		return ret;

	ret = geni_se_resources_on(se);
	if (ret)
		goto out_icc_disable;

	/*
	 * Disable high-priority interrupts until all currently executing
	 * low-priority interrupts have been fully handled.
	 */
	geni_setbits32(se->wrapper->base + QUPV3_COMMON_CFG, FAST_SWITCH_TO_HIGH_DISABLE);

	/* Set AHB_M_CLK_CGC_ON to indicate hardware controls se-wrapper cgc clock. */
	geni_setbits32(se->wrapper->base + QUPV3_SE_AHB_M_CFG, AHB_M_CLK_CGC_ON);

	/* Let hardware to control common cgc. */
	geni_setbits32(se->wrapper->base + QUPV3_COMMON_CGC_CTRL, COMMON_CSR_SLV_CLK_CGC_ON);

	/*
	 * Setting individual bits in GENI_OUTPUT_CTRL activates corresponding output lines,
	 * allowing the hardware to drive data as configured.
	 */
	writel(0x0, se->base + GENI_OUTPUT_CTRL);

	/* Set SCLK and HCLK to program RAM */
	geni_setbits32(se->base + SE_GENI_CGC_CTRL, PROG_RAM_SCLK_OFF | PROG_RAM_HCLK_OFF);
	writel(0x0, se->base + SE_GENI_CLK_CTRL);
	geni_clrbits32(se->base + SE_GENI_CGC_CTRL, PROG_RAM_SCLK_OFF | PROG_RAM_HCLK_OFF);

	/* Enable required clocks for DMA CSR, TX and RX. */
	reg_value = AHB_SEC_SLV_CLK_CGC_ON | DMA_AHB_SLV_CLK_CGC_ON |
		    DMA_TX_CLK_CGC_ON | DMA_RX_CLK_CGC_ON;
	geni_setbits32(se->base + SE_DMA_GENERAL_CFG, reg_value);

	/* Let hardware control CGC by default. */
	writel(DEFAULT_CGC_EN, se->base + SE_GENI_CGC_CTRL);

	/* Set version of the configuration register part of firmware. */
	writel(le16_to_cpu(hdr->cfg_version), se->base + SE_GENI_INIT_CFG_REVISION);
	writel(le16_to_cpu(hdr->cfg_version), se->base + SE_GENI_S_INIT_CFG_REVISION);

	/* Configure GENI primitive table. */
	for (i = 0; i < le16_to_cpu(hdr->cfg_size_in_items); i++)
		writel(cfg_val_arr[i],
		       se->base + SE_GENI_CFG_REG0 + (cfg_idx_arr[i] * sizeof(u32)));

	/* Configure condition for assertion of RX_RFR_WATERMARK condition. */
	reg_value = geni_se_get_rx_fifo_depth(se);
	writel(reg_value - 2, se->base + SE_GENI_RX_RFR_WATERMARK_REG);

	/* Let hardware control CGC */
	geni_setbits32(se->base + GENI_OUTPUT_CTRL, DEFAULT_IO_OUTPUT_CTRL_MSK);

	ret = geni_configure_xfer_mode(se, mode);
	if (ret)
		goto out_resources_off;

	geni_enable_interrupts(se);

	geni_write_fw_revision(se, le16_to_cpu(hdr->serial_protocol), le16_to_cpu(hdr->fw_version));

	/* Program RAM address space. */
	memcpy_toio(se->base + SE_GENI_CFG_RAMN, fw_data,
		    le16_to_cpu(hdr->fw_size_in_items) * sizeof(u32));

	/* Put default values on GENI's output pads. */
	writel_relaxed(0x1, se->base + GENI_FORCE_DEFAULT_REG);

	/* Toggle SCLK/HCLK from high to low to finalize RAM programming and apply config. */
	geni_setbits32(se->base + SE_GENI_CGC_CTRL, PROG_RAM_SCLK_OFF | PROG_RAM_HCLK_OFF);
	geni_setbits32(se->base + SE_GENI_CLK_CTRL, SER_CLK_SEL);
	geni_clrbits32(se->base + SE_GENI_CGC_CTRL, PROG_RAM_SCLK_OFF | PROG_RAM_HCLK_OFF);

	/* Serial engine DMA interface is enabled. */
	geni_setbits32(se->base + SE_DMA_IF_EN, DMA_IF_EN);

	/* Enable or disable FIFO interface of the serial engine. */
	if (mode == GENI_SE_FIFO)
		geni_clrbits32(se->base + SE_FIFO_IF_DISABLE, FIFO_IF_DISABLE);
	else
		geni_setbits32(se->base + SE_FIFO_IF_DISABLE, FIFO_IF_DISABLE);

out_resources_off:
	geni_se_resources_off(se);

out_icc_disable:
	geni_icc_disable(se);
	return ret;
}

/**
 * geni_load_se_firmware() - Load firmware for SE based on protocol
 * @se: Pointer to the concerned serial engine.
 * @protocol: Protocol type to be used with the SE (e.g., UART, SPI, I2C).
 *
 * Retrieves the firmware name from device properties and sets the transfer mode
 * (FIFO or GSI DMA) based on device tree configuration. Enforces FIFO mode for
 * UART protocol due to lack of GSI DMA support. Requests the firmware and loads
 * it into the SE.
 *
 * Return: 0 on success, negative error code on failure.
 */
int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol)
{
	const char *fw_name;
	const struct firmware *fw;
	enum geni_se_xfer_mode mode = GENI_SE_FIFO;
	int ret;

	if (protocol >= ARRAY_SIZE(protocol_name)) {
		dev_err(se->dev, "Invalid geni-se protocol: %d", protocol);
		return -EINVAL;
	}

	ret = device_property_read_string(se->wrapper->dev, "firmware-name", &fw_name);
	if (ret) {
		dev_err(se->dev, "Failed to read firmware-name property: %d\n", ret);
		return -EINVAL;
	}

	if (of_property_read_bool(se->dev->of_node, "qcom,enable-gsi-dma"))
		mode = GENI_GPI_DMA;

	/* GSI mode is not supported by the UART driver; therefore, setting FIFO mode */
	if (protocol == GENI_SE_UART)
		mode = GENI_SE_FIFO;

	ret = request_firmware(&fw, fw_name, se->dev);
	if (ret) {
		if (ret == -ENOENT)
			return -EPROBE_DEFER;

		dev_err(se->dev, "Failed to request firmware '%s' for protocol %d: ret: %d\n",
			fw_name, protocol, ret);
		return ret;
	}

	ret = geni_load_se_fw(se, fw, mode, protocol);
	release_firmware(fw);

	if (ret) {
		dev_err(se->dev, "Failed to load SE firmware for protocol %d: ret: %d\n",
			protocol, ret);
		return ret;
	}

	dev_dbg(se->dev, "Firmware load for %s protocol is successful for xfer mode: %d\n",
		protocol_name[protocol], mode);
	return 0;
}
EXPORT_SYMBOL_GPL(geni_load_se_firmware);

static int geni_se_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct geni_wrapper *wrapper;
	const struct geni_se_desc *desc;
	int ret;

	wrapper = devm_kzalloc(dev, sizeof(*wrapper), GFP_KERNEL);
	if (!wrapper)
		return -ENOMEM;

	wrapper->dev = dev;
	wrapper->base = devm_platform_ioremap_resource(pdev, 0);
	if (IS_ERR(wrapper->base))
		return PTR_ERR(wrapper->base);

	desc = device_get_match_data(&pdev->dev);

	if (!has_acpi_companion(&pdev->dev) && desc->num_clks) {
		int i;

		wrapper->num_clks = min_t(unsigned int, desc->num_clks, MAX_CLKS);

		for (i = 0; i < wrapper->num_clks; ++i)
			wrapper->clks[i].id = desc->clks[i];

		ret = of_count_phandle_with_args(dev->of_node, "clocks", "#clock-cells");
		if (ret < 0) {
			dev_err(dev, "invalid clocks property at %pOF\n", dev->of_node);
			return ret;
		}

		if (ret < wrapper->num_clks) {
			dev_err(dev, "invalid clocks count at %pOF, expected %d entries\n",
				dev->of_node, wrapper->num_clks);
			return -EINVAL;
		}

		ret = devm_clk_bulk_get(dev, wrapper->num_clks, wrapper->clks);
		if (ret) {
			dev_err(dev, "Err getting clks %d\n", ret);
			return ret;
		}
	}

	dev_set_drvdata(dev, wrapper);
	dev_dbg(dev, "GENI SE Driver probed\n");
	return devm_of_platform_populate(dev);
}

static const char * const qup_clks[] = {
	"m-ahb",
	"s-ahb",
};

static const struct geni_se_desc qup_desc = {
	.clks = qup_clks,
	.num_clks = ARRAY_SIZE(qup_clks),
};

static const struct geni_se_desc sa8255p_qup_desc = {};

static const char * const i2c_master_hub_clks[] = {
	"s-ahb",
};

static const struct geni_se_desc i2c_master_hub_desc = {
	.clks = i2c_master_hub_clks,
	.num_clks = ARRAY_SIZE(i2c_master_hub_clks),
};

static const struct of_device_id geni_se_dt_match[] = {
	{ .compatible = "qcom,geni-se-qup", .data = &qup_desc },
	{ .compatible = "qcom,geni-se-i2c-master-hub", .data = &i2c_master_hub_desc },
	{ .compatible = "qcom,sa8255p-geni-se-qup", .data = &sa8255p_qup_desc },
	{}
};
MODULE_DEVICE_TABLE(of, geni_se_dt_match);

static struct platform_driver geni_se_driver = {
	.driver = {
		.name = "geni_se_qup",
		.of_match_table = geni_se_dt_match,
	},
	.probe = geni_se_probe,
};
module_platform_driver(geni_se_driver);

MODULE_DESCRIPTION("GENI Serial Engine Driver");
MODULE_LICENSE("GPL v2");