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
//! Clock configuration.
//!
//! This module provides functionality to configure the RCC to generate the requested clocks.
//!
//! # Example
//!
//! ```
//! let dp = pac::Peripherals::take().unwrap();
//! let clocks = rcc
//!     .cfgr
//!     .use_hse(8.mhz())
//!     .sysclk(168.mhz())
//!     .pclk1(24.mhz())
//!     .i2s_clk(86.mhz())
//!     .require_pll48clk()
//!     .freeze();
//!     // Test that the I2S clock is suitable for 48000KHz audio.
//!     assert!(clocks.i2s_clk().unwrap() == 48.mhz().into());
//! ```
//!
//! # Limitations
//!
//! Unlike the clock configuration tool provided by ST, the code does not extensively search all
//! possible configurations. Instead, it often relies on an iterative approach to reduce
//! compitational complexity. On most MCUs the code will first generate a configuration for the 48
//! MHz clock and the system clock without taking other requested clocks into account, even if the
//! accuracy of these clocks is affected. **If you specific accuracy requirements, you should
//! always check the resulting frequencies!**
//!
//! Whereas the hardware often supports flexible clock source selection and many clocks can be
//! sourced from multiple PLLs, the code implements a fixed mapping between PLLs and clocks. The 48
//! MHz clock is always generated by the main PLL, the I2S clocks are always generated by the I2S
//! PLL (unless a matching external clock input is provided), and similarly the SAI clocks are
//! always generated by the SAI PLL. It is therefore not possible to, for example, specify two
//! different I2S frequencies unless you also provide a matching I2S_CKIN signal for one of them.
//!
//! Some MCUs have limited clock generation hardware and do not provide either I2S or SAI PLLs even
//! though I2S or SAI are available. On the STM32F410, the I2S clock is generated by the main PLL,
//! and on the STM32F413/423 SAI clocks are generated by the I2S PLL. On these MCUs, the actual
//! frequencies may substantially deviate from the requested frequencies.

use crate::pac::rcc::cfgr::{HPRE_A, SW_A};
use crate::pac::{rcc, RCC};

use crate::time::Hertz;

#[cfg(not(feature = "stm32f410"))]
use pll::I2sPll;
use pll::MainPll;
#[cfg(any(
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
use pll::SaiPll;

mod pll;

mod enable;
use crate::pac::rcc::RegisterBlock as RccRB;

/// Bus associated to peripheral
pub trait RccBus: crate::Sealed {
    /// Bus type;
    type Bus;
}

/// Enable/disable peripheral
pub trait Enable: RccBus {
    fn enable(rcc: &RccRB);
    fn disable(rcc: &RccRB);
}

/// Low power enable/disable peripheral
pub trait LPEnable: RccBus {
    fn low_power_enable(rcc: &RccRB);
    fn low_power_disable(rcc: &RccRB);
}

/// Reset peripheral
pub trait Reset: RccBus {
    fn reset(rcc: &RccRB);
}

/// Extension trait that constrains the `RCC` peripheral
pub trait RccExt {
    /// Constrains the `RCC` peripheral so it plays nicely with the other abstractions
    fn constrain(self) -> Rcc;
}

pub trait GetBusFreq {
    fn get_frequency(clocks: &Clocks) -> Hertz;
    fn get_timer_frequency(clocks: &Clocks) -> Hertz {
        Self::get_frequency(clocks)
    }
}

impl<T> GetBusFreq for T
where
    T: RccBus,
    T::Bus: GetBusFreq,
{
    fn get_frequency(clocks: &Clocks) -> Hertz {
        T::Bus::get_frequency(clocks)
    }
    fn get_timer_frequency(clocks: &Clocks) -> Hertz {
        T::Bus::get_timer_frequency(clocks)
    }
}

/// AMBA High-performance Bus 1 (AHB1) registers
pub struct AHB1 {
    _0: (),
}

impl AHB1 {
    #[inline(always)]
    fn enr(rcc: &RccRB) -> &rcc::AHB1ENR {
        &rcc.ahb1enr
    }
    #[inline(always)]
    fn lpenr(rcc: &RccRB) -> &rcc::AHB1LPENR {
        &rcc.ahb1lpenr
    }
    #[inline(always)]
    fn rstr(rcc: &RccRB) -> &rcc::AHB1RSTR {
        &rcc.ahb1rstr
    }
}

/// AMBA High-performance Bus 2 (AHB2) registers
#[cfg(not(feature = "stm32f410"))]
pub struct AHB2 {
    _0: (),
}

#[cfg(not(feature = "stm32f410"))]
impl AHB2 {
    #[inline(always)]
    fn enr(rcc: &RccRB) -> &rcc::AHB2ENR {
        &rcc.ahb2enr
    }
    #[inline(always)]
    fn lpenr(rcc: &RccRB) -> &rcc::AHB2LPENR {
        &rcc.ahb2lpenr
    }
    #[inline(always)]
    fn rstr(rcc: &RccRB) -> &rcc::AHB2RSTR {
        &rcc.ahb2rstr
    }
}

/// AMBA High-performance Bus 3 (AHB3) registers
#[cfg(any(feature = "fsmc", feature = "fmc"))]
pub struct AHB3 {
    _0: (),
}

#[cfg(any(feature = "fsmc", feature = "fmc"))]
impl AHB3 {
    #[inline(always)]
    fn enr(rcc: &RccRB) -> &rcc::AHB3ENR {
        &rcc.ahb3enr
    }
    #[cfg(feature = "fmc")]
    #[inline(always)]
    fn lpenr(rcc: &RccRB) -> &rcc::AHB3LPENR {
        &rcc.ahb3lpenr
    }
    #[inline(always)]
    fn rstr(rcc: &RccRB) -> &rcc::AHB3RSTR {
        &rcc.ahb3rstr
    }
}

/// Advanced Peripheral Bus 1 (APB1) registers
pub struct APB1 {
    _0: (),
}

impl APB1 {
    #[inline(always)]
    fn enr(rcc: &RccRB) -> &rcc::APB1ENR {
        &rcc.apb1enr
    }
    #[inline(always)]
    fn lpenr(rcc: &RccRB) -> &rcc::APB1LPENR {
        &rcc.apb1lpenr
    }
    #[inline(always)]
    fn rstr(rcc: &RccRB) -> &rcc::APB1RSTR {
        &rcc.apb1rstr
    }
}

/// Advanced Peripheral Bus 2 (APB2) registers
pub struct APB2 {
    _0: (),
}

impl APB2 {
    #[inline(always)]
    fn enr(rcc: &RccRB) -> &rcc::APB2ENR {
        &rcc.apb2enr
    }
    #[inline(always)]
    fn lpenr(rcc: &RccRB) -> &rcc::APB2LPENR {
        &rcc.apb2lpenr
    }
    #[inline(always)]
    fn rstr(rcc: &RccRB) -> &rcc::APB2RSTR {
        &rcc.apb2rstr
    }
}

impl GetBusFreq for AHB1 {
    fn get_frequency(clocks: &Clocks) -> Hertz {
        clocks.hclk
    }
}

#[cfg(not(feature = "stm32f410"))]
impl GetBusFreq for AHB2 {
    fn get_frequency(clocks: &Clocks) -> Hertz {
        clocks.hclk
    }
}

#[cfg(any(feature = "fsmc", feature = "fmc"))]
impl GetBusFreq for AHB3 {
    fn get_frequency(clocks: &Clocks) -> Hertz {
        clocks.hclk
    }
}

impl GetBusFreq for APB1 {
    fn get_frequency(clocks: &Clocks) -> Hertz {
        clocks.pclk1
    }
    fn get_timer_frequency(clocks: &Clocks) -> Hertz {
        let pclk_mul = if clocks.ppre1 == 1 { 1 } else { 2 };
        Hertz(clocks.pclk1.0 * pclk_mul)
    }
}

impl GetBusFreq for APB2 {
    fn get_frequency(clocks: &Clocks) -> Hertz {
        clocks.pclk2
    }
    fn get_timer_frequency(clocks: &Clocks) -> Hertz {
        let pclk_mul = if clocks.ppre2 == 1 { 1 } else { 2 };
        Hertz(clocks.pclk2.0 * pclk_mul)
    }
}

impl RccExt for RCC {
    fn constrain(self) -> Rcc {
        Rcc {
            cfgr: CFGR {
                hse: None,
                hse_bypass: false,
                hclk: None,
                pclk1: None,
                pclk2: None,
                sysclk: None,
                pll48clk: false,
                i2s_ckin: None,
                #[cfg(any(
                    feature = "stm32f401",
                    feature = "stm32f405",
                    feature = "stm32f407",
                    feature = "stm32f410",
                    feature = "stm32f411",
                    feature = "stm32f415",
                    feature = "stm32f417",
                    feature = "stm32f427",
                    feature = "stm32f429",
                    feature = "stm32f437",
                    feature = "stm32f439",
                    feature = "stm32f469",
                    feature = "stm32f479"
                ))]
                i2s_clk: None,
                #[cfg(any(
                    feature = "stm32f412",
                    feature = "stm32f413",
                    feature = "stm32f423",
                    feature = "stm32f446",
                ))]
                i2s_apb1_clk: None,
                #[cfg(any(
                    feature = "stm32f412",
                    feature = "stm32f413",
                    feature = "stm32f423",
                    feature = "stm32f446",
                ))]
                i2s_apb2_clk: None,
                #[cfg(any(
                    feature = "stm32f413",
                    feature = "stm32f423",
                    feature = "stm32f427",
                    feature = "stm32f429",
                    feature = "stm32f437",
                    feature = "stm32f439",
                    feature = "stm32f446",
                    feature = "stm32f469",
                    feature = "stm32f479",
                ))]
                sai1_clk: None,
                #[cfg(any(
                    feature = "stm32f413",
                    feature = "stm32f423",
                    feature = "stm32f427",
                    feature = "stm32f429",
                    feature = "stm32f437",
                    feature = "stm32f439",
                    feature = "stm32f446",
                    feature = "stm32f469",
                    feature = "stm32f479",
                ))]
                sai2_clk: None,
            },
        }
    }
}

/// Constrained RCC peripheral
pub struct Rcc {
    pub cfgr: CFGR,
}

/// Built-in high speed clock frequency
pub const HSI: u32 = 16_000_000; // Hz

#[cfg(any(
    feature = "stm32f401",
    feature = "stm32f405",
    feature = "stm32f407",
    feature = "stm32f410",
    feature = "stm32f411",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f415",
    feature = "stm32f417",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f469",
    feature = "stm32f479"
))]
/// Minimum system clock frequency
pub const SYSCLK_MIN: u32 = 24_000_000;

#[cfg(any(feature = "stm32f446"))]
/// Minimum system clock frequency
pub const SYSCLK_MIN: u32 = 12_500_000;

#[cfg(feature = "stm32f401")]
/// Maximum system clock frequency
pub const SYSCLK_MAX: u32 = 84_000_000;

#[cfg(any(
    feature = "stm32f405",
    feature = "stm32f407",
    feature = "stm32f415",
    feature = "stm32f417"
))]
/// Maximum system clock frequency
pub const SYSCLK_MAX: u32 = 168_000_000;

#[cfg(any(
    feature = "stm32f410",
    feature = "stm32f411",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423"
))]
/// Maximum system clock frequency
pub const SYSCLK_MAX: u32 = 100_000_000;

#[cfg(any(
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479"
))]
/// Maximum system clock frequency
pub const SYSCLK_MAX: u32 = 180_000_000;

#[cfg(any(
    feature = "stm32f401",
    feature = "stm32f410",
    feature = "stm32f411",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423"
))]
/// Maximum APB2 peripheral clock frequency
pub const PCLK2_MAX: u32 = SYSCLK_MAX;

#[cfg(not(any(
    feature = "stm32f401",
    feature = "stm32f410",
    feature = "stm32f411",
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423"
)))]
/// Maximum APB2 peripheral clock frequency
pub const PCLK2_MAX: u32 = SYSCLK_MAX / 2;

/// Maximum APB1 peripheral clock frequency
pub const PCLK1_MAX: u32 = PCLK2_MAX / 2;

pub struct CFGR {
    hse: Option<u32>,
    hse_bypass: bool,
    hclk: Option<u32>,
    pclk1: Option<u32>,
    pclk2: Option<u32>,
    sysclk: Option<u32>,
    pll48clk: bool,

    i2s_ckin: Option<u32>,
    #[cfg(any(
        feature = "stm32f401",
        feature = "stm32f405",
        feature = "stm32f407",
        feature = "stm32f410",
        feature = "stm32f411",
        feature = "stm32f415",
        feature = "stm32f417",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479"
    ))]
    i2s_clk: Option<u32>,
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    i2s_apb1_clk: Option<u32>,
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    i2s_apb2_clk: Option<u32>,
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f446",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    sai1_clk: Option<u32>,
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f446",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    sai2_clk: Option<u32>,
}

impl CFGR {
    /// Uses HSE (external oscillator) instead of HSI (internal RC oscillator) as the clock source.
    /// Will result in a hang if an external oscillator is not connected or it fails to start.
    pub fn use_hse<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.hse = Some(freq.into().0);
        self
    }

    /// Bypasses the high-speed external oscillator and uses an external clock input on the OSC_IN
    /// pin.
    ///
    /// For this configuration, the OSC_IN pin should be connected to a clock source with a
    /// frequency specified in the call to use_hse(), and the OSC_OUT pin should not be connected.
    ///
    /// This function has no effect unless use_hse() is also called.
    pub fn bypass_hse_oscillator(self) -> Self {
        CFGR {
            hse_bypass: true,
            ..self
        }
    }

    pub fn hclk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.hclk = Some(freq.into().0);
        self
    }

    pub fn pclk1<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.pclk1 = Some(freq.into().0);
        self
    }

    pub fn pclk2<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.pclk2 = Some(freq.into().0);
        self
    }

    pub fn sysclk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sysclk = Some(freq.into().0);
        self
    }

    pub fn require_pll48clk(mut self) -> Self {
        self.pll48clk = true;
        self
    }

    /// Declares that the selected frequency is available at the I2S clock input pin (I2S_CKIN).
    ///
    /// If this frequency matches the requested SAI or I2S frequencies, the external I2S clock is
    /// used to generate the clocks.
    pub fn i2s_ckin<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.i2s_ckin = Some(freq.into().0);
        self
    }

    /// Selects an I2S clock frequency and enables the I2S clock.
    #[cfg(any(
        feature = "stm32f401",
        feature = "stm32f405",
        feature = "stm32f407",
        feature = "stm32f410",
        feature = "stm32f411",
        feature = "stm32f415",
        feature = "stm32f417",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479"
    ))]
    pub fn i2s_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.i2s_clk = Some(freq.into().0);
        self
    }

    /// Selects an I2S clock frequency for the first set of I2S instancesand enables the I2S clock.
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    pub fn i2s_apb1_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.i2s_apb1_clk = Some(freq.into().0);
        self
    }

    /// Selects an I2S clock frequency for the second set of I2S instances and enables the I2S clock.
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    pub fn i2s_apb2_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.i2s_apb2_clk = Some(freq.into().0);
        self
    }

    /// Selects a SAIA clock frequency and enables the SAIA clock.
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    pub fn saia_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sai1_clk = Some(freq.into().0);
        self
    }

    /// Selects a SAIB clock frequency and enables the SAIB clock.
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    pub fn saib_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sai2_clk = Some(freq.into().0);
        self
    }

    /// Selects a SAI1 clock frequency and enables the SAI1 clock.
    #[cfg(any(feature = "stm32f446",))]
    pub fn sai1_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sai1_clk = Some(freq.into().0);
        self
    }

    /// Selects a SAI2 clock frequency and enables the SAI2 clock.
    #[cfg(any(feature = "stm32f446",))]
    pub fn sai2_clk<F>(mut self, freq: F) -> Self
    where
        F: Into<Hertz>,
    {
        self.sai2_clk = Some(freq.into().0);
        self
    }
    #[cfg(feature = "stm32f410")]
    #[inline(always)]
    fn pll_setup(&self, pllsrcclk: u32, pllsysclk: Option<u32>) -> PllSetup {
        let i2s_clocks = self.i2s_clocks();

        let main_pll = if let Some(i2s_clk) = i2s_clocks.pll_i2s_clk {
            // The I2S frequency is generated by the main PLL. The frequency needs to be accurate,
            // so we need an expensive full PLL configuration search.
            MainPll::setup_with_i2s(
                pllsrcclk,
                self.hse.is_some(),
                pllsysclk,
                self.pll48clk,
                i2s_clk,
            )
        } else {
            MainPll::fast_setup(pllsrcclk, self.hse.is_some(), pllsysclk, self.pll48clk)
        };

        PllSetup {
            use_pll: main_pll.use_pll,
            pllsysclk: main_pll.pllsysclk,
            pll48clk: main_pll.pll48clk,
            i2s: i2s_clocks.real(main_pll.plli2sclk, self.i2s_ckin),
        }
    }

    #[cfg(any(feature = "stm32f413", feature = "stm32f423"))]
    #[inline(always)]
    fn pll_setup(&self, pllsrcclk: u32, pllsysclk: Option<u32>) -> PllSetup {
        let rcc = unsafe { &*RCC::ptr() };

        let i2s_clocks = self.i2s_clocks();
        let sai_clocks = self.sai_clocks();

        let main_pll = MainPll::fast_setup(pllsrcclk, self.hse.is_some(), pllsysclk, self.pll48clk);

        let (i2s_pll, real_sai_clk) = if let Some(i2s_clk) = i2s_clocks.pll_i2s_clk {
            // Currently, we only support generating SAI/PLL clocks with the I2S PLL. This is only
            // really usable when the frequencies are identical or the I2S frequency is a multiple of
            // the SAI frequency. Therefore, we just optimize the PLL for the I2S frequency and then
            // derive the SAI frequency from the I2S frequency.
            let i2s_pll = I2sPll::setup(pllsrcclk, Some(i2s_clk));

            if let Some(sai_clk) = sai_clocks.pll_sai_clk {
                let div = u32::min(
                    u32::max((i2s_pll.plli2sclk.unwrap() + (sai_clk >> 1)) / sai_clk, 1),
                    31,
                );
                rcc.dckcfgr.modify(|_, w| w.plli2sdivr().bits(div as u8));
                let real_sai_clk = sai_clk / div;
                (i2s_pll, Some(real_sai_clk))
            } else {
                (i2s_pll, None)
            }
        } else if let Some(pll_sai_clk) = sai_clocks.pll_sai_clk {
            // We try all divider values to get the best approximation of the requested frequency.
            // NOTE: STM32F413/423 have a different divider range than other models!
            let (i2s_pll, real_sai_clk, div) = (1..31)
                .map(|div| {
                    let i2s_pll = I2sPll::setup(pllsrcclk, Some(pll_sai_clk * div));
                    let real_clk = i2s_pll.plli2sclk.unwrap() / div;
                    (i2s_pll, real_clk, div)
                })
                .min_by_key(|(_, real_clk, _)| (*real_clk as i32 - pll_sai_clk as i32).abs())
                .unwrap();
            rcc.dckcfgr.modify(|_, w| w.plli2sdivr().bits(div as u8));
            (i2s_pll, Some(real_sai_clk))
        } else {
            (I2sPll::unused(), None)
        };

        PllSetup {
            use_pll: main_pll.use_pll,
            use_i2spll: i2s_pll.use_pll,
            pllsysclk: main_pll.pllsysclk,
            pll48clk: main_pll.pll48clk,
            i2s: i2s_clocks.real(i2s_pll.plli2sclk, self.i2s_ckin),
            sai: sai_clocks.real(real_sai_clk, self.i2s_ckin),
        }
    }

    #[cfg(any(feature = "stm32f411", feature = "stm32f412", feature = "stm32f446"))]
    #[inline(always)]
    fn pll_setup(&self, pllsrcclk: u32, pllsysclk: Option<u32>) -> PllSetup {
        let i2s_clocks = self.i2s_clocks();
        #[cfg(feature = "stm32f446")]
        let sai_clocks = self.sai_clocks();

        // All PLLs are completely independent.
        let main_pll = MainPll::fast_setup(pllsrcclk, self.hse.is_some(), pllsysclk, self.pll48clk);
        let i2s_pll = I2sPll::setup(pllsrcclk, i2s_clocks.pll_i2s_clk);
        #[cfg(feature = "stm32f446")]
        let sai_pll = SaiPll::setup(pllsrcclk, sai_clocks.pll_sai_clk);

        PllSetup {
            use_pll: main_pll.use_pll,
            use_i2spll: i2s_pll.use_pll,
            #[cfg(feature = "stm32f446")]
            use_saipll: sai_pll.use_pll,
            pllsysclk: main_pll.pllsysclk,
            pll48clk: main_pll.pll48clk,
            i2s: i2s_clocks.real(i2s_pll.plli2sclk, self.i2s_ckin),
            #[cfg(feature = "stm32f446")]
            sai: sai_clocks.real(sai_pll.sai_clk, self.i2s_ckin),
        }
    }

    #[cfg(any(
        feature = "stm32f401",
        feature = "stm32f405",
        feature = "stm32f407",
        feature = "stm32f415",
        feature = "stm32f417",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479"
    ))]
    #[inline(always)]
    fn pll_setup(&self, pllsrcclk: u32, pllsysclk: Option<u32>) -> PllSetup {
        let i2s_clocks = self.i2s_clocks();
        #[cfg(any(
            feature = "stm32f427",
            feature = "stm32f429",
            feature = "stm32f437",
            feature = "stm32f439",
            feature = "stm32f469",
            feature = "stm32f479"
        ))]
        let sai_clocks = self.sai_clocks();

        // We have separate PLLs, but they share the "M" divider.
        let main_pll = MainPll::fast_setup(pllsrcclk, self.hse.is_some(), pllsysclk, self.pll48clk);
        let i2s_pll = I2sPll::setup_shared_m(pllsrcclk, main_pll.m, i2s_clocks.pll_i2s_clk);
        #[cfg(any(
            feature = "stm32f427",
            feature = "stm32f429",
            feature = "stm32f437",
            feature = "stm32f439",
            feature = "stm32f469",
            feature = "stm32f479"
        ))]
        let sai_pll =
            SaiPll::setup_shared_m(pllsrcclk, main_pll.m.or(i2s_pll.m), sai_clocks.pll_sai_clk);

        PllSetup {
            use_pll: main_pll.use_pll,
            use_i2spll: i2s_pll.use_pll,
            #[cfg(any(
                feature = "stm32f427",
                feature = "stm32f429",
                feature = "stm32f437",
                feature = "stm32f439",
                feature = "stm32f469",
                feature = "stm32f479"
            ))]
            use_saipll: sai_pll.use_pll,
            pllsysclk: main_pll.pllsysclk,
            pll48clk: main_pll.pll48clk,
            i2s: i2s_clocks.real(i2s_pll.plli2sclk, self.i2s_ckin),
            #[cfg(any(
                feature = "stm32f427",
                feature = "stm32f429",
                feature = "stm32f437",
                feature = "stm32f439",
                feature = "stm32f469",
                feature = "stm32f479"
            ))]
            sai: sai_clocks.real(sai_pll.sai_clk, self.i2s_ckin),
        }
    }

    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f446",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    fn sai_clocks(&self) -> SaiClocks {
        let sai1_ext = self.sai1_clk.is_some() && self.sai1_clk == self.i2s_ckin;
        #[cfg(not(feature = "stm32f446"))]
        let sai2_ext = self.sai2_clk.is_some() && self.sai2_clk == self.i2s_ckin;
        // Not the PLL output, but the target clock after the divider.
        let pll_sai_clk = if sai1_ext { None } else { self.sai1_clk };
        // The STM32F446 only supports I2S_CKIN for SAI1.
        #[cfg(feature = "stm32f446")]
        let pll_sai_clk2 = self.sai2_clk;
        #[cfg(not(feature = "stm32f446"))]
        let pll_sai_clk2 = if sai2_ext { None } else { self.sai2_clk };
        if pll_sai_clk.is_some() && pll_sai_clk2.is_some() && pll_sai_clk != pll_sai_clk2 {
            panic!("only one SAI PLL frequency implemented");
        }
        SaiClocks {
            sai1_ext,
            #[cfg(not(feature = "stm32f446"))]
            sai2_ext,
            pll_sai_clk,
        }
    }

    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    fn i2s_clocks(&self) -> I2sClocks {
        let i2s_apb1_ext = self.i2s_apb1_clk.is_some() && self.i2s_apb1_clk == self.i2s_ckin;
        let i2s_apb2_ext = self.i2s_apb2_clk.is_some() && self.i2s_apb2_clk == self.i2s_ckin;
        let pll_i2s_clk = if i2s_apb1_ext {
            None
        } else {
            self.i2s_apb1_clk
        };
        let pll_i2s_clk2 = if i2s_apb2_ext {
            None
        } else {
            self.i2s_apb2_clk
        };
        if pll_i2s_clk.is_some() && pll_i2s_clk2.is_some() && pll_i2s_clk != pll_i2s_clk2 {
            panic!("only one I2S PLL frequency implemented");
        }
        I2sClocks {
            i2s_apb1_ext,
            i2s_apb2_ext,
            pll_i2s_clk,
        }
    }

    #[cfg(not(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    )))]
    fn i2s_clocks(&self) -> I2sClocks {
        let i2s_ext = self.i2s_clk.is_some() && self.i2s_clk == self.i2s_ckin;
        let pll_i2s_clk = if i2s_ext { None } else { self.i2s_clk };
        I2sClocks {
            i2s_ext,
            pll_i2s_clk,
        }
    }

    fn flash_setup(sysclk: u32) {
        use crate::pac::FLASH;

        #[cfg(any(
            feature = "stm32f401",
            feature = "stm32f405",
            feature = "stm32f407",
            feature = "stm32f410",
            feature = "stm32f411",
            feature = "stm32f412",
            feature = "stm32f415",
            feature = "stm32f417",
            feature = "stm32f427",
            feature = "stm32f429",
            feature = "stm32f437",
            feature = "stm32f439",
            feature = "stm32f446",
            feature = "stm32f469",
            feature = "stm32f479"
        ))]
        let flash_latency_step = 30_000_000;

        #[cfg(any(feature = "stm32f413", feature = "stm32f423"))]
        let flash_latency_step = 25_000_000;

        unsafe {
            let flash = &(*FLASH::ptr());
            // Adjust flash wait states
            flash.acr.modify(|_, w| {
                w.latency().bits(((sysclk - 1) / flash_latency_step) as u8);
                w.prften().set_bit();
                w.icen().set_bit();
                w.dcen().set_bit()
            })
        }
    }

    /// Initialises the hardware according to CFGR state returning a Clocks instance.
    /// Panics if overclocking is attempted.
    pub fn freeze(self) -> Clocks {
        self.freeze_internal(false)
    }

    /// Initialises the hardware according to CFGR state returning a Clocks instance.
    /// Allows overclocking.
    ///
    /// # Safety
    ///
    /// This method does not check if the clocks are bigger or smaller than the officially
    /// recommended.
    pub unsafe fn freeze_unchecked(self) -> Clocks {
        self.freeze_internal(true)
    }

    fn freeze_internal(self, unchecked: bool) -> Clocks {
        let rcc = unsafe { &*RCC::ptr() };

        //let (use_pll, sysclk_on_pll, sysclk, pll48clk) = self.pll_setup();
        let pllsrcclk = self.hse.unwrap_or(HSI);
        let sysclk = self.sysclk.unwrap_or(pllsrcclk);
        let sysclk_on_pll = sysclk != pllsrcclk;

        let plls = self.pll_setup(pllsrcclk, if sysclk_on_pll { Some(sysclk) } else { None });
        let sysclk = if sysclk_on_pll {
            plls.pllsysclk.unwrap()
        } else {
            sysclk
        };

        assert!(unchecked || !sysclk_on_pll || (SYSCLK_MIN..=SYSCLK_MAX).contains(&sysclk));

        let hclk = self.hclk.unwrap_or(sysclk);
        let (hpre_bits, hpre_div) = match (sysclk + hclk - 1) / hclk {
            0 => unreachable!(),
            1 => (HPRE_A::DIV1, 1),
            2 => (HPRE_A::DIV2, 2),
            3..=5 => (HPRE_A::DIV4, 4),
            6..=11 => (HPRE_A::DIV8, 8),
            12..=39 => (HPRE_A::DIV16, 16),
            40..=95 => (HPRE_A::DIV64, 64),
            96..=191 => (HPRE_A::DIV128, 128),
            192..=383 => (HPRE_A::DIV256, 256),
            _ => (HPRE_A::DIV512, 512),
        };

        // Calculate real AHB clock
        let hclk = sysclk / hpre_div;

        let pclk1 = self
            .pclk1
            .unwrap_or_else(|| core::cmp::min(PCLK1_MAX, hclk));
        let (ppre1_bits, ppre1) = match (hclk + pclk1 - 1) / pclk1 {
            0 => unreachable!(),
            1 => (0b000, 1),
            2 => (0b100, 2),
            3..=5 => (0b101, 4),
            6..=11 => (0b110, 8),
            _ => (0b111, 16),
        };

        // Calculate real APB1 clock
        let pclk1 = hclk / u32::from(ppre1);

        assert!(unchecked || pclk1 <= PCLK1_MAX);

        let pclk2 = self
            .pclk2
            .unwrap_or_else(|| core::cmp::min(PCLK2_MAX, hclk));
        let (ppre2_bits, ppre2) = match (hclk + pclk2 - 1) / pclk2 {
            0 => unreachable!(),
            1 => (0b000, 1),
            2 => (0b100, 2),
            3..=5 => (0b101, 4),
            6..=11 => (0b110, 8),
            _ => (0b111, 16),
        };

        // Calculate real APB2 clock
        let pclk2 = hclk / u32::from(ppre2);

        assert!(unchecked || pclk2 <= PCLK2_MAX);

        Self::flash_setup(sysclk);

        if self.hse.is_some() {
            // enable HSE and wait for it to be ready
            rcc.cr.modify(|_, w| {
                if self.hse_bypass {
                    w.hsebyp().bypassed();
                }
                w.hseon().set_bit()
            });
            while rcc.cr.read().hserdy().bit_is_clear() {}
        }

        if plls.use_pll {
            // Enable PLL
            rcc.cr.modify(|_, w| w.pllon().set_bit());

            // Enable voltage regulator overdrive if HCLK is above the limit
            #[cfg(any(
                feature = "stm32f427",
                feature = "stm32f429",
                feature = "stm32f437",
                feature = "stm32f439",
                feature = "stm32f446",
                feature = "stm32f469",
                feature = "stm32f479"
            ))]
            if hclk > 168_000_000 {
                // Enable clock for PWR peripheral
                rcc.apb1enr.modify(|_, w| w.pwren().set_bit());

                // Stall the pipeline to work around erratum 2.1.13 (DM00037591)
                cortex_m::asm::dsb();

                let pwr = unsafe { &*crate::pac::PWR::ptr() };
                pwr.cr.modify(|_, w| w.oden().set_bit());
                while pwr.csr.read().odrdy().bit_is_clear() {}
                pwr.cr.modify(|_, w| w.odswen().set_bit());
                while pwr.csr.read().odswrdy().bit_is_clear() {}
            }

            // Wait for PLL to stabilise
            while rcc.cr.read().pllrdy().bit_is_clear() {}
        }

        #[cfg(not(feature = "stm32f410"))]
        if plls.use_i2spll {
            // Enable PLL.
            rcc.cr.modify(|_, w| w.plli2son().set_bit());

            // Wait for PLL to stabilise
            while rcc.cr.read().plli2srdy().bit_is_clear() {}
        }

        #[cfg(any(
            feature = "stm32f427",
            feature = "stm32f429",
            feature = "stm32f437",
            feature = "stm32f439",
            feature = "stm32f446",
            feature = "stm32f469",
            feature = "stm32f479",
        ))]
        if plls.use_saipll {
            // Enable PLL.
            rcc.cr.modify(|_, w| w.pllsaion().set_bit());

            // Wait for PLL to stabilise
            while rcc.cr.read().pllsairdy().bit_is_clear() {}
        }

        // Select I2S and SAI clocks
        plls.i2s.config_clocksel();
        #[cfg(any(
            feature = "stm32f413",
            feature = "stm32f423",
            feature = "stm32f427",
            feature = "stm32f429",
            feature = "stm32f437",
            feature = "stm32f439",
            feature = "stm32f446",
            feature = "stm32f469",
            feature = "stm32f479",
        ))]
        plls.sai.config_clocksel();

        // Set scaling factors
        rcc.cfgr.modify(|_, w| unsafe {
            w.ppre2()
                .bits(ppre2_bits)
                .ppre1()
                .bits(ppre1_bits)
                .hpre()
                .variant(hpre_bits)
        });

        // Wait for the new prescalers to kick in
        // "The clocks are divided with the new prescaler factor from 1 to 16 AHB cycles after write"
        cortex_m::asm::delay(16);

        // Select system clock source
        rcc.cfgr.modify(|_, w| {
            w.sw().variant(if sysclk_on_pll {
                SW_A::PLL
            } else if self.hse.is_some() {
                SW_A::HSE
            } else {
                SW_A::HSI
            })
        });

        let clocks = Clocks {
            hclk: Hertz(hclk),
            pclk1: Hertz(pclk1),
            pclk2: Hertz(pclk2),
            ppre1,
            ppre2,
            sysclk: Hertz(sysclk),
            pll48clk: plls.pll48clk.map(Hertz),

            #[cfg(not(any(
                feature = "stm32f412",
                feature = "stm32f413",
                feature = "stm32f423",
                feature = "stm32f446",
            )))]
            i2s_clk: plls.i2s.i2s_clk.map(Hertz),
            #[cfg(any(
                feature = "stm32f412",
                feature = "stm32f413",
                feature = "stm32f423",
                feature = "stm32f446",
            ))]
            i2s_apb1_clk: plls.i2s.i2s_apb1_clk.map(Hertz),
            #[cfg(any(
                feature = "stm32f412",
                feature = "stm32f413",
                feature = "stm32f423",
                feature = "stm32f446",
            ))]
            i2s_apb2_clk: plls.i2s.i2s_apb2_clk.map(Hertz),

            #[cfg(any(
                feature = "stm32f413",
                feature = "stm32f423",
                feature = "stm32f427",
                feature = "stm32f429",
                feature = "stm32f437",
                feature = "stm32f439",
                feature = "stm32f469",
                feature = "stm32f479",
            ))]
            saia_clk: plls.sai.sai1_clk.map(Hertz),
            #[cfg(any(
                feature = "stm32f413",
                feature = "stm32f423",
                feature = "stm32f427",
                feature = "stm32f429",
                feature = "stm32f437",
                feature = "stm32f439",
                feature = "stm32f469",
                feature = "stm32f479",
            ))]
            saib_clk: plls.sai.sai2_clk.map(Hertz),
            #[cfg(feature = "stm32f446")]
            sai1_clk: plls.sai.sai1_clk.map(Hertz),
            #[cfg(feature = "stm32f446")]
            sai2_clk: plls.sai.sai2_clk.map(Hertz),
        };

        if self.pll48clk {
            assert!(clocks.is_pll48clk_valid());
        }

        clocks
    }
}

struct PllSetup {
    use_pll: bool,
    #[cfg(not(feature = "stm32f410"))]
    use_i2spll: bool,
    #[cfg(any(
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f446",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    use_saipll: bool,

    pllsysclk: Option<u32>,
    pll48clk: Option<u32>,

    i2s: RealI2sClocks,

    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f446",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    sai: RealSaiClocks,
}

#[cfg(any(
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f446",
))]
struct I2sClocks {
    /// True if the clock for the APB1 I2S instances is identical to I2S_CKIN.
    i2s_apb1_ext: bool,
    /// True if the clock for the APB2 I2S instances is identical to I2S_CKIN.
    i2s_apb2_ext: bool,
    /// Target for the I2S PLL output.
    pll_i2s_clk: Option<u32>,
}

#[cfg(not(any(
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f446",
)))]
struct I2sClocks {
    /// True if the clock for I2S is identical to I2S_CKIN.
    i2s_ext: bool,
    /// Target for the I2S PLL output.
    pll_i2s_clk: Option<u32>,
}

impl I2sClocks {
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    fn real(&self, pll_i2s_clk: Option<u32>, i2s_ckin: Option<u32>) -> RealI2sClocks {
        RealI2sClocks {
            i2s_apb1_ext: self.i2s_apb1_ext,
            i2s_apb2_ext: self.i2s_apb2_ext,
            i2s_apb1_clk: if self.i2s_apb1_ext {
                i2s_ckin
            } else {
                pll_i2s_clk
            },
            i2s_apb2_clk: if self.i2s_apb2_ext {
                i2s_ckin
            } else {
                pll_i2s_clk
            },
        }
    }

    #[cfg(not(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    )))]
    fn real(&self, pll_i2s_clk: Option<u32>, i2s_ckin: Option<u32>) -> RealI2sClocks {
        RealI2sClocks {
            i2s_ext: self.i2s_ext,
            i2s_clk: if self.i2s_ext { i2s_ckin } else { pll_i2s_clk },
        }
    }
}

#[cfg(any(
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f446",
))]
struct RealI2sClocks {
    i2s_apb1_ext: bool,
    i2s_apb2_ext: bool,
    i2s_apb1_clk: Option<u32>,
    i2s_apb2_clk: Option<u32>,
}

#[cfg(not(any(
    feature = "stm32f412",
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f446",
)))]
struct RealI2sClocks {
    i2s_ext: bool,
    i2s_clk: Option<u32>,
}

impl RealI2sClocks {
    fn config_clocksel(&self) {
        let rcc = unsafe { &*RCC::ptr() };

        #[cfg(not(any(
            feature = "stm32f410",
            feature = "stm32f412",
            feature = "stm32f413",
            feature = "stm32f423",
            feature = "stm32f446",
        )))]
        if self.i2s_ext {
            rcc.cfgr.modify(|_, w| w.i2ssrc().ckin());
        } else {
            rcc.cfgr.modify(|_, w| w.i2ssrc().plli2s());
        }
        #[cfg(feature = "stm32f410")]
        if self.i2s_ext {
            rcc.dckcfgr.modify(|_, w| w.i2ssrc().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.i2ssrc().pllclkr());
        }
        #[cfg(any(
            feature = "stm32f412",
            feature = "stm32f413",
            feature = "stm32f423",
            feature = "stm32f446",
        ))]
        if self.i2s_apb1_ext {
            rcc.dckcfgr.modify(|_, w| w.i2s1src().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.i2s1src().plli2sr());
        }
        #[cfg(any(
            feature = "stm32f412",
            feature = "stm32f413",
            feature = "stm32f423",
            feature = "stm32f446",
        ))]
        if self.i2s_apb2_ext {
            rcc.dckcfgr.modify(|_, w| w.i2s2src().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.i2s2src().plli2sr());
        }
    }
}

#[cfg(any(
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
struct SaiClocks {
    /// True if the clock for SAI1 (STM32F446) or SAIA (all other models) is identical to I2S_CKIN.
    sai1_ext: bool,
    /// True if the clock for SAIB is identical to I2S_CKIN.
    #[cfg(not(feature = "stm32f446"))]
    sai2_ext: bool,
    /// Target for the SAI clock as generated by PLL and SAI clock divider.
    pll_sai_clk: Option<u32>,
}

#[cfg(any(
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
impl SaiClocks {
    fn real(&self, pll_sai_clk: Option<u32>, i2s_ckin: Option<u32>) -> RealSaiClocks {
        RealSaiClocks {
            sai1_ext: self.sai1_ext,
            #[cfg(not(feature = "stm32f446"))]
            sai2_ext: self.sai2_ext,
            sai1_clk: if self.sai1_ext { i2s_ckin } else { pll_sai_clk },
            #[cfg(not(feature = "stm32f446"))]
            sai2_clk: if self.sai2_ext { i2s_ckin } else { pll_sai_clk },
            #[cfg(feature = "stm32f446")]
            sai2_clk: pll_sai_clk,
        }
    }
}

#[cfg(any(
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
struct RealSaiClocks {
    sai1_ext: bool,
    #[cfg(not(feature = "stm32f446"))]
    sai2_ext: bool,
    sai1_clk: Option<u32>,
    sai2_clk: Option<u32>,
}

#[cfg(any(
    feature = "stm32f413",
    feature = "stm32f423",
    feature = "stm32f427",
    feature = "stm32f429",
    feature = "stm32f437",
    feature = "stm32f439",
    feature = "stm32f446",
    feature = "stm32f469",
    feature = "stm32f479",
))]
impl RealSaiClocks {
    fn config_clocksel(&self) {
        let rcc = unsafe { &*RCC::ptr() };

        // Configure SAI clocks.
        #[cfg(not(feature = "stm32f446",))]
        if self.sai1_ext {
            rcc.dckcfgr.modify(|_, w| w.sai1asrc().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.sai1asrc().pllsai());
        }
        #[cfg(not(feature = "stm32f446",))]
        if self.sai2_ext {
            rcc.dckcfgr.modify(|_, w| w.sai1bsrc().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.sai1bsrc().pllsai());
        }
        #[cfg(feature = "stm32f446")]
        if self.sai1_ext {
            rcc.dckcfgr.modify(|_, w| w.sai1src().i2s_ckin());
        } else {
            rcc.dckcfgr.modify(|_, w| w.sai1src().pllsai());
        }
    }
}

/// Frozen clock frequencies
///
/// The existence of this value indicates that the clock configuration can no longer be changed
#[derive(Clone, Copy)]
pub struct Clocks {
    hclk: Hertz,
    pclk1: Hertz,
    pclk2: Hertz,
    ppre1: u8,
    ppre2: u8,
    sysclk: Hertz,
    pll48clk: Option<Hertz>,

    #[cfg(not(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    )))]
    i2s_clk: Option<Hertz>,
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    i2s_apb1_clk: Option<Hertz>,
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    i2s_apb2_clk: Option<Hertz>,

    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    saia_clk: Option<Hertz>,
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    saib_clk: Option<Hertz>,
    #[cfg(feature = "stm32f446")]
    sai1_clk: Option<Hertz>,
    #[cfg(feature = "stm32f446")]
    sai2_clk: Option<Hertz>,
}

impl Clocks {
    /// Returns the frequency of the AHB1
    pub fn hclk(&self) -> Hertz {
        self.hclk
    }

    /// Returns the frequency of the APB1
    pub fn pclk1(&self) -> Hertz {
        self.pclk1
    }

    /// Returns the frequency of the APB2
    pub fn pclk2(&self) -> Hertz {
        self.pclk2
    }

    /// Returns the prescaler of the APB1
    pub fn ppre1(&self) -> u8 {
        self.ppre1
    }

    /// Returns the prescaler of the APB2
    pub fn ppre2(&self) -> u8 {
        self.ppre2
    }

    /// Returns the system (core) frequency
    pub fn sysclk(&self) -> Hertz {
        self.sysclk
    }

    /// Returns the frequency of the PLL48 clock line
    pub fn pll48clk(&self) -> Option<Hertz> {
        self.pll48clk
    }

    /// Returns true if the PLL48 clock is within USB
    /// specifications. It is required to use the USB functionality.
    pub fn is_pll48clk_valid(&self) -> bool {
        // USB specification allows +-0.25%
        self.pll48clk
            .map(|freq| (48_000_000 - freq.0 as i32).abs() <= 120_000)
            .unwrap_or(false)
    }

    /// Returns the frequency of the I2S clock.
    #[cfg(not(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    )))]
    pub fn i2s_clk(&self) -> Option<Hertz> {
        self.i2s_clk
    }
    /// Returns the frequency of the first I2S clock (for the I2S peripherals on APB1).
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    pub fn i2s_apb1_clk(&self) -> Option<Hertz> {
        self.i2s_apb1_clk
    }
    /// Returns the frequency of the second I2S clock (for the I2S peripherals on APB2).
    #[cfg(any(
        feature = "stm32f412",
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f446",
    ))]
    pub fn i2s_apb2_clk(&self) -> Option<Hertz> {
        self.i2s_apb2_clk
    }

    /// Returns the frequency of the SAI A clock.
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    pub fn saia_clk(&self) -> Option<Hertz> {
        self.saia_clk
    }
    /// Returns the frequency of the SAI B clock.
    #[cfg(any(
        feature = "stm32f413",
        feature = "stm32f423",
        feature = "stm32f427",
        feature = "stm32f429",
        feature = "stm32f437",
        feature = "stm32f439",
        feature = "stm32f469",
        feature = "stm32f479",
    ))]
    pub fn saib_clk(&self) -> Option<Hertz> {
        self.saib_clk
    }
    /// Returns the frequency of the SAI1 clock.
    #[cfg(feature = "stm32f446")]
    pub fn sai1_clk(&self) -> Option<Hertz> {
        self.sai1_clk
    }
    /// Returns the frequency of the SAI2 clock.
    #[cfg(feature = "stm32f446")]
    pub fn sai2_clk(&self) -> Option<Hertz> {
        self.sai2_clk
    }
}