summaryrefslogtreecommitdiff
path: root/Radio/HW/BladeRF/src/bladerf.c
blob: f19c3a6836e940c0796dddb310ac4bc6a7966903 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
/*
 * This file is part of the bladeRF project:
 *   http://www.github.com/nuand/bladeRF
 *
 * Copyright (C) 2013-2016 Nuand LLC
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <libbladeRF.h>

#include "log.h"
#include "rel_assert.h"
#define LOGGER_ID_STRING
#include "logger_entry.h"
#include "logger_id.h"

#include "backend/backend.h"
#include "backend/usb/usb.h"
#include "board/board.h"
#include "conversions.h"
#include "driver/fx3_fw.h"
#include "device_calibration.h"
#include "streaming/async.h"
#include "version.h"

#include "expansion/xb100.h"
#include "expansion/xb200.h"
#include "expansion/xb300.h"

#include "devinfo.h"
#include "helpers/configfile.h"
#include "helpers/file.h"
#include "helpers/have_cap.h"
#include "helpers/interleave.h"

#define CHECK_NULL(...) do { \
    const void* _args[] = { __VA_ARGS__, NULL }; \
    for (size_t _i = 0; _args[_i] != NULL; ++_i) { \
        if (_args[_i] == NULL) { \
            log_error("%s:%d: Argument %zu is a NULL pointer\n", __FILE__, __LINE__, _i + 1); \
            return BLADERF_ERR_INVAL; \
        } \
    } \
} while (0)

#define CHECK_STATUS(fn)                                \
    do {                                                \
        status = fn;                                    \
        if (status != 0) {                              \
            log_error("%s: %s %s\n", __FUNCTION__, #fn, \
                      bladerf_strerror(status));        \
            goto error;                                 \
        }                                               \
    } while (0)


/******************************************************************************/
/* Private Function Declarations */
/******************************************************************************/

/**
 * Sets up the register configuration for oversample feature.
 *
 * @param       dev         Device handle
 *
 * @return 0 on success, value from \ref RETCODES list on failure
 */
int bladerf_set_oversample_register_config(struct bladerf *dev);

/******************************************************************************/
/* Open / Close */
/******************************************************************************/

/* dev path becomes device specifier string (osmosdr-like) */
int bladerf_open(struct bladerf **dev, const char *dev_id)
{
    struct bladerf_devinfo devinfo;
    int status;

    *dev = NULL;

    /* Populate dev-info from string */
    status = str2devinfo(dev_id, &devinfo);
    if (!status) {
        status = bladerf_open_with_devinfo(dev, &devinfo);
    }

    return status;
}

int bladerf_open_with_devinfo(struct bladerf **opened_device,
                              struct bladerf_devinfo *devinfo)
{
    struct bladerf *dev;
    struct bladerf_devinfo any_device;
    unsigned int i;
    int status;

    if (devinfo == NULL) {
        bladerf_init_devinfo(&any_device);
        devinfo = &any_device;
    }

    *opened_device = NULL;

    dev = calloc(1, sizeof(struct bladerf));
    if (dev == NULL) {
        return BLADERF_ERR_MEM;
    }

    /* Open backend */
    status = backend_open(dev, devinfo);
    if (status != 0) {
        free(dev);
        return status;
    }

    /* Find matching board */
    for (i = 0; i < bladerf_boards_len; i++) {
        if (bladerf_boards[i]->matches(dev)) {
            dev->board = bladerf_boards[i];
            break;
        }
    }
    /* If no matching board was found */
    if (i == bladerf_boards_len) {
        dev->backend->close(dev);
        free(dev);
        return BLADERF_ERR_NODEV;
    }

    MUTEX_INIT(&dev->lock);

    /* Open board */
    status = dev->board->open(dev, devinfo);

    if (status < 0) {
        bladerf_close(dev);
        return status;
    }

    /* Load configuration file */
    status = config_load_options_file(dev);

    if (status < 0) {
        bladerf_close(dev);
        return status;
    }

    *opened_device = dev;

    return 0;
}

int bladerf_get_devinfo(struct bladerf *dev, struct bladerf_devinfo *info)
{
    if (dev) {
        MUTEX_LOCK(&dev->lock);
        memcpy(info, &dev->ident, sizeof(struct bladerf_devinfo));
        MUTEX_UNLOCK(&dev->lock);
        return 0;
    } else {
        return BLADERF_ERR_INVAL;
    }
}

int bladerf_get_backendinfo(struct bladerf *dev, struct bladerf_backendinfo *info)
{
    if (dev) {
        MUTEX_LOCK(&dev->lock);
        info->lock_count = 1;
        info->lock = &dev->lock;

        info->handle_count = 1;
        dev->backend->get_handle(dev, &info->handle);
        MUTEX_UNLOCK(&dev->lock);
        return 0;
    } else {
        return BLADERF_ERR_INVAL;
    }
}

void bladerf_close(struct bladerf *dev)
{
    if (dev) {
        MUTEX_LOCK(&dev->lock);

        dev->board->close(dev);

        if (dev->backend) {
            dev->backend->close(dev);
        }

        /** Free gain table entries */
        for (int i = 0; i < NUM_GAIN_CAL_TBLS; i++) {
            gain_cal_tbl_free(&dev->gain_tbls[i]);
        }

        MUTEX_UNLOCK(&dev->lock);

        free(dev);
    }
}

/******************************************************************************/
/* FX3 Firmware (common to bladerf1 and bladerf2) */
/******************************************************************************/

int bladerf_jump_to_bootloader(struct bladerf *dev)
{
    int status;

    if (!dev->backend->jump_to_bootloader) {
        return BLADERF_ERR_UNSUPPORTED;
    }

    MUTEX_LOCK(&dev->lock);

    status = dev->backend->jump_to_bootloader(dev);

    MUTEX_UNLOCK(&dev->lock);

    return status;
}

int bladerf_get_bootloader_list(struct bladerf_devinfo **devices)
{
    return probe(BACKEND_PROBE_FX3_BOOTLOADER, devices);
}

int bladerf_load_fw_from_bootloader(const char *device_identifier,
                                    bladerf_backend backend,
                                    uint8_t bus,
                                    uint8_t addr,
                                    const char *file)
{
    int status;
    uint8_t *buf;
    size_t buf_len;
    struct fx3_firmware *fw = NULL;
    struct bladerf_devinfo devinfo;

    if (device_identifier == NULL) {
        bladerf_init_devinfo(&devinfo);
        devinfo.backend  = backend;
        devinfo.usb_bus  = bus;
        devinfo.usb_addr = addr;
    } else {
        status = str2devinfo(device_identifier, &devinfo);
        if (status != 0) {
            return status;
        }
    }

    status = file_read_buffer(file, &buf, &buf_len);
    if (status != 0) {
        return status;
    }

    status = fx3_fw_parse(&fw, buf, buf_len);
    free(buf);
    if (status != 0) {
        return status;
    }

    assert(fw != NULL);

    status = backend_load_fw_from_bootloader(devinfo.backend, devinfo.usb_bus,
                                             devinfo.usb_addr, fw);

    fx3_fw_free(fw);

    return status;
}

int bladerf_get_fw_log(struct bladerf *dev, const char *filename)
{
    int status;
    FILE *f = NULL;
    logger_entry e;

    MUTEX_LOCK(&dev->lock);

    if (!have_cap(dev->board->get_capabilities(dev),
                  BLADERF_CAP_READ_FW_LOG_ENTRY)) {
        struct bladerf_version fw_version;

        if (dev->board->get_fw_version(dev, &fw_version) == 0) {
            log_debug("FX3 FW v%s does not support log retrieval.\n",
                      fw_version.describe);
        }

        status = BLADERF_ERR_UNSUPPORTED;
        goto error;
    }

    if (filename != NULL) {
        f = fopen(filename, "w");
        if (f == NULL) {
            switch (errno) {
                case ENOENT:
                    status = BLADERF_ERR_NO_FILE;
                    break;
                case EACCES:
                    status = BLADERF_ERR_PERMISSION;
                    break;
                default:
                    status = BLADERF_ERR_IO;
                    break;
            }
            goto error;
        }
    } else {
        f = stdout;
    }

    do {
        status = dev->backend->read_fw_log(dev, &e);
        if (status != 0) {
            log_debug("Failed to read FW log: %s\n", bladerf_strerror(status));
            goto error;
        }

        if (e == LOG_ERR) {
            fprintf(f, "<Unexpected error>,,\n");
        } else if (e != LOG_EOF) {
            uint8_t file_id;
            uint16_t line;
            uint16_t data;
            const char *src_file;

            logger_entry_unpack(e, &file_id, &line, &data);
            src_file = logger_id_string(file_id);

            fprintf(f, "%s, %u, 0x%04x\n", src_file, line, data);
        }
    } while (e != LOG_EOF && e != LOG_ERR);

error:
    MUTEX_UNLOCK(&dev->lock);

    if (f != NULL && f != stdout) {
        fclose(f);
    }

    return status;
}

/******************************************************************************/
/* Properties */
/******************************************************************************/

bladerf_dev_speed bladerf_device_speed(struct bladerf *dev)
{
    bladerf_dev_speed speed;
    MUTEX_LOCK(&dev->lock);

    speed = dev->board->device_speed(dev);

    MUTEX_UNLOCK(&dev->lock);
    return speed;
}

int bladerf_get_serial(struct bladerf *dev, char *serial)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    /** TODO: add deprecation warning */

    status = dev->board->get_serial(dev, serial);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_serial_struct(struct bladerf *dev,
                              struct bladerf_serial *serial)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    char serialstr[sizeof(serial->serial)];

    status = dev->board->get_serial(dev, serialstr);

    if (status >= 0) {
        strncpy(serial->serial, serialstr, sizeof(serial->serial));
        serial->serial[sizeof(serial->serial)-1] = '\0';
    }

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_fpga_size(struct bladerf *dev, bladerf_fpga_size *size)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_fpga_size(dev, size);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_fpga_bytes(struct bladerf *dev, size_t *size)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_fpga_bytes(dev, size);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_flash_size(struct bladerf *dev, uint32_t *size, bool *is_guess)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_flash_size(dev, size, is_guess);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_is_fpga_configured(struct bladerf *dev)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->is_fpga_configured(dev);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_fpga_source(struct bladerf *dev, bladerf_fpga_source *source)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_fpga_source(dev, source);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

const char *bladerf_get_board_name(struct bladerf *dev)
{
    return dev->board->name;
}

size_t bladerf_get_channel_count(struct bladerf *dev, bladerf_direction dir)
{
    return dev->board->get_channel_count(dev, dir);
}

/******************************************************************************/
/* Versions */
/******************************************************************************/

int bladerf_fpga_version(struct bladerf *dev, struct bladerf_version *version)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_fpga_version(dev, version);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_fw_version(struct bladerf *dev, struct bladerf_version *version)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_fw_version(dev, version);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

void bladerf_version(struct bladerf_version *version)
{
/* Sanity checks for version reporting mismatches */
#ifndef LIBBLADERF_API_VERSION
#error LIBBLADERF_API_VERSION is missing
#endif
#if LIBBLADERF_VERSION_MAJOR != ((LIBBLADERF_API_VERSION >> 24) & 0xff)
#error LIBBLADERF_API_VERSION: Major version mismatch
#endif
#if LIBBLADERF_VERSION_MINOR != ((LIBBLADERF_API_VERSION >> 16) & 0xff)
#error LIBBLADERF_API_VERSION: Minor version mismatch
#endif
#if LIBBLADERF_VERSION_PATCH != ((LIBBLADERF_API_VERSION >> 8) & 0xff)
#error LIBBLADERF_API_VERSION: Patch version mismatch
#endif
    version->major    = LIBBLADERF_VERSION_MAJOR;
    version->minor    = LIBBLADERF_VERSION_MINOR;
    version->patch    = LIBBLADERF_VERSION_PATCH;
    version->describe = LIBBLADERF_VERSION;
}

/******************************************************************************/
/* Enable/disable */
/******************************************************************************/

int bladerf_enable_module(struct bladerf *dev, bladerf_channel ch, bool enable)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->enable_module(dev, ch, enable);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Gain */
/******************************************************************************/

int bladerf_set_gain(struct bladerf *dev, bladerf_channel ch, int gain)
{
    int status;
    bladerf_gain_mode gain_mode;
    bladerf_frequency freq;
    bladerf_gain assigned_gain = gain;
    MUTEX_LOCK(&dev->lock);

    /* Change gain mode to manual if ch = RX */
    if (BLADERF_CHANNEL_IS_TX(ch) == false) {
        status = dev->board->get_gain_mode(dev, ch, &gain_mode);
        if (status != 0) {
            log_error("Failed to get gain mode\n");
            goto error;
        }

        if (gain_mode != BLADERF_GAIN_MGC) {
            log_warning("Setting gain mode to manual\n");
            status = dev->board->set_gain_mode(dev, ch, BLADERF_GAIN_MGC);
            if (status != 0) {
                log_error("Failed to set gain mode\n");
                goto error;
            }
        }
    }

    dev->gain_tbls[ch].gain_target = gain;

    if (dev->gain_tbls[ch].enabled == true) {
        dev->board->get_frequency(dev, ch, &freq);
        get_gain_correction(dev, freq, ch, &assigned_gain);
    }

    status = dev->board->set_gain(dev, ch, assigned_gain);
    if (status != 0) {
        log_error("Failed to set gain\n");
        goto error;
    }

error:
    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_gain(struct bladerf *dev, bladerf_channel ch, int *gain)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_gain(dev, ch, gain);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_set_gain_mode(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_gain_mode mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_gain_mode(dev, ch, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_gain_mode(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_gain_mode *mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_gain_mode(dev, ch, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_gain_modes(struct bladerf *dev,
                           bladerf_channel ch,
                           struct bladerf_gain_modes const **modes)
{
    return dev->board->get_gain_modes(dev, ch, modes);
}

int bladerf_get_gain_range(struct bladerf *dev,
                           bladerf_channel ch,
                           struct bladerf_range const **range)
{
    return dev->board->get_gain_range(dev, ch, range);
}

int bladerf_set_gain_stage(struct bladerf *dev,
                           bladerf_channel ch,
                           const char *stage,
                           bladerf_gain gain)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_gain_stage(dev, ch, stage, gain);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_gain_stage(struct bladerf *dev,
                           bladerf_channel ch,
                           const char *stage,
                           bladerf_gain *gain)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_gain_stage(dev, ch, stage, gain);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_gain_stage_range(struct bladerf *dev,
                                 bladerf_channel ch,
                                 const char *stage,
                                 struct bladerf_range const **range)
{
    return dev->board->get_gain_stage_range(dev, ch, stage, range);
}

int bladerf_get_gain_stages(struct bladerf *dev,
                            bladerf_channel ch,
                            const char **stages,
                            size_t count)
{
    return dev->board->get_gain_stages(dev, ch, stages, count);
}

/******************************************************************************/
/* Sample Rate */
/******************************************************************************/

int bladerf_set_sample_rate(struct bladerf *dev,
                            bladerf_channel ch,
                            bladerf_sample_rate rate,
                            bladerf_sample_rate *actual)
{
    int status;
    bladerf_feature feature = dev->feature;

    MUTEX_LOCK(&dev->lock);
    status = dev->board->set_sample_rate(dev, ch, rate, actual);
    MUTEX_UNLOCK(&dev->lock);

    /*****************************************************
      Sample rate assignments clear previous register
      values. We must reassign oversample register config
      for every set_samplerate().
    *******************************************************/
    if ((feature & BLADERF_FEATURE_OVERSAMPLE)) {
        status = bladerf_set_oversample_register_config(dev);
        if (status != 0) {
            log_error("Oversample register config failure\n");
        }
    }

    return status;
}

int bladerf_get_sample_rate(struct bladerf *dev,
                            bladerf_channel ch,
                            bladerf_sample_rate *rate)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_sample_rate(dev, ch, rate);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_sample_rate_range(struct bladerf *dev,
                                  bladerf_channel ch,
                                  const struct bladerf_range **range)
{
    return dev->board->get_sample_rate_range(dev, ch, range);
}

int bladerf_set_rational_sample_rate(struct bladerf *dev,
                                     bladerf_channel ch,
                                     struct bladerf_rational_rate *rate,
                                     struct bladerf_rational_rate *actual)
{
    int status;
    bladerf_feature feature = dev->feature;

    MUTEX_LOCK(&dev->lock);
    status = dev->board->set_rational_sample_rate(dev, ch, rate, actual);
    MUTEX_UNLOCK(&dev->lock);

    /*****************************************************
      Register config for OVERSAMPLE operation

      Sample rate assignments clear previous register
      values. We must reassign for every set_samplerate().

      Note: bladerf_set_rfic_register is mutex locked. Must
            be placed outside of a mutex lock like above.
    *******************************************************/
    if ((feature & BLADERF_FEATURE_OVERSAMPLE)) {
        status = bladerf_set_oversample_register_config(dev);
        if (status != 0) {
            log_error("Oversample register config failure\n");
        }
    }

    return status;
}

int bladerf_get_rational_sample_rate(struct bladerf *dev,
                                     bladerf_channel ch,
                                     struct bladerf_rational_rate *rate)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_rational_sample_rate(dev, ch, rate);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Bandwidth */
/******************************************************************************/

int bladerf_set_bandwidth(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_bandwidth bandwidth,
                          bladerf_bandwidth *actual)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_bandwidth(dev, ch, bandwidth, actual);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_bandwidth(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_bandwidth *bandwidth)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_bandwidth(dev, ch, bandwidth);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_bandwidth_range(struct bladerf *dev,
                                bladerf_channel ch,
                                const struct bladerf_range **range)
{
    return dev->board->get_bandwidth_range(dev, ch, range);
}

/******************************************************************************/
/* Frequency */
/******************************************************************************/

int bladerf_set_frequency(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_frequency frequency)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_frequency(dev, ch, frequency);

    if (dev->gain_tbls[ch].enabled && status == 0) {
        status = apply_gain_correction(dev, ch, frequency);
        if (status != 0) {
            log_error("Failed to set gain correction\n");
        }
    }

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_frequency(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_frequency *frequency)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_frequency(dev, ch, frequency);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_frequency_range(struct bladerf *dev,
                                bladerf_channel ch,
                                const struct bladerf_range **range)
{
    return dev->board->get_frequency_range(dev, ch, range);
}

int bladerf_select_band(struct bladerf *dev,
                        bladerf_channel ch,
                        bladerf_frequency frequency)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->select_band(dev, ch, frequency);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* RF Ports*/
/******************************************************************************/

int bladerf_set_rf_port(struct bladerf *dev,
                        bladerf_channel ch,
                        const char *port)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_rf_port(dev, ch, port);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_rf_port(struct bladerf *dev,
                        bladerf_channel ch,
                        const char **port)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_rf_port(dev, ch, port);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_rf_ports(struct bladerf *dev,
                         bladerf_channel ch,
                         const char **ports,
                         unsigned int count)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_rf_ports(dev, ch, ports, count);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Scheduled Tuning */
/******************************************************************************/

int bladerf_get_quick_tune(struct bladerf *dev,
                           bladerf_channel ch,
                           struct bladerf_quick_tune *quick_tune)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_quick_tune(dev, ch, quick_tune);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_print_quick_tune(struct bladerf *dev, const struct bladerf_quick_tune *qt) {
    if (dev == NULL || qt == NULL) {
        log_error("Device handle or quick tune structure is NULL.\n");
        return BLADERF_ERR_INVAL;
    }

    const char *board_name = bladerf_get_board_name(dev);
    if (board_name == NULL) {
        log_error("Failed to get board name.\n");
        return BLADERF_ERR_UNEXPECTED;
    }

    printf("board: %s\n", board_name);
    if (strcmp(board_name, "bladerf1") == 0) {
        printf("freqsel: %u\n", qt->freqsel);
        printf("vcocap: %u\n", qt->vcocap);
        printf("nint: %u\n", qt->nint);
        printf("nfrac: %u\n", qt->nfrac);
        printf("flags: %u\n", qt->flags);
        printf("xb_gpio: %u\n", qt->xb_gpio);
    } else if (strcmp(board_name, "bladerf2") == 0) {
        printf("nios_profile: %u\n", qt->nios_profile);
        printf("rffe_profile: %u\n", qt->rffe_profile);
        printf("port: %u\n", qt->port);
        printf("spdt: %u\n", qt->spdt);
    } else {
        log_error("Unknown bladeRF board name: %s\n", board_name);
        return BLADERF_ERR_UNEXPECTED;
    }

    return 0;
}

int bladerf_schedule_retune(struct bladerf *dev,
                            bladerf_channel ch,
                            bladerf_timestamp timestamp,
                            bladerf_frequency frequency,
                            struct bladerf_quick_tune *quick_tune)

{
    int status;
    MUTEX_LOCK(&dev->lock);

    status =
        dev->board->schedule_retune(dev, ch, timestamp, frequency, quick_tune);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_cancel_scheduled_retunes(struct bladerf *dev, bladerf_channel ch)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->cancel_scheduled_retunes(dev, ch);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* DC/Phase/Gain Correction */
/******************************************************************************/

int bladerf_get_correction(struct bladerf *dev,
                           bladerf_channel ch,
                           bladerf_correction corr,
                           bladerf_correction_value *value)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_correction(dev, ch, corr, value);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_set_correction(struct bladerf *dev,
                           bladerf_channel ch,
                           bladerf_correction corr,
                           bladerf_correction_value value)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_correction(dev, ch, corr, value);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Trigger */
/******************************************************************************/

int bladerf_trigger_init(struct bladerf *dev,
                         bladerf_channel ch,
                         bladerf_trigger_signal signal,
                         struct bladerf_trigger *trigger)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trigger_init(dev, ch, signal, trigger);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_trigger_arm(struct bladerf *dev,
                        const struct bladerf_trigger *trigger,
                        bool arm,
                        uint64_t resv1,
                        uint64_t resv2)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trigger_arm(dev, trigger, arm, resv1, resv2);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_trigger_fire(struct bladerf *dev,
                         const struct bladerf_trigger *trigger)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trigger_fire(dev, trigger);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_trigger_state(struct bladerf *dev,
                          const struct bladerf_trigger *trigger,
                          bool *is_armed,
                          bool *has_fired,
                          bool *fire_requested,
                          uint64_t *reserved1,
                          uint64_t *reserved2)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trigger_state(dev, trigger, is_armed, has_fired,
                                       fire_requested, reserved1, reserved2);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Streaming */
/******************************************************************************/

int bladerf_init_stream(struct bladerf_stream **stream,
                        struct bladerf *dev,
                        bladerf_stream_cb callback,
                        void ***buffers,
                        size_t num_buffers,
                        bladerf_format format,
                        size_t samples_per_buffer,
                        size_t num_transfers,
                        void *data)
{
    int status;
    bladerf_sample_rate tx_samp_rate;
    bladerf_sample_rate rx_samp_rate;
    MUTEX_LOCK(&dev->lock);

    if (format == BLADERF_FORMAT_SC8_Q7 || format == BLADERF_FORMAT_SC8_Q7_META) {
        if (strcmp(bladerf_get_board_name(dev), "bladerf2") != 0) {
            log_error("bladeRF 2.0 required for 8bit format\n");
            return BLADERF_ERR_UNSUPPORTED;
        }
    }

    status = dev->board->init_stream(stream, dev, callback, buffers,
                                     num_buffers, format, samples_per_buffer,
                                     num_transfers, data);

    dev->board->get_sample_rate(dev, BLADERF_MODULE_TX, &tx_samp_rate);
    if (tx_samp_rate) {
        if (tx_samp_rate < num_transfers * samples_per_buffer / (*stream)->transfer_timeout) {
            log_warning("TX samples may be dropped.\n");
            log_warning("Condition to meet: samp_rate > num_transfers * samples_per_buffer / transfer_timeout\n");
        }
    }

    dev->board->get_sample_rate(dev, BLADERF_MODULE_RX, &rx_samp_rate);
    if (rx_samp_rate) {
        if (rx_samp_rate < num_transfers * samples_per_buffer / (*stream)->transfer_timeout) {
            log_warning("RX samples may be dropped.\n");
            log_warning("Condition to meet: samp_rate > num_transfers * samples_per_buffer / transfer_timeout\n");
        }
    }

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_stream(struct bladerf_stream *stream, bladerf_channel_layout layout)
{
    return stream->dev->board->stream(stream, layout);
}

int bladerf_submit_stream_buffer(struct bladerf_stream *stream,
                                 void *buffer,
                                 unsigned int timeout_ms)
{
    return stream->dev->board->submit_stream_buffer(stream, buffer, timeout_ms,
                                                    false);
}

int bladerf_submit_stream_buffer_nb(struct bladerf_stream *stream, void *buffer)
{
    return stream->dev->board->submit_stream_buffer(stream, buffer, 0, true);
}

void bladerf_deinit_stream(struct bladerf_stream *stream)
{
    if (stream) {
        stream->dev->board->deinit_stream(stream);
    }
}

int bladerf_set_stream_timeout(struct bladerf *dev,
                               bladerf_direction dir,
                               unsigned int timeout)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_stream_timeout(dev, dir, timeout);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_stream_timeout(struct bladerf *dev,
                               bladerf_direction dir,
                               unsigned int *timeout)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_stream_timeout(dev, dir, timeout);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_sync_config(struct bladerf *dev,
                        bladerf_channel_layout layout,
                        bladerf_format format,
                        unsigned int num_buffers,
                        unsigned int buffer_size,
                        unsigned int num_transfers,
                        unsigned int stream_timeout)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    if (format == BLADERF_FORMAT_SC8_Q7 || format == BLADERF_FORMAT_SC8_Q7_META) {
        if (strcmp(bladerf_get_board_name(dev), "bladerf2") != 0) {
            log_error("bladeRF 2.0 required for 8bit format\n");
            return BLADERF_ERR_UNSUPPORTED;
        }
    }

    status =
        dev->board->sync_config(dev, layout, format, num_buffers, buffer_size,
                                num_transfers, stream_timeout);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_sync_tx(struct bladerf *dev,
                    void const *samples,
                    unsigned int num_samples,
                    struct bladerf_metadata *metadata,
                    unsigned int timeout_ms)
{
    CHECK_NULL(samples);
    return dev->board->sync_tx(dev, samples, num_samples, metadata, timeout_ms);
}

int bladerf_sync_rx(struct bladerf *dev,
                    void *samples,
                    unsigned int num_samples,
                    struct bladerf_metadata *metadata,
                    unsigned int timeout_ms)
{
    return dev->board->sync_rx(dev, samples, num_samples, metadata, timeout_ms);
}

int bladerf_get_timestamp(struct bladerf *dev,
                          bladerf_direction dir,
                          bladerf_timestamp *timestamp)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_timestamp(dev, dir, timestamp);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_interleave_stream_buffer(bladerf_channel_layout layout,
                                     bladerf_format format,
                                     unsigned int buffer_size,
                                     void *samples)
{
    return _interleave_interleave_buf(layout, format, buffer_size, samples);
}

int bladerf_deinterleave_stream_buffer(bladerf_channel_layout layout,
                                       bladerf_format format,
                                       unsigned int buffer_size,
                                       void *samples)
{
    return _interleave_deinterleave_buf(layout, format, buffer_size, samples);
}

/******************************************************************************/
/* FPGA/Firmware Loading/Flashing */
/******************************************************************************/

int bladerf_load_fpga(struct bladerf *dev, const char *fpga_file)
{
    uint8_t *buf = NULL;
    size_t buf_size;
    int status;

    status = file_read_buffer(fpga_file, &buf, &buf_size);
    if (status != 0) {
        log_error("Failed to read FPGA image: %s\n", bladerf_strerror(status));
        goto exit;
    }

    status = dev->board->load_fpga(dev, buf, buf_size);

exit:
    free(buf);
    return status;
}

int bladerf_flash_fpga(struct bladerf *dev, const char *fpga_file)
{
    uint8_t *buf = NULL;
    size_t buf_size;
    int status;

    status = file_read_buffer(fpga_file, &buf, &buf_size);
    if (status != 0) {
        goto exit;
    }

    MUTEX_LOCK(&dev->lock);
    status = dev->board->flash_fpga(dev, buf, buf_size);
    MUTEX_UNLOCK(&dev->lock);

exit:
    free(buf);
    return status;
}

int bladerf_erase_stored_fpga(struct bladerf *dev)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->erase_stored_fpga(dev);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_flash_firmware(struct bladerf *dev, const char *firmware_file)
{
    uint8_t *buf = NULL;
    size_t buf_size;
    int status;

    status = file_read_buffer(firmware_file, &buf, &buf_size);
    if (status != 0) {
        goto exit;
    }

    MUTEX_LOCK(&dev->lock);
    status = dev->board->flash_firmware(dev, buf, buf_size);
    MUTEX_UNLOCK(&dev->lock);

exit:
    free(buf);
    return status;
}

int bladerf_device_reset(struct bladerf *dev)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->device_reset(dev);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Tuning mode */
/******************************************************************************/

int bladerf_set_tuning_mode(struct bladerf *dev, bladerf_tuning_mode mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_tuning_mode(dev, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_tuning_mode(struct bladerf *dev, bladerf_tuning_mode *mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_tuning_mode(dev, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Loopback */
/******************************************************************************/

int bladerf_get_loopback_modes(struct bladerf *dev,
                               struct bladerf_loopback_modes const **modes)
{
    int status;

    status = dev->board->get_loopback_modes(dev, modes);

    return status;
}

bool bladerf_is_loopback_mode_supported(struct bladerf *dev,
                                        bladerf_loopback mode)
{
    struct bladerf_loopback_modes modes;
    struct bladerf_loopback_modes const *modesptr = &modes;
    int i, count;

    count = bladerf_get_loopback_modes(dev, &modesptr);

    for (i = 0; i < count; ++i) {
        if (modesptr[i].mode == mode) {
            return true;
        }
    }

    return false;
}

int bladerf_set_loopback(struct bladerf *dev, bladerf_loopback l)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_loopback(dev, l);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_loopback(struct bladerf *dev, bladerf_loopback *l)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_loopback(dev, l);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Sample RX FPGA Mux */
/******************************************************************************/

int bladerf_set_rx_mux(struct bladerf *dev, bladerf_rx_mux mux)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_rx_mux(dev, mux);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_rx_mux(struct bladerf *dev, bladerf_rx_mux *mux)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_rx_mux(dev, mux);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Low-level VCTCXO Tamer Mode */
/******************************************************************************/

int bladerf_set_vctcxo_tamer_mode(struct bladerf *dev,
                                  bladerf_vctcxo_tamer_mode mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->set_vctcxo_tamer_mode(dev, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_vctcxo_tamer_mode(struct bladerf *dev,
                                  bladerf_vctcxo_tamer_mode *mode)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_vctcxo_tamer_mode(dev, mode);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Low-level VCTCXO Trim DAC access */
/******************************************************************************/

int bladerf_get_vctcxo_trim(struct bladerf *dev, uint16_t *trim)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->get_vctcxo_trim(dev, trim);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_trim_dac_read(struct bladerf *dev, uint16_t *trim)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trim_dac_read(dev, trim);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_trim_dac_write(struct bladerf *dev, uint16_t trim)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->trim_dac_write(dev, trim);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_dac_read(struct bladerf *dev, uint16_t *trim)
{
    return bladerf_trim_dac_read(dev, trim);
}
int bladerf_dac_write(struct bladerf *dev, uint16_t trim)
{
    return bladerf_trim_dac_write(dev, trim);
}

/******************************************************************************/
/* Low-level Trigger control access */
/******************************************************************************/

int bladerf_read_trigger(struct bladerf *dev,
                         bladerf_channel ch,
                         bladerf_trigger_signal trigger,
                         uint8_t *val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->read_trigger(dev, ch, trigger, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_write_trigger(struct bladerf *dev,
                          bladerf_channel ch,
                          bladerf_trigger_signal trigger,
                          uint8_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->write_trigger(dev, ch, trigger, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Low-level Wishbone Master access */
/******************************************************************************/
int bladerf_wishbone_master_read(struct bladerf *dev, uint32_t addr, uint32_t *data)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->wishbone_master_read(dev, addr, data);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_wishbone_master_write(struct bladerf *dev, uint32_t addr, uint32_t data)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->wishbone_master_write(dev, addr, data);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Low-level Configuration GPIO access */
/******************************************************************************/

int bladerf_config_gpio_read(struct bladerf *dev, uint32_t *val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->config_gpio_read(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_config_gpio_write(struct bladerf *dev, uint32_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->config_gpio_write(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Low-level SPI Flash access */
/******************************************************************************/

int bladerf_erase_flash(struct bladerf *dev,
                        uint32_t erase_block,
                        uint32_t count)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->erase_flash(dev, erase_block, count);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_erase_flash_bytes(struct bladerf *dev,
                              uint32_t address,
                              uint32_t length)
{
    int      status;
    uint32_t eb;
    uint32_t count;

    /* Make sure address is aligned to an erase block boundary */
    if( (address % dev->flash_arch->ebsize_bytes) == 0 ) {
        /* Convert into units of flash pages */
        eb = address / dev->flash_arch->ebsize_bytes;
    } else {
        log_error("Address or length not aligned on a flash page boundary.\n");
        return BLADERF_ERR_INVAL;
    }

    /* Check for the case of erasing less than 1 erase block.
     * For example, the calibration data. If so, round up to 1 EB.
     * If erasing more than 1 EB worth of data, make sure the length
     * is aligned to an EB boundary. */
    if( (length > 0) && (length < dev->flash_arch->ebsize_bytes) ) {
        count = 1;
    } else if ((length % dev->flash_arch->ebsize_bytes) == 0) {
        /* Convert into units of flash pages */
        count = length  / dev->flash_arch->ebsize_bytes;
    } else {
        log_error("Address or length not aligned on a flash page boundary.\n");
        return BLADERF_ERR_INVAL;
    }

    status = bladerf_erase_flash(dev, eb, count);

    return status;
}

int bladerf_read_flash(struct bladerf *dev,
                       uint8_t *buf,
                       uint32_t page,
                       uint32_t count)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->read_flash(dev, buf, page, count);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_read_flash_bytes(struct bladerf *dev,
                             uint8_t *buf,
                             uint32_t address,
                             uint32_t length)
{
    int      status;
    uint32_t page;
    uint32_t count;

    /* Check alignment */
    if( ((address % dev->flash_arch->psize_bytes) != 0) ||
        ((length  % dev->flash_arch->psize_bytes) != 0) ) {
        log_error("Address or length not aligned on a flash page boundary.\n");
        return BLADERF_ERR_INVAL;
    }

    /* Convert into units of flash pages */
    page  = address / dev->flash_arch->psize_bytes;
    count = length  / dev->flash_arch->psize_bytes;

    status = bladerf_read_flash(dev, buf, page, count);

    return status;
}

int bladerf_write_flash(struct bladerf *dev,
                        const uint8_t *buf,
                        uint32_t page,
                        uint32_t count)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->write_flash(dev, buf, page, count);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_write_flash_bytes(struct bladerf *dev,
                              const uint8_t *buf,
                              uint32_t address,
                              uint32_t length)
{
    int      status;
    uint32_t page;
    uint32_t count;

    /* Check alignment */
    if( ((address % dev->flash_arch->psize_bytes) != 0) ||
        ((length  % dev->flash_arch->psize_bytes) != 0) ) {
        log_error("Address or length not aligned on a flash page boundary.\n");
        return BLADERF_ERR_INVAL;
    }

    /* Convert address and length into units of flash pages */
    page  = address / dev->flash_arch->psize_bytes;
    count = length  / dev->flash_arch->psize_bytes;

    status = bladerf_write_flash(dev, buf, page, count);
    return status;
}

int bladerf_read_otp(struct bladerf *dev,
                       uint8_t *buf)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->backend->get_otp(dev, (char *)buf);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_write_otp(struct bladerf *dev,
                        uint8_t *buf)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->backend->write_otp(dev, (char *)buf);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_lock_otp(struct bladerf *dev)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->backend->lock_otp(dev);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Helpers & Miscellaneous */
/******************************************************************************/

const char *bladerf_strerror(int error)
{
    switch (error) {
        case BLADERF_ERR_UNEXPECTED:
            return "An unexpected error occurred";
        case BLADERF_ERR_RANGE:
            return "Provided parameter was out of the allowable range";
        case BLADERF_ERR_INVAL:
            return "Invalid operation or parameter";
        case BLADERF_ERR_MEM:
            return "A memory allocation error occurred";
        case BLADERF_ERR_IO:
            return "File or device I/O failure";
        case BLADERF_ERR_TIMEOUT:
            return "Operation timed out";
        case BLADERF_ERR_NODEV:
            return "No devices available";
        case BLADERF_ERR_UNSUPPORTED:
            return "Operation not supported";
        case BLADERF_ERR_MISALIGNED:
            return "Misaligned flash access";
        case BLADERF_ERR_CHECKSUM:
            return "Invalid checksum";
        case BLADERF_ERR_NO_FILE:
            return "File not found";
        case BLADERF_ERR_UPDATE_FPGA:
            return "An FPGA update is required";
        case BLADERF_ERR_UPDATE_FW:
            return "A firmware update is required";
        case BLADERF_ERR_TIME_PAST:
            return "Requested timestamp is in the past";
        case BLADERF_ERR_QUEUE_FULL:
            return "Could not enqueue data into full queue";
        case BLADERF_ERR_FPGA_OP:
            return "An FPGA operation reported a failure";
        case BLADERF_ERR_PERMISSION:
            return "Insufficient permissions for the requested operation";
        case BLADERF_ERR_WOULD_BLOCK:
            return "The operation would block, but has been requested to be "
                   "non-blocking";
        case BLADERF_ERR_NOT_INIT:
            return "Insufficient initialization for the requested operation";
        case 0:
            return "Success";
        default:
            return "Unknown error code";
    }
}

const char *bladerf_backend_str(bladerf_backend backend)
{
    return backend2str(backend);
}

void bladerf_log_set_verbosity(bladerf_log_level level)
{
    log_set_verbosity(level);
#if defined(LOG_SYSLOG_ENABLED)
    log_debug("Log verbosity has been set to: %d", level);
#endif
}

void bladerf_set_usb_reset_on_open(bool enabled)
{
#if ENABLE_USB_DEV_RESET_ON_OPEN
    bladerf_usb_reset_device_on_open = enabled;

    log_verbose("USB reset on open %s\n", enabled ? "enabled" : "disabled");
#else
    log_verbose("%s has no effect. "
                "ENABLE_USB_DEV_RESET_ON_OPEN not set at compile-time.\n",
                __FUNCTION__);
#endif
}

/******************************************************************************/
/* Expansion board APIs */
/******************************************************************************/

int bladerf_expansion_attach(struct bladerf *dev, bladerf_xb xb)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->expansion_attach(dev, xb);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_get_attached(struct bladerf *dev, bladerf_xb *xb)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = dev->board->expansion_get_attached(dev, xb);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/* XB100 */

int bladerf_expansion_gpio_read(struct bladerf *dev, uint32_t *val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_read(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_gpio_write(struct bladerf *dev, uint32_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_write(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_gpio_masked_write(struct bladerf *dev,
                                        uint32_t mask,
                                        uint32_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_masked_write(dev, mask, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_gpio_dir_read(struct bladerf *dev, uint32_t *val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_dir_read(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_gpio_dir_write(struct bladerf *dev, uint32_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_dir_write(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_expansion_gpio_dir_masked_write(struct bladerf *dev,
                                            uint32_t mask,
                                            uint32_t val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb100_gpio_dir_masked_write(dev, mask, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/* XB200 */

int bladerf_xb200_set_filterbank(struct bladerf *dev,
                                 bladerf_channel ch,
                                 bladerf_xb200_filter filter)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb200_set_filterbank(dev, ch, filter);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb200_get_filterbank(struct bladerf *dev,
                                 bladerf_channel ch,
                                 bladerf_xb200_filter *filter)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb200_get_filterbank(dev, ch, filter);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb200_set_path(struct bladerf *dev,
                           bladerf_channel ch,
                           bladerf_xb200_path path)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb200_set_path(dev, ch, path);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb200_get_path(struct bladerf *dev,
                           bladerf_channel ch,
                           bladerf_xb200_path *path)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb200_get_path(dev, ch, path);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/* XB300 */

int bladerf_xb300_set_trx(struct bladerf *dev, bladerf_xb300_trx trx)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb300_set_trx(dev, trx);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb300_get_trx(struct bladerf *dev, bladerf_xb300_trx *trx)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb300_get_trx(dev, trx);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb300_set_amplifier_enable(struct bladerf *dev,
                                       bladerf_xb300_amplifier amp,
                                       bool enable)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb300_set_amplifier_enable(dev, amp, enable);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb300_get_amplifier_enable(struct bladerf *dev,
                                       bladerf_xb300_amplifier amp,
                                       bool *enable)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb300_get_amplifier_enable(dev, amp, enable);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_xb300_get_output_power(struct bladerf *dev, float *val)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = xb300_get_output_power(dev, val);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

/******************************************************************************/
/* Features */
/******************************************************************************/

int bladerf_enable_feature(struct bladerf *dev, bladerf_feature feature, bool enable)
{
    int status;
    MUTEX_LOCK(&dev->lock);

    status = 0;

    if(feature == BLADERF_FEATURE_DEFAULT) {
        dev->feature = 0;
    } else {
        if(feature == BLADERF_FEATURE_OVERSAMPLE) {
            if (strcmp(bladerf_get_board_name(dev), "bladerf2") != 0) {
                log_error("BladeRF2 required for OVERSAMPLE feature\n");
                status = BLADERF_ERR_UNSUPPORTED;
            }
        } else {
            /* Unknown / Unsupported feature */
            status = BLADERF_ERR_UNSUPPORTED;
        }

        if (status == 0) {
            if (enable) {
                dev->feature |= feature;
            } else {
                dev->feature &= ~feature;
            }
        }
    }

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_get_feature(struct bladerf *dev, bladerf_feature* feature)
{
    MUTEX_LOCK(&dev->lock);
    *feature = dev->feature;
    MUTEX_UNLOCK(&dev->lock);

    return 0;
}

int bladerf_set_oversample_register_config(struct bladerf *dev) {
    const char *board_name;
    board_name = bladerf_get_board_name(dev);

    if (strcmp(board_name, "bladerf2") != 0) {
        log_error("Oversample register config only applicable\n"
                  "for the bladeRF 2.0");

        return BLADERF_ERR_UNSUPPORTED;
    }

    bladerf_set_rfic_register(dev,0x003,0x54); // OC Register

    /* TX Register Assignments */
    bladerf_set_rfic_register(dev,0x02,0xc0);  // TX Enable and Filter Control
    bladerf_set_rfic_register(dev,0xc2,0x9f);  // TX BBF R1
    bladerf_set_rfic_register(dev,0xc3,0x9f);  // TX baseband filter R2
    bladerf_set_rfic_register(dev,0xc4,0x9f);  // TX baseband filter R3
    bladerf_set_rfic_register(dev,0xc5,0x9f);  // TX baseband filter R4
    bladerf_set_rfic_register(dev,0xc6,0x9f);  // TX baseband filter real pole word
    bladerf_set_rfic_register(dev,0xc7,0x00);  // TX baseband filter C1
    bladerf_set_rfic_register(dev,0xc8,0x00);  // TX baseband filter C2
    bladerf_set_rfic_register(dev,0xc9,0x00);  // TX baseband filter real pole word

    /* RX Register Assignments */
    // Gain and calibration
    bladerf_set_rfic_register(dev,0x1e0,0x00);  // RX1 BBF R1A
    bladerf_set_rfic_register(dev,0x1e1,0x00);  // RX2 BBF R1A
    bladerf_set_rfic_register(dev,0x1e2,0x00);  // RX1 tune control
    bladerf_set_rfic_register(dev,0x1e3,0x00);  // RX2 tune control
    bladerf_set_rfic_register(dev,0x1e4,0x00);  // RX1 BBF R5
    bladerf_set_rfic_register(dev,0x1e5,0x00);  // RX2 BBF R5
    bladerf_set_rfic_register(dev,0x1e6,0x00);  // RX BBF R2346

    // Miller and BBF caps
    bladerf_set_rfic_register(dev,0x1e7,0x00);  // RX BBF C1 MSB
    bladerf_set_rfic_register(dev,0x1e8,0x00);  // RX BBF C1 LSB
    bladerf_set_rfic_register(dev,0x1e9,0x00);  // RX baseband filter real pole word
    bladerf_set_rfic_register(dev,0x1ea,0x00);
    bladerf_set_rfic_register(dev,0x1eb,0x00);
    bladerf_set_rfic_register(dev,0x1ec,0x00);
    bladerf_set_rfic_register(dev,0x1ed,0x00);
    bladerf_set_rfic_register(dev,0x1ee,0x00);
    bladerf_set_rfic_register(dev,0x1ef,0x00);

    // BIST and Data Port Test Config [D1:D0] "Must be 2’b00"
    bladerf_set_rfic_register(dev,0x3f6,0x03);

    return 0;
}

/******************************************************************************/
/* Calibration */
/******************************************************************************/

int bladerf_load_gain_calibration(struct bladerf *dev, bladerf_channel ch, const char* cal_file_loc)
{
    int status = 0;
    const char *board_name;
    char *full_path = NULL;
    char *full_path_bin = NULL;
    char *ext;

    size_t filename_len = PATH_MAX;
    char *filename = (char *)calloc(1, filename_len + 1);
    CHECK_NULL(filename);

    bladerf_gain_mode gain_mode_before_gain_reset;

    log_debug("Loading gain calibration\n");
    MUTEX_LOCK(&dev->lock);

    board_name = bladerf_get_board_name(dev);
    if (strcmp(board_name, "bladerf2") != 0) {
        log_error("Gain calibration unsupported on this device: %s\n", board_name);
        status = BLADERF_ERR_UNSUPPORTED;
        goto error;
    }

    if (cal_file_loc != NULL) {
        strcpy(filename, cal_file_loc);
    } else {
        log_debug("No calibration file specified, using serial number\n");
        strcpy(filename, dev->ident.serial);
        filename_len -= strlen(filename);

        if (BLADERF_CHANNEL_IS_TX(ch))
            strncat(filename, "_tx_gain_cal.tbl", filename_len);
        else
            strncat(filename, "_rx_gain_cal.tbl", filename_len);
    }

    full_path = file_find(filename);
    if (full_path == NULL) {
        log_error("Failed to find gain calibration file: %s\n", filename);
        status = BLADERF_ERR_NO_FILE;
        goto error;
    }

    /** Convert to binary format if CSV */
    full_path_bin = (char*)malloc(strlen(full_path) + 1);
    strcpy(full_path_bin, full_path);
    ext = strstr(full_path_bin, ".csv");
    if (ext) {
        log_debug("Converting gain calibration to binary format\n");
        strcpy(ext, ".tbl");
        status = gain_cal_csv_to_bin(dev, full_path, full_path_bin, ch);
        if (status != 0) {
            log_error("Failed to convert csv to binary: %s -> %s\n",
                full_path, full_path_bin);
            status = EXIT_FAILURE;
            goto error;
        }
    }

    status = load_gain_calibration(dev, ch, full_path_bin);
    if (status != 0) {
        log_error("Failed to load calibration\n");
        status = BLADERF_ERR_UNEXPECTED;
        goto error;
    }

    MUTEX_UNLOCK(&dev->lock);

    /* Save current gain mode before gain reset */
    if (BLADERF_CHANNEL_IS_TX(ch) == false)
        dev->board->get_gain_mode(dev, ch, &gain_mode_before_gain_reset);

    /* Reset gain to ensure calibration adjustment is applied after loading */
    status = bladerf_set_gain(dev, ch, dev->gain_tbls[ch].gain_target);
    if (status != 0) {
        log_error("%s: Failed to reset gain.\n", __FUNCTION__);
        goto error;
    }

    /** Restore previous gain mode */
    if (BLADERF_CHANNEL_IS_TX(ch) == false) {
        status = bladerf_set_gain_mode(dev, ch, gain_mode_before_gain_reset);
        if (status != 0) {
            log_error("%s: Failed to reset gain mode.\n", __FUNCTION__);
            goto error;
        }
    }

error:
    if (full_path)
        free(full_path);
    if (full_path_bin)
        free(full_path_bin);
    if (filename)
        free(filename);

    MUTEX_UNLOCK(&dev->lock);
    return status;
}

int bladerf_enable_gain_calibration(struct bladerf *dev, bladerf_channel ch, bool en)
{
    CHECK_NULL(dev);
    int status = 0;

    if (dev->gain_tbls[ch].state == BLADERF_GAIN_CAL_UNINITIALIZED) {
        log_warning("%s: Gain calibration not loaded\n", __FUNCTION__);
        return 0;
    }

    dev->gain_tbls[ch].enabled = en;
    status = bladerf_set_gain(dev, ch, dev->gain_tbls[ch].gain_target);
    if (status != 0) {
        log_error("%s: Failed to reset gain.\n", __FUNCTION__);
        return status;
    }

    return status;
}

int bladerf_print_gain_calibration(struct bladerf *dev, bladerf_channel ch, bool with_entries)
{
    CHECK_NULL(dev);
    int status = 0;
    const char *board_name;
    struct bladerf_gain_cal_tbl *gain_tbls = dev->gain_tbls;

    board_name = bladerf_get_board_name(dev);
    if (strcmp(board_name, "bladerf2") != 0) {
        log_error("Gain calibration unsupported on this device: %s\n", board_name);
        status = BLADERF_ERR_UNSUPPORTED;
        goto error;
    }

    if (gain_tbls[ch].state == BLADERF_GAIN_CAL_UNINITIALIZED) {
        printf("Gain Calibration [%s]: uninitialized\n", channel2str(ch));
        return 0;
    }

    printf("Gain Calibration [%s]: loaded\n", channel2str(ch));
    printf("  Status: %s\n", (gain_tbls[ch].enabled) ? "enabled" : "disabled");
    printf("  Version: %i.%i.%i\n",
        gain_tbls[ch].version.major, gain_tbls[ch].version.minor, gain_tbls[ch].version.patch);
    printf("  Number of Entries: %u\n", gain_tbls[ch].n_entries);
    printf("  Start Frequency: %" PRIu64 " Hz\n", gain_tbls[ch].start_freq);
    printf("  Stop Frequency: %" PRIu64 " Hz\n", gain_tbls[ch].stop_freq);
    printf("  File Path: %s\n", gain_tbls[ch].file_path);

    if (with_entries) {
        for (size_t i = 0; i < gain_tbls[ch].n_entries; i++) {
            printf("%" PRIu64 ",%f\n", gain_tbls[ch].entries[i].freq, gain_tbls[ch].entries[i].gain_corr);
        }
    }

error:
    return status;
}

int bladerf_get_gain_calibration(struct bladerf *dev, bladerf_channel ch, const struct bladerf_gain_cal_tbl **tbl)
{
    CHECK_NULL(dev);
    MUTEX_LOCK(&dev->lock);

    if (dev->gain_tbls[ch].state != BLADERF_GAIN_CAL_LOADED) {
        log_error("%s: Gain calibration not loaded\n", __FUNCTION__);
        MUTEX_UNLOCK(&dev->lock);
        return BLADERF_ERR_UNEXPECTED;
    }

    *tbl = &(dev->gain_tbls[ch]);

    MUTEX_UNLOCK(&dev->lock);
    return 0;
}

int bladerf_get_gain_target(struct bladerf *dev, bladerf_channel ch, int *gain_target)
{
    int status = 0;
    CHECK_NULL(dev);
    MUTEX_LOCK(&dev->lock);
    bladerf_frequency current_frequency;
    struct bladerf_gain_cal_tbl *cal_table = &dev->gain_tbls[ch];
    struct bladerf_gain_cal_entry current_entry;
    bladerf_gain current_gain;
    bladerf_gain_mode gain_mode;


    if (dev->gain_tbls[ch].state == BLADERF_GAIN_CAL_UNINITIALIZED) {
        log_error("Gain calibration not loaded\n");
        status = BLADERF_ERR_UNEXPECTED;
        goto error;
    }

    if (BLADERF_CHANNEL_IS_TX(ch) == true) {
        *gain_target = cal_table->gain_target;
        goto error;
    }

    dev->board->get_gain_mode(dev, ch, &gain_mode);

    if (gain_mode == BLADERF_GAIN_MGC) {
        *gain_target = cal_table->gain_target;
        goto error;
    }

    CHECK_STATUS(dev->board->get_gain(dev, ch, &current_gain));
    CHECK_STATUS(dev->board->get_frequency(dev, ch, &current_frequency));
    CHECK_STATUS(get_gain_cal_entry(cal_table, current_frequency, &current_entry));
    *gain_target = current_gain + current_entry.gain_corr;

error:
    MUTEX_UNLOCK(&dev->lock);
    return status;
}