Linux preempt-rt

Check our new training course

Real-Time Linux with PREEMPT_RT

Check our new training course
with Creative Commons CC-BY-SA
lecture and lab materials

Bootlin logo

Elixir Cross Referencer

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
/*
 * Copyright (c) 2020 Antmicro <www.antmicro.com>
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/types.h>
#include <device.h>
#include <devicetree.h>
#include <drivers/clock_control.h>
#include <drivers/clock_control/clock_control_litex.h>
#include "clock_control_litex.h"
#include <logging/log.h>
#include <logging/log_ctrl.h>
#include <sys/util.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <kernel.h>

LOG_MODULE_REGISTER(CLK_CTRL_LITEX, CONFIG_CLOCK_CONTROL_LOG_LEVEL);

static struct litex_clk_device *ldev;	/* global struct for whole driver */
static struct litex_clk_clkout *clkouts;/* clkout array for whole driver */

/* All DRP regs addresses and sizes */
static struct litex_drp_reg drp[] = {
	{DRP_ADDR_RESET,  DRP_SIZE_RESET},
	{DRP_ADDR_LOCKED, DRP_SIZE_LOCKED},
	{DRP_ADDR_READ,   DRP_SIZE_READ},
	{DRP_ADDR_WRITE,  DRP_SIZE_WRITE},
	{DRP_ADDR_DRDY,   DRP_SIZE_DRDY},
	{DRP_ADDR_ADR,    DRP_SIZE_ADR},
	{DRP_ADDR_DAT_W,  DRP_SIZE_DAT_W},
	{DRP_ADDR_DAT_R,  DRP_SIZE_DAT_R},
};

struct litex_clk_regs_addr litex_clk_regs_addr_init(void)
{
	struct litex_clk_regs_addr m;
	uint32_t i, addr;

	addr = CLKOUT0_REG1;
	for (i = 0; i <= CLKOUT_MAX; i++) {
		if (i == 5) {
		/*
		 *special case because CLKOUT5 have its reg addresses
		 *placed lower than other CLKOUTs
		 */
			m.clkout[5].reg1 = CLKOUT5_REG1;
			m.clkout[5].reg2 = CLKOUT5_REG2;
		} else {
			m.clkout[i].reg1 = addr;
			addr++;
			m.clkout[i].reg2 = addr;
			addr++;
		}
	}
	return m;
}

/*
 * These lookup tables are taken from:
 * https://github.com/Digilent/Zybo-hdmi-out/blob/b991fff6e964420ae3c00c3dbee52f2ad748b3ba/sdk/displaydemo/src/dynclk/dynclk.h
 *
 *	2015 Copyright Digilent Incorporated
 *	Author: Sam Bobrowicz
 *
 */

/* MMCM loop filter lookup table */
static const uint32_t litex_clk_filter_table[] = {
	 0b0001011111,
	 0b0001010111,
	 0b0001111011,
	 0b0001011011,
	 0b0001101011,
	 0b0001110011,
	 0b0001110011,
	 0b0001110011,
	 0b0001110011,
	 0b0001001011,
	 0b0001001011,
	 0b0001001011,
	 0b0010110011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001010011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0001100011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010010011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011,
	 0b0010100011
};

/* MMCM lock detection lookup table */
static const uint64_t litex_clk_lock_table[] = {
	0b0011000110111110100011111010010000000001,
	0b0011000110111110100011111010010000000001,
	0b0100001000111110100011111010010000000001,
	0b0101101011111110100011111010010000000001,
	0b0111001110111110100011111010010000000001,
	0b1000110001111110100011111010010000000001,
	0b1001110011111110100011111010010000000001,
	0b1011010110111110100011111010010000000001,
	0b1100111001111110100011111010010000000001,
	0b1110011100111110100011111010010000000001,
	0b1111111111111000010011111010010000000001,
	0b1111111111110011100111111010010000000001,
	0b1111111111101110111011111010010000000001,
	0b1111111111101011110011111010010000000001,
	0b1111111111101000101011111010010000000001,
	0b1111111111100111000111111010010000000001,
	0b1111111111100011111111111010010000000001,
	0b1111111111100010011011111010010000000001,
	0b1111111111100000110111111010010000000001,
	0b1111111111011111010011111010010000000001,
	0b1111111111011101101111111010010000000001,
	0b1111111111011100001011111010010000000001,
	0b1111111111011010100111111010010000000001,
	0b1111111111011001000011111010010000000001,
	0b1111111111011001000011111010010000000001,
	0b1111111111010111011111111010010000000001,
	0b1111111111010101111011111010010000000001,
	0b1111111111010101111011111010010000000001,
	0b1111111111010100010111111010010000000001,
	0b1111111111010100010111111010010000000001,
	0b1111111111010010110011111010010000000001,
	0b1111111111010010110011111010010000000001,
	0b1111111111010010110011111010010000000001,
	0b1111111111010001001111111010010000000001,
	0b1111111111010001001111111010010000000001,
	0b1111111111010001001111111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001,
	0b1111111111001111101011111010010000000001
};
/* End of copied code */

/* Helper function for filter lookup table */
static inline uint32_t litex_clk_lookup_filter(uint32_t glob_mul)
{
	return litex_clk_filter_table[glob_mul - 1];
}

/* Helper function for lock lookup table */
static inline uint64_t litex_clk_lookup_lock(uint32_t glob_mul)
{
	return litex_clk_lock_table[glob_mul - 1];
}

static inline void litex_clk_set_reg(uint32_t reg, uint32_t val)
{
	litex_write((uint32_t *)drp[reg].addr, drp[reg].size, val);
}

static inline uint32_t litex_clk_get_reg(uint32_t reg)
{
	return litex_read((uint32_t *)drp[reg].addr, drp[reg].size);
}

static inline void litex_clk_assert_reg(uint32_t reg)
{
	int assert = (1 << (drp[reg].size * BITS_PER_BYTE)) - 1;

	litex_clk_set_reg(reg, assert);
}

static inline void litex_clk_deassert_reg(uint32_t reg)
{
	litex_clk_set_reg(reg, ZERO_REG);
}

static int litex_clk_wait(uint32_t reg)
{
	uint32_t timeout;

	__ASSERT(reg == DRP_LOCKED || reg == DRP_DRDY, "Unsupported register! Please provide DRP_LOCKED or DRP_DRDY");

	if (reg == DRP_LOCKED) {
		timeout = ldev->timeout.lock;
	} else {
		timeout = ldev->timeout.drdy;
	}
	/*Waiting for signal to assert in reg*/
	while (!litex_clk_get_reg(reg) && timeout) {
		timeout--;
		k_sleep(K_MSEC(1));
	}
	if (timeout == 0) {
		LOG_WRN("Timeout occured when waiting for the register: 0x%x", reg);
		return -ETIME;
	}
	return 0;
}

/* Read value written in given internal MMCM register*/
static int litex_clk_get_DO(uint8_t clk_reg_addr, uint16_t *res)
{
	int ret;

	litex_clk_set_reg(DRP_ADR, clk_reg_addr);
	litex_clk_assert_reg(DRP_READ);

	litex_clk_deassert_reg(DRP_READ);
	ret = litex_clk_wait(DRP_DRDY);
	if (ret != 0) {
		return ret;
	}

	*res = litex_clk_get_reg(DRP_DAT_R);

	return 0;
}

/* Get global divider and multiplier values and update global config */
static int litex_clk_update_global_config(void)
{
	int ret;
	uint16_t divreg, mult2;
	uint8_t low_time, high_time;

	ret = litex_clk_get_DO(CLKFBOUT_REG2, &mult2);
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_get_DO(DIV_REG, &divreg);
	if (ret != 0) {
		return ret;
	}

	if (mult2 & (NO_CNT_MASK << NO_CNT_POS)) {
		ldev->g_config.mul = 1;
	} else {
		uint16_t mult1;

		ret = litex_clk_get_DO(CLKFBOUT_REG1, &mult1);
		if (ret != 0) {
			return ret;
		}
		low_time = mult1 & HL_TIME_MASK;
		high_time = (mult1 >> HIGH_TIME_POS) & HL_TIME_MASK;
		ldev->g_config.mul = low_time + high_time;
	}

	if (divreg & (NO_CNT_MASK << NO_CNT_DIVREG_POS)) {
		ldev->g_config.div = 1;
	} else {
		low_time = divreg & HL_TIME_MASK;
		high_time = (divreg >> HIGH_TIME_POS) & HL_TIME_MASK;
		ldev->g_config.div = low_time + high_time;
	}

	return 0;
}

static uint64_t litex_clk_calc_global_frequency(uint32_t mul, uint32_t div)
{
	uint64_t f;

	f = (uint64_t)ldev->sys_clk_freq * (uint64_t)mul;
	f /= div;

	return f;
}

/* Calculate frequency with real global params and update global config */
static uint64_t litex_clk_get_real_global_frequency(void)
{
	uint64_t f;

	litex_clk_update_global_config();
	f = litex_clk_calc_global_frequency(ldev->g_config.mul,
					    ldev->g_config.div);
	ldev->g_config.freq = f;
	ldev->ts_g_config.div = ldev->g_config.div;
	ldev->ts_g_config.mul = ldev->g_config.mul;
	ldev->ts_g_config.freq = ldev->g_config.freq;

	return f;
}

/* Return dividers of given CLKOUT */
static int litex_clk_get_clkout_divider(struct litex_clk_clkout *lcko,
					uint32_t *divider, uint32_t *fract_cnt)
{
	struct litex_clk_regs_addr drp_addr = litex_clk_regs_addr_init();
	int ret;
	uint16_t div, frac;
	uint8_t clkout_nr = lcko->id;
	uint8_t low_time, high_time;

	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg1, &div);
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg2, &frac);
	if (ret != 0) {
		return ret;
	}

	low_time = div & HL_TIME_MASK;
	high_time = (div >> HIGH_TIME_POS) & HL_TIME_MASK;
	*divider = low_time + high_time;
	*fract_cnt = (frac >> FRAC_POS) & FRAC_MASK;

	return 0;
}

/* Debug functions */
#ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG

static void litex_clk_check_DO(char *reg_name, uint8_t clk_reg_addr,
					       uint16_t *res)
{
	int ret;

	ret = litex_clk_get_DO(clk_reg_addr, res);
	if (ret != 0)
		LOG_ERR("%s: read error: %d", reg_name, ret);
	else
		LOG_DBG("%s:  0x%x", reg_name, *res);
}

static void litex_clk_print_general_regs(void)
{
	uint16_t power_reg, div_reg, clkfbout_reg1, clkfbout_reg2,
	lock_reg1, lock_reg2, lock_reg3, filt_reg1, filt_reg2;

	litex_clk_check_DO("POWER_REG", POWER_REG, &power_reg);
	litex_clk_check_DO("DIV_REG", DIV_REG, &div_reg);
	litex_clk_check_DO("MUL_REG1", CLKFBOUT_REG1, &clkfbout_reg1);
	litex_clk_check_DO("MUL_REG2", CLKFBOUT_REG2, &clkfbout_reg2);
	litex_clk_check_DO("LOCK_REG1", LOCK_REG1, &lock_reg1);
	litex_clk_check_DO("LOCK_REG2", LOCK_REG2, &lock_reg2);
	litex_clk_check_DO("LOCK_REG3", LOCK_REG3, &lock_reg3);
	litex_clk_check_DO("FILT_REG1", FILT_REG1, &filt_reg1);
	litex_clk_check_DO("FILT_REG2", FILT_REG2, &filt_reg2);
}

static void litex_clk_print_clkout_regs(uint8_t clkout, uint8_t reg1,
							uint8_t reg2)
{
	uint16_t clkout_reg1, clkout_reg2;
	char reg_name[16];

	sprintf(reg_name, "CLKOUT%u REG1", clkout);
	litex_clk_check_DO(reg_name, reg1, &clkout_reg1);

	sprintf(reg_name, "CLKOUT%u REG2", clkout);
	litex_clk_check_DO(reg_name, reg2, &clkout_reg2);
}

static void litex_clk_print_all_regs(void)
{
	struct litex_clk_regs_addr drp_addr = litex_clk_regs_addr_init();
	uint32_t i;

	litex_clk_print_general_regs();
	for (i = 0; i < ldev->nclkout; i++) {
		litex_clk_print_clkout_regs(i, drp_addr.clkout[i].reg1,
					       drp_addr.clkout[i].reg2);
	}
}

static void litex_clk_print_params(struct litex_clk_clkout *lcko)
{
	LOG_DBG("CLKOUT%d DUMP:", lcko->id);
	LOG_DBG("Defaults:");
	LOG_DBG("f: %u d: %u/%u p: %u",
		lcko->def.freq, lcko->def.duty.num,
		lcko->def.duty.den, lcko->def.phase);
	LOG_DBG("Config to set:");
	LOG_DBG("div: %u freq: %u duty: %u/%u phase: %d per_off: %u",
		lcko->ts_config.div, lcko->ts_config.freq,
		lcko->ts_config.duty.num, lcko->ts_config.duty.den,
		lcko->ts_config.phase, lcko->config.period_off);
	LOG_DBG("Config:");
	LOG_DBG("div: %u freq: %u duty: %u/%u phase: %d per_off: %u",
		lcko->config.div, lcko->config.freq,
		lcko->config.duty.num, lcko->config.duty.den,
		lcko->config.phase, lcko->config.period_off);
	LOG_DBG("Divide group:");
	LOG_DBG("e: %u ht: %u lt: %u nc: %u",
		lcko->div.edge, lcko->div.high_time,
		lcko->div.low_time, lcko->div.no_cnt);
	LOG_DBG("Frac group:");
	LOG_DBG("f: %u fen: %u fwff: %u fwfr: %u pmf: %u",
		lcko->frac.frac, lcko->frac.frac_en, lcko->frac.frac_wf_f,
		lcko->frac.frac_wf_r, lcko->frac.phase_mux_f);
	LOG_DBG("Phase group:");
	LOG_DBG("dt: %u pm: %u mx: %u",
		lcko->phase.delay_time, lcko->phase.phase_mux, lcko->phase.mx);
}

static void litex_clk_print_all_params(void)
{
	uint32_t c;

	LOG_DBG("Global Config to set:");
	LOG_DBG("freq: %llu mul: %u div: %u",
		ldev->ts_g_config.freq, ldev->ts_g_config.mul,
					ldev->ts_g_config.div);
	LOG_DBG("Global Config:");
	LOG_DBG("freq: %llu mul: %u div: %u",
		ldev->g_config.freq, ldev->g_config.mul, ldev->g_config.div);
	for (c = 0; c < ldev->nclkout; c++) {
		litex_clk_print_params(&ldev->clkouts[c]);
	}
}
#endif /* #ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG */

/* Returns raw value ready to be written into MMCM */
static inline uint16_t litex_clk_calc_DI(uint16_t DO_val, uint16_t mask,
							  uint16_t bitset)
{
	uint16_t DI_val;

	DI_val = DO_val & mask;
	DI_val |= bitset;

	return DI_val;
}

/* Sets calculated DI value into DI DRP register */
static int litex_clk_set_DI(uint16_t DI_val)
{
	int ret;

	litex_clk_set_reg(DRP_DAT_W, DI_val);
	litex_clk_assert_reg(DRP_WRITE);
	litex_clk_deassert_reg(DRP_WRITE);
	ret = litex_clk_wait(DRP_DRDY);
	return ret;
}

/*
 * Change register value as specified in arguments
 *
 * mask:		preserve or zero MMCM register bits
 *			by selecting 1 or 0 on desired specific mask positions
 * bitset:		set those bits in MMCM register which are 1 in bitset
 * clk_reg_addr:	internal MMCM address of control register
 *
 */
static int litex_clk_change_value(uint16_t mask, uint16_t bitset,
						 uint8_t clk_reg_addr)
{
	uint16_t DO_val, DI_val;
	int ret;

	litex_clk_assert_reg(DRP_RESET);

	ret = litex_clk_get_DO(clk_reg_addr, &DO_val);
	if (ret != 0) {
		return ret;
	}
	DI_val = litex_clk_calc_DI(DO_val, mask, bitset);
	ret = litex_clk_set_DI(DI_val);
	if (ret != 0) {
		return ret;
	}
#ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG
	DI_val = litex_clk_get_reg(DRP_DAT_W);
	LOG_DBG("set 0x%x under: 0x%x", DI_val, clk_reg_addr);
#endif
	litex_clk_deassert_reg(DRP_DAT_W);
	litex_clk_deassert_reg(DRP_RESET);
	ret = litex_clk_wait(DRP_LOCKED);
	return ret;
}

/*
 * Set register values for given CLKOUT
 *
 * clkout_nr:		clock output number
 * mask_regX:		preserve or zero MMCM register X bits
 *			by selecting 1 or 0 on desired specific mask positions
 * bitset_regX:		set those bits in MMCM register X which are 1 in bitset
 *
 */
static int litex_clk_set_clock(uint8_t clkout_nr, uint16_t mask_reg1,
			      uint16_t bitset_reg1, uint16_t mask_reg2,
						 uint16_t bitset_reg2)
{
	struct litex_clk_regs_addr drp_addr = litex_clk_regs_addr_init();
	int ret;

	if (!(mask_reg2 == FULL_REG_16 && bitset_reg2 == ZERO_REG)) {
		ret = litex_clk_change_value(mask_reg2, bitset_reg2,
					     drp_addr.clkout[clkout_nr].reg2);
		if (ret != 0) {
			return ret;
		}
	}
	if (!(mask_reg1 == FULL_REG_16 && bitset_reg1 == ZERO_REG)) {
		ret = litex_clk_change_value(mask_reg1, bitset_reg1,
					     drp_addr.clkout[clkout_nr].reg1);
		if (ret != 0) {
			return ret;
		}
	}

	return 0;
}

/* Set global divider for all CLKOUTs */
static int litex_clk_set_divreg(void)
{
	int ret;
	uint8_t no_cnt = 0, edge = 0, ht = 0, lt = 0,
		div = ldev->ts_g_config.div;
	uint16_t bitset = 0;

	if (div == 1) {
		no_cnt = 1;
	} else {
		ht = div / 2;
		lt = ht;
		edge = div % 2;
		if (edge) {
			lt += edge;
		}
	}

	bitset = (edge << EDGE_DIVREG_POS)	|
		 (no_cnt << NO_CNT_DIVREG_POS)	|
		 (ht << HIGH_TIME_POS)		|
		 (lt << LOW_TIME_POS);

	ret = litex_clk_change_value(KEEP_IN_DIV, bitset, DIV_REG);
	if (ret != 0) {
		return ret;
	}

	ldev->g_config.div = div;
	LOG_DBG("Global divider set to %u", div);

	return 0;
}

/* Set global multiplier for all CLKOUTs */
static int litex_clk_set_mulreg(void)
{
	int ret;
	uint8_t no_cnt = 0, edge = 0, ht = 0, lt = 0,
		mul = ldev->ts_g_config.mul;
	uint16_t bitset1 = 0;

	if (mul == 1) {
		no_cnt = 1;
	} else {
		ht = mul / 2;
		lt = ht;
		edge = mul % 2;
		if (edge) {
			lt += edge;
		}
	}

	bitset1 = (ht << HIGH_TIME_POS) |
		  (lt << LOW_TIME_POS);

	ret = litex_clk_change_value(KEEP_IN_MUL_REG1, bitset1, CLKFBOUT_REG1);
	if (ret != 0) {
		return ret;
	}

	if (edge || no_cnt) {
		uint16_t bitset2 = (edge << EDGE_POS)	|
				(no_cnt << NO_CNT_POS);

		ret = litex_clk_change_value(KEEP_IN_MUL_REG2,
				       bitset2, CLKFBOUT_REG2);
		if (ret != 0) {
			return ret;
		}
	}

	ldev->g_config.mul = mul;
	LOG_DBG("Global multiplier set to %u", mul);

	return 0;
}

static int litex_clk_set_filt(void)
{
	uint16_t filt_reg;
	uint32_t filt, mul;
	int ret;

	mul = ldev->g_config.mul;
	filt = litex_clk_lookup_filter(mul);

	/*
	 * Preparing and setting filter register values
	 * according to reg map form Xilinx XAPP888
	 */
	filt_reg = (((filt >> 9) & 0x1) << 15) |
		   (((filt >> 7) & 0x3) << 11) |
		   (((filt >> 6) & 0x1) << 8);
	ret = litex_clk_change_value(FILT1_MASK, filt_reg, FILT_REG1);
	if (ret != 0)  {
		return ret;
	}

	filt_reg = (((filt >> 5) & 0x1) << 15) |
		   (((filt >> 3) & 0x3) << 11) |
		   (((filt >> 1) & 0x3) << 7) |
		   (((filt) & 0x1) << 4);
	ret = litex_clk_change_value(FILT2_MASK, filt_reg, FILT_REG2);

	return ret;
}

static int litex_clk_set_lock(void)
{
	uint16_t lock_reg;
	uint32_t mul;
	uint64_t lock;
	int ret;

	mul = ldev->g_config.mul;
	lock = litex_clk_lookup_lock(mul);

	/*
	 * Preparing and setting lock register values
	 * according to reg map form Xilinx XAPP888
	 */
	lock_reg = (lock >> 20) & 0x3FF;
	ret = litex_clk_change_value(LOCK1_MASK, lock_reg, LOCK_REG1);
	if (ret != 0) {
		return ret;
	}

	lock_reg = (((lock >> 30) & 0x1F) << 10) |
		     (lock & 0x3FF);
	ret = litex_clk_change_value(LOCK23_MASK, lock_reg, LOCK_REG2);
	if (ret != 0) {
		return ret;
	}

	lock_reg = (((lock >> 35) & 0x1F) << 10) |
		   ((lock >> 10) & 0x3FF);
	ret = litex_clk_change_value(LOCK23_MASK, lock_reg, LOCK_REG3);

	return ret;
}

/* Set all multiplier-related regs: mul, filt and lock regs */
static int litex_clk_set_mul(void)
{
	int ret;

	ret = litex_clk_set_mulreg();
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_set_filt();
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_set_lock();
	return ret;
}

static int litex_clk_set_both_globs(void)
{
	/*
	 * we need to check what change first to prevent
	 * getting our VCO_FREQ out of possible range
	 */
	uint64_t vco_freq;
	int ret;

	/* div-first case */
	vco_freq = litex_clk_calc_global_frequency(
					ldev->g_config.mul,
					ldev->ts_g_config.div);
	if (vco_freq > ldev->vco.max || vco_freq < ldev->vco.min) {
		/* div-first not safe */
		vco_freq = litex_clk_calc_global_frequency(
					ldev->ts_g_config.mul,
					ldev->g_config.div);
		if (vco_freq > ldev->vco.max || vco_freq < ldev->vco.min) {
			/* mul-first not safe */
			ret = litex_clk_set_divreg();
			/* Ignore timeout because we expect that to happen */
			if (ret != -ETIME && ret != 0) {
				return ret;
			} else if (ret == -ETIME) {
				ldev->g_config.div = ldev->ts_g_config.div;
				LOG_DBG("Global divider set to %u",
					 ldev->g_config.div);
			}
			ret = litex_clk_set_mul();
			if (ret != 0) {
				return ret;
			}
		} else {
			/* mul-first safe */
			ret = litex_clk_set_mul();
			if (ret != 0) {
				return ret;
			}
			ret = litex_clk_set_divreg();
			if (ret != 0) {
				return ret;
			}
		}
	} else {
		/* div-first safe */
		ret = litex_clk_set_divreg();
		if (ret != 0) {
			return ret;
		}
		ret = litex_clk_set_mul();
		if (ret != 0) {
			return ret;
		}
	}
	return 0;
}

/* Set global divider, multiplier, filt and lock values */
static int litex_clk_set_globs(void)
{
	int ret;
	uint8_t set_div = 0,
	   set_mul = 0;

	set_div = ldev->ts_g_config.div != ldev->g_config.div;
	set_mul = ldev->ts_g_config.mul != ldev->g_config.mul;

	if (set_div || set_mul) {
		if (set_div && set_mul) {
			ret = litex_clk_set_both_globs();
			if (ret != 0) {
				return ret;
			}
		} else if (set_div) {
			/* set divider only */
			ret = litex_clk_set_divreg();
			if (ret != 0) {
				return ret;
			}
		} else {
			/* set multiplier only */
			ret = litex_clk_set_mul();
			if (ret != 0) {
				return ret;
			}
		}
		ldev->g_config.freq = ldev->ts_g_config.freq;
	}
	return 0;
}

/* Round scaled value*/
static inline uint32_t litex_round(uint32_t val, uint32_t mod)
{
	if (val % mod > mod / 2) {
		return val / mod + 1;
	}
	return val / mod;
}

/*
 *	Duty Cycle
 */

/* Returns accurate duty ratio of given clkout*/
int litex_clk_get_duty_cycle(struct litex_clk_clkout *lcko,
			     struct clk_duty *duty)
{
	struct litex_clk_regs_addr drp_addr = litex_clk_regs_addr_init();
	int ret;
	uint32_t divider;
	uint16_t clkout_reg1, clkout_reg2;
	uint8_t clkout_nr, high_time, edge, no_cnt, frac_en, frac_cnt;

	clkout_nr = lcko->id;
	/* Check if divider is off */
	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg2, &clkout_reg2);
	if (ret != 0) {
		return ret;
	}

	edge = (clkout_reg2 >> EDGE_POS) & EDGE_MASK;
	no_cnt = (clkout_reg2 >> NO_CNT_POS) & NO_CNT_MASK;
	frac_en = (clkout_reg2 >> FRAC_EN_POS) & FRAC_EN_MASK;
	frac_cnt = (clkout_reg2 >> FRAC_POS) & FRAC_MASK;

	/* get duty 50% when divider is off or fractional is enabled */
	if (no_cnt || (frac_en && frac_cnt)) {
		duty->num = 1;
		duty->den = 2;
		return 0;
	}

	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg1, &clkout_reg1);
	if (ret != 0) {
		return ret;
	}

	divider = clkout_reg1 & HL_TIME_MASK;
	high_time = (clkout_reg1 >> HIGH_TIME_POS) & HL_TIME_MASK;
	divider += high_time;

	/* Scaling to consider edge control bit */
	duty->num = high_time * 10 + edge * 5;
	duty->den = (divider + edge) * 10;

	return 0;
}

/* Calculates duty cycle for given ratio in percent, 1% accuracy */
static inline uint8_t litex_clk_calc_duty_percent(struct clk_duty *duty)
{
	uint32_t div, duty_ratio, ht;

	ht = duty->num;
	div = duty->den;
	duty_ratio = ht * 10000 / div;

	return (uint8_t)litex_round(duty_ratio, 100);
}

/* Calculate necessary values for setting duty cycle in normal mode */
static int litex_clk_calc_duty_normal(struct litex_clk_clkout *lcko,
					 int calc_new)
{
	struct clk_duty duty;
	int delta_d;
	uint32_t ht_aprox, synth_duty, min_d;
	uint8_t high_time_it, edge_it, high_duty,
	   divider = lcko->config.div;

	if (calc_new) {
		duty = lcko->ts_config.duty;
	} else {
		litex_clk_get_duty_cycle(lcko, &duty);
	}

	high_duty = litex_clk_calc_duty_percent(&duty);
	min_d = INT_MAX;
	/* check if duty is available to set */
	ht_aprox = high_duty * divider;

	if (ht_aprox > ((HIGH_LOW_TIME_REG_MAX * 100) + 50) ||
		       ((HIGH_LOW_TIME_REG_MAX * 100) + 50) <
			(divider * 100) - ht_aprox) {
		return -EINVAL;
	}

	/* to prevent high_time == 0 or low_time == 0 */
	for (high_time_it = 1; high_time_it < divider; high_time_it++) {
		for (edge_it = 0; edge_it < 2; edge_it++) {
			synth_duty = (high_time_it * 100 + 50 * edge_it) /
								  divider;
			delta_d = synth_duty - high_duty;
			delta_d = abs(delta_d);
			/* check if low_time won't be above acceptable range */
			if (delta_d < min_d && (divider - high_time_it) <=
						  HIGH_LOW_TIME_REG_MAX) {
				min_d = delta_d;
				lcko->div.high_time = high_time_it;
				lcko->div.low_time = divider - high_time_it;
				lcko->div.edge = edge_it;
				lcko->config.duty.num = high_time_it * 100 + 50
								     * edge_it;
				lcko->config.duty.den = divider * 100;
			}
		}
	}
	/*
	 * Calculating values in normal mode,
	 * clear control bits of fractional part
	 */
	lcko->frac.frac_wf_f = 0;
	lcko->frac.frac_wf_r = 0;

	return 0;
}

/* Calculates duty high_time for given divider and ratio */
static inline int litex_clk_calc_duty_high_time(struct clk_duty *duty,
						   uint32_t divider)
{
	uint32_t high_duty;

	high_duty = litex_clk_calc_duty_percent(duty) * divider;

	return litex_round(high_duty, 100);
}

/* Set duty cycle with given ratio */
static int litex_clk_set_duty_cycle(struct litex_clk_clkout *lcko,
			     struct clk_duty *duty)
{
	int ret;
	uint16_t bitset1, bitset2;
	uint8_t clkout_nr = lcko->id,
	   *edge = &lcko->div.edge,
	   *high_time = &lcko->div.high_time,
	    high_duty = litex_clk_calc_duty_percent(duty),
	   *low_time = &lcko->div.low_time;

	if (lcko->frac.frac == 0) {
		int ret;

		lcko->ts_config.duty = *duty;
		LOG_DBG("CLKOUT%d: setting duty: %u/%u",
			lcko->id, duty->num, duty->den);
		ret = litex_clk_calc_duty_normal(lcko, true);
		if (ret != 0) {
			LOG_ERR("CLKOUT%d: cannot set %d%% duty cycle",
				clkout_nr, high_duty);
			return ret;
		}
	} else {
		LOG_ERR("CLKOUT%d: cannot set duty cycle when fractional divider enabled",
								     clkout_nr);
		return -EACCES;
	}

	bitset1 = (*high_time << HIGH_TIME_POS) |
		  (*low_time << LOW_TIME_POS);
	bitset2 = (*edge << EDGE_POS);

	LOG_DBG("SET DUTY CYCLE: e:%u ht:%u lt:%u\nbitset1: 0x%x bitset2: 0x%x",
		*edge, *high_time, *low_time, bitset1, bitset2);

	ret = litex_clk_set_clock(clkout_nr, REG1_DUTY_MASK, bitset1,
					     REG2_DUTY_MASK, bitset2);
	if (ret != 0) {
		return ret;
	}

	LOG_INF("CLKOUT%d: set duty: %d%%", lcko->id,
		litex_clk_calc_duty_percent(&lcko->config.duty));
	return 0;
}

/*
 *	Phase
 */

/* Calculate necessary values for setting phase in normal mode */
static int litex_clk_calc_phase_normal(struct litex_clk_clkout *lcko)
{
	uint64_t period_buff;
	uint32_t post_glob_div_f, global_period,  clkout_period,
	    *period_off = &lcko->ts_config.period_off;
	uint8_t divider = lcko->config.div;
	/* ps unit */

	post_glob_div_f = (uint32_t)litex_clk_get_real_global_frequency();
	period_buff = PICOS_IN_SEC;
	period_buff /= post_glob_div_f;
	global_period = (uint32_t)period_buff;
	clkout_period = global_period * divider;

	if (lcko->ts_config.phase != 0) {
		int synth_phase, delta_p, min_p, p_o;
		uint8_t delay, p_m;

		*period_off = litex_round(clkout_period * (*period_off), 10000);

		if (*period_off / global_period > DELAY_TIME_MAX) {
			return -EINVAL;
		}

		min_p = INT_MAX;
		p_o = *period_off;
		/* Delay_time: (0-63) */
		for (delay = 0; delay <= DELAY_TIME_MAX; delay++) {
			/* phase_mux: (0-7) */
			for (p_m = 0; p_m <= PHASE_MUX_MAX; p_m++) {
				synth_phase = (delay * global_period) +
				((p_m * ((global_period * 100) / 8) / 100));

				delta_p = synth_phase - p_o;
				delta_p = abs(delta_p);
				if (delta_p < min_p) {
					min_p = delta_p;
					lcko->phase.phase_mux = p_m;
					lcko->phase.delay_time = delay;
					lcko->config.period_off = synth_phase;
				}
			}
		}
	} else {
		/* Don't change phase offset*/
		lcko->phase.phase_mux = 0;
		lcko->phase.delay_time = 0;
	}
	/*
	 * Calculating values in normal mode,
	 * fractional control bits need to be zero
	 */
	lcko->frac.phase_mux_f = 0;

	return 0;
}

/* Convert phase offset to positive lower than 360 deg. and calculate period */
static int litex_clk_prepare_phase(struct litex_clk_clkout *lcko)
{
	int *phase = &lcko->ts_config.phase;

	*phase %= 360;

	if (*phase < 0) {
		*phase += 360;
	}

	lcko->ts_config.period_off = ((*phase * 10000) / 360);

	return 0;
}

/* Calculate necessary values for setting phase */
static int litex_clk_calc_phase(struct litex_clk_clkout *lcko)
{
	litex_clk_prepare_phase(lcko);

	return litex_clk_calc_phase_normal(lcko);
}

/* Returns phase-specific values of given clock output */
static int litex_clk_get_phase_data(struct litex_clk_clkout *lcko,
				    uint8_t *phase_mux, uint8_t *delay_time)
{
	struct litex_clk_regs_addr drp_addr = litex_clk_regs_addr_init();
	int ret;
	uint16_t r1, r2;
	uint8_t clkout_nr = lcko->id;

	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg1, &r1);
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_get_DO(drp_addr.clkout[clkout_nr].reg2, &r2);
	if (ret != 0) {
		return ret;
	}

	*phase_mux = (r1 >> PHASE_MUX_POS) & PHASE_MUX_MASK;
	*delay_time = (r2 >> DELAY_TIME_POS) & HL_TIME_MASK;

	return 0;
}

/* Returns phase of given clock output in time offset */
int litex_clk_get_phase(struct litex_clk_clkout *lcko)
{
	uint64_t period_buff;
	uint32_t divider = 0, fract_cnt, post_glob_div_f,
	    pm, global_period, clkout_period, period;
	uint8_t phase_mux = 0, delay_time = 0;

	litex_clk_get_phase_data(lcko, &phase_mux, &delay_time);
	litex_clk_get_clkout_divider(lcko, &divider, &fract_cnt);

	post_glob_div_f = (uint32_t)litex_clk_get_real_global_frequency();
	period_buff = PICOS_IN_SEC;
	period_buff /= post_glob_div_f;
	/* ps unit */
	global_period = (uint32_t)period_buff;
	clkout_period = global_period * divider;

	pm = (phase_mux * global_period * 1000) / PHASE_MUX_RES_FACTOR;
	pm = litex_round(pm, 1000);

	period = delay_time * global_period + pm;

	period = period * 1000 / clkout_period;
	period = period * 360;

	return litex_round(period, 1000);
}

/* Returns phase of given clock output in degrees */
int litex_clk_get_phase_deg(struct litex_clk_clkout *lcko)
{
	uint64_t post_glob_div_f, buff, clkout_period;

	post_glob_div_f = (uint32_t)litex_clk_get_real_global_frequency();
	buff = PICOS_IN_SEC;
	buff /= post_glob_div_f;
	clkout_period = (uint32_t)buff;
	clkout_period *= lcko->config.div;

	buff = lcko->config.period_off * 1000 / clkout_period;
	buff *= 360;
	buff = litex_round(buff, 1000);

	return (int)buff;
}
/* Sets phase given in degrees on given clock output */
int litex_clk_set_phase(struct litex_clk_clkout *lcko, int degrees)
{
	int ret;
	uint16_t bitset1, bitset2, reg2_mask;
	uint8_t *phase_mux = &lcko->phase.phase_mux,
	   *delay_time = &lcko->phase.delay_time,
	   clkout_nr = lcko->id;

	lcko->ts_config.phase = degrees;
	reg2_mask = REG2_PHASE_MASK;
	LOG_DBG("CLKOUT%d: setting phase: %u deg", lcko->id, degrees);

	ret = litex_clk_calc_phase(lcko);
	if (ret != 0) {
		LOG_ERR("CLKOUT%d: phase offset %d deg is too high",
			 clkout_nr, degrees);
		return ret;
	}

	bitset1 = (*phase_mux << PHASE_MUX_POS);
	bitset2 = (*delay_time << DELAY_TIME_POS);

	ret = litex_clk_set_clock(clkout_nr, REG1_PHASE_MASK, bitset1,
						   reg2_mask, bitset2);
	if (ret != 0) {
		return ret;
	}
	lcko->config.phase = litex_clk_get_phase_deg(lcko);
	LOG_INF("CLKOUT%d: set phase: %d deg", lcko->id, lcko->config.phase);
	LOG_DBG("SET PHASE: pm:%u dt:%u\nbitset1: 0x%x bitset2: 0x%x",
		*phase_mux, *delay_time, bitset1, bitset2);

	return 0;
}

/*
 *	Frequency
 */

/* Returns rate in Hz */
static inline uint32_t litex_clk_calc_rate(struct litex_clk_clkout *lcko)
{
	uint64_t f = litex_clk_calc_global_frequency(ldev->ts_g_config.mul,
						  ldev->ts_g_config.div);

	f /= lcko->config.div;

	return (uint32_t)f;
}

/*
 * Written since there is no pow() in math.h. Only for exponent
 * and base above 0. Used for calculating scaling factor for
 * frequency margin
 *
 */
static uint32_t litex_clk_pow(uint32_t base, uint32_t exp)
{
	int ret = 1;

	while (exp--) {
		ret *= base;
	}

	return ret;
}

/* Returns true when possible to set frequency with given global settings */
static int litex_clk_calc_clkout_params(struct litex_clk_clkout *lcko,
					 uint64_t vco_freq)
{
	int delta_f;
	uint64_t m, clk_freq = 0;
	uint32_t d, margin = 1;

	if (lcko->margin.exp) {
		margin = litex_clk_pow(10, lcko->margin.exp);
	}

	lcko->div.no_cnt = 0;

	for (d = lcko->clkout_div.min; d <= lcko->clkout_div.max; d++) {
		clk_freq = vco_freq;
		clk_freq /= d;
		m = lcko->ts_config.freq * lcko->margin.m;
		/* Scale margin according to its exponent */
		if (lcko->margin.exp) {
			m /= margin;
		}

		delta_f = clk_freq - lcko->ts_config.freq;
		delta_f = abs(delta_f);
		if (delta_f <= m) {
			lcko->config.freq = (uint32_t)clk_freq;
			if (lcko->config.div != d) {
				ldev->update_clkout[lcko->id] = 1;
			}
			lcko->config.div = d;
			/* for sake of completeness */
			lcko->ts_config.div = d;
			/* we are not using fractional divider */
			lcko->frac.frac_en = 0;
			lcko->frac.frac = 0;
			if (d == 1) {
				lcko->div.no_cnt = 1;
			}
			LOG_DBG("CLKOUT%d: freq:%u div:%u gdiv:%u gmul:%u",
				 lcko->id, lcko->config.freq, lcko->config.div,
				 ldev->ts_g_config.div, ldev->ts_g_config.mul);
			return true;
		}
	}

	return false;
}

/* Compute dividers for all active clock outputs */
static int litex_clk_calc_all_clkout_params(uint64_t vco_freq)
{
	struct litex_clk_clkout *lcko;
	uint32_t c;

	for (c = 0; c < ldev->nclkout; c++) {
		lcko = &ldev->clkouts[c];
		if (!litex_clk_calc_clkout_params(lcko, vco_freq)) {
			return false;
		}
	}
	return true;
}

/* Calculate parameters for whole active part of MMCM */
static int litex_clk_calc_all_params(void)
{
	uint32_t div, mul;
	uint64_t vco_freq = 0;

	for (div = ldev->divclk.min; div <= ldev->divclk.max; div++) {
		ldev->ts_g_config.div = div;
		for (mul = ldev->clkfbout.max; mul >= ldev->clkfbout.min;
								 mul--) {
			int bellow, above, all_valid = true;

			vco_freq = (uint64_t)ldev->sys_clk_freq * (uint64_t)mul;
			vco_freq /= div;
			bellow = vco_freq < (ldev->vco.min
					     * (1 + ldev->vco_margin));
			above = vco_freq > (ldev->vco.max
					    * (1 - ldev->vco_margin));

			if (!bellow && !above) {
				all_valid = litex_clk_calc_all_clkout_params
								     (vco_freq);
				if (all_valid) {
					ldev->ts_g_config.mul = mul;
					ldev->ts_g_config.freq = vco_freq;
					LOG_DBG("GLOBAL: freq:%llu g_div:%u g_mul:%u",
						ldev->ts_g_config.freq,
						ldev->ts_g_config.div,
						ldev->ts_g_config.mul);
					return 0;
				}
			}
		}
	}
	LOG_ERR("Cannot find correct settings for all clock outputs!");
	return -ENOTSUP;
}

int litex_clk_check_rate_range(struct litex_clk_clkout *lcko, uint32_t rate)
{
	uint64_t max, min, m;
	uint32_t div, margin;

	m = rate * lcko->margin.m;
	if (lcko->margin.exp) {
		margin = litex_clk_pow(10, lcko->margin.exp);
	}

	max = (uint64_t)ldev->sys_clk_freq * (uint64_t)ldev->clkfbout.max;
	div = ldev->divclk.min * lcko->clkout_div.min;
	max /= div;
	max += m;

	min = ldev->sys_clk_freq * ldev->clkfbout.min;
	div = ldev->divclk.max * lcko->clkout_div.max;
	min /= div;

	if (min < m) {
		min = 0;
	} else {
		min -= m;
	}

	if ((uint64_t)rate < min || (uint64_t)rate > max) {
		return -EINVAL;
	}
	return 0;
}

/* Returns closest available clock rate in Hz */
long litex_clk_round_rate(struct litex_clk_clkout *lcko, unsigned long rate)
{
	int ret;

	ret = litex_clk_check_rate_range(lcko, rate);
	if (ret != 0) {
		return -EINVAL;
	}

	lcko->ts_config.freq = rate;

	ret = litex_clk_calc_all_params();
	if (ret != 0) {
		return ret;
	}

	return litex_clk_calc_rate(lcko);
}

int litex_clk_write_rate(struct litex_clk_clkout *lcko)
{
	int ret;
	uint16_t bitset1, bitset2;
	uint8_t *divider = &lcko->config.div,
	   *edge = &lcko->div.edge,
	   *high_time = &lcko->div.high_time,
	   *low_time = &lcko->div.low_time,
	   *no_cnt = &lcko->div.no_cnt,
	   *frac = &lcko->frac.frac,
	   *frac_en = &lcko->frac.frac_en,
	   *frac_wf_r = &lcko->frac.frac_wf_r;

	bitset1 = (*high_time << HIGH_TIME_POS)	|
		  (*low_time << LOW_TIME_POS);

	bitset2 = (*frac << FRAC_POS)		|
		  (*frac_en << FRAC_EN_POS)	|
		  (*frac_wf_r << FRAC_WF_R_POS)	|
		  (*edge << EDGE_POS)		|
		  (*no_cnt << NO_CNT_POS);

	LOG_DBG("SET RATE: div:%u f:%u fwfr:%u fen:%u nc:%u e:%u ht:%u lt:%u\nbitset1: 0x%x bitset2: 0x%x",
		*divider, *frac, *frac_wf_r, *frac_en,
		*no_cnt, *edge, *high_time, *low_time, bitset1, bitset2);

	ret = litex_clk_set_clock(lcko->id, REG1_FREQ_MASK, bitset1,
					    REG2_FREQ_MASK, bitset2);
	if (ret != 0) {
		return ret;
	}

	ldev->update_clkout[lcko->id] = 0;

	return 0;
}

int litex_clk_update_clkouts(void)
{
	struct litex_clk_clkout *lcko;
	int ret;
	uint8_t c;

	for (c = 0; c < ldev->nclkout; c++) {
		if (ldev->update_clkout[c]) {
			lcko = &ldev->clkouts[c];
			ret = litex_clk_calc_duty_normal(lcko, false);
			if (ret != 0) {
				return ret;
			}
			ret = litex_clk_write_rate(lcko);
			if (ret != 0) {
				return ret;
			}
			LOG_INF("CLKOUT%d: updated rate: %u to %u HZ",
					lcko->id, lcko->ts_config.freq,
						     lcko->config.freq);
		}
	}

	return 0;
}
/* Set closest available clock rate in Hz, parent_rate ignored */
int litex_clk_set_rate(struct litex_clk_clkout *lcko, unsigned long rate)
{
	int ret;

	LOG_DBG("CLKOUT%d: setting rate: %lu", lcko->id, rate);
	ret = litex_clk_round_rate(lcko, rate);
	if (ret < 0) {
		return ret;
	}
	ret = litex_clk_set_globs();
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_calc_duty_normal(lcko, false);
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_write_rate(lcko);
	if (ret != 0) {
		return ret;
	}
	LOG_INF("CLKOUT%d: set rate: %u HZ", lcko->id, lcko->config.freq);
	ret = litex_clk_update_clkouts();
	if (ret != 0) {
		return ret;
	}

#ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG
	litex_clk_print_all_params();
	litex_clk_print_all_regs();
#endif /* #ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG */

	return 0;
}

/* Set default clock value from device tree for given clkout*/
static int litex_clk_set_def_clkout(int clkout_nr)
{
	struct litex_clk_clkout *lcko = &ldev->clkouts[clkout_nr];
	int ret;

	ret = litex_clk_set_rate(lcko, lcko->def.freq);
	if (ret != 0) {
		return ret;
	}
	ret = litex_clk_set_duty_cycle(lcko, &lcko->def.duty);
	if (ret != 0) {
		return ret;
	}
	return litex_clk_set_phase(lcko, lcko->def.phase);
}

static int litex_clk_set_all_def_clkouts(void)
{
	int c, ret;

	for (c = 0; c < ldev->nclkout; c++) {
		ret = litex_clk_set_def_clkout(c);
		if (ret != 0) {
			return ret;
		}
	}
	return 0;
}

/*
 * Returns parameters of given clock output
 *
 * clock:		device structure for driver
 * sub_system:		pointer to struct litex_clk_clkout
 *			casted to clock_control_subsys with
 *			all clkout parameters
 */
static int litex_clk_get_subsys_rate(const struct device *clock,
				     clock_control_subsys_t sys, uint32_t *rate)
{
	struct litex_clk_setup *setup = sys;
	struct litex_clk_clkout *lcko;

	lcko = &ldev->clkouts[setup->clkout_nr];
	*rate = litex_clk_calc_rate(lcko);

	return 0;
}

static enum clock_control_status litex_clk_get_status(const struct device *dev,
						     clock_control_subsys_t sys)
{
	struct litex_clk_setup *setup = sys;
	struct clk_duty duty;
	struct litex_clk_clkout *lcko;
	int ret;

	lcko = &ldev->clkouts[setup->clkout_nr];

	setup->rate = litex_clk_calc_rate(lcko);
	ret = litex_clk_get_duty_cycle(lcko, &duty);
	if (ret != 0) {
		return ret;
	}
	setup->duty = litex_clk_calc_duty_percent(&duty);
	setup->phase = litex_clk_get_phase(lcko);

	return CLOCK_CONTROL_STATUS_ON;
}

static inline int litex_clk_on(const struct device *dev, clock_control_subsys_t sys)
{
	struct litex_clk_setup *setup = sys;
	struct clk_duty duty;
	struct litex_clk_clkout *lcko;
	uint8_t duty_perc;
	int ret;

	lcko = &ldev->clkouts[setup->clkout_nr];

	if (lcko->config.freq != setup->rate) {
		ret = litex_clk_set_rate(lcko, setup->rate);
		if (ret != 0) {
			return ret;
		}
	}
	if (lcko->config.phase != setup->phase) {
		ret = litex_clk_set_phase(lcko, setup->phase);
		if (ret != 0) {
			return ret;
		}
	}
	duty_perc = litex_clk_calc_duty_percent(&lcko->config.duty);
	if (duty_perc != setup->duty) {
		duty.num = setup->duty;
		duty.den = 100;
		ret = litex_clk_set_duty_cycle(lcko, &duty);
		if (ret != 0) {
			return ret;
		}
	}
	return 0;
}

static inline int litex_clk_off(const struct device *dev,
				clock_control_subsys_t sub_system)
{
	return litex_clk_change_value(ZERO_REG, ZERO_REG, POWER_REG);
}

static const struct clock_control_driver_api litex_clk_api = {
	.on = litex_clk_on,
	.off = litex_clk_off,
	.get_rate = litex_clk_get_subsys_rate,
	.get_status = litex_clk_get_status
};

static void litex_clk_dts_clkout_ranges_read(struct litex_clk_range *clkout_div)
{
	clkout_div->min = CLKOUT_DIVIDE_MIN;
	clkout_div->max = CLKOUT_DIVIDE_MAX;
}

static int litex_clk_dts_timeout_read(struct litex_clk_timeout *timeout)
{
	/* Read wait_lock timeout from device property*/
	timeout->lock = LOCK_TIMEOUT;
	if (timeout->lock < 1) {
		LOG_ERR("LiteX CLK driver cannot wait shorter than ca. 1ms\n");
		return -EINVAL;
	}

	/* Read wait_drdy timeout from device property*/
	timeout->drdy = DRDY_TIMEOUT;
	if (timeout->drdy < 1) {
		LOG_ERR("LiteX CLK driver cannot wait shorter than ca. 1ms\n");
		return -EINVAL;
	}

	return 0;
}

static int litex_clk_dts_clkouts_read(void)
{
	struct litex_clk_range clkout_div;
	struct litex_clk_clkout *lcko;

	litex_clk_dts_clkout_ranges_read(&clkout_div);

#if CLKOUT_EXIST(0) == 1
		CLKOUT_INIT(0)
#endif
#if CLKOUT_EXIST(1) == 1
		CLKOUT_INIT(1)
#endif
#if CLKOUT_EXIST(2) == 1
		CLKOUT_INIT(2)
#endif
#if CLKOUT_EXIST(3) == 1
		CLKOUT_INIT(3)
#endif
#if CLKOUT_EXIST(4) == 1
		CLKOUT_INIT(4)
#endif
#if CLKOUT_EXIST(5) == 1
		CLKOUT_INIT(5)
#endif
#if CLKOUT_EXIST(6) == 1
		CLKOUT_INIT(6)
#endif
	return 0;
}

static void litex_clk_init_clkouts(void)
{
	struct litex_clk_clkout *lcko;
	int i;

	for (i = 0; i < ldev->nclkout; i++) {
		lcko = &ldev->clkouts[i];
		lcko->base = ldev->base;
		/* mark defaults to set */
		lcko->ts_config.freq = lcko->def.freq;
		lcko->ts_config.duty = lcko->def.duty;
		lcko->ts_config.phase = lcko->def.phase;
	}
}

static int litex_clk_dts_cnt_clocks(void)
{
	return NCLKOUT;
}

static void litex_clk_dts_global_ranges_read(void)
{
	ldev->divclk.min = DIVCLK_DIVIDE_MIN;
	ldev->divclk.max = DIVCLK_DIVIDE_MAX;
	ldev->clkfbout.min = CLKFBOUT_MULT_MIN;
	ldev->clkfbout.max = CLKFBOUT_MULT_MAX;
	ldev->vco.min = VCO_FREQ_MIN;
	ldev->vco.max = VCO_FREQ_MAX;
	ldev->vco_margin = VCO_MARGIN;
}

static int litex_clk_dts_global_read(void)
{
	int ret;

	ldev->sys_clk_freq = SYS_CLOCK_FREQUENCY;

	ldev->nclkout = litex_clk_dts_cnt_clocks();

	clkouts = k_malloc(sizeof(struct litex_clk_clkout) * ldev->nclkout);
	ldev->update_clkout = k_malloc(sizeof(uint8_t) * ldev->nclkout);
	if (!clkouts || !ldev->update_clkout) {
		LOG_ERR("CLKOUT memory allocation failure!");
		return -ENOMEM;
	}
	ldev->clkouts = clkouts;

	ret = litex_clk_dts_timeout_read(&ldev->timeout);
	if (ret != 0) {
		return ret;
	}

	litex_clk_dts_global_ranges_read();

	return 0;
}

static int litex_clk_init_glob_clk(void)
{
	int ret;

	/* Power on MMCM module */
	ret = litex_clk_change_value(FULL_REG_16, FULL_REG_16, POWER_REG);
	if (ret != 0) {
		LOG_ERR("MMCM initialization failure, ret: %d", ret);
		return ret;
	}

	return 0;
}
/* Enable module, set global divider, multiplier, default clkout parameters */
static int litex_clk_init(const struct device *dev)
{
	int ret;

	ldev = k_malloc(sizeof(struct litex_clk_device));
	if (ldev == NULL) {
		return -ENOMEM;
	}

	ldev->base = (uint32_t *)DRP_BASE;
	if (ldev->base == NULL) {
		return -EIO;
	}

	ret = litex_clk_dts_global_read();
	if (ret != 0) {
		return ret;
	}

	ret = litex_clk_dts_clkouts_read();
	if (ret != 0) {
		return ret;
	}

	litex_clk_init_clkouts();

	ret = litex_clk_init_glob_clk();
	if (ret != 0) {
		return ret;
	}

	ret = litex_clk_set_all_def_clkouts();
	if (ret != 0) {
		return ret;
	}

#ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG
	litex_clk_print_all_params();
	litex_clk_print_all_regs();
#endif /* #ifdef CONFIG_CLOCK_CONTROL_LOG_LEVEL_DBG */

	LOG_INF("LiteX Clock Control driver initialized");
	return 0;
}

static const struct litex_clk_device ldev_init = {
	.base = (uint32_t *)DRP_BASE,
	.timeout = {LOCK_TIMEOUT, DRDY_TIMEOUT},
	.divclk = {DIVCLK_DIVIDE_MIN, DIVCLK_DIVIDE_MAX},
	.clkfbout = {CLKFBOUT_MULT_MIN, CLKFBOUT_MULT_MAX},
	.vco = {VCO_FREQ_MIN, VCO_FREQ_MAX},
	.sys_clk_freq = SYS_CLOCK_FREQUENCY,
	.vco_margin = VCO_MARGIN,
	.nclkout = NCLKOUT
};

DEVICE_DT_DEFINE(DT_NODELABEL(clock0), &litex_clk_init, device_pm_control_nop,
		    NULL, &ldev_init, POST_KERNEL,
		    CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &litex_clk_api);