summaryrefslogtreecommitdiff
path: root/service/src/node_etherfabric.c
blob: ca9777139fda362823ba079a8c5125580b8b415a (plain)
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
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
#include <rte_branch_prediction.h>
#include <rte_graph.h>
#include <rte_graph_worker.h>
#include <rte_hash.h>
#include <rte_hash_crc.h>
#include <rte_malloc.h>

#include <MESA_prof_load.h>
#include <link_db.h>
#include <mrb_define.h>
#include <port_adapter_mapping.h>
#include <sc_metrics.h>
#include <sc_node_common.h>
#include <sc_trace.h>
#include <stdint.h>

/******************************************* Etherfabric adapter struct ***********************************************/
/* Etherfabric adapter mode */
enum ef_adapter_mode
{
    EF_MODE_INVALID = 0,
    EF_MODE_VIRTUAL_WIRE,
    EF_MODE_TAP,
};

/* Etherfabric adapter struct */
struct ef_adapter
{
    uint16_t id;
    enum ef_adapter_mode mode;
    struct mr_dev_desc * listening_device;
};

struct ef_adapter_handle
{
    uint16_t capacity;
    uint16_t nr_adapters;
    struct ef_adapter * adapters;
};

/********************************************** Etherfabric peer struct ***********************************************/
/* Should match the #define LCORE_CACHE_SIZE value in rte_cuckoo_hash.h */
#define LCORE_CACHE_SIZE 64
#define SC_EF_PEER_ENTRIES 256
// #define SC_EF_PEER_MEMBER (SC_EF_PEER_ENTRIES + (RTE_MAX_LCORE - 1) * (LCORE_CACHE_SIZE - 1) + 1)
#define SC_EF_PEER_CAPACITY_CALC(entries, cache_size) ((entries) + (RTE_MAX_LCORE - 1) * ((cache_size)-1) + 1)

/* ef_peer key */
union ef_peer_key {
    struct
    {
        uint32_t ip_src;
        struct rte_ether_addr mac_src;
    };
};

/* ef_peer struct */
struct ef_peer
{
    uint32_t ef_ip_addr;
    rte_atomic64_t state;
    struct rte_ether_addr ef_mac_addr;
} __rte_cache_aligned;

/* ef_peer handle */
struct ef_peer_handle
{
    uint32_t capacity;
    uint32_t entries;
    uint32_t remaining_entries;
    struct rte_hash * ef_peer_hash;
    struct ef_peer * ef_peers;
};

/******************************************** Traffic Link Peer Map struct ********************************************/
struct tl_to_ef_peer_map_handle
{
    uint16_t capacity;
    rte_atomic64_t * maps_table;
};

/********************************************** Etherfabric main struct ***********************************************/
/* Set the pkt offset */
const static int ef_encap_len = sizeof(struct rte_ether_hdr) + sizeof(struct rte_ipv4_hdr) +
                                sizeof(struct rte_udp_hdr) + sizeof(struct g_vxlan_hdr);

/* Etherfabric ingress next node */
enum
{
    EF_INGR_NEXT_CLASSIFIER = 0,
    EF_INGR_NEXT_PKT_DROP,
    EF_INGR_NEXT_MAX
};

/* Etherfabric egress next node */
enum
{
    EF_EGR_NEXT_ETH_EGRESS = 0,
    EF_EGR_NEXT_PKT_DROP,
    EF_EGR_NEXT_MAX
};

/* Etherfabric ingress metrics key */
enum ef_node_ingress_metrics_key
{
    EF_INGR_METRIC_TOT_PKTS = 0,
    EF_INGR_METRIC_PKTS_PER_BATCH,
    EF_INGR_METRIC_TO_CLASSIFIER,
    EF_INGR_METRIC_DROP_ADP_NONEXIST,
    EF_INGR_METRIC_DROP_PRE_SID_ERR,
    EF_INGR_METRIC_DROP_EF_PEER_ADD_ERR,
    EF_INGR_METRIC_DROP_TL_TO_EF_PEER_MAP_ERR,
    EF_INGR_METRIC_MAX
};

/* Etherfabric ingress metrics string */
char * ef_ingr_metrics_str[EF_INGR_METRIC_MAX] = {"total_pkts",
                                                  "pkts_per_batch",
                                                  "to_classifier",
                                                  "drop_rsn_adapter_lookup_miss",
                                                  "drop_rsn_sid_prepend_err",
                                                  "drop_rsn_ef_peer_add_err",
                                                  "drop_rsn_tl_to_ef_peer_map_err"};

/* Etherfabric egress metrics key */
enum ef_node_egress_metrics_key
{
    EF_EGR_METRIC_TOT_PKTS = 0,
    EF_EGR_METRIC_PKTS_PER_BATCH,
    EF_EGR_METRIC_VXLAN_ENCAP,
    EF_EGR_METRIC_TO_ETH_EGRESS,
    EF_EGR_METRIC_DROP_RSN_TAP_MODE,
    EF_EGR_METRIC_DROP_RSN_INVALID_MODE,
    EF_EGR_METRIC_MAX
};

/* Etherfabric egress metrics string */
char * ef_egr_metrics_str[EF_EGR_METRIC_MAX] = {"total_pkts",    "pkts_per_batch",    "vxlan_encap",
                                                "to_eth_egress", "drop_rsn_tap_mode", "drop_rsn_invalid_mode"};

/* Etherfabric config handle */
struct ef_config_handle
{
    uint16_t nr_adapters;
    uint32_t sid_start;
    uint32_t sid_end;
    uint32_t ef_adapters_max;
    uint32_t link_dbs_max;
    struct ef_adapter * ef_adapters_data;
};

/* Etherfabric node main struct */
struct ef_node_main
{
    /* Number of graphs */
    uint16_t nr_graphs;

    struct sid_handle * sid_handle;
    struct ef_adapter_handle * ef_adapter_handle;
    struct link_db_ctx * link_db_ctx;
    struct ef_peer_handle * ef_peer_handle;
    struct tl_to_ef_peer_map_handle * tl_to_ef_peer_map_handle;

    /* Etherfabric metrics handles */
    struct sc_metrics_handle ** ingress_metrics_handles;
    struct sc_metrics_handle ** egress_metrics_handles;
} __rte_cache_aligned;

/* Global variable for etherfabric management */
static struct ef_node_main * g_ef_main = NULL;

/******************************************** Etherfabric adapter func ************************************************/
/**
 * @brief Creates an ef_adapter_handle structure with the given capacity and adapter data.
 *
 * This function initializes an ef_adapter_handle structure to manage a collection of
 * ef_adapter structures. It allocates memory for the handle and its adapters array based
 * on the specified capacity. The function checks for invalid input conditions, such as
 * zero capacity or a number of adapters that exceeds the capacity, and returns NULL
 * if these conditions are met.
 *
 * @param adapters_data Pointer to an array of ef_adapter structures that contain the adapter data.
 * @param capacity The maximum number of adapters that can be managed by the handle.
 * @param nr_adapters The number of adapters provided in the adapters_data array.
 *
 * @return Pointer to the created ef_adapter_handle structure if successful, NULL otherwise.
 */
struct ef_adapter_handle * ef_adapter_handle_create(struct ef_adapter * adapters_data, uint16_t capacity,
                                                    uint16_t nr_adapters)
{
    if (capacity == 0)
    {
        MR_ERROR("The capacity is 0.");
        return NULL;
    }
    else if (nr_adapters > capacity)
    {
        MR_ERROR("The nr_adapters out of capacity.");
        return NULL;
    }

    assert(adapters_data != NULL);

    struct ef_adapter_handle * handle = ZMALLOC(sizeof(struct ef_adapter_handle));
    MR_VERIFY_MALLOC(handle);

    handle->capacity = capacity;
    handle->nr_adapters = nr_adapters;
    handle->adapters = ZMALLOC(sizeof(struct ef_adapter) * capacity);
    MR_VERIFY_MALLOC(handle->adapters);

    for (int i = 0; i < capacity; i++)
    {
        handle->adapters[i].id = adapters_data[i].id;
        handle->adapters[i].mode = adapters_data[i].mode;
        handle->adapters[i].listening_device = adapters_data[i].listening_device;
    }

    return handle;
}

/**
 * @brief Deletes an ef_adapter_handle structure and frees its associated resources.
 *
 * This function releases the memory allocated for an ef_adapter_handle structure and
 * its internal adapters array. It ensures that the handle and its adapters are properly
 * freed, and sets the pointers to NULL to prevent dangling pointers. If the provided
 * handle is NULL, an error is logged, and the function returns an error code.
 *
 * @param handle Pointer to the ef_adapter_handle structure to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if the handle is NULL.
 */
int ef_adapter_handle_delete(struct ef_adapter_handle * handle)
{
    if (handle == NULL)
    {
        MR_ERROR("The ef_adapter_handle is NULL.");
        return RT_ERR;
    }

    if (handle->adapters != NULL)
    {
        FREE(handle->adapters);
        handle->adapters = NULL;
    }

    FREE(handle);

    return RT_SUCCESS;
}

/**
 * @brief Retrieves the capacity of the ef_adapter_handle.
 *
 * This function returns the maximum number of adapters that the specified ef_adapter_handle
 * can manage. The function asserts that the handle is not NULL before accessing its capacity.
 *
 * @param handle Pointer to the ef_adapter_handle structure.
 *
 * @return The capacity of the ef_adapter_handle.
 */
uint16_t ef_adapter_handle_capacity_get(struct ef_adapter_handle * handle)
{
    assert(handle != NULL);
    return handle->capacity;
}

/**
 * @brief Retrieves the number of adapters currently in the ef_adapter_handle.
 *
 * This function returns the current number of adapters stored in the specified ef_adapter_handle.
 * The function asserts that the handle is not NULL before accessing its number of adapters.
 *
 * @param handle Pointer to the ef_adapter_handle structure.
 *
 * @return The number of adapters currently in the ef_adapter_handle.
 */
uint16_t ef_adapter_handle_nr_adapters_get(struct ef_adapter_handle * handle)
{
    assert(handle != NULL);
    return handle->nr_adapters;
}

/**
 * @brief Retrieves a pointer to an ef_adapter by its ID within the ef_adapter_handle.
 *
 * This inline function returns a pointer to the ef_adapter structure within the ef_adapter_handle
 * corresponding to the specified adapter ID. The function asserts that the handle is not NULL
 * and that the adapter ID is within the valid range of the handle's capacity.
 *
 * @param handle Pointer to the ef_adapter_handle structure.
 * @param adapter_id The ID of the adapter to retrieve.
 *
 * @return Pointer to the ef_adapter structure with the specified ID.
 */
static inline struct ef_adapter * __ef_adapter_handle_adapter_get_by_id(struct ef_adapter_handle * handle,
                                                                        uint16_t adapter_id)
{
    assert(handle != NULL);
    assert(adapter_id < handle->capacity);

    return &handle->adapters[adapter_id];
}

/**
 * @brief Retrieves a pointer to an ef_adapter by its ID within the ef_adapter_handle.
 *
 * This function returns a pointer to the ef_adapter structure within the ef_adapter_handle
 * corresponding to the specified adapter ID. It calls an internal function
 * `__ef_adapter_handle_adapter_get_by_id` to perform the actual retrieval. The function asserts
 * that the handle is not NULL and that the adapter ID is within the valid range of the handle's capacity.
 *
 * @param handle Pointer to the ef_adapter_handle structure.
 * @param adapter_id The ID of the adapter to retrieve.
 *
 * @return Pointer to the ef_adapter structure with the specified ID.
 */
struct ef_adapter * ef_adapter_handle_adapter_get_by_id(struct ef_adapter_handle * handle, uint16_t adapter_id)
{
    assert(handle != NULL);
    assert(adapter_id < handle->capacity);

    return __ef_adapter_handle_adapter_get_by_id(handle, adapter_id);
}

/**
 * @brief Retrieves the ID of the specified ef_adapter.
 *
 * This function returns the ID of the given ef_adapter structure. The function asserts
 * that the ef_adapter pointer is not NULL before accessing its ID.
 *
 * @param ef_adapter Pointer to the ef_adapter structure.
 *
 * @return The ID of the specified ef_adapter.
 */
uint16_t ef_adapter_id_get(struct ef_adapter * ef_adapter)
{
    assert(ef_adapter != NULL);
    return ef_adapter->id;
}

/**
 * @brief Looks up an ef_adapter in the ef_adapter_handle by destination address.
 *
 * This function searches through the ef_adapter structures within the given ef_adapter_handle
 * to find an adapter whose listening device matches the specified destination address (`dst_addr`).
 * If a match is found, the ID of the matching adapter is stored in `out_ef_adapter_id`, and the
 * function returns `RT_SUCCESS`. If no match is found, the function returns `RT_ERR`. The function
 * asserts that the handle and the output pointer (`out_ef_adapter_id`) are not NULL.
 *
 * @param handle Pointer to the ef_adapter_handle structure containing the adapters.
 * @param dst_addr The destination address to match against the adapters' listening devices.
 * @param out_ef_adapter_id Pointer to a variable where the ID of the matching adapter will be stored.
 *
 * @return RT_SUCCESS if a matching adapter is found, RT_ERR otherwise.
 */
int ef_adapter_handle_adapter_lookup(struct ef_adapter_handle * handle, uint32_t dst_addr, uint16_t * out_ef_adapter_id)
{
    assert(handle != NULL);
    assert(out_ef_adapter_id != NULL);

    for (uint16_t index = 0; index < handle->capacity; index++)
    {
        struct ef_adapter * ef_adapter = __ef_adapter_handle_adapter_get_by_id(handle, index);

        if (ef_adapter->mode == EF_MODE_INVALID)
            continue;

        if (dst_addr == ef_adapter->listening_device->in_addr.s_addr)
        {
            *out_ef_adapter_id = ef_adapter->id;
            return RT_SUCCESS;
        }
    }
    return RT_ERR;
}

/*********************************************** Etherfabric peer func ************************************************/
/**
 * @brief Computes a hash value for an ef_peer based on its IP address and MAC address.
 *
 * This inline function calculates a CRC32-based hash value for a given `ef_peer_key`, which
 * consists of an IP source address and a MAC source address. The function primarily uses the
 * IP address (`ip_src`) as the key for the hash. It also includes an unused section where
 * the MAC address is incorporated into the hash calculation. The function returns the computed
 * hash value.
 *
 * @param data Pointer to the `ef_peer_key` structure containing the IP and MAC addresses.
 * @param data_len Unused parameter indicating the length of the data.
 * @param init_val Initial value for the CRC32 hash computation.
 *
 * @return The computed CRC32 hash value.
 */
static inline uint32_t ef_peer_hash_crc(const void * data, __rte_unused uint32_t data_len, uint32_t init_val)
{
    /* use the etherfabric's ip addr as key */
    const union ef_peer_key * key = data;
    return key->ip_src;

    const uint32_t * mac_0 = (const uint32_t *)&key->mac_src.addr_bytes[0];
    const uint32_t * mac_1 = (const uint32_t *)&key->mac_src.addr_bytes[4];

    init_val = rte_hash_crc_4byte(key->ip_src, init_val);
    init_val = rte_hash_crc_4byte(*mac_0, init_val);
    init_val = rte_hash_crc_4byte(*mac_1, init_val);

    return init_val;
}

/**
 * @brief Creates a hash table for managing ef_peer entries.
 *
 * This function initializes and creates an RTE hash table specifically for storing and
 * managing `ef_peer` entries. The function sets up the parameters for the hash table,
 * including the number of entries, key length, hash function, and additional flags for
 * memory and concurrency support. The hash function used is `ef_peer_hash_crc`. If the
 * hash table cannot be created, an error is logged, and the function returns `NULL`.
 *
 * @param entries The maximum number of entries that the hash table can contain.
 *
 * @return Pointer to the created RTE hash table if successful, NULL otherwise.
 */
struct rte_hash * ef_peer_hash_create(uint32_t entries)
{
    struct rte_hash_parameters ef_peer_hash_params = {
        .name = "ef_peer_hash",
        .entries = entries,
        //.entries = SC_EF_PEER_ENTRIES,
        .key_len = sizeof(union ef_peer_key),
        .hash_func = ef_peer_hash_crc,
        .hash_func_init_val = 0,
        .socket_id = 0,
        .extra_flag = RTE_HASH_EXTRA_FLAGS_TRANS_MEM_SUPPORT | RTE_HASH_EXTRA_FLAGS_MULTI_WRITER_ADD |
                      RTE_HASH_EXTRA_FLAGS_RW_CONCURRENCY_LF,
    };

    struct rte_hash * ef_peer_hash = rte_hash_create(&ef_peer_hash_params);
    if (ef_peer_hash == NULL)
    {
        MR_ERROR("Unable to create the ef_peer hash on socket 0 .");
        return NULL;
    }

    return ef_peer_hash;
}

/**
 * @brief Deletes the ef_peer hash table and frees its associated resources.
 *
 * This function frees the memory allocated for the ef_peer hash table. It checks if the
 * provided hash table pointer is NULL, logs an error if it is, and returns an error code.
 * If the pointer is valid, the hash table is freed, and the function returns `RT_SUCCESS`.
 *
 * @param ef_peer_hash Pointer to the RTE hash table to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if the hash table is NULL.
 */
int ef_peer_hash_delete(struct rte_hash * ef_peer_hash)
{
    if (ef_peer_hash == NULL)
    {
        MR_ERROR("The ef_peer_hash is NULL.");
        return RT_ERR;
    }

    rte_hash_free(ef_peer_hash);
    return RT_SUCCESS;
}

/**
 * @brief Deletes an ef_peer_handle structure and frees its associated resources.
 *
 * This function releases the memory allocated for an `ef_peer_handle` structure and its
 * associated resources, including the `ef_peer_hash` hash table and the `ef_peers` array.
 * It checks if the `ef_peer_handle` is NULL and logs an error if it is. If valid, it
 * proceeds to delete the hash table and free the peers array before freeing the handle itself.
 * The function returns `RT_SUCCESS` upon successful deletion, or `RT_ERR` if the handle is NULL.
 *
 * @param ef_peer_handle Pointer to the ef_peer_handle structure to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if the handle is NULL.
 */
int ef_peer_handle_delete(struct ef_peer_handle * ef_peer_handle)
{
    if (ef_peer_handle == NULL)
    {
        MR_ERROR("The ef_peer_handle is NULL.");
        return RT_ERR;
    }

    if (ef_peer_handle->ef_peer_hash != NULL)
    {
        ef_peer_hash_delete(ef_peer_handle->ef_peer_hash);
        ef_peer_handle->ef_peer_hash = NULL;
    }

    if (ef_peer_handle->ef_peers != NULL)
    {
        FREE(ef_peer_handle->ef_peers);
        ef_peer_handle->ef_peers = NULL;
    }

    FREE(ef_peer_handle);

    return RT_SUCCESS;
}

/**
 * @brief Creates an ef_peer_handle structure with the specified number of entries.
 *
 * This function initializes and creates an `ef_peer_handle` structure to manage `ef_peer` entries.
 * It first calculates the capacity based on the number of entries and checks if the entries value
 * is valid. The function allocates memory for the `ef_peer_handle` structure and its associated
 * peers array, initializing the atomic state for each peer. It then creates the associated `ef_peer_hash`
 * table. If any allocation or creation fails, appropriate error messages are logged, and the resources
 * are cleaned up before returning `NULL`.
 *
 * @param entries The number of `ef_peer` entries to manage within the handle.
 *
 * @return Pointer to the created `ef_peer_handle` structure if successful, NULL otherwise.
 */
struct ef_peer_handle * ef_peer_handle_create(uint32_t entries)
{
    if (entries == 0)
    {
        MR_ERROR("The ef_peer entries value is 0.");
        return NULL;
    }

    uint32_t capacity = SC_EF_PEER_CAPACITY_CALC(entries, LCORE_CACHE_SIZE);
    if (entries >= capacity)
    {
        MR_ERROR("The ef_peer entries value is too large.");
        return NULL;
    }

    struct ef_peer_handle * ef_peer_handle = ZMALLOC(sizeof(struct ef_peer_handle));
    MR_VERIFY_MALLOC(ef_peer_handle);

    struct ef_peer * ef_peers = ZMALLOC(sizeof(struct ef_peer) * capacity);
    MR_VERIFY_MALLOC(ef_peers);

    ef_peer_handle->capacity = capacity;
    ef_peer_handle->entries = entries;
    ef_peer_handle->remaining_entries = entries;
    ef_peer_handle->ef_peers = ef_peers;

    for (int i = 0; i < capacity; i++)
    {
        rte_atomic64_init(&ef_peers[i].state);
    }

    ef_peer_handle->ef_peer_hash = ef_peer_hash_create(entries);
    if (ef_peer_handle->ef_peer_hash == NULL)
    {
        MR_ERROR("Failed to create the ef_peer hash.");
        ef_peer_handle_delete(ef_peer_handle);
        return NULL;
    }

    return ef_peer_handle;
}

/**
 * @brief Retrieves the capacity of the ef_peer_handle.
 *
 * This function returns the maximum number of `ef_peer` entries that the specified
 * `ef_peer_handle` can manage. The function asserts that the handle is not NULL
 * before accessing its capacity.
 *
 * @param handle Pointer to the `ef_peer_handle` structure.
 *
 * @return The capacity of the `ef_peer_handle`.
 */
uint32_t ef_peer_handle_capacity_get(struct ef_peer_handle * handle)
{
    assert(handle != NULL);
    return handle->capacity;
}

/**
 * @brief Retrieves the number of entries in the ef_peer_handle.
 *
 * This function returns the number of `ef_peer` entries currently managed by the specified
 * `ef_peer_handle`. The function asserts that the handle is not NULL before accessing its entries.
 *
 * @param handle Pointer to the `ef_peer_handle` structure.
 *
 * @return The number of entries in the `ef_peer_handle`.
 */
uint32_t ef_peer_handle_entries_get(struct ef_peer_handle * handle)
{
    assert(handle != NULL);
    return handle->entries;
}

/**
 * @brief Retrieves the number of remaining entries in the ef_peer_handle.
 *
 * This function returns the number of remaining `ef_peer` entries that can be added to the specified
 * `ef_peer_handle`. The function asserts that the handle is not NULL before accessing its remaining entries.
 *
 * @param handle Pointer to the `ef_peer_handle` structure.
 *
 * @return The number of remaining entries in the `ef_peer_handle`.
 */
uint32_t ef_peer_handle_remaining_entries_get(struct ef_peer_handle * handle)
{
    assert(handle != NULL);
    return handle->remaining_entries;
}

/**
 * @brief Retrieves a pointer to an ef_peer by its index within the ef_peer_handle.
 *
 * This inline function returns a pointer to the `ef_peer` structure within the specified
 * `ef_peer_handle` corresponding to the given `ef_peer_index`. The function asserts that
 * the handle is not NULL and that the index is within the valid range of the handle's capacity.
 *
 * @param handle Pointer to the `ef_peer_handle` structure.
 * @param ef_peer_index The index of the peer to retrieve.
 *
 * @return Pointer to the `ef_peer` structure at the specified index.
 */
static inline struct ef_peer * __ef_peer_handle_peer_get(struct ef_peer_handle * handle, uint16_t ef_peer_index)
{
    assert(handle != NULL);
    assert(ef_peer_index < handle->capacity);

    return &handle->ef_peers[ef_peer_index];
}

/**
 * @brief Retrieves a pointer to an ef_peer by its index within the ef_peer_handle.
 *
 * This function returns a pointer to the `ef_peer` structure within the specified
 * `ef_peer_handle` corresponding to the given `ef_peer_index`. It simply calls the
 * internal function `__ef_peer_handle_peer_get` to perform the retrieval.
 *
 * @param handle Pointer to the `ef_peer_handle` structure.
 * @param ef_peer_index The index of the peer to retrieve.
 *
 * @return Pointer to the `ef_peer` structure at the specified index.
 */
struct ef_peer * ef_peer_handle_peer_get(struct ef_peer_handle * handle, uint16_t ef_peer_index)
{
    return __ef_peer_handle_peer_get(handle, ef_peer_index);
}

/**
 * @brief Looks up an ef_peer in the ef_peer_handle by its key.
 *
 * This inline function searches for an `ef_peer` within the specified `ef_peer_handle` using
 * the given `ef_peer_key`. It utilizes the `rte_hash_lookup` function to find the index
 * corresponding to the key in the hash table. The function returns the index of the found
 * peer or a negative value if the key is not found.
 *
 * @param handle Pointer to the `ef_peer_handle` structure containing the hash table.
 * @param key Pointer to the `ef_peer_key` used for lookup.
 *
 * @return The index of the found `ef_peer`, or a negative value if the key is not found.
 */
static inline int __ef_peer_handle_peer_lookup(struct ef_peer_handle * handle, const union ef_peer_key * key)
{
    return rte_hash_lookup(handle->ef_peer_hash, (const void *)key);
}

/**
 * @brief Looks up an ef_peer in the ef_peer_handle by its key.
 *
 * This function searches for an `ef_peer` within the specified `ef_peer_handle` using the
 * provided `ef_peer_key`. It calls the internal function `__ef_peer_handle_peer_lookup`
 * to perform the actual lookup using the hash table. The function returns the index of the
 * found peer or a negative value if the key is not found.
 *
 * @param handle Pointer to the `ef_peer_handle` structure containing the hash table.
 * @param key Pointer to the `ef_peer_key` used for lookup.
 *
 * @return The index of the found `ef_peer`, or a negative value if the key is not found.
 */
int ef_peer_handle_peer_lookup(struct ef_peer_handle * handle, const union ef_peer_key * key)
{
    return __ef_peer_handle_peer_lookup(handle, key);
}

/**
 * @brief Adds a new ef_peer to the ef_peer_handle using the specified key.
 *
 * This function attempts to add a new `ef_peer` to the `ef_peer_handle` using the provided
 * `ef_peer_key`. It first adds the key to the hash table using `rte_hash_add_key`. If the
 * addition is successful, the function retrieves the corresponding `ef_peer` structure and
 * initializes its state and properties. The number of remaining entries in the handle is
 * then decremented. If the addition is successful, information about the new `ef_peer` is
 * logged, including its IP and MAC addresses. The function returns the index of the added
 * peer if successful, or `RT_ERR` if the addition fails.
 *
 * @param handle Pointer to the `ef_peer_handle` structure where the peer will be added.
 * @param key Pointer to the `ef_peer_key` structure containing the peer's IP and MAC addresses.
 *
 * @return The index of the added `ef_peer` if successful, or `RT_ERR` if the addition fails.
 */
int ef_peer_handle_peer_add(struct ef_peer_handle * handle, const union ef_peer_key * key)
{
    /* Add the new ef_peer */
    int ret = rte_hash_add_key(handle->ef_peer_hash, (void *)key);

    if (likely(ret >= 0))
    {
        /* Set the ef_peer state */
        struct ef_peer * ef_peer = __ef_peer_handle_peer_get(handle, ret);
        if (rte_atomic64_test_and_set(&ef_peer->state))
        {
            /* Save the ef_peer info */
            ef_peer->ef_ip_addr = key->ip_src;
            rte_ether_addr_copy(&key->mac_src, &ef_peer->ef_mac_addr);

            /* Decrease the remaining entries */
            handle->remaining_entries--;

            /* Dump ef_peer for  new add */
            char str_in_addr[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &ef_peer->ef_ip_addr, str_in_addr, sizeof(str_in_addr));

            char str_mac_addr[RTE_ETHER_ADDR_FMT_SIZE];
            rte_ether_format_addr(str_mac_addr, sizeof(str_mac_addr), &ef_peer->ef_mac_addr);

            MR_INFO("Ef Peer add, index %d, core %u, ip addr:%s, mac addr:%s, remaining entries:%u", ret,
                    rte_lcore_id(), str_in_addr, str_mac_addr, handle->remaining_entries);
        }

        return ret;
    }

    return RT_ERR;
}

/**
 * @brief Retrieves the IP address of the specified ef_peer.
 *
 * This function returns the IP address of the given `ef_peer` structure. The function asserts
 * that the `ef_peer` pointer is not NULL before accessing its IP address.
 *
 * @param ef_peer Pointer to the `ef_peer` structure.
 *
 * @return The IP address of the specified `ef_peer`.
 */
uint32_t ef_peer_ip_addr_get(struct ef_peer * ef_peer)
{
    assert(ef_peer != NULL);
    return ef_peer->ef_ip_addr;
}

/**
 * @brief Retrieves the MAC address of the specified ef_peer.
 *
 * This function returns a pointer to the MAC address of the given `ef_peer` structure. The function
 * asserts that the `ef_peer` pointer is not NULL before accessing its MAC address.
 *
 * @param ef_peer Pointer to the `ef_peer` structure.
 *
 * @return Pointer to the MAC address of the specified `ef_peer`.
 */
struct rte_ether_addr * ef_peer_mac_addr_get(struct ef_peer * ef_peer)
{
    assert(ef_peer != NULL);
    return &ef_peer->ef_mac_addr;
}

/********************************************* Traffic Link Peer Map func *********************************************/
/**
 * @brief Creates a tl_to_ef_peer_map_handle structure with the specified capacity.
 *
 * This function initializes and allocates memory for a `tl_to_ef_peer_map_handle` structure,
 * which maps TL peers to EF peers. The function ensures the provided capacity is not zero
 * and allocates memory for the handle and its internal maps table. Each entry in the maps
 * table is initialized with an atomic value of -1. If any allocation fails, an error is
 * logged, and the function returns NULL.
 *
 * @param capacity The maximum number of entries in the maps table.
 *
 * @return Pointer to the created `tl_to_ef_peer_map_handle` structure if successful, NULL otherwise.
 */
struct tl_to_ef_peer_map_handle * tl_to_ef_peer_map_handle_create(uint16_t capacity)
{
    if (capacity == 0)
    {
        MR_ERROR("The capacity is 0.");
        return NULL;
    }

    struct tl_to_ef_peer_map_handle * handle = ZMALLOC(sizeof(struct tl_to_ef_peer_map_handle));
    MR_VERIFY_MALLOC(handle);

    handle->capacity = capacity;
    handle->maps_table = ZMALLOC(sizeof(rte_atomic64_t) * capacity);
    MR_VERIFY_MALLOC(handle->maps_table);

    for (int i = 0; i < capacity; i++)
    {
        rte_atomic64_init(&handle->maps_table[i]);
        rte_atomic64_set(&handle->maps_table[i], -1);
    }

    return handle;
}

/**
 * @brief Deletes a tl_to_ef_peer_map_handle structure and frees its associated resources.
 *
 * This function releases the memory allocated for a `tl_to_ef_peer_map_handle` structure
 * and its internal maps table. It checks if the handle is NULL and logs an error if it is.
 * If valid, it frees the maps table and the handle itself. The function returns `RT_SUCCESS`
 * upon successful deletion, or `RT_ERR` if the handle is NULL.
 *
 * @param handle Pointer to the `tl_to_ef_peer_map_handle` structure to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if the handle is NULL.
 */
int tl_to_ef_peer_map_handle_delete(struct tl_to_ef_peer_map_handle * handle)
{
    if (handle == NULL)
    {
        MR_ERROR("Invalid argument: handle is NULL.");
        return RT_ERR;
    }

    if (handle->maps_table != NULL)
    {
        FREE(handle->maps_table);
        handle->maps_table = NULL;
    }

    FREE(handle);

    return RT_SUCCESS;
}

/**
 * @brief Associates a traffic link ID with an ef_peer index in the tl_to_ef_peer_map_handle.
 *
 * This inline function sets the association between a `traffic_link_id` and an `ef_peer_index`
 * in the `tl_to_ef_peer_map_handle`. It checks that the `traffic_link_id` is within the valid
 * range of the handle's capacity before setting the value in the maps table. The function returns
 * `RT_SUCCESS` if the association is successful, or `RT_ERR` if the `traffic_link_id` is out of bounds.
 *
 * @param handle Pointer to the `tl_to_ef_peer_map_handle` structure.
 * @param traffic_link_id The traffic link ID to associate.
 * @param ef_peer_index The ef_peer index to associate with the traffic link ID.
 *
 * @return RT_SUCCESS on successful association, RT_ERR if the `traffic_link_id` is out of bounds.
 */
static inline int __tl_to_ef_peer_map_handle_associate(struct tl_to_ef_peer_map_handle * handle,
                                                       uint16_t traffic_link_id, int ef_peer_index)
{
    assert(handle != NULL);

    if (unlikely(traffic_link_id >= handle->capacity))
    {
        return RT_ERR;
    }

    rte_atomic64_set(&handle->maps_table[traffic_link_id], ef_peer_index);

    return RT_SUCCESS;
}

/**
 * @brief Associates a traffic link ID with an ef_peer index in the tl_to_ef_peer_map_handle.
 *
 * This function sets the association between a `traffic_link_id` and an `ef_peer_index`
 * in the `tl_to_ef_peer_map_handle` by calling the internal function `__tl_to_ef_peer_map_handle_associate`.
 *
 * @param handle Pointer to the `tl_to_ef_peer_map_handle` structure.
 * @param traffic_link_id The traffic link ID to associate.
 * @param ef_peer_index The ef_peer index to associate with the traffic link ID.
 *
 * @return RT_SUCCESS on successful association, RT_ERR if the `traffic_link_id` is out of bounds.
 */
int tl_to_ef_peer_map_handle_associate(struct tl_to_ef_peer_map_handle * handle, uint16_t traffic_link_id,
                                       int ef_peer_index)
{
    return __tl_to_ef_peer_map_handle_associate(handle, traffic_link_id, ef_peer_index);
}

/**
 * @brief Retrieves the capacity of the tl_to_ef_peer_map_handle.
 *
 * This function returns the maximum number of traffic link IDs that can be mapped within
 * the specified `tl_to_ef_peer_map_handle`. The function asserts that the handle is not NULL
 * before accessing its capacity.
 *
 * @param handle Pointer to the `tl_to_ef_peer_map_handle` structure.
 *
 * @return The capacity of the `tl_to_ef_peer_map_handle`.
 */
uint16_t tl_to_ef_peer_map_handle_capacity_get(struct tl_to_ef_peer_map_handle * handle)
{
    assert(handle != NULL);
    return handle->capacity;
}

/**
 * @brief Retrieves the EF peer index associated with a given traffic link ID.
 *
 * This function searches for the EF peer index associated with the specified `traffic_link_id`
 * within the `tl_to_ef_peer_map_handle`. If the handle is NULL or the `traffic_link_id` is out
 * of range, the function returns `RT_ERR`. If the `traffic_link_id` is valid, the associated
 * EF peer index is stored in `out_ef_peer_index`, and the function returns `RT_SUCCESS`.
 *
 * @param handle Pointer to the `tl_to_ef_peer_map_handle` structure.
 * @param traffic_link_id The traffic link ID to look up.
 * @param out_ef_peer_index Pointer to where the associated EF peer index will be stored.
 *
 * @return RT_SUCCESS if the EF peer index is successfully retrieved, RT_ERR otherwise.
 */
int tl_to_ef_peer_map_handle_get_ef_peer_index_by_tl_id(struct tl_to_ef_peer_map_handle * handle,
                                                        uint16_t traffic_link_id, uint16_t * out_ef_peer_index)
{
    if (handle == NULL)
    {
        return RT_ERR;
    }

    if (unlikely(traffic_link_id < handle->capacity))
    {
        *out_ef_peer_index = rte_atomic64_read(&handle->maps_table[traffic_link_id]);
        return RT_SUCCESS;
    }

    return RT_ERR;
}

/*********************************************** Etherfabric main func ************************************************/
/**
 * @brief Creates an ef_config_handle structure with the specified maximum number of EF adapters.
 *
 * This function initializes and allocates memory for an `ef_config_handle` structure, which holds
 * configuration data for EF adapters. It allocates memory for the handle itself and for the array
 * that stores EF adapter data. The function asserts that the maximum number of adapters is greater
 * than zero and verifies that the memory allocations are successful.
 *
 * @param ef_adapters_max The maximum number of EF adapters to be managed within the handle.
 *
 * @return Pointer to the created `ef_config_handle` structure if successful, NULL otherwise.
 */
struct ef_config_handle * ef_config_handle_create(uint32_t ef_adapters_max)
{
    assert(ef_adapters_max > 0);

    struct ef_config_handle * cfg_handle = ZMALLOC(sizeof(struct ef_config_handle));
    MR_VERIFY_MALLOC(cfg_handle);

    cfg_handle->ef_adapters_data = ZMALLOC(sizeof(struct ef_adapter) * ef_adapters_max);
    MR_VERIFY_MALLOC(cfg_handle->ef_adapters_data);

    cfg_handle->ef_adapters_max = ef_adapters_max;
    return cfg_handle;
}

/**
 * @brief Deletes an ef_config_handle structure and frees its associated resources.
 *
 * This function releases the memory allocated for an `ef_config_handle` structure and its
 * associated EF adapters data. It checks if the handle or its data is NULL and logs an error
 * if either is NULL. If valid, the function frees the adapters data and the handle itself.
 * The function returns `RT_SUCCESS` upon successful deletion, or `RT_ERR` if the handle or
 * its data is NULL.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if the handle or its data is NULL.
 */
int ef_config_handle_delete(struct ef_config_handle * cfg_handle)
{
    if (cfg_handle == NULL)
    {
        MR_ERROR("The ef_node_cfg is NULL.");
        return RT_ERR;
    }

    if (cfg_handle->ef_adapters_data == NULL)
    {
        MR_ERROR("The ef_node_cfg->ef_adapters_data is NULL.");
        return RT_ERR;
    }

    FREE(cfg_handle->ef_adapters_data);
    cfg_handle->ef_adapters_data = NULL;

    FREE(cfg_handle);

    return RT_SUCCESS;
}

/**
 * @brief Parses the Etherfabric adapter configuration from the specified configuration file.
 *
 * This function reads and parses the configuration file to load the settings for Etherfabric
 * adapters. It retrieves the maximum number of link databases, SID start and end values,
 * and iterates through the configuration sections to load adapter mode, adapter ID, and
 * listening device information. The function checks for valid configurations and logs errors
 * if any invalid configurations are found. It also checks that the number of adapters does not
 * exceed the SID capacity. The parsed data is saved into the `ef_config_handle` structure.
 *
 * @param sc Pointer to the `sc_main` structure containing the configuration file and device manager.
 * @param cfg_handle Pointer to the `ef_config_handle` structure where the parsed data will be stored.
 *
 * @return RT_SUCCESS if the configuration is successfully parsed, RT_ERR otherwise.
 */
int ef_config_parse(struct sc_main * sc, struct ef_config_handle * cfg_handle)
{
    /* Get the max ef adapters */
    uint32_t link_dbs_max = 0;
    MESA_load_profile_uint_def(sc->local_cfgfile, "limits", "nr_max_link_dbs", &link_dbs_max, 64);
    if (link_dbs_max == 0)
    {
        MR_ERROR("The 'nr_max_link_dbs' is invalid.");
        return RT_ERR;
    }

    /* Get sid range start */
    uint32_t sid_start = 0;
    MESA_load_profile_uint_def(sc->local_cfgfile, "ef_adapters", "sid_start", &sid_start, 100);

    /* Get sid range end */
    uint32_t sid_end = 0;
    MESA_load_profile_uint_def(sc->local_cfgfile, "ef_adapters", "sid_end", &sid_end, 200);

    /* Check the sid range */
    if (sid_start > sid_end)
    {
        MR_ERROR("Etherfabric adapters config 'sid_end' less than 'sid_start' .");
        return RT_ERR;
    }

    /* Parsing all config */
    uint16_t nr_adapters = 0;
    for (int index = 0; index < cfg_handle->ef_adapters_max; index++)
    {
        char str_conf_section[MR_STRING_MAX] = {};
        snprintf(str_conf_section, sizeof(str_conf_section), "ef_adapter:%d", index);

        /* Get etherfabric adapter mode */
        uint32_t mode;
        int ret = MESA_load_profile_uint_nodef(sc->local_cfgfile, str_conf_section, "mode", &mode);
        if (ret < 0)
        {
            continue;
        }

        if ((mode != EF_MODE_VIRTUAL_WIRE) && (mode != EF_MODE_TAP))
        {
            MR_ERROR("The : %s 'mode' is invalid:  %u", str_conf_section, mode);
            return RT_ERR;
        }

        /* Get etherfabric adapter id */
        uint32_t ef_adapter_id = 0;
        ret = MESA_load_profile_uint_nodef(sc->local_cfgfile, str_conf_section, "ef_adapter_id", &ef_adapter_id);

        if (ret < 0)
        {
            MR_ERROR("The : %s ,No config the 'ef_adapter_id'.", str_conf_section);
            return RT_ERR;
        }

        if (ef_adapter_id >= cfg_handle->ef_adapters_max)
        {
            MR_ERROR("The : %s 'ef_adapter_id' is invalid:  %u", str_conf_section, ef_adapter_id);
            return RT_ERR;
        }

        /* Parsing listen device */
        char str_listen_device[MR_STRING_MAX] = {};
        ret = MESA_load_profile_string_nodef(sc->local_cfgfile, str_conf_section, "listen_device", str_listen_device,
                                             sizeof(str_listen_device));
        if (ret < 0)
        {
            MR_ERROR("The : %s ,No config the 'listen_device'.", str_conf_section);
            return RT_ERR;
        }

        struct mr_dev_desc * dev_desc = mr_dev_desc_lookup(sc->devmgr_main, str_listen_device);
        if (dev_desc == NULL)
        {
            MR_ERROR("The : %s 'listen_device' is invalid:  %s", str_conf_section, str_listen_device);
            return RT_ERR;
        }

        if (dev_desc->dev_mode == MR_DEV_MODE_TRUNK)
        {
            MR_ERROR("The : %s 'listen_device[%s]' is in trunk mode, which is not supported by Etherfabric.",
                     str_conf_section, str_listen_device);
            return RT_ERR;
        }

        /* Port adapter mapping insert */
        port_adapter_mapping_insert(dev_desc->port_id, ADAPTER_TYPE_EF);

        /* Save The Listen Device Port Index */
        struct ef_adapter * ef_adapter = &cfg_handle->ef_adapters_data[ef_adapter_id];
        ef_adapter->id = ef_adapter_id;
        ef_adapter->mode = mode;
        ef_adapter->listening_device = dev_desc;
        nr_adapters++;
    }

    /* Check nr adapter */
    uint32_t sid_capacity = sid_end - sid_start + 1;
    if (nr_adapters > sid_capacity)
    {
        MR_ERROR("Etherfabric adapters num:%u out of sid num: %u .", nr_adapters, sid_capacity);
        return RT_ERR;
    }

    /* Save the etherfabric adapter config date */
    cfg_handle->nr_adapters = nr_adapters;
    cfg_handle->sid_start = sid_start;
    cfg_handle->sid_end = sid_end;
    cfg_handle->link_dbs_max = link_dbs_max;

    return RT_SUCCESS;
}

/**
 * @brief Retrieves the EF adapters data array from the ef_config_handle.
 *
 * This function returns a pointer to the array of `ef_adapter` structures stored within the
 * specified `ef_config_handle`. The function asserts that the handle is not NULL before
 * accessing the data.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return Pointer to the array of `ef_adapter` structures.
 */
struct ef_adapter * ef_config_handle_adapters_data_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->ef_adapters_data;
}

/**
 * @brief Retrieves the number of adapters currently configured in the ef_config_handle.
 *
 * This function returns the number of EF adapters that have been successfully configured
 * within the specified `ef_config_handle`. The function asserts that the handle is not NULL
 * before accessing the number of adapters.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return The number of configured EF adapters.
 */
uint16_t ef_config_handle_nr_adapters_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->nr_adapters;
}

/**
 * @brief Retrieves the starting SID (Service ID) from the ef_config_handle.
 *
 * This function returns the starting Service ID (SID) for the EF adapters as specified in the
 * configuration stored within the `ef_config_handle`. The function asserts that the handle is
 * not NULL before accessing the SID start value.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return The starting SID for the EF adapters.
 */
uint32_t ef_config_handle_sid_start_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->sid_start;
}

/**
 * @brief Retrieves the ending SID (Service ID) from the ef_config_handle.
 *
 * This function returns the ending Service ID (SID) for the EF adapters as specified in the
 * configuration stored within the `ef_config_handle`. The function asserts that the handle is
 * not NULL before accessing the SID end value.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return The ending SID for the EF adapters.
 */
uint32_t ef_config_handle_sid_end_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->sid_end;
}

/**
 * @brief Retrieves the maximum number of EF adapters that can be configured in the ef_config_handle.
 *
 * This function returns the maximum number of EF adapters that the specified `ef_config_handle`
 * can manage. The function asserts that the handle is not NULL before accessing the maximum value.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return The maximum number of EF adapters that can be configured.
 */
uint32_t ef_config_handle_ef_adapters_max_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->ef_adapters_max;
}

/**
 * @brief Retrieves the maximum number of link databases in the ef_config_handle.
 *
 * This function returns the maximum number of link databases that can be configured
 * within the specified `ef_config_handle`. The function asserts that the handle is not NULL
 * before accessing the maximum number of link databases.
 *
 * @param cfg_handle Pointer to the `ef_config_handle` structure.
 *
 * @return The maximum number of link databases.
 */
uint32_t ef_config_handle_link_dbs_max_get(struct ef_config_handle * cfg_handle)
{
    assert(cfg_handle != NULL);
    return cfg_handle->link_dbs_max;
}

/**
 * @brief Retrieves a pointer to the global ef_node_main structure (internal function).
 *
 * This inline function returns a pointer to the global `ef_node_main` structure. It is an
 * internal helper function used to access the global variable `g_ef_main`.
 *
 * @return Pointer to the global `ef_node_main` structure.
 */
static inline struct ef_node_main * __g_ef_node_main_get(void)
{
    return g_ef_main;
}

/**
 * @brief Retrieves a pointer to the global ef_node_main structure.
 *
 * This function returns a pointer to the global `ef_node_main` structure by calling the
 * internal helper function `__g_ef_node_main_get`. It provides external access to the
 * global variable `g_ef_main`.
 *
 * @return Pointer to the global `ef_node_main` structure.
 */
struct ef_node_main * g_ef_node_main_get(void)
{
    return __g_ef_node_main_get();
}

/**
 * @brief Sets the global ef_node_main structure.
 *
 * This inline function assigns the provided `ef_node_main` structure to the global variable
 * `g_ef_main`. It is used to update the global state with the new EF node main configuration.
 *
 * @param ef_main Pointer to the `ef_node_main` structure to be set as the global instance.
 *
 * @return RT_SUCCESS indicating the operation was successful.
 */
static inline int g_ef_node_main_set(struct ef_node_main * ef_main)
{
    g_ef_main = ef_main;
    return RT_SUCCESS;
}

/**
 * @brief Deletes the ef_node_main structure and frees its associated resources.
 *
 * This function releases the memory and resources allocated for the `ef_node_main` structure,
 * including the metrics handles, SID handle, EF adapter handle, link database context, EF peer
 * handle, and traffic link to EF peer map handle. It checks for NULL pointers and logs errors
 * if any are encountered. The function returns `RT_SUCCESS` upon successful deletion, or `RT_ERR`
 * if any of the resources could not be freed.
 *
 * @param ef_main Pointer to the `ef_node_main` structure to be deleted.
 *
 * @return RT_SUCCESS on successful deletion, RT_ERR if any resource deletion fails.
 */
int node_ef_main_delete(struct ef_node_main * ef_main)
{
    if (ef_main == NULL)
    {
        MR_ERROR("The ef_main is NULL.");
        return RT_ERR;
    }

    /* Delete the metrics handles */
    for (uint16_t i = 0; i < ef_main->nr_graphs; i++)
    {
        if (ef_main->ingress_metrics_handles[i] != NULL)
        {
            sc_metrics_handle_delete(ef_main->ingress_metrics_handles[i]);
            ef_main->ingress_metrics_handles[i] = NULL;
        }

        if (ef_main->egress_metrics_handles[i] != NULL)
        {
            sc_metrics_handle_delete(ef_main->egress_metrics_handles[i]);
            ef_main->egress_metrics_handles[i] = NULL;
        }
    }

    /* Delete the sid handle */
    if (ef_main->sid_handle != NULL)
    {
        sid_handle_delete(ef_main->sid_handle);
        ef_main->sid_handle = NULL;
    }

    /* Delete the ef_adapter_handle */
    if (ef_main->ef_adapter_handle != NULL)
    {
        ef_adapter_handle_delete(ef_main->ef_adapter_handle);
        ef_main->ef_adapter_handle = NULL;
    }

    /* Delete the link db ctx */
    if (ef_main->link_db_ctx != NULL)
    {
        link_db_destroy(&ef_main->link_db_ctx);
        ef_main->link_db_ctx = NULL;
    }

    /* Delete the ef_peer_handle */
    if (ef_main->ef_peer_handle != NULL)
    {
        ef_peer_handle_delete(ef_main->ef_peer_handle);
        ef_main->ef_peer_handle = NULL;
    }

    /* Delete the tl_to_ef_peer_map_handle */
    if (ef_main->tl_to_ef_peer_map_handle != NULL)
    {
        tl_to_ef_peer_map_handle_delete(ef_main->tl_to_ef_peer_map_handle);
        ef_main->tl_to_ef_peer_map_handle = NULL;
    }

    FREE(ef_main);

    return RT_SUCCESS;
}

/**
 * @brief Creates an ef_node_main structure and initializes its components.
 *
 * This function initializes and allocates memory for an `ef_node_main` structure, which manages
 * various resources related to Etherfabric nodes. It creates metrics handles, SID handle, EF adapter
 * handle, link database context, EF peer handle, and traffic link to EF peer map handle. If any
 * component creation fails, the function logs an error, cleans up resources, and returns NULL.
 *
 * @param sc Pointer to the `sc_main` structure containing the configuration file and other resources.
 * @param ef_node_cfg Pointer to the `ef_config_handle` structure containing configuration data.
 *
 * @return Pointer to the created `ef_node_main` structure if successful, NULL otherwise.
 */
struct ef_node_main * node_ef_main_create(struct sc_main * sc, struct ef_config_handle * ef_node_cfg)
{
    /* Check the input */
    if (sc == NULL)
    {
        MR_ERROR("The sc is NULL.");
        return NULL;
    }

    if (ef_node_cfg == NULL)
    {
        MR_ERROR("The ef_node_cfg is NULL.");
        return NULL;
    }

    /* Create the ef main */
    struct ef_node_main * ef_main = ZMALLOC(sizeof(struct ef_node_main));
    MR_VERIFY_MALLOC(ef_main);

    /* Set the number of graphs */
    ef_main->nr_graphs = sc->nr_io_thread;

    /* Create the metrics handles */
    ef_main->ingress_metrics_handles = ZMALLOC(sizeof(struct sc_metrics_handle *) * ef_main->nr_graphs);
    MR_VERIFY_MALLOC(ef_main->ingress_metrics_handles);

    ef_main->egress_metrics_handles = ZMALLOC(sizeof(struct sc_metrics_handle *) * ef_main->nr_graphs);
    MR_VERIFY_MALLOC(ef_main->egress_metrics_handles);

    for (uint16_t i = 0; i < ef_main->nr_graphs; i++)
    {
        ef_main->ingress_metrics_handles[i] = sc_metrics_handle_create(EF_INGR_METRIC_MAX);
        if (ef_main->ingress_metrics_handles[i] == NULL)
        {
            MR_ERROR("Failed to create the ingress metrics handle.");
            goto end;
        }

        ef_main->egress_metrics_handles[i] = sc_metrics_handle_create(EF_EGR_METRIC_MAX);
        if (ef_main->egress_metrics_handles[i] == NULL)
        {
            MR_ERROR("Failed to create the egress metrics handle.");
            goto end;
        }
    }

    /* Create sid handle */
    ef_main->sid_handle = sid_handle_create(ef_node_cfg->sid_start, ef_node_cfg->sid_end);
    if (ef_main->sid_handle == NULL)
    {
        MR_ERROR("Failed to create the sid handle.");
        goto end;
    }

    /* Create ef_adapter_handle */
    ef_main->ef_adapter_handle = ef_adapter_handle_create(ef_node_cfg->ef_adapters_data, ef_node_cfg->ef_adapters_max,
                                                          ef_node_cfg->nr_adapters);
    if (ef_main->ef_adapter_handle == NULL)
    {
        MR_ERROR("Failed to create the ef_adapter_handle.");
        goto end;
    }

    /* Create link db ctx */
    ef_main->link_db_ctx = link_db_create(LINK_DB_TYPE_EF, ef_node_cfg->link_dbs_max);
    if (ef_main->link_db_ctx == NULL)
    {
        MR_ERROR("Failed to create the link db ctx.");
        goto end;
    }

    if (link_db_config_parse(sc->local_cfgfile, ef_main->link_db_ctx) == RT_ERR)
    {
        MR_ERROR("Failed to parse the link db config.");
        goto end;
    }

    /* Create ef peer handle */
    ef_main->ef_peer_handle = ef_peer_handle_create(SC_EF_PEER_ENTRIES);
    if (ef_main->ef_peer_handle == NULL)
    {
        MR_ERROR("Failed to create the ef peer handle.");
        goto end;
    }

    /* Create tl to ef peer map handle */
    ef_main->tl_to_ef_peer_map_handle = tl_to_ef_peer_map_handle_create(UINT16_MAX);
    if (ef_main->tl_to_ef_peer_map_handle == NULL)
    {
        MR_ERROR("Failed to create the traffic link to ef peer map handle.");
        goto end;
    }

    return ef_main;

end:
    node_ef_main_delete(ef_main);
    return NULL;
}

/**
 * @brief Retrieves the number of graphs in the ef_node_main structure.
 *
 * This function returns the number of graphs (I/O threads) configured in the specified
 * `ef_node_main` structure. The function asserts that the `ef_node_main` pointer is not NULL
 * before accessing the number of graphs.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return The number of graphs (I/O threads) in the `ef_node_main` structure.
 */
uint16_t node_ef_main_nr_graphs_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->nr_graphs;
}

/**
 * @brief Retrieves the SID handle from the ef_node_main structure.
 *
 * This function returns a pointer to the SID handle (`sid_handle`) stored within the specified
 * `ef_node_main` structure. The function asserts that the `ef_node_main` pointer is not NULL
 * before accessing the SID handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return Pointer to the `sid_handle` structure.
 */
struct sid_handle * node_ef_main_sid_handle_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->sid_handle;
}

/**
 * @brief Retrieves the EF adapter handle from the ef_node_main structure.
 *
 * This function returns a pointer to the EF adapter handle (`ef_adapter_handle`) stored within
 * the specified `ef_node_main` structure. The function asserts that the `ef_node_main` pointer
 * is not NULL before accessing the EF adapter handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return Pointer to the `ef_adapter_handle` structure.
 */
struct ef_adapter_handle * node_ef_main_ef_adapter_handle_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->ef_adapter_handle;
}

/**
 * @brief Retrieves the link database context from the ef_node_main structure.
 *
 * This function returns a pointer to the link database context (`link_db_ctx`) stored within
 * the specified `ef_node_main` structure. The function asserts that the `ef_node_main` pointer
 * is not NULL before accessing the link database context.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return Pointer to the `link_db_ctx` structure.
 */
struct link_db_ctx * node_ef_main_link_db_ctx_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->link_db_ctx;
}

/**
 * @brief Retrieves the EF peer handle from the ef_node_main structure.
 *
 * This function returns a pointer to the EF peer handle (`ef_peer_handle`) stored within the
 * specified `ef_node_main` structure. The function asserts that the `ef_node_main` pointer is
 * not NULL before accessing the EF peer handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return Pointer to the `ef_peer_handle` structure.
 */
struct ef_peer_handle * node_ef_main_ef_peer_handle_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->ef_peer_handle;
}

/**
 * @brief Retrieves the traffic link to EF peer map handle from the ef_node_main structure.
 *
 * This function returns a pointer to the traffic link to EF peer map handle (`tl_to_ef_peer_map_handle`)
 * stored within the specified `ef_node_main` structure. The function asserts that the `ef_node_main`
 * pointer is not NULL before accessing the map handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 *
 * @return Pointer to the `tl_to_ef_peer_map_handle` structure.
 */
struct tl_to_ef_peer_map_handle * node_ef_main_tl_to_ef_peer_map_handle_get(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);
    return ef_main->tl_to_ef_peer_map_handle;
}

/**
 * @brief Retrieves the ingress metrics handle for a specific graph from the ef_node_main structure.
 *
 * This function returns a pointer to the ingress metrics handle (`sc_metrics_handle`) corresponding
 * to the specified `graph_id` within the `ef_node_main` structure. The function asserts that the
 * `ef_node_main` pointer is not NULL and that the `graph_id` is within the valid range before
 * accessing the ingress metrics handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 * @param graph_id The ID of the graph (I/O thread) for which to retrieve the ingress metrics handle.
 *
 * @return Pointer to the ingress `sc_metrics_handle` structure for the specified graph.
 */
struct sc_metrics_handle * node_ef_main_ingress_metrics_handle_get(struct ef_node_main * ef_main, uint16_t graph_id)
{
    assert(ef_main != NULL);
    assert(graph_id < ef_main->nr_graphs);

    return ef_main->ingress_metrics_handles[graph_id];
}

/**
 * @brief Retrieves the egress metrics handle for a specific graph from the ef_node_main structure.
 *
 * This function returns a pointer to the egress metrics handle (`sc_metrics_handle`) corresponding
 * to the specified `graph_id` within the `ef_node_main` structure. The function asserts that the
 * `ef_node_main` pointer is not NULL and that the `graph_id` is within the valid range before
 * accessing the egress metrics handle.
 *
 * @param ef_main Pointer to the `ef_node_main` structure.
 * @param graph_id The ID of the graph (I/O thread) for which to retrieve the egress metrics handle.
 *
 * @return Pointer to the egress `sc_metrics_handle` structure for the specified graph.
 */
struct sc_metrics_handle * node_ef_main_egress_metrics_handle_get(struct ef_node_main * ef_main, uint16_t graph_id)
{
    assert(ef_main != NULL);
    assert(graph_id < ef_main->nr_graphs);

    return ef_main->egress_metrics_handles[graph_id];
}

/**
 * @brief Dumps the configuration information of Etherfabric adapters.
 *
 * This function logs detailed information about the Etherfabric adapters managed by the
 * specified `ef_node_main` structure. It retrieves the capacity of the EF adapters and
 * SID handle, and logs the total number of adapters, SID range, and the mode and listening
 * device for each adapter. If no adapters are configured, the function returns without
 * logging anything.
 *
 * @param ef_main Pointer to the `ef_node_main` structure containing the EF adapter configuration.
 */
void ef_info_dump(struct ef_node_main * ef_main)
{
    assert(ef_main != NULL);

    uint16_t ef_adapter_capacity = ef_adapter_handle_capacity_get(ef_main->ef_adapter_handle);

    if (ef_adapter_capacity == 0)
    {
        return;
    }

    uint16_t sid_capacity = sid_handle_capacity_get(ef_main->sid_handle);
    uint32_t sid_start = sid_handle_sid_start_get(ef_main->sid_handle);
    uint32_t sid_end = sid_handle_sid_end_get(ef_main->sid_handle);

    MR_INFO(" ");
    MR_INFO("Etherfabric adapter, total num: %u, sid num: %u, sid start: %u, sid end:%u", ef_adapter_capacity,
            sid_capacity, sid_start, sid_end);

    for (int i = 0; i < ef_adapter_capacity; i++)
    {
        char str_mode[MR_STRING_MAX] = {};
        struct ef_adapter * ef_adapter = ef_adapter_handle_adapter_get_by_id(ef_main->ef_adapter_handle, i);
        switch (ef_adapter->mode)
        {
        case EF_MODE_VIRTUAL_WIRE:
            sprintf(str_mode, "virtual-wire");
            break;
        case EF_MODE_TAP:
            sprintf(str_mode, "tap");
            break;
        default:
            continue;
        }

        MR_INFO("Etherfabric adapter, id:%u, mode: %s, listen device: %s", ef_adapter->id, str_mode,
                ef_adapter->listening_device->symbol);
    }
}

/**
 * @brief Initializes the Etherfabric node.
 *
 * This function initializes the Etherfabric node by retrieving the maximum number of EF adapters,
 * creating the EF adapter configuration, and parsing the configuration data. It then creates the
 * `ef_node_main` structure and inserts the corresponding SIDs into the forwarder table. If any step
 * fails, the function logs an error, cleans up resources, and returns an error code. Upon successful
 * initialization, the function dumps the Etherfabric adapter configuration and sets the global EF main.
 *
 * @param sc Pointer to the `sc_main` structure containing the main configuration and resources.
 *
 * @return RT_SUCCESS if the initialization is successful, RT_ERR otherwise.
 */
int ef_init(struct sc_main * sc)
{
    /* Get ef max entry,default is 256 */
    uint32_t ef_adapters_max = 0;
    int ret = adapters_max_get(sc, "nr_max_ef_adapters", &ef_adapters_max);
    if (ret != RT_SUCCESS)
    {
        MR_ERROR("Failed to get the ef adapters max.");
        return RT_ERR;
    }

    /* Create the ef adapter config */
    struct ef_config_handle * ef_node_cfg = ef_config_handle_create(ef_adapters_max);
    if (ef_node_cfg == NULL)
    {
        MR_ERROR("Failed to create the ef adapter cfg.");
        return RT_ERR;
    }

    /* Parse the ef adapter config */
    ret = ef_config_parse(sc, ef_node_cfg);
    if (ret != RT_SUCCESS)
    {
        MR_ERROR("Failed to parse the ef adapter config.");
        ret = RT_ERR;
        goto end;
    }

    struct ef_node_main * ef_main = node_ef_main_create(sc, ef_node_cfg);
    if (ef_main == NULL)
    {
        MR_ERROR("Failed to create the ef main.");
        ret = RT_ERR;
        goto end;
    }

    /* Inserter sid to forwarder table */
    uint32_t sid_start = sid_handle_sid_start_get(ef_main->sid_handle);
    for (int index = 0; index < ef_adapters_max; index++)
    {
        struct ef_adapter * ef_adapter = ef_adapter_handle_adapter_get_by_id(ef_main->ef_adapter_handle, index);
        if (ef_adapter->mode == EF_MODE_INVALID)
            continue;

        forwarder_table_insert(sid_start + ef_adapter->id, FORWARDER_TYPE_EF);
    }

    /* Dump the etherfabric adapter config */
    ef_info_dump(ef_main);

    /* Set the global ef main */
    g_ef_node_main_set(ef_main);
    ret = RT_SUCCESS;

end:
    ef_config_handle_delete(ef_node_cfg);
    return ret;
}

/**
 * @brief Deinitializes the Etherfabric node.
 *
 * This function deinitializes the Etherfabric node by retrieving the global `ef_node_main` structure,
 * deleting it, and resetting the global EF main pointer to NULL. If the `ef_node_main` structure is
 * not found, the function logs an error and returns an error code.
 *
 * @return RT_SUCCESS if the deinitialization is successful, RT_ERR otherwise.
 */
int ef_deinit()
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    if (ef_main == NULL)
    {
        MR_ERROR("The ef_main is NULL.");
        return RT_ERR;
    }

    node_ef_main_delete(ef_main);
    g_ef_node_main_set(NULL);

    return RT_SUCCESS;
}

/***********************************************  Extern func ************************************************/
/**
 * @brief Checks if a given EF adapter ID is valid.
 *
 * This function checks the validity of a specified `ef_adapter_id` by ensuring that the
 * Etherfabric node is initialized, the EF adapter capacity is non-zero, and the adapter ID
 * is within the valid range. It also checks if the adapter's mode is not set to `EF_MODE_INVALID`.
 * If any of these conditions are not met, the function returns `RT_ERR`, otherwise, it returns
 * `RT_SUCCESS`.
 *
 * @param ef_adapter_id The ID of the EF adapter to check.
 *
 * @return RT_SUCCESS if the EF adapter ID is valid, RT_ERR otherwise.
 */
int ef_adapter_id_check(uint32_t ef_adapter_id)
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    if (ef_main == NULL)
    {
        MR_ERROR("The ef node is not initialized.");
        return RT_ERR;
    }

    uint16_t ef_adapter_capacity = ef_adapter_handle_capacity_get(ef_main->ef_adapter_handle);
    if (ef_adapter_capacity == 0)
    {
        MR_ERROR("The ef adapter capacity is 0.");
        return RT_ERR;
    }

    if (ef_adapter_id >= ef_adapter_capacity)
    {
        return RT_ERR;
    }

    struct ef_adapter * ef_adapter = ef_adapter_handle_adapter_get_by_id(ef_main->ef_adapter_handle, ef_adapter_id);
    if (ef_adapter->mode == EF_MODE_INVALID)
    {
        return RT_ERR;
    }

    return RT_SUCCESS;
}

/**
 * @brief Retrieves the number of active EF adapters.
 *
 * This function returns the number of EF adapters currently configured and active within
 * the Etherfabric node. It retrieves the `ef_node_main` structure and calls
 * `ef_adapter_handle_nr_adapters_get` to get the number of adapters.
 *
 * @return The number of active EF adapters.
 */
uint16_t ef_nr_adapters_get()
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    return ef_adapter_handle_nr_adapters_get(ef_main->ef_adapter_handle);
}

/**
 * @brief Retrieves the IDs of all active EF adapters.
 *
 * This function populates an array with the IDs of all active EF adapters within the
 * Etherfabric node. It iterates through the EF adapter list and copies the IDs of adapters
 * that are not in the `EF_MODE_INVALID` state into the provided `ef_adapter_ids` array. The
 * function stops when it has filled the array with the specified number of adapter IDs (`nr_adapters`).
 *
 * @param ef_adapter_ids Pointer to the array where the EF adapter IDs will be stored.
 * @param nr_adapters The number of adapter IDs to retrieve.
 */
void ef_adapter_ids_get(uint16_t * ef_adapter_ids, uint16_t nr_adapters)
{
    uint16_t adapter_count = 0;
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    uint16_t ef_adapters_capacity = ef_adapter_handle_capacity_get(ef_main->ef_adapter_handle);

    for (int i = 0; i < ef_adapters_capacity; i++)
    {
        struct ef_adapter * ef_adapter = ef_adapter_handle_adapter_get_by_id(ef_main->ef_adapter_handle, i);
        if (ef_adapter->mode != EF_MODE_INVALID)
        {
            ef_adapter_ids[adapter_count] = ef_adapter->id;
            adapter_count++;
        }

        if (adapter_count == nr_adapters)
        {
            return;
        }
    }
}

/**
 * @brief Retrieves the maximum number of EF adapters.
 *
 * This function returns the maximum number of EF adapters that the Etherfabric node can manage.
 * It retrieves this value from the `ef_node_main` structure by calling
 * `ef_adapter_handle_capacity_get`.
 *
 * @return The maximum number of EF adapters.
 */
unsigned int nr_max_ef_adapters_get()
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    return ef_adapter_handle_capacity_get(ef_main->ef_adapter_handle);
}

/**
 * @brief Retrieves the starting SID (Service ID) from the Etherfabric node.
 *
 * This function returns the starting Service ID (SID) configured within the Etherfabric node.
 * It retrieves the SID start value from the `sid_handle` associated with the global
 * `ef_node_main` structure.
 *
 * @return The starting SID for the Etherfabric node.
 */
uint32_t ef_sid_start_get()
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    return sid_handle_sid_start_get(ef_main->sid_handle);
}

/**
 * @brief Retrieves the EF peer index associated with a given traffic link ID.
 *
 * This function looks up the EF peer index associated with the specified `traffic_link_id`
 * within the `tl_to_ef_peer_map_handle`. It first ensures that the Etherfabric node is initialized
 * and that the `traffic_link_id` is within the valid range of the map's capacity. If the node is
 * not initialized or the ID is out of range, the function returns `RT_ERR`. Otherwise, it retrieves
 * the EF peer index from the map table and stores it in `out_ef_peer_index`, returning `RT_SUCCESS`.
 *
 * @param traffic_link_id The traffic link ID to look up.
 * @param out_ef_peer_index Pointer to where the associated EF peer index will be stored.
 *
 * @return RT_SUCCESS if the EF peer index is successfully retrieved, RT_ERR otherwise.
 */
int ef_peer_index_get_by_tl_id_get(uint16_t traffic_link_id, uint16_t * out_ef_peer_index)
{
    struct ef_node_main * ef_main = __g_ef_node_main_get();
    if (unlikely(ef_main == NULL))
    {
        MR_ERROR("The ef node is not initialized.");
        return RT_ERR;
    }

    struct tl_to_ef_peer_map_handle * handle = ef_main->tl_to_ef_peer_map_handle;
    if (traffic_link_id < handle->capacity)
    {
        *out_ef_peer_index = rte_atomic64_read(&handle->maps_table[traffic_link_id]);
        return RT_SUCCESS;
    }

    return RT_ERR;
}

/************************************************ Auxiliary functions *************************************************/
/**
 * @brief Swaps the Ethernet and IP source/destination addresses in a forwarded packet.
 *
 * This inline function modifies a packet's Ethernet and IP headers for VXLAN encapsulation.
 * It swaps the source and destination MAC addresses in the Ethernet header and swaps the
 * source and destination IP addresses in the IPv4 header. This is typically done before
 * VXLAN encapsulation to ensure that the packet is routed correctly.
 *
 * @param mbuf Pointer to the `rte_mbuf` structure containing the packet.
 */
static inline void vxlan_encap_forwarded_pkt(struct rte_mbuf * mbuf)
{
    /* swap eth_hdr */
    struct rte_ether_hdr * eth_hdr = rte_pktmbuf_mtod(mbuf, struct rte_ether_hdr *);
    swap_mac_addr(eth_hdr);

    struct rte_ipv4_hdr * ip_hdr = rte_pktmbuf_mtod_offset(mbuf, struct rte_ipv4_hdr *, sizeof(struct rte_ether_hdr));
    uint32_t _swap_ip_addr = ip_hdr->src_addr;
    ip_hdr->src_addr = ip_hdr->dst_addr;
    ip_hdr->dst_addr = _swap_ip_addr;
}

/**
 * @brief Generates a source port for VXLAN encapsulation according to RFC 7348.
 *
 * This inline function generates a source port number for VXLAN encapsulation by hashing
 * the packet's data (specifically the inner headers) and mapping the result to a range of
 * ephemeral ports (49152 to 65535). The generated source port helps to distribute the
 * VXLAN traffic across different paths in the network.
 *
 * @param mbuf Pointer to the `rte_mbuf` structure containing the packet.
 *
 * @return The generated source port for VXLAN encapsulation.
 */
static inline uint16_t generate_vxlan_src_port(struct rte_mbuf * mbuf)
{
    uint16_t min = 49152;
    uint16_t range = 65535 - 49152 + 1;

    return min + (uint16_t)(mbuf->hash.usr % range);
}

/**
 * @brief Constructs the VXLAN encapsulation headers for a given packet.
 *
 * This inline function constructs the VXLAN encapsulation headers, including the outer Ethernet,
 * IPv4, and UDP headers, as well as the VXLAN header itself. It ensures that the packet is
 * prepared for transmission over a VXLAN tunnel. The function returns `RT_SUCCESS` if the
 * headers are successfully constructed, or `RT_ERR` if any header cannot be added.
 *
 * @param mbuf Pointer to the `rte_mbuf` structure containing the packet.
 * @param mrb_meta Pointer to the `mrb_metadata` structure containing metadata for the packet.
 * @param ef_peer Pointer to the `ef_peer` structure representing the destination peer.
 * @param dev_desc Pointer to the `mr_dev_desc` structure representing the device description.
 *
 * @return RT_SUCCESS if the headers are successfully constructed, RT_ERR otherwise.
 */
static inline int vxlan_encap_constructed_pkt(struct rte_mbuf * mbuf, struct mrb_metadata * mrb_meta,
                                              struct ef_peer * ef_peer, struct mr_dev_desc * dev_desc)
{
    /* construct the packet by the order of inner to outer */
    struct g_vxlan_hdr * p_vxlan_hdr = (struct g_vxlan_hdr *)rte_pktmbuf_prepend(mbuf, sizeof(struct g_vxlan_hdr));
    if (unlikely(p_vxlan_hdr == NULL))
    {
        return RT_ERR;
    }

    /* clear the vxlan header */
    memset(p_vxlan_hdr, 0, sizeof(struct g_vxlan_hdr));
    p_vxlan_hdr->dir = mrb_meta->dir;
    p_vxlan_hdr->link_id = mrb_meta->ef_link_id;

    /* then, the outer udp header */
    struct rte_udp_hdr * p_udp_hdr = (struct rte_udp_hdr *)rte_pktmbuf_prepend(mbuf, sizeof(struct rte_udp_hdr));
    if (unlikely(p_udp_hdr == NULL))
    {
        return RT_ERR;
    }

    /* TODO: the source port need to be fill with the hash of inner 2-tuple or 4-tuple,
     * ignore the udp checksum */
    p_udp_hdr->src_port = htons(generate_vxlan_src_port(mbuf));
    p_udp_hdr->dst_port = htons(4789);
    p_udp_hdr->dgram_len = htons(rte_pktmbuf_pkt_len(mbuf));
    p_udp_hdr->dgram_cksum = 0;

    /* then, the outer ip header */
    struct rte_ipv4_hdr * p_ipv4_hdr = (struct rte_ipv4_hdr *)rte_pktmbuf_prepend(mbuf, sizeof(struct rte_ipv4_hdr));
    if (unlikely(p_ipv4_hdr == NULL))
    {
        return RT_ERR;
    }

    p_ipv4_hdr->version_ihl = 0x45;
    p_ipv4_hdr->type_of_service = 0x00;
    p_ipv4_hdr->packet_id = 0x0100;
    p_ipv4_hdr->fragment_offset = 0x0000;
    p_ipv4_hdr->time_to_live = 0x40;
    p_ipv4_hdr->next_proto_id = IPPROTO_UDP;
    p_ipv4_hdr->src_addr = dev_desc->in_addr.s_addr;
    p_ipv4_hdr->dst_addr = ef_peer->ef_ip_addr;
    p_ipv4_hdr->total_length = htons(rte_pktmbuf_pkt_len(mbuf));

    p_ipv4_hdr->hdr_checksum = 0;
    p_ipv4_hdr->hdr_checksum = rte_ipv4_cksum(p_ipv4_hdr);

    /* outermost ether header */
    struct rte_ether_hdr * eth_hdr = (struct rte_ether_hdr *)rte_pktmbuf_prepend(mbuf, sizeof(struct rte_ether_hdr));

    eth_hdr->ether_type = htons(RTE_ETHER_TYPE_IPV4);
    rte_ether_addr_copy(&ef_peer->ef_mac_addr, &eth_hdr->dst_addr);
    rte_ether_addr_copy(&dev_desc->eth_addr, &eth_hdr->src_addr);

    return RT_SUCCESS;
}

/**
 * @brief Generates and stores trace information for ingress packets.
 *
 * This function generates a trace record for an ingress packet as it moves through the
 * network. It records details such as the next node, reason for dropping the packet
 * (if applicable), and other metadata. The trace record is then emitted for analysis or
 * debugging purposes.
 *
 * @param node Pointer to the `rte_node` structure representing the current node.
 * @param mbuf Pointer to the `rte_mbuf` structure containing the packet.
 * @param next_node_index Index of the next node in the processing pipeline.
 * @param prepend_sid The SID to prepend in the trace.
 * @param drop_reason The reason for dropping the packet, if applicable.
 */
void gen_store_trace_info_ingress(struct rte_node * node, struct rte_mbuf * mbuf, uint16_t next_node_index,
                                  uint16_t prepend_sid, enum ef_node_ingress_metrics_key drop_reason)
{
    /* Populate the next node infomation */
    char str_record[MR_STRING_MAX];
    struct mrb_metadata * mrb_meta = mrbuf_cz_data(mbuf, MR_NODE_CTRLZONE_ID);
    int len = snprintf(str_record, sizeof(str_record), "next node:%s", node->nodes[next_node_index]->name);

    /* Populate the reason for next node */
    if (unlikely(next_node_index == EF_INGR_NEXT_PKT_DROP))
    {
        assert(drop_reason < EF_INGR_METRIC_MAX);
        len += snprintf(str_record + len, sizeof(str_record) - len, ", rsn:%s", ef_ingr_metrics_str[drop_reason]);
    }
    else
    {
        /* Populate the ef id, traffic link id adn prepend sid */
        len += snprintf(str_record + len, sizeof(str_record) - len, ", ef id:%u, trf lk id:%u, prep sid:%u",
                        mrb_meta->adapter_id, mrb_meta->traffic_link_id, prepend_sid);

        /* Populate the sids information */
        len += embed_sid_info(mbuf, str_record + len, sizeof(str_record) - len);
    }

    /* Emit the trace record */
    struct dp_trace_record_meta meta = {
        .measurement_type = DP_TRACE_MEASUREMENT_TYPE_TRACE, .appsym = MR_TRACE_APPSYM, .module = node->name};
    dp_trace_record_emit_str(sc_main_get()->trace, mbuf, rte_lcore_id(), &meta, str_record);
}

/**
 * @brief Generates and stores trace information for egress packets.
 *
 * This function creates a trace record for a packet as it exits the network through an egress node.
 * It logs information about the next node, the reason for dropping the packet (if applicable),
 * and other relevant metadata. The function checks if the packet is being dropped and, if so,
 * records the specific reason. If the packet was created by a network function (NF), it also
 * logs that information. Finally, the trace record is emitted for analysis or debugging.
 *
 * @param node Pointer to the `rte_node` structure representing the current node.
 * @param mbuf Pointer to the `rte_mbuf` structure containing the packet.
 * @param next_node_index Index of the next node in the processing pipeline.
 * @param drop_reason The reason for dropping the packet, if applicable.
 */
static void gen_store_trace_info_egress(struct rte_node * node, struct rte_mbuf * mbuf, uint16_t next_node_index,
                                        enum ef_node_egress_metrics_key drop_reason)
{
    /* Populate the next node infomation */
    char str_record[MR_STRING_MAX];
    int len = snprintf(str_record, sizeof(str_record), "next node:%s", node->nodes[next_node_index]->name);

    /* Populate the reason for next node */
    struct mrb_metadata * mrb_meta = mrbuf_cz_data(mbuf, MR_NODE_CTRLZONE_ID);

    if (unlikely(next_node_index == EF_EGR_NEXT_PKT_DROP))
    {
        assert(drop_reason < EF_EGR_METRIC_MAX);
        len += snprintf(str_record + len, sizeof(str_record) - len, ", rsn:%s", ef_egr_metrics_str[drop_reason]);
    }
    else
    {
        /* Populate the ef id and egress port information */
        len += snprintf(str_record + len, sizeof(str_record) - len, ", ef id:%u, tx:%u", mrb_meta->adapter_id,
                        mrb_meta->port_egress);
    }

    /* Populate the nf create information */
    if (unlikely(mrb_meta->packet_create_from_nf))
    {
        len += snprintf(str_record + len, sizeof(str_record) - len, ", nf cr:%u", mrb_meta->packet_create_from_nf);
    }

    /* Emit the trace record */
    struct dp_trace_record_meta meta = {
        .measurement_type = DP_TRACE_MEASUREMENT_TYPE_TRACE, .appsym = MR_TRACE_APPSYM, .module = node->name};
    dp_trace_record_emit_str(sc_main_get()->trace, mbuf, rte_lcore_id(), &meta, str_record);
}

/**
 * @brief Monitors and aggregates ingress metrics for Etherfabric nodes.
 *
 * This function monitors the ingress metrics for each graph (I/O thread) in the Etherfabric node
 * and aggregates the data into a JSON object. It retrieves the metric values for each graph and
 * stores them in an array. If the total packet count (`EF_INGR_METRIC_TOT_PKTS`) for a graph is zero,
 * it skips further processing for that graph. Finally, the function creates a JSON object that
 * contains the aggregated metrics data for each metric type across all graphs.
 *
 * @param sc Pointer to the `sc_main` structure containing the main configuration and resources.
 *
 * @return Pointer to the `cJSON` object containing the aggregated ingress metrics data.
 */
cJSON * ef_ingress_node_monit_loop(struct sc_main * sc)
{
    cJSON * json_root = cJSON_CreateObject();
    unsigned int nr_graphs = sc->nr_io_thread;
    struct ef_node_main * ef_main = __g_ef_node_main_get();

    assert(nr_graphs == ef_main->nr_graphs);

    uint64_t values_for_graphs[EF_INGR_METRIC_MAX][nr_graphs];

    for (uint32_t graph_id = 0; graph_id < nr_graphs; graph_id++)
    {
        uint64_t values[EF_INGR_METRIC_MAX];
        sc_metrics_values_get(ef_main->ingress_metrics_handles[graph_id], values, EF_INGR_METRIC_MAX);

        if (values[EF_INGR_METRIC_TOT_PKTS] == 0)
        {
            for (uint32_t i = 0; i < EF_INGR_METRIC_MAX; i++)
            {
                values_for_graphs[i][graph_id] = 0;
            }
            continue;
        }

        for (uint32_t i = 0; i < EF_INGR_METRIC_MAX; i++)
        {
            values_for_graphs[i][graph_id] = values[i];
        }
    }

    for (uint32_t i = 0; i < EF_INGR_METRIC_MAX; i++)
    {
        char str_title[MR_STRING_MAX];
        snprintf(str_title, sizeof(str_title), "ef_ingress, %s", ef_ingr_metrics_str[i]);

        cJSON * json_counter = create_uint64_array(values_for_graphs[i], nr_graphs);
        cJSON_AddItemToObject(json_root, str_title, json_counter);
    }

    return json_root;
}

/**
 * @brief Monitors and aggregates egress metrics for Etherfabric nodes.
 *
 * This function monitors the egress metrics for each graph (I/O thread) in the Etherfabric node
 * and aggregates the data into a JSON object. It retrieves the metric values for each graph and
 * stores them in an array. If the total packet count (`EF_EGR_METRIC_TOT_PKTS`) for a graph is zero,
 * it skips further processing for that graph. Finally, the function creates a JSON object that
 * contains the aggregated metrics data for each metric type across all graphs.
 *
 * @param sc Pointer to the `sc_main` structure containing the main configuration and resources.
 *
 * @return Pointer to the `cJSON` object containing the aggregated egress metrics data.
 */
cJSON * ef_egress_node_monit_loop(struct sc_main * sc)
{
    cJSON * json_root = cJSON_CreateObject();
    unsigned int nr_graphs = sc->nr_io_thread;
    struct ef_node_main * ef_main = __g_ef_node_main_get();

    assert(nr_graphs == ef_main->nr_graphs);

    uint64_t values_for_graphs[EF_EGR_METRIC_MAX][nr_graphs];

    for (uint32_t graph_id = 0; graph_id < nr_graphs; graph_id++)
    {
        uint64_t values[EF_EGR_METRIC_MAX];
        sc_metrics_values_get(ef_main->ingress_metrics_handles[graph_id], values, EF_EGR_METRIC_MAX);

        if (values[EF_INGR_METRIC_TOT_PKTS] == 0)
        {
            for (uint32_t i = 0; i < EF_EGR_METRIC_MAX; i++)
            {
                values_for_graphs[i][graph_id] = 0;
            }
            continue;
        }

        for (uint32_t i = 0; i < EF_EGR_METRIC_MAX; i++)
        {
            values_for_graphs[i][graph_id] = values[i];
        }
    }

    for (uint32_t i = 0; i < EF_EGR_METRIC_MAX; i++)
    {
        char str_title[MR_STRING_MAX];
        snprintf(str_title, sizeof(str_title), "ef_egress, %s", ef_egr_metrics_str[i]);

        cJSON * json_counter = create_uint64_array(values_for_graphs[i], nr_graphs);
        cJSON_AddItemToObject(json_root, str_title, json_counter);
    }

    return json_root;
}

/**
 * @brief Monitors the state and details of EF peers in the Etherfabric node.
 *
 * This function iterates through all EF peers in the Etherfabric node and collects information
 * about active peers. For each active peer, it retrieves the IP and MAC addresses and stores
 * them in a JSON object. The function then adds this information to the root JSON object.
 * The total number of active peers is also recorded. The JSON object provides a snapshot of
 * the current state of all EF peers in the system.
 *
 * @param sc Pointer to the `sc_main` structure containing the main configuration and resources.
 *
 * @return Pointer to the `cJSON` object containing the monitored EF peer information.
 */
cJSON * ef_peer_monit_loop(struct sc_main * sc)
{
    int nr_ef_peer = 0;
    cJSON * json_root = cJSON_CreateObject();
    struct ef_node_main * ef_main = __g_ef_node_main_get();

    uint16_t capacity = ef_peer_handle_capacity_get(ef_main->ef_peer_handle);

    for (int i = 0; i < capacity; i++)
    {
        struct ef_peer * ef_peer = __ef_peer_handle_peer_get(ef_main->ef_peer_handle, i);

        if (rte_atomic64_read(&ef_peer->state) == 0)
            continue;

        char str_in_addr[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &ef_peer->ef_ip_addr, str_in_addr, sizeof(str_in_addr));

        char str_mac_addr[RTE_ETHER_ADDR_FMT_SIZE];
        rte_ether_format_addr(str_mac_addr, sizeof(str_mac_addr), &ef_peer->ef_mac_addr);

        cJSON * ef_peer_obj = cJSON_CreateObject();
        cJSON_AddStringToObject(ef_peer_obj, "ip addr", str_in_addr);
        cJSON_AddStringToObject(ef_peer_obj, "mac addr", str_mac_addr);

        char ef_peer_index[MR_STRING_MAX];
        snprintf(ef_peer_index, sizeof(ef_peer_index), "ef_peer:%u", i);
        cJSON_AddItemToObject(json_root, ef_peer_index, ef_peer_obj);
        nr_ef_peer++;
    }

    cJSON_AddNumberToObject(json_root, "total_num", nr_ef_peer);
    return json_root;
}

/********************************************** Etherfabric ingress Node **********************************************/
/* Etherfabric ingress node process function */
static __rte_always_inline uint16_t ef_ingress_node_process(struct rte_graph * graph, struct rte_node * node,
                                                            void ** objs, uint16_t cnt)
{
    void ** batch_pkts = objs;
    struct rte_mbuf ** mbufs = (struct rte_mbuf **)objs;

    /* Single packet processing */
    uint16_t n_left_from = cnt;
    uint16_t last_spec = 0, next_node_index = 0;
    uint16_t batch_next_node_index = EF_INGR_NEXT_PKT_DROP;

    struct ef_node_main * ef_main = __g_ef_node_main_get();
    uint32_t sid_start = sid_handle_sid_start_get(ef_main->sid_handle);
    uint64_t inc_values[EF_INGR_METRIC_MAX] = {0};
    enum ef_node_ingress_metrics_key drop_reason;

    while (n_left_from > 0)
    {
        uint16_t prepend_sid = 0;
        struct rte_mbuf * mbuf = mbufs[0];
        mbufs += 1;
        n_left_from -= 1;

        /* Prepare headers */
        struct rte_ether_hdr * outer_ether_hdr = rte_pktmbuf_mtod_offset(mbuf, struct rte_ether_hdr *, 0);
        struct rte_ipv4_hdr * outer_ipv4_hdr = rte_pktmbuf_mtod_offset(mbuf, struct rte_ipv4_hdr *,
                                                                       sizeof(struct rte_ether_hdr));
        struct g_vxlan_hdr * outer_g_vxlan_hdr = rte_pktmbuf_mtod_offset(
            mbuf, struct g_vxlan_hdr *,
            sizeof(struct rte_udp_hdr) + sizeof(struct rte_ipv4_hdr) + sizeof(struct rte_ether_hdr));

        assert(outer_ipv4_hdr != NULL);
        assert(outer_g_vxlan_hdr != NULL);

        /* Etherfabric adapter lookup */
        uint16_t ef_adapter_id = UINT16_MAX;
        int ret = ef_adapter_handle_adapter_lookup(ef_main->ef_adapter_handle, outer_ipv4_hdr->dst_addr,
                                                   &ef_adapter_id);
        if (unlikely(ret == RT_ERR))
        {
            next_node_index = EF_INGR_NEXT_PKT_DROP;
            drop_reason = EF_INGR_METRIC_DROP_ADP_NONEXIST;
            inc_values[drop_reason]++;
            goto node_enqueue;
        }

        /* ef_peer lookup */
        union ef_peer_key key = {.ip_src = outer_ipv4_hdr->src_addr};
        rte_ether_addr_copy(&outer_ether_hdr->src_addr, &key.mac_src);

        int ef_peer_index = __ef_peer_handle_peer_lookup(ef_main->ef_peer_handle, &key);

        if (unlikely(ef_peer_index < 0))
        {
            ef_peer_index = ef_peer_handle_peer_add(ef_main->ef_peer_handle, &key);
            if (unlikely(ef_peer_index == RT_ERR))
            {
                next_node_index = EF_INGR_NEXT_PKT_DROP;
                drop_reason = EF_INGR_METRIC_DROP_EF_PEER_ADD_ERR;
                inc_values[drop_reason]++;
                goto node_enqueue;
            }
        }

        /* Traffic link id lookup */
        uint16_t traffic_link_id;
        struct link_db_match_field match_field;
        match_field.ef_link_id = outer_g_vxlan_hdr->link_id;
        match_field.ef_ip_addr = outer_ipv4_hdr->src_addr;
        link_db_match(ef_main->link_db_ctx, &match_field, 1, &traffic_link_id);

        /* Associate the traffic link id with ef_peer index */
        if (likely(traffic_link_id != UINT16_MAX))
        {
            ret = __tl_to_ef_peer_map_handle_associate(ef_main->tl_to_ef_peer_map_handle, traffic_link_id,
                                                       ef_peer_index);
            if (unlikely(ret == RT_ERR))
            {
                next_node_index = EF_INGR_NEXT_PKT_DROP;
                drop_reason = EF_INGR_METRIC_DROP_TL_TO_EF_PEER_MAP_ERR;
                inc_values[drop_reason]++;
                goto node_enqueue;
            }
        }

        /* Fill ef_peer index and dir */
        struct mrb_metadata * mrb_meta = mrbuf_cz_data(mbuf, MR_NODE_CTRLZONE_ID);
        mrb_meta->dir = outer_g_vxlan_hdr->dir;
        mrb_meta->adapter_type = ADAPTER_TYPE_EF;
        mrb_meta->adapter_id = ef_adapter_id;
        mrb_meta->ef_link_id = outer_g_vxlan_hdr->link_id;
        mrb_meta->traffic_link_id = traffic_link_id;
        mrb_meta->ef_peer_index = ef_peer_index;

        /* Insert sid*/
        prepend_sid = sid_start + ef_adapter_id;
        ret = sid_list_prepend(&mrb_meta->sid_list, &prepend_sid, 1);
        if (unlikely(ret != RT_SUCCESS))
        {
            next_node_index = EF_INGR_NEXT_PKT_DROP;
            drop_reason = EF_INGR_METRIC_DROP_PRE_SID_ERR;
            inc_values[drop_reason]++;
            goto node_enqueue;
        }

        /* Swap the outer mac and ip addr */
        vxlan_encap_forwarded_pkt(mbuf);

        complex_layer_adjust(&mrb_meta->pkt_parser_result, ef_encap_len);
        rte_pktmbuf_adj(mbuf, ef_encap_len);

        /* Send the pkt to classifier */
        next_node_index = EF_INGR_NEXT_CLASSIFIER;
        inc_values[EF_INGR_METRIC_TO_CLASSIFIER]++;

    node_enqueue:
#if 0
        /* Check if tracing is enabled for the current Mbuf */
        if (unlikely(dp_trace_record_can_emit(mbuf, DP_TRACE_MEASUREMENT_TYPE_TRACE)))
        {
            gen_store_trace_info_ingress(node, mbuf, next_node_index, prepend_sid, drop_reason);
            // gen_store_trace_info_sid_list(node, mbuf);
            //  gen_store_trace_info_rte_mbuf(node, mbuf);
        }

        if (unlikely(dp_trace_record_can_emit(mbuf, DP_TRACE_MEASUREMENT_TYPE_TELEMETRY)))
        {
            gen_store_telemetry_info_adapter(mbuf);
        }
#endif

        /* Judge the next index whether to change */
        if (unlikely(batch_next_node_index != next_node_index))
        {
            /* If the next index has been changed,Enqueue last pkts */
            rte_node_enqueue(graph, node, batch_next_node_index, batch_pkts, last_spec);
            batch_pkts += last_spec;
            last_spec = 1;
            batch_next_node_index = next_node_index;
        }
        else
        {
            /* If the next index not change, update the lasts */
            last_spec++;
        }
    }

    /* Process the remaining packets */
    if (likely(last_spec > 0))
        rte_node_enqueue(graph, node, batch_next_node_index, batch_pkts, last_spec);

    /* Update metrics */
    inc_values[EF_INGR_METRIC_TOT_PKTS] = cnt;
    sc_metrics_accumulate(ef_main->ingress_metrics_handles[graph->id], inc_values, EF_INGR_METRIC_MAX);
    sc_metrics_value_set(ef_main->ingress_metrics_handles[graph->id], cnt, EF_INGR_METRIC_PKTS_PER_BATCH);

    return cnt;
}

/* Etherfabric ingress node base */
static struct rte_node_register ef_ingress_node_base = {
    .process = ef_ingress_node_process,
    .name = "ef_ingress",
    .init = NULL,
    .nb_edges = EF_INGR_NEXT_MAX,
    .next_nodes =
        {
            [EF_INGR_NEXT_CLASSIFIER] = "classifier",
            [EF_INGR_NEXT_PKT_DROP] = "pkt_drop_trap",
        },
};

RTE_NODE_REGISTER(ef_ingress_node_base);

/*********************************************** Etherfabric egress Node **********************************************/
/* Etherfabric egress node process function */
static uint16_t ef_egress_node_process(struct rte_graph * graph, struct rte_node * node, void ** objs, uint16_t cnt)
{
    void ** batch_pkts = objs;
    struct rte_mbuf ** mbufs = (struct rte_mbuf **)objs;

    /* prefetch the mbuf and it's content */
    rte_prefetch0_write(mbufs[0]);
    rte_prefetch0_write(mrbuf_cz_data(mbufs[0], MR_NODE_CTRLZONE_ID));

    uint16_t last_spec = 0;
    uint16_t n_left_from = cnt;
    uint16_t next_node_index = EF_EGR_NEXT_ETH_EGRESS;
    uint16_t batch_next_node_index = EF_EGR_NEXT_ETH_EGRESS;

    struct ef_node_main * ef_main = __g_ef_node_main_get();
    uint32_t sid_start = sid_handle_sid_start_get(ef_main->sid_handle);
    uint64_t inc_values[EF_EGR_METRIC_MAX] = {0};
    enum ef_node_egress_metrics_key drop_reason = EF_EGR_METRIC_MAX;

    while (n_left_from > 0)
    {
        struct rte_mbuf * mbuf = mbufs[0];
        mbufs += 1;
        n_left_from -= 1;

        /* prefetch next mbuf */
        if (n_left_from > 0)
        {
            rte_prefetch0_write(mbufs[0]);
            rte_prefetch0_write(mrbuf_cz_data(mbufs[0], MR_NODE_CTRLZONE_ID));
        }

        /* Get the buffer metadata */
        struct mrb_metadata * mrb_meta = mrbuf_cz_data(mbuf, MR_NODE_CTRLZONE_ID);

        /* Get etherfabric adapter item */
        uint16_t ef_adapter_id = mrb_meta->cur_sid - sid_start;
        struct ef_adapter * ef_adapter = __ef_adapter_handle_adapter_get_by_id(ef_main->ef_adapter_handle,
                                                                               ef_adapter_id);

        /* According the etherfabric adapter mode to process the packet */
        switch (ef_adapter->mode)
        {
        case EF_MODE_VIRTUAL_WIRE: {
            /* Get port egress */
            struct mr_dev_desc * listen_device = ef_adapter->listening_device;
            mrb_meta->port_egress = listen_device->port_id;

            /* Fill Ether IPv4 Udp Vxlan hdr for the pkt */
            if (unlikely(mrb_meta->packet_create_from_nf))
            {
                assert(mrb_meta->ef_peer_index < ef_peer_handle_capacity_get(ef_main->ef_peer_handle));
                struct ef_peer * ef_peer = __ef_peer_handle_peer_get(ef_main->ef_peer_handle, mrb_meta->ef_peer_index);
                vxlan_encap_constructed_pkt(mbuf, mrb_meta, ef_peer, listen_device);
                inc_values[EF_EGR_METRIC_VXLAN_ENCAP]++;
            }
            else
            {
                rte_pktmbuf_prepend(mbuf, ef_encap_len);
            }

            next_node_index = EF_EGR_NEXT_ETH_EGRESS;
            inc_values[EF_EGR_METRIC_TO_ETH_EGRESS]++;
        }
        break;
        case EF_MODE_TAP:
            next_node_index = EF_EGR_NEXT_PKT_DROP;
            drop_reason = EF_EGR_METRIC_DROP_RSN_TAP_MODE;
            inc_values[drop_reason]++;
            break;
        default:
            next_node_index = EF_EGR_NEXT_PKT_DROP;

            drop_reason = EF_EGR_METRIC_DROP_RSN_INVALID_MODE;
            inc_values[drop_reason]++;
            break;
        }

        /* Check if tracing is enabled for the current Mbuf */
        if (unlikely(dp_trace_record_can_emit(mbuf, DP_TRACE_MEASUREMENT_TYPE_TRACE)))
        {
            gen_store_trace_info_egress(node, mbuf, next_node_index, drop_reason);
            // gen_store_trace_info_rte_mbuf(node, mbuf);
        }

        /* Determine if the next index should be changed */
        if (unlikely(batch_next_node_index != next_node_index))
        {
            /* If the next index has been changed, enqueue the last packets */
            rte_node_enqueue(graph, node, batch_next_node_index, batch_pkts, last_spec);
            batch_pkts += last_spec;
            last_spec = 1;
            batch_next_node_index = next_node_index;
        }
        else
        {
            /* If the next index does not change, update the last items */
            last_spec++;
        }
    }

    /* Process the remaining packets */
    if (likely(last_spec > 0))
        rte_node_enqueue(graph, node, batch_next_node_index, batch_pkts, last_spec);

    /* Update metrics */
    inc_values[EF_EGR_METRIC_TOT_PKTS] = cnt;
    sc_metrics_accumulate(ef_main->egress_metrics_handles[graph->id], inc_values, EF_EGR_METRIC_MAX);
    sc_metrics_value_set(ef_main->egress_metrics_handles[graph->id], cnt, EF_EGR_METRIC_PKTS_PER_BATCH);
    return cnt;
}

/* Etherfabric egress node base */
static struct rte_node_register ef_egress_node_base = {
    .process = ef_egress_node_process,
    .name = "ef_egress",
    .init = NULL,
    .nb_edges = EF_EGR_NEXT_MAX,
    .next_nodes =
        {
            [EF_EGR_NEXT_ETH_EGRESS] = "eth_egress",
            [EF_EGR_NEXT_PKT_DROP] = "pkt_drop_trap",
        },
};

RTE_NODE_REGISTER(ef_egress_node_base);