summaryrefslogtreecommitdiff
path: root/cesar/mac/sar/src/sar.c
blob: ae405375f4796f37b4a05352ebc6ca22960f9ce9 (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
/* Cesar project {{{
 *
 * Copyright (C) 2007 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    mac/sar/src/sar.c
 * \brief   sar source functions.
 * \ingroup mac_sar
 *
 * All the necessary functions to for the SAR.
 *
 */
#include "common/std.h"
#include "lib/slist.h"
#include "mac/common/timings.h"
#include "mac/common/ntb.h"
#include "mac/common/store.h"
#include "mac/common/mfs.h"
#include "mac/pbproc/pbproc.h"
#include "mac/sar/sar.h"
#include "mac/sar/inc/sar_context.h"
#include "mac/sar/inc/sar.h"
#include "mac/sar/inc/sar_expiration.h"
#include "lib/seq_check.h"

#include "hal/arch/arch.h"
#include "common/defs/priority.h"
#include "config/sar.h"
#include "config/mac/sar.h"
#include "lib/stats.h"
#include <string.h>

/** Time SAR thread sleeps. */
#define SAR_THREAD_DELAY_RTC 10

/** Define the JOB length for the second job to avoid bridgedma bug see
 * maria:#905. */
#define SAR_BRGBUG_SECOND_JOB_LENGTH 16

/**
 * Store missing PBs stats in the MFS.
 * \param  mfs  the MFS to update the stats.
 * \param  pb_missing  the missing PB counter.
 */
#define sar_mfs_stats_missing_pbs(mfs, pb_missing) \
    do { \
        (mfs)->stats.num_segs_missed += (pb_missing); \
        (pb_missing) = 0; \
    } while (0)

static struct sar_t sar_global;

/**
 * Callback when the lib sequencer detect a wrong sequencing.
 * \param  user  user data
 * \param  vlan  the VLAN id
 * \param  seq_expected  the sequence number expected
 * \param  seq_actual  the actual sequence number found in the packet
 */
void
sar_lib_seq_check_cb (void *user, uint vlan, uint seq_expected,
                      uint seq_actual);

void
sar_lib_seq_check_cb (void *user, uint vlan, uint seq_expected,
                      uint seq_actual)
{
    dbg_assert (user);
    trace_do (sar_t *ctx = (sar_t *) user);
    SAR_TRACE (SEQ_CHECK, vlan, seq_expected, seq_actual);
}

/**
 * Compute the gap between two SSNs.
 * \param  a  the first SSN,
 * \param  b  the Second SSN.
 * \return  the GAP.
 *
 * a must be after b.
 */
inline uint
sar_ssn_gap (u16 a, u16 b)
{
    return (u16) (a - b - 1);
}

/**
 * Compute the gap between the PB next and the PB or between PB and SSN Min.
 * \param  mfs  the MFS to get the SSN min.
 * \param  PB  the PB to use the SSN from the header.
 * \return  the number of PBs lost.
 */
inline uint
sar_stats_rx_gap_between_pb_ssn_min (mfs_rx_t *mfs, pb_t *pb)
{
    uint pb_missing;
    if (pb->next
        && less_mod2p16 (pb->next->header.ssn, mfs->ssn_min))
        pb_missing = sar_ssn_gap (pb->next->header.ssn, pb->header.ssn);
    else
        pb_missing = sar_ssn_gap (mfs->ssn_min, pb->header.ssn);
    return pb_missing;
}

/**
 * Increment stats on MPDU.
 * \param  rx  the rx parameters.
 * \param  mfs  the mfs to use.
 * \param  pb_nb  the number of PBs received.
 * \param  pb_dropped  the number of PBs dropped.
 */
static inline void
sar_stats_mpdu_process (pbproc_rx_params_t *rx, mfs_rx_t *mfs,
                        uint pb_nb, uint pb_dropped)
{
    mfs->stats.num_segs_suc += pb_nb - pb_dropped;
    mfs->stats.num_pbs += pb_nb;
    mfs->stats.num_mpdus ++;
    if (rx->mpdu_cnt == 0)
        mfs->stats.num_bursts ++;
}

/**
 * Apply the MFS command on the MFS.
 * \param  ctx  the SAR context.
 * \param  mfs  the MFS to apply the command.
 */
static inline void
sar_rx_mfs_cmd_apply__cmd_init (sar_t *ctx, mfs_rx_t *mfs)
{
    bool bcast;
    bool mme;
    uint lid;
    uint tei;
    bool added;
    mfs_t *mfs_new;

    bcast = mfs->common.bcast;
    mme = mfs->common.mme;
    lid = mfs->common.lid;
    tei = mfs->common.tei;

    sar_mfs_free_rx (ctx, mfs);
    mfs_new = mac_store_mfs_add (ctx->mac_store, false,
                                 bcast, mme, lid, tei, &added);
    dbg_assert (added);
    sar_mfs_add (ctx, mfs_new);
    blk_release (mfs_new);
}

/**
 * Apply the MFS command on the MFS.
 * \param  ctx  the SAR context.
 * \param  params  the RX Parameters.
 */
static inline void
sar_rx_mfs_cmd_apply (sar_t *ctx, pbproc_rx_params_t *params)
{
    mfs_rx_t *mfs;
    dbg_claim (ctx);
    dbg_claim (params);
    dbg_claim (MAC_TEI_IS_STA(params->tei));

    if (params->mfs_cmd_data == MFS_FSM_CMD_INIT)
    {
        mfs = mac_store_mfs_get_rx (ctx->mac_store,
                                    params->bcast,
                                    false /* DATA. */,
                                    params->lid,
                                    params->tei);

        if (mfs)
        {
            SAR_TRACE (MFS_CMD, mfs, params->mfs_cmd_data);
            sar_rx_mfs_cmd_apply__cmd_init (ctx, mfs);
            blk_release (mfs);
        }
    }

    if (params->mfs_cmd_mme == MFS_FSM_CMD_INIT)
    {
        mfs = mac_store_mfs_get_rx (ctx->mac_store,
                                    params->bcast,
                                    true /* MME. */,
                                    MAC_LID_NONE,
                                    params->tei);

        if (mfs)
        {
            SAR_TRACE (MFS_CMD, mfs, params->mfs_cmd_mme);
            sar_rx_mfs_cmd_apply__cmd_init (ctx, mfs);
            blk_release (mfs);
        }
    }
}

/**
 * Create a MME temporary link.
 * \param  ctx  the sar context.
 * \param  rx  the rx parameters.
 * \return  the new temporary MFS MME.
 */
static inline mfs_rx_t *
sar_rx_get_associated_mfs__mme_temporary_link (sar_t *ctx, sar_mpdu_t *rx)
{
    rx->rx.mfs_mme = mac_store_mfs_unassociated_add (
        ctx->mac_store, false, rx->rx.params.bcast, true, MAC_LID_NONE,
        rx->rx.params.tei);
    sar_mfs_add (ctx, rx->rx.mfs_mme);

    return &rx->rx.mfs_mme->rx;
}

/**
 * Create a non temporary MFS.
 * \param  ctx  the sar context.
 * \param  rx  the rx parameters.
 * \param  pb  the PB which require the MFS.
 * \param  mme  true if MME false otherwise.
 * \return  the MFS.
 *
 * If the LID of the MFS is not a PLID for DATA MFS, this will return NULL.
 */
static inline mfs_rx_t*
sar_rx_get_associated_mfs__from_mac_store (
    sar_t *ctx, pbproc_rx_t *rx, pb_t *pb, bool mme)
{
    mfs_rx_t *local_mfs;
    bool added;
    dbg_assert (MAC_TEI_IS_STA(rx->params.tei));
    /* If the MFS is not a lid one and it request a DATA MFS return NULL.
     * The SAR is not allowed to create non PLID MFSs. */
    if (!mme && !MAC_LID_IS_PLID (rx->params.lid)
        && !CONFIG_MAC_SAR_EOC_PERMANENT_MFS)
    {
        local_mfs = mac_store_mfs_get_rx (
            ctx->mac_store, rx->params.bcast, false /* data requested. */,
            rx->params.lid, rx->params.tei);
    }
    else
    {
        local_mfs = mac_store_mfs_add_rx (ctx->mac_store,
          rx->params.bcast, mme, mme ? MAC_LID_NONE : rx->params.lid,
          rx->params.tei, &added);
        /* Configure the MFS created, only do this if the MFS has been created*/
        if (added)
        {
            if (pb)
                local_mfs->ssn_min = pb->header.ssn;
            sar_mfs_add (ctx, PARENT_OF (mfs_t, rx, local_mfs));
            /* Special behavior for bcast MFS, the ssn min should be set to
             * the first PB on the MPDU. This allow the station to receive PBs
             * with a SSN higher than 0x7fff when SSN min is 0. See #2357
             */
            if (local_mfs->common.bcast)
                local_mfs->ssn_min = pb->header.ssn;
        }
    }
    if (mme)
        rx->mfs_mme = PARENT_OF_OR_NULL (mfs_t, rx, local_mfs);
    else
        rx->mfs = PARENT_OF_OR_NULL (mfs_t, rx, local_mfs);
    return local_mfs;
}

/**
 * Get the associated MFS from mac store.
 * \param  sar  the SAR context.
 * \param  rx  the rx_mpdu
 * \param  pb  The PB for the one the MFS is needed.
 * \param  mme  true if MME false otherwise.
 * \return  the MFS corresponding, or the new created one.
 *
 * If the MFS does not exists it use the rx_params LID and source TEI to add
 * it to the mac store.
 */
inline mfs_rx_t *
sar_rx_get_associated_mfs (sar_t *ctx, sar_mpdu_t * rx, pb_t *pb, bool mme)
{
    dbg_assert (rx);
    if (mme && rx->rx.mfs_mme)
        return (mfs_rx_t *) rx->rx.mfs_mme;
    else if (!mme && rx->rx.mfs)
        return (mfs_rx_t *) rx->rx.mfs;
    /* Temporary link. */
    if (mme && ((rx->rx.params.tei == MAC_TEI_UNASSOCIATED)
                || (rx->rx.params.multi_net_bcast)))
        return sar_rx_get_associated_mfs__mme_temporary_link (ctx, rx);
    /* Normal link. */
    else
        return sar_rx_get_associated_mfs__from_mac_store (ctx, &rx->rx, pb,
                                                          mme);
}

/**
 * Resize the SSN window size.
 * \param  pb  the PB to make the test.
 * \param  mfs  the MFS to verify.
 * \param  pb_nb  number of PBs in the MPDU given by the pbproc.
 */
inline void
sar_rx_mfs_resize_ssn (mfs_rx_t *mfs, pb_t *pb, uint pb_nb)
{
    u16 ssn_max, ssn_min_last;
    uint pb_missing = 0;
    dbg_assert (pb);
    dbg_assert (mfs);
    ssn_max = mfs->ssn_min + mfs->window_size - 1;
    if ((pb_nb == 1)
        && pb->header.opsf
        && less_mod2p16 (ssn_max, pb->header.ssn))
    {
        ssn_min_last = mfs->ssn_min;
        mfs->ssn_min = pb->header.ssn;
        if (mfs->head)
        {
            while (mfs->head
                   && less_mod2p16 (mfs->head->header.ssn, mfs->ssn_min))
            {
                pb_missing += sar_stats_rx_gap_between_pb_ssn_min (
                    mfs, mfs->head);
                mfs->head = sar_pb_release (mfs->head);
            }
        }
        else
            /* SSN last is a missing PB too, this function compute the gap
             * between two SSN, it consider ssn_min_last has been received. */
            pb_missing = sar_ssn_gap (mfs->ssn_min, ssn_min_last) + 1;
        sar_mfs_stats_missing_pbs (mfs, pb_missing);
    }
}

/**
 * Compute the GAP between the MFS HEAD and the MFS last SSN min.
 * \param  ctx  the module context.
 * \param  mfs  the MFS used.
 * \param  ssn_last  the last SSN min.
 *
 * \warn Call only this function function if the SSN last is lesser than the
 * SSN min.
 */
inline u16
sar_stats_rx_missing_pbs_before_head (sar_t *ctx, mfs_rx_t *mfs, u16 ssn_last)
{
    uint gap = 0;
    dbg_assert (less_mod2p16 (ssn_last, mfs->ssn_min));
    if (mfs->head
        && less_mod2p16 (mfs->head->header.ssn, mfs->ssn_min)
        && less_mod2p16 (ssn_last, mfs->head->header.ssn))
        gap = sar_ssn_gap (mfs->head->header.ssn, ssn_last - 1);
    else if ((mfs->head
              && less_mod2p16 (mfs->ssn_min, mfs->head->header.ssn))
             || !mfs->head)
        gap = sar_ssn_gap (mfs->ssn_min, ssn_last - 1);
    return gap;
}

/**
 * Set the correct SSN min using the pb ssn and the mfs_ssn_min.
 * \param  mfs  the MFS to use.
 */
inline void
sar_rx_mfs_ssn_min_update (sar_t *ctx, mfs_rx_t *mfs)
{
    pb_t *pb;
    pb_t *pb_previous = INVALID_PTR;
    uint pb_missing, pb_dropped = 0;
    bool chain_unchanged;
    bool bcast_restart = false;
    dbg_claim (mfs);
    pb = mfs->head;
    u16 ssn_min_last = mfs->ssn_min;
    while (pb)
    {
        chain_unchanged = true;
        /* PB's SSN is the MIN SSN. */
        if (pb->header.ssn == mfs->ssn_min)
            mfs->ssn_min ++;
        else if (pb->header.opsf && CONFIG_SAR_DROP_OLD_SEG)
            mfs->ssn_min = pb->header.ssn + 1;
        /* PB's SSN is greater than the SSN MAX. */
        else if (less_mod2p16 (mfs->window_size + mfs->ssn_min - 1
                                + MFS_WINDOW_TOLERANCE,
                               pb->header.ssn))
        {
            if (mfs->common.bcast)
            {
                mfs->ssn_min = (u16) (pb->header.ssn - mfs->window_size + 1);
                /* Restart the chain, the firsts PBs may be the current
                 * SSN min. */
                bcast_restart = true;
            }
            else
            {
                SAR_TRACE (MFS_SSN_UPDATE, mfs->ssn_min,
                           mfs->window_size, pb->header.ssn);
                chain_unchanged = false;
                if (pb == mfs->head)
                    mfs->head = pb = sar_pb_release (pb);
                else
                {
                    pb_previous->next = pb->next;
                    pb = sar_pb_release (pb);
                }
                /* The PB is dropped because it is outside the window, The
                 * segment is considered received but the PB not. */
                pb_dropped++;
            }
        }
        if (chain_unchanged)
        {
            pb_previous = pb;
            pb = pb->next;
        }
    }
    /* Special process for broadcast links. */
    if (bcast_restart)
    {
        for (pb = mfs->head; pb; pb = pb->next)
        {
            if (pb->header.ssn == mfs->ssn_min)
                mfs->ssn_min++;
            else if (less_mod2p16 (mfs->ssn_min, pb->header.ssn))
                break;
        }
    }
    /* Compute the gap between the last SSN Min and the current head. */
    if (ssn_min_last != mfs->ssn_min)
    {
        pb_missing = sar_stats_rx_missing_pbs_before_head (
            ctx, mfs, ssn_min_last);
        sar_mfs_stats_missing_pbs (mfs, pb_missing);
    }
    /* Decrease number of PBs received using the pb_dropped local variable. */
    mfs->stats.num_pbs -= pb_dropped;
}

#if CONFIG_STATS
/**
 * Initialize the statistics of the SAR.
 * \param  ctx  the statistics context.
 */
static inline void
sar_stats_init (sar_stats_t *ctx)
{
    /* Check parameter. */
    dbg_assert (ctx);
    /* Reset to 0. */
    ctx->rx_pb_count = 0;
    ctx->rx_pb_crc_error_count = 0;
    ctx->rx_pb_rejected = 0;
    ctx->ber_sum = 0;
    ctx->tx_pb_expired = 0;
    ctx->rx_pb_expired = 0;
    ctx->pb_pool_not_filled = 0;
    /* Register our statistics. */
    lib_stats_set_stat_value_notype ("rx_pb_count", &ctx->rx_pb_count,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_USER);
    lib_stats_set_stat_value_notype ("rx_pb_crc_error_count",
                                     &ctx->rx_pb_crc_error_count,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_USER);
    lib_stats_set_stat_value_notype ("ber_sum", &ctx->ber_sum,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_USER);
    lib_stats_set_stat_value_notype ("sar_pb_pool_not_filled",
                                     &ctx->pb_pool_not_filled,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_DEBUG);
}
#endif

/**
 * Fill the job DMA descriptor part.
 * \param  job  the job to fill.
 * \param  tx  if it is a TX way
 */
inline void
sar_job_mfs_fill (sar_job_mfs_t *job, bool tx)
{
    job->job.next = 0;
    job->job.last = 0;
    job->job.data_addr = 0;
    job->job.direction = !tx;
    job->job.crc_error = tx ? false : true;
    job->job.crc_reset = 1;
    job->job.crc_store = 1;
    job->job.append_zero = 1;
    job->job.job_it = false;
    job->job.eth_buffer_mask = 0;
    job->job.segment_len = BLK_SIZE;
    job->pb_last_taken = false;
}

sar_t *
sar_init (mac_store_t *mac_store, pbproc_t *pbproc, ca_t *ca, u32 seed)
{
    sar_t *ctx;
    dbg_assert (mac_store);
    dbg_assert (pbproc);
    dbg_assert (ca);
    memset (&sar_global, 0, sizeof (sar_t));
    sar_global.ca = ca;
    sar_global.mac_store = mac_store;
    //reassembly
    sar_reassembly_init (&sar_global.data_ctx);
    sar_reassembly_init (&sar_global.mme_ctx);
    //pbproc
    sar_global.pbproc_ctx = pbproc;
    pbproc_init_cb (pbproc, &sar_global, sar_mpdu_add, sar_beacon_add);
    // Init the bridgedma context by giving the functions to call back when a
    // job had been bridge.
    sar_global.bridgedma_ctx = phy_bridgedma_init (&sar_global,
            NULL, NULL);
    /* Fill the PBPOOL */
    sar_pb_pool_refill (&sar_global, CONFIG_SAR_PBPOOL_SIZE);
    /** Trace system. */
    ctx = &sar_global;
    sar_trace_init(ctx);
    /* Initialize sequence checker. */
    lib_seq_check_init (&ctx->seq, sar_lib_seq_check_cb, &sar_global);
#if CONFIG_STATS
    sar_stats_init (&ctx->stats);
#endif
    lib_rnd_init (&ctx->rnd_gen, seed ^ 0x19257164);
    /* Resume the thread only if the SAR is not in unit test. */
#ifndef SAR_UNIT_TEST
    // Create the Thread for the SAR.
    cyg_thread_create (MAC_SAR_THREAD_PRIORITY,
                       &sar_process,
                       (cyg_addrword_t) ctx,
                       "MAC_SAR",
                       ctx->thread_stack,
                       MAC_SAR_THREAD_STACK_SIZE,
                       &ctx->thread_handle, &ctx->thread);
    cyg_thread_resume (ctx->thread_handle);
#endif
    /* Initialise the TX static job. */
    static sar_job_mfs_t job_tx;
    sar_global.job_tx = ARCH_CPU_TO_DMA (&job_tx);
    sar_job_mfs_fill (&job_tx, true);
    return &sar_global;
}

/**
 * Call uper layer to give back the buffer and MFS.
 * \param  ctx  the sar context.
 * \param  buffer  the buffer containing the frame.
 * \param  mfs  the MFS to used.
 * \param  user_data  opaque object to give back to the upper layer.
 */
static inline void
sar_tx_done (sar_t *ctx, u8 *buffer, mfs_tx_t *mfs, void *user_data)
{
    dbg_assert (ctx);
    dbg_assert (buffer);

    if (mfs->common.mme)
        ctx->sar_seg_msg_done_cb (ctx->ul_msg_ctx, buffer,
                                  user_data);
    else
        ctx->sar_seg_data_done_cb (ctx->ul_data_ctx, buffer,
                                   user_data);
}

void
sar_reassembly_init (sar_reassembly_ctx_t *ctx)
{
    dbg_assert (ctx);

    ctx->sar_rea_done = NULL;
    slist_init (ctx->jobs_pending_list., bare);
    slist_init (ctx->buffer_list., bare);
}

void
sar_init_data_context (sar_t *ctx, void *user)
{
    dbg_assert (ctx);

    ctx->ul_data_ctx = user;
}

void
sar_init_mme_context (sar_t *ctx, void *user)
{
    dbg_assert (ctx);

    ctx->ul_msg_ctx = user;
}

void
sar_init_measure_context (sar_t *ctx, void *user)
{
    dbg_assert (ctx);

    ctx->ul_ce_ctx = user;
}

void
sar_init_segmentation_mme_cb (sar_t *ctx,
                              sar_segmentation_done_cb_t sar_seg_done)
{
    dbg_assert (ctx);

    ctx->sar_seg_msg_done_cb = sar_seg_done;
}

void
sar_init_segmentation_data_cb (sar_t *ctx,
                               sar_segmentation_done_cb_t sar_seg_done)
{
    dbg_assert (ctx);

    ctx->sar_seg_data_done_cb = sar_seg_done;
}

void
sar_init_reassembly_ul (sar_t *ctx,
                        sar_reassembly_done_cb_t sar_rea_done, bool data)
{
    dbg_assert (ctx);

    if (data)
    {
        dbg_assert (ctx->ul_data_ctx);
        ctx->data_ctx.sar_rea_done = sar_rea_done;
    }
    else
    {
        dbg_assert (ctx->ul_msg_ctx);
        ctx->mme_ctx.sar_rea_done = sar_rea_done;
    }
}

void
sar_init_measurement_cb (sar_t *ctx,
                         sar_measurement_cb_t sar_measurement)
{
    dbg_assert (ctx);

    ctx->sar_measurement = sar_measurement;
}

void
sar_uninit (sar_t *ctx)
{
    dbg_assert (ctx);
#ifndef SAR_UNIT_TEST
    cyg_thread_suspend (ctx->thread_handle);
    cyg_thread_delete (ctx->thread_handle);
#endif
    phy_bridgedma_uninit(ctx->bridgedma_ctx);
    sar_trace_uninit (ctx);
}

/**
 * Release the PBs of the MPDU.
 * \param  mpdu  the MPDU object.
 */
static void
sar_mpdu_release_content (sar_t *ctx, sar_mpdu_t *mpdu)
{
    if (CONFIG_TRACE)
    {
        arch_load_cache ((u32*) &mpdu->rx.pb_first->header, 1);
        arch_load_cache ((u32*) &mpdu->rx.pb_last->header, 1);
        SAR_TRACE (MPDU_EXPIRE, phy_date (), mpdu->rx.pb_first->header.ssn,
                   mpdu->rx.pb_last->header.ssn);
    }

    if (mpdu->rx.mfs)
        blk_release (mpdu->rx.mfs);
    if (mpdu->rx.mfs_mme)
        blk_release (mpdu->rx.mfs_mme);
    if (mpdu->rx.pb_first)
        blk_release_desc_range (&mpdu->rx.pb_first->blk,
                                &mpdu->rx.pb_last->blk);
    if (mpdu->rx.chandata_first)
        blk_release_desc_range_nb (&mpdu->rx.chandata_first->blk,
                                   mpdu->rx.chandata_nb);
}

void
sar_buffer_add (sar_t *ctx, u8* buffer_addr, bool data)
{
    sar_reassembly_ctx_t *rea_ctx;
    if (data)
        rea_ctx = &ctx->data_ctx;
    else
        rea_ctx = &ctx->mme_ctx;

    /* Lock DSR because this function can be called in DSR or task context. */
    arch_dsr_lock ();
    slist_push_back (rea_ctx->buffer_list., (sar_buffer_t*) buffer_addr,
                     bare);
    if (ctx->activate)
    {
        /* If there is RX pending JOB provide the head to the bridge DMA. */
        sar_rx_upper_layer_transmit_data (ctx, rea_ctx);
        phy_bridgedma_stopped (ctx->bridgedma_ctx);
        sar_bridge_dma_free_head (ctx);
    }
    if (ctx->pbs_missing_for_pbproc)
        /* Refill the PB pool if missing block were registered. */
        sar_pb_pool_refill (ctx, 0);
    arch_dsr_unlock ();
}

void
sar_mpdu_add (void *user, pbproc_rx_desc_t *rx_desc)
{
    sar_t *ctx;
    sar_mpdu_t *mpdu;
    sta_t *sta = NULL;

    dbg_assert (user);
    dbg_assert (rx_desc);
    dbg_assert (rx_desc->rx);
    ctx = (sar_t *) user;
    /* Do not lock DSR, this function is called only in DSR context. */

    mpdu = PARENT_OF (sar_mpdu_t, rx, rx_desc->rx);
    /* Collect agc_gain value for station */
    if (MAC_TEI_IS_STA (mpdu->rx.params.tei))
        sta = mac_store_sta_get (ctx->mac_store, mpdu->rx.params.tei);
    if (sta)
    {
        sta->upstream_att = mpdu->rx.params.agc_gain;
        blk_release (sta);
    }

    dbg_assert (!mpdu->rx.mfs || mpdu->rx.mfs->common.mme == false);
    dbg_assert (!mpdu->rx.mfs_mme || mpdu->rx.mfs_mme->common.mme == true);

    /* It the SAR is not activated the packets are directly dropped. */
    if (ctx->activate)
    {
        /* See section 4.4.2 Format of Long MPDU Payload of AV specification.
         */
        if (mpdu->rx.pb_nb == 1 && mpdu->rx.params.pb_size == PHY_PB_SIZE_136)
            *((u32*) &mpdu->rx.pb_first->data[128]) = 0;
        mpdu->arrival_ntb = mpdu->rx.params.preamble_ntb;
        if (mpdu->rx.pb_nb)
            mpdu->rx.pb_last->next = NULL;

        /** Tracing system. */
        SAR_TRACE (RX, phy_date (), mpdu->rx.params.tei,
                   mpdu->rx.params.lid, mpdu->rx.pb_nb);

        sar_reassembly_run (ctx, mpdu);
        phy_bridgedma_stopped (ctx->bridgedma_ctx);
        sar_bridge_dma_free_head (ctx);
    }
    else
    {
        sar_mpdu_release_content (ctx, mpdu);
        /* Allocate new PBs to the PBProc PB pool. */
        sar_pb_pool_refill (ctx, SAR_MPDU_RX_REFILL + mpdu->rx.pb_nb
                            + mpdu->rx.chandata_nb);
    }

    blk_release_desc (&rx_desc->blk);
}

/**
 * The MFS MME/PLID is in the release state, recreate one.
 * \param  ctx  the sar context.
 * \param  mfs  the MFS to recreate.
 * \return  the reference on the new MFS.
 */
static inline mfs_tx_t*
sar_msdu_add__mfs_mme_plid_in_release (sar_t *ctx, mfs_tx_t *mfs)
{
    bool bcast;
    bool mme;
    uint lid;
    uint tei;
    bool added;

    bcast = mfs->common.bcast;
    mme = mfs->common.mme;
    lid = mfs->common.lid;
    tei = mfs->common.tei;
    /* Remove the MFS. */
    sar_mfs_free_tx (ctx, mfs);
    mfs = mac_store_mfs_add_tx (ctx->mac_store, bcast,
                                mme, lid,
                                tei, &added);
    dbg_assert (added);
    sar_mfs_add (ctx, (mfs_t *) mfs);
    blk_release (mfs);
    return mfs;
}

/**
 * Prepare the MSDU to be sent over the medium.
 * \param  ctx  the sar context.
 * \param  buffer  the buffer containing the frame.
 * \param  mfs  the MFS to use.
 * \param  user_data  opaque object to give back to the upper layer.
 * \param  arrival_time_ntb  the arrival NTB date.
 */
inline void
sar_msdu_add__send_frame (sar_t *ctx, u8 *buffer, u16 length, mfs_tx_t *mfs,
                          void *user_data, u32 arrival_time_ntb)
{
    sar_msdu_t msdu;

    blk_addref (mfs);
    if (mfs->common.mme)
        msdu.ats_confounder = lib_rnd32 (&ctx->rnd_gen);
    else
        msdu.ats_confounder = arrival_time_ntb;
    msdu.length = length;
    msdu.mfs = mfs;
    msdu.buffer_address = buffer;
    msdu.user_data = user_data;
    msdu.arrival_ntb = arrival_time_ntb;
    SAR_TRACE (TX, phy_date (), buffer, length, mfs->common.tei,
               mfs->common.lid, arrival_time_ntb);
    /* Lock DSR because this function can be called in DSR or task context. */
    arch_dsr_lock ();
    sar_tx_mac_framing (ctx, &msdu);
    sar_expiration_mfs_update_ntb (
        ctx, PARENT_OF (mfs_t, tx, msdu.mfs), msdu.arrival_ntb);
    phy_bridgedma_stopped (ctx->bridgedma_ctx);
    sar_bridge_dma_free_head (ctx);
    if (ctx->pbs_missing_for_pbproc)
        /* Refill the PB pool if missing block were registered. */
        sar_pb_pool_refill (ctx, 0);
    arch_dsr_unlock ();
}

void
sar_msdu_add (sar_t *ctx, u8 *buffer, u16 length, mfs_tx_t *mfs,
              void *user_data, u32 arrival_time_ntb)
{
    dbg_claim (ctx);
    dbg_claim (mfs);
    dbg_claim (mfs->common.tx);
    dbg_claim ((length >= ETH_PACKET_MIN_SIZE_ALLOWED)
                && (length <= ETH_PACKET_MAX_SIZE));

    /* Link statistics. */
    mfs->stats.num_msdus ++;
    mfs->stats.octets += length;

    /* Check sequence. */
    lib_seq_check_packet (&ctx->seq, buffer, length);

    /* Enough block available to send a frame and SAR is activated ? */
    if ((blk_slack () || mfs->common.mme) && ctx->activate)
    {
        if (mfs->fsm_state == MFS_FSM_CMD_RELEASE)
        {
            if (MAC_LID_IS_PLID (mfs->common.lid) || mfs->common.mme)
                mfs = sar_msdu_add__mfs_mme_plid_in_release (ctx, mfs);
            else
            {
                SAR_TRACE (MSDU_DROPPED_MFS_RELEASE, buffer, mfs);
                sar_tx_done (ctx, buffer, mfs, user_data);
                return;
            }
        }

        sar_msdu_add__send_frame (ctx, buffer, length, mfs,
                                  user_data, arrival_time_ntb);
    }
    else
    {
        SAR_TRACE (MSDU_DROPPED, buffer);
        sar_tx_done (ctx, buffer, mfs, user_data);
    }
}

void
sar_mfs_add (sar_t *ctx, mfs_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    mfs->common.expiration_ntb = mac_ntb ()
        + MAC_MS_TO_TCK (MFS_ACTIVITY_DELAY_MS);
    /* Add the MFS to the CA. */
    if (mfs->common.tx)
        ca_mfs_add (ctx->ca, &mfs->tx);
    SAR_TRACE (MFS_ADD, mfs);
}

void
sar_mfs_remove (sar_t *ctx, mfs_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    arch_dsr_lock ();
    if (mfs->common.tx)
    {
        /* Remove the MFS from the CA. */
        ca_mfs_remove (ctx->ca, &mfs->tx);
        pbproc_mfs_remove_all (&mfs->tx);
        /* Compute the new expiration date. */
        mfs->common.expiration_ntb = mac_ntb ()
            + MAC_MS_TO_TCK (MFS_RELEASE_DELAY_MS);
        /* Put the MFS in the RELEASE state. */
        mfs->tx.fsm_state = MFS_FSM_CMD_RELEASE;
    }
    else
        sar_mfs_free_rx (ctx, &mfs->rx);
    arch_dsr_unlock ();
}

/**
 * Process the bridgedma free head on RX reception.
 * \param  ctx  the SAR context.
 * \param  job  the job containing the data.
 */
static void
sar_bridge_dma_free_head_rx (sar_t *ctx, sar_job_mfs_t *job)
{
    bool sta_auth, encrypted;
    sar_reassembly_done_cb_t sar_rea_done;
    void *ul_ctx;
    dbg_assert (ctx);
    dbg_assert (job);

#if CONFIG_SAR_BRG_JOB_ERROR
    dbg_assert (job->job.mf_header1 != 0xdeaddead);
#endif

    /* If the CRC error is not raised i.e. THE checksum is correct. */
    if (!job->job.crc_error)
    {
        /* Link stats. */
        job->mfs->rx.stats.num_msdus++;
        job->mfs->rx.stats.octets += job->job.data_len;

        if (((mfs_rx_t *) job->mfs)->common.mme)
        {
            uint cpt;
            pb_t *pb;

            encrypted = false;
            sta_auth = false;
            /* Verify the station status. */
            if (((mfs_rx_t *) job->mfs)->common.tei != MAC_TEI_UNASSOCIATED)
            {
                encrypted = true;
                /** Check if the Frame is encrypted. */
                for (cpt = job->pb_quantity,
                     pb = (pb_t *)job->job.first_pb_desc;
                     pb && encrypted && cpt;
                     pb = pb->next, cpt --)
                {
                    encrypted &= pb->header.spc_encrypted;
                    sta_auth |= pb->header.spc_encrypted;
                }
            }

            sar_rea_done = ctx->mme_ctx.sar_rea_done;
            ul_ctx = ctx->ul_msg_ctx;
        }
        else
        {
            /* Always true for data, if the data is not encrypted it had
             * already been dropped in the rx_mpdu_process function. */
            encrypted = true;
            sta_auth = true;

            sar_rea_done = ctx->data_ctx.sar_rea_done;
            ul_ctx = ctx->ul_data_ctx;
        }
        dbg_assert (sar_rea_done);
        (*sar_rea_done) (ul_ctx, job->job.data_addr, job->job.data_len,
                         (mfs_rx_t *) job->mfs, encrypted);

        SAR_TRACE (BRIDGE_RX,
                   ((pb_t*) job->job.first_pb_desc)->header.ssn,
                   job->job.first_pb_offset,
                   job->job.data_len, job->mfs);

        if (sta_auth
            && !CONFIG_MAC_SAR_EOC_PERMANENT_MFS
            && ((mfs_rx_t *) job->mfs)->common.tei != MAC_TEI_UNASSOCIATED)
        {
            sta_t * sta = mac_store_sta_get (ctx->mac_store,
                                     ((mfs_rx_t *) job->mfs)->common.tei);
            if (sta)
            {
                sta->authenticated = true;
                blk_release (sta);
            }
        }
    }
    else
    {
        /* Link stats. */
        job->mfs->rx.stats.num_icv_fails ++;
        /* Keep the buffer for another reassembly. */
        sar_buffer_add (ctx, job->job.data_addr,
                        !((mfs_rx_t *) job->mfs)->common.mme);
    }

    /* Release the PBs in the job. */
    blk_release_desc_range_nb ((blk_t *) job->job.first_pb_desc,
                               job->pb_quantity);
}

/**
 * Process the bridgedma free head on TX reception.
 * \param  ctx  the SAR context.
 * \param  job  the job containing the data.
 */
static void
sar_bridge_dma_free_head_tx (sar_t *ctx, sar_job_mfs_t *job)
{
    mfs_tx_t *local_mfs;
    dbg_assert (ctx);
    dbg_assert (job);

    local_mfs = &job->mfs->tx;
    uint pb_quantity = job->pb_quantity;

#if CONFIG_SAR_BRG_JOB_ERROR
    sar_mf_t sar_mf;
    sar_mf_header ((pb_t*) job->job.first_pb_desc, job->job.first_pb_offset,
                   &sar_mf);
    dbg_assert (sar_mf.type == (job->job.mf_header1 & 0x3));
#endif
    SAR_TRACE (BRIDGE_TX,
               ((pb_t*) job->job.first_pb_desc)->header.ssn,
               job->job.first_pb_offset,
               job->job.data_len, job->mfs);

    /* Link statistics. */
    local_mfs->stats.num_segs += job->pb_last_taken ? pb_quantity - 1:
        pb_quantity;

    /* Release the PBs in the job. */
    blk_release_desc_range_nb ((blk_t *) job->job.first_pb_desc, pb_quantity);
    pbproc_mfs_provide (&job->mfs->tx, pb_quantity);
    if ((!CONFIG_MAC_SAR_EOC_PERMANENT_MFS
          || !job->mfs->tx.cfp)
        && job->mfs->tx.fsm_state != MFS_FSM_CMD_RELEASE
        && job->mfs->tx.ca_state != CA_MFS_STATE_REMOVED)
        ca_mfs_update (ctx->ca, &job->mfs->tx);
    sar_tx_done (ctx, job->job.data_addr, &job->mfs->tx, job->user_data);
}

/**
 * Process the job when the SAR is not activated.
 * \param  ctx  the SAR context.
 * \param  job  the job got.
 */
static void
sar_bridge_dma_free_header_not_activate (sar_t *ctx, sar_job_mfs_t *job)
{
    dbg_assert (ctx);
    dbg_assert (job);

    /* Release the PBs in the job. */
    blk_release_desc_range_nb ((blk_t *) job->job.first_pb_desc,
                               job->pb_quantity);

    if (job->mfs->common.tx)
    {
        /* If TX give back the buffer. Data addr pointer can stay in a unknown
         * state, on each TX this pointer is correctly intialised. */
        if (job->job.data_addr)
            sar_tx_done (ctx, job->job.data_addr, &job->mfs->tx,
                         job->user_data);
    }
    else
    {
        /* Keep the reassembly buffer. */
        if (job->job.data_addr)
            sar_buffer_add (ctx, job->job.data_addr, !job->mfs->common.mme);
    }
}

void
sar_bridge_dma_free_head (sar_t *ctx)
{
    sar_job_mfs_t *job;
    sar_job_mfs_t *jobs;
    dbg_assert (ctx);
    /* Get the ended list of jobs from the bridge DMA. */
    jobs =
        PARENT_OF_OR_NULL (
            sar_job_mfs_t, job,
            phy_bridgedma_jobs_get_ended (ctx->bridgedma_ctx));
    while (jobs)
    {
        job = jobs;
        /* Load job data into cache. */
        arch_load_cache (((u32 *) &job->job) + 5, 2);
        /* Workaround bridge dma bug maria:#905. */
        if (job->job.direction
            && job->job.crc_store == false)
        {
            dbg_assert (job->job.next
                        && job->job.next->header_len == 0);
            /* Load job data into cache. */
            arch_load_cache (((u32 *) job->job.next) + 5, 2);
            /* Release the second job. */
            sar_job_mfs_t *j = job->next;
            /* Restore original job values. */
            job->job.crc_error = j->job.crc_error;
            job->job.data_len += j->job.data_len;
            job->job.next = j->job.next;
            /* Free the second job. */
            blk_release (j);
        }
        jobs = job->next;
        if (!ctx->activate)
            sar_bridge_dma_free_header_not_activate (ctx, job);
        else if (!job->job.direction)
            sar_bridge_dma_free_head_tx (ctx, job);
        else
            sar_bridge_dma_free_head_rx (ctx, job);
        blk_release (job->mfs);
        /* Release the JOB only for RX jobs. TX is static. */
        if (job->job.direction)
        {
            blk_release (job);
            ctx->stats.rx_jobs_waiting_count--;
        }
    }
}

void
sar_pb_pool_refill (sar_t *ctx, uint pb_nb)
{
    pb_t *head = NULL;
    pb_t *tail = NULL;
    blk_t *blk_tail;

    dbg_assert (ctx);
    dbg_assert (ctx->pbproc_ctx);
    pb_nb += ctx->pbs_missing_for_pbproc;
    if (pb_nb)
    {
        uint available = blk_slack ();
        uint allocate = MIN (pb_nb, available);
        ctx->pbs_missing_for_pbproc = pb_nb - allocate;
        if (allocate)
        {
            head = (pb_t*) blk_alloc_desc_range (allocate, &blk_tail);
            tail = (pb_t*) blk_tail;
            pbproc_rx_segment_refill (ctx->pbproc_ctx, head, tail, allocate);
        }
        else
            ctx->stats.pb_pool_not_filled++;
    }
}

/**
 * Try to extract MF from the PBs present in the MFS.
 * \param  ctx  the SAR context.
 * \param  mfs  the MFS to use.
 * \param  opsf_ssn  The ssn of the oldest pending PB received.
 */
void
sar_mac_frame_reconstitute (sar_t *ctx, mfs_rx_t *mfs,
                            sar_reassembly_ctx_t *rea_ctx)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    dbg_assert (rea_ctx);

    sar_rx_mfs_ssn_min_update (ctx, mfs);
    sar_rx_mfs_process (ctx, mfs, rea_ctx);
    blk_release (mfs);
}

void
sar_reassembly_run (sar_t *ctx, sar_mpdu_t *rx)
{
    dbg_assert (ctx);
    dbg_assert (rx);

    sar_pb_pool_refill (ctx, SAR_MPDU_RX_REFILL + rx->rx.pb_nb
                    + rx->rx.chandata_nb);
    if (MAC_TEI_IS_STA(rx->rx.params.tei))
        mac_store_sta_add (ctx->mac_store, rx->rx.params.tei);

    /** If the message only contains chandata.
     * send the noise measurements to the CE. */
    if (rx->rx.chandata_first && !rx->rx.pb_first)
    {
        dbg_assert (!rx->rx.mfs);
        dbg_assert (!rx->rx.mfs_mme);
        /* Channel data ownership is handed over to callee. */
        ctx->sar_measurement (ctx->ul_ce_ctx, &rx->rx.params, 0,
                              rx->rx.chandata_first, rx->rx.chandata_nb,
                              0, 0);
    }
    else
    {
        if (MAC_TEI_IS_STA(rx->rx.params.tei))
            sar_rx_mfs_cmd_apply (ctx, &rx->rx.params);
        sar_rx_mpdu_process (ctx, rx);
        if (rx->rx.mfs)
        {
            if (rx->rx.pb_first)
                sar_expiration_mfs_update_ntb (ctx, rx->rx.mfs, rx->arrival_ntb);
            sar_mac_frame_reconstitute (ctx, &rx->rx.mfs->rx, &ctx->data_ctx);
        }
        if (rx->rx.mfs_mme)
        {
            if (rx->rx.pb_first)
                sar_expiration_mfs_update_ntb (ctx, rx->rx.mfs_mme,
                                           rx->arrival_ntb);
            sar_mac_frame_reconstitute (ctx, &rx->rx.mfs_mme->rx,
                                        &ctx->mme_ctx);
        }
    }
}

/**
 * Drop the PB and increment the stat associated.
 * \param  ctx  the module context.
 * \param  pb  the PB to drop.
 * \param  stat  the stat to increment.
 * \return  the next PB.
 */
static pb_t*
sar_rx_drop_and_stat  (sar_t *ctx, pb_t *pb, uint *stat)
{
    (*stat)++;
    return sar_pb_release (pb);
}

void
sar_rx_mpdu_process (sar_t *ctx, sar_mpdu_t * rx)
{
    pb_t *rx_head;
    pb_t *pb_new;
    mfs_rx_t *mfs_current = NULL;
    pb_t *pb_current = NULL;
    bool mme = false;
    u8 pb_crc_error = 0;
    u32 ber_sum = 0;
    /* Statistics variables. */
    uint pb_data_nb = 0;
    uint pb_data_dropped = 0;
    uint pb_mme_nb = 0;
    uint pb_mme_dropped = 0;
    /* Pointer to statistics variable (to save time). */
    uint *pb_nb = &pb_data_nb;
    uint *pb_dropped = &pb_data_dropped;
    /* Delay the RX PBs have to pass the mac layer.
     * Initialised with the mfs->common.expiration_delay_tck later. */
    uint pb_delay_tck = 0;

    dbg_assert (ctx);
    dbg_assert (rx);

    dbg_assert (ctx->sar_measurement);

    /* Initialise data. */
    rx_head = rx->rx.pb_first;
    /* The current PB pointing a PB in the MFS current. This can evolve and
     * the objective of this pointer is to be always lesser than the rx_head.
     * If the rx_head PB is valid and its SSN is lesser than the PB current
     * will be reinitialised to the MFS's head PB. This Allows this algorithm
     * to always inser the rx_head after pb_current. */
    pb_current = NULL;

    // Start to sort the mfs
    while (rx_head)
    {
        /* Refresh Leon cache for the PB. Load both PB header and PB
         * Measurements. */
        arch_load_cache ((u32 *) &rx_head->header, 2);
        /* If PB is not valid, crc error or Data not encrypt, Drop the PB.*/
        if (!rx_head->header.vpbf
            || rx_head->phy_pb.pb_rx.pb_measurement.crc_error
            || ((!rx_head->header.mmqf)
                && (rx->rx.params.eks == MAC_EKS_CLEAR)))
        {
            if (rx_head->phy_pb.pb_rx.pb_measurement.crc_error)
                pb_crc_error ++;
            else
                ber_sum += rx_head->phy_pb.pb_rx.pb_measurement.ber;
            SAR_TRACE (PB_ERROR, rx_head->header.ssn);
            rx_head = sar_pb_release (rx_head);
        }
        else
        {
            ber_sum += rx_head->phy_pb.pb_rx.pb_measurement.ber;
            /* Store the Spidcom encrypted flag. */
            rx_head->header.spc_encrypted = rx->rx.params.eks < MAC_EKS_NB;
            /* Get the current MFS. */
            if ((mfs_current == NULL) || (mme != rx_head->header.mmqf))
            {
                mfs_current = sar_rx_get_associated_mfs (
                    ctx, rx, rx_head, rx_head->header.mmqf);
                if (mfs_current)
                {
                    sar_rx_mfs_resize_ssn (mfs_current, rx_head,
                                           rx_head->header.ssn);

                    pb_current = mfs_current->head;
                    mme = rx_head->header.mmqf;
                    if (mme)
                    {
                        pb_nb = &pb_mme_nb;
                        pb_dropped = &pb_mme_dropped;
                        pb_delay_tck =
                            mfs_current->common.expiration_delay_tck;
                    }
                    else
                    {
                        pb_nb = &pb_data_nb;
                        pb_dropped = &pb_data_dropped;
                        pb_delay_tck =
                            mfs_current->common.expiration_delay_tck;
                    }
                }
            }
            /* The MFS may not exists (case of the lid ones). */
            if (mfs_current)
            {
                /* Store Expiration time in the PB header. */
                rx_head->expiration_ntb = rx->arrival_ntb + pb_delay_tck;
                /* Increment the correct variable for stats. */
                (*pb_nb)++;
                /* PB is lesser than the SSN min. */
                if (less_mod2p16 (rx_head->header.ssn, mfs_current->ssn_min))
                    rx_head = sar_rx_drop_and_stat (ctx, rx_head, pb_dropped);
                else if (mfs_current->head == NULL)
                {
                    mfs_current->head = rx_head;
                    pb_current = rx_head;
                    rx_head = rx_head->next;
                    pb_current->next = NULL;
                }
                /* While rx_head->header.ssn is lesser than the MFS head's
                 *  SSN, insert it in it. */
                else if (less_mod2p16 (rx_head->header.ssn,
                                       mfs_current->head->header.ssn))
                {
                    pb_current = rx_head;
                    rx_head = rx_head->next;
                    pb_current->next = mfs_current->head;
                    mfs_current->head = pb_current;
                }
                else
                {
                    /* Reinitialise the pointer, rx_head correspond to the
                     * next group of PBs. */
                    if (less_mod2p16 (rx_head->header.ssn,
                                      pb_current->header.ssn))
                        pb_current = mfs_current->head;
                    /* Go ahead until the PB's in the MFS are lesser than
                     * the current rx_head. */
                    while (pb_current->next
                           && lesseq_mod2p16 (pb_current->next->header.ssn,
                                              rx_head->header.ssn))
                        pb_current = pb_current->next;
                    if (pb_current->header.ssn == rx_head->header.ssn)
                        rx_head = sar_rx_drop_and_stat (ctx, rx_head,
                                                        pb_dropped);
                    /* Insert the rx_head in the MFS. */
                    else
                    {
                        pb_new = rx_head;
                        rx_head = rx_head->next;
                        pb_new->next = pb_current->next;
                        pb_current->next = pb_new;
                        pb_current = pb_new;
                    }
                }
            }
            else
                rx_head = sar_pb_release (rx_head);
        }
    }
    /* Call the CE. */
    ctx->sar_measurement (ctx->ul_ce_ctx, &rx->rx.params, rx->rx.pb_nb,
                          rx->rx.chandata_first, rx->rx.chandata_nb,
                          pb_crc_error, ber_sum);
#if CONFIG_STATS
    /* Increase statistics. */
    ctx->stats.rx_pb_count += rx->rx.pb_nb;
    ctx->stats.rx_pb_crc_error_count += pb_crc_error;
    ctx->stats.rx_pb_rejected += pb_data_dropped;
    ctx->stats.ber_sum += ber_sum;
#endif
    if (rx->rx.pb_nb == pb_data_dropped + pb_crc_error)
        rx->rx.pb_first = NULL;
    /* Link statistics. Only DATA are incremented. */
    if (rx->rx.mfs)
        sar_stats_mpdu_process (&rx->rx.params, &rx->rx.mfs->rx,
                                pb_data_nb, pb_data_dropped);
    if (rx->rx.mfs_mme)
        sar_stats_mpdu_process (&rx->rx.params, &rx->rx.mfs_mme->rx,
                                pb_mme_nb, pb_mme_dropped);
}

/**
 * Create a job descriptor for the Bridge DMA.
 * \param  job  the job to prepare.
 * \param  mfs  the MFS associated.
 * \param  first_pb  the first PB to use for the reassembly.
 * \param  offset  the offset of the Mac Frame in the first PB.
 * \param  sar_mf  the sar_mf structure to have more details on the Mac frame.
 */
static inline void
sar_rx_job_desc_create (phy_bridgedma_job_t *job, mfs_rx_t *mfs,
                        pb_t *first_pb, u16 offset, sar_mf_t *sar_mf)
{
    /* Verify that the data are not null */
    dbg_claim (job);
    dbg_claim (mfs);
    dbg_claim (first_pb);
    dbg_claim (sar_mf);

    job->first_pb_desc = (blk_t *) first_pb;
    job->first_pb_offset = offset;
    job->data_len = sar_mf->length;

    /* Fill the header of the job */
    switch (sar_mf->type)
    {
        case SAR_MF_TYPE_DATA:
            job->header_len = SAR_MF_MFH_SIZE;
            break;
        default:
            job->header_len = SAR_MF_MFH_SIZE + SAR_MF_ATS_SIZE;
    }

    offset += sar_mf->length_complete;
    if (offset < BLK_SIZE)
    {
        first_pb->header.mfbo = offset;
    }
    else
    {
        first_pb->header.mfbf = 0x0;
        first_pb->header.mfbo = 0;
    }
}


/**
 * Create a RX job with all the minimum configuration for the bridge DMA.
 * \return  sar_job_mfs object for the bridge DMA.
 */
inline sar_job_mfs_t*
sar_job_mfs_create_rx (void)
{
    sar_job_mfs_t *sar_job;
    sar_job = blk_alloc ();
    sar_job_mfs_fill (sar_job, false /* RX */);
    return sar_job;
}

/**
 * Allocate and fill the PB's headers to store a new MF.
 * \param  length  the length of the Mac Frame.
 * \param  ssn  the next SSN to put in the header.
 * \param  mme  if the segments will contain MMEs.
 * \param  begin  the first pb of the chain
 * \param  last  the last pb of the chain.
 * \param  expiration_time_ntb  the expiration PB date in NTB ticks.
 * \return  the number of PBs allocated.
 */
static inline uint
sar_tx_job_desc_create_complete_list (u16 length, u16 ssn, bool mme,
                                      pb_t **begin, pb_t **last,
                                      u32 expiration_time_ntb)
{
    pb_t *pb_first;
    pb_t *pb_last;
    pb_t *pb;
    blk_t *blk_last;
    u8 number_pb;
    pb_header_t header;

    number_pb = (length + BLK_SIZE - 1) / BLK_SIZE;

    pb_first = (pb_t *) blk_alloc_desc_range (number_pb,
                                              &blk_last);
    pb_last = (pb_t *) blk_last;
    pb_last->next = NULL;

    header.opsf = false;
    header.mfbf = 0x0;
    header.mfbo = 0x0;
    header.mmqf = mme;
    header.vpbf = true;
    header.rsvd = 0x0;

    // Fill the header for each PB
    for (pb = pb_first; pb; pb = pb->next, ssn ++)
    {
        blk_addref_desc ((blk_t*) pb);
        header.ssn = ssn;
        pb->header = header;

        /* Add the expiration time. */
        pb->expiration_ntb = expiration_time_ntb;
    }

    *begin = pb_first;
    *last = pb_last;

    return number_pb;
}

/**
 * Verify the possibility to reassembly the frame.
 * \param  ctx  the sar context.
 * \param  mfs  the MFS used.
 * \param  pb  the pb.
 * \param  sar_mf  the sar mac frame header structure.
 * \return true on success.
 */
static inline bool
sar_rx_mfs_detect_and_reconstitute_mf__possible (sar_t *ctx, mfs_rx_t *mfs,
                                                 pb_t *pb, sar_mf_t *sar_mf)
{
    dbg_claim (ctx);
    dbg_claim (mfs);
    dbg_claim (pb);
    dbg_claim (sar_mf);

    /* Does a MF exists in the PB? and there are free blocks */
    if (pb->header.mfbf)
    {
        /* Get the Mac Frame header. */
        sar_mf_header (pb, pb->header.mfbo, sar_mf);

        /* Frame is present and the length is correct ? */
        if ((sar_mf->type != SAR_MF_TYPE_NONE)
            && sar_mf->header_complete
            && (sar_mf->length <= ETH_PACKET_MAX_SIZE)
            && (sar_mf->length >= ETH_PACKET_MIN_SIZE_ALLOWED))
        {
            /* Check the MF Type with the MFS type. */
            if ((sar_mf->type == SAR_MF_TYPE_DATA)
                && (mfs->common.ats == false))
                return true;
            else if ((sar_mf->type == SAR_MF_TYPE_MME)
                    && (mfs->common.mme == true))
                return true;
            else if ((sar_mf->type == SAR_MF_TYPE_DATA_ATS)
                        && (mfs->common.ats == true))
                return true;
        }
    }

    return false;
}

/**
 * Create the job for the bridge DMA.
 * \param  ctx  the SAR context.
 * \param  mfs  the MFS containing the PBs.
 * \param  sar_mf  the data read from the PB.
 * \param  pb_mf_ends  the last PB containing the end of the MAC Frame.
 *
 * A MAC Frame is present in the PBs from the MFS's head to pb_mf_ends, the
 * function will use the informations read from the MFS's head PB to create a
 * job for the Bridge DMA and provide the PBs contining the MAC Frame to
 * reconstitute.
 */
inline sar_job_mfs_t *
sar_rx_mfs_detect_and_reconstitute_mf__create_job (sar_t *ctx, mfs_rx_t *mfs,
                                                   sar_mf_t *sar_mf,
                                                   pb_t *pb_mf_ends)
{
    sar_job_mfs_t *job;
    dbg_claim (ctx);
    dbg_claim (mfs);
    dbg_claim (sar_mf);
    dbg_assert (pb_mf_ends);
    job = sar_job_mfs_create_rx ();
    job->mfs = (mfs_t *) mfs;
    job->pb_quantity = sar_mf->qte;
    job->tail = pb_mf_ends;
    uint offset = mfs->head->header.mfbo;
    sar_rx_job_desc_create (&job->job, mfs, mfs->head,
                            mfs->head->header.mfbo,
                            sar_mf);

    ctx->stats.rx_jobs_count++;
    ctx->stats.rx_jobs_waiting_count++;

    uint icv_pos_end = sar_mf->length_complete + offset;
    /* Workaround for bridgedma bug see maria:#905 */
    if (sar_mf->length > SAR_BRGBUG_SECOND_JOB_LENGTH
        && icv_pos_end % BLK_SIZE != 0
        && icv_pos_end % BLK_SIZE <= 4)
    {
        sar_job_mfs_t *j2 = sar_job_mfs_create_rx ();
        uint second_job_start =
            (icv_pos_end - SAR_BRGBUG_SECOND_JOB_LENGTH - SAR_MF_ICV_SIZE);
        pb_t *pb;
        for (pb = mfs->head;
             second_job_start > BLK_SIZE;
             second_job_start -= BLK_SIZE, pb = pb->next);
        j2->job.first_pb_desc = &pb->blk;
        j2->job.header_len = 0;
        j2->job.data_len = SAR_BRGBUG_SECOND_JOB_LENGTH;
        j2->job.first_pb_offset = second_job_start;
        j2->job.crc_reset = false;
        job->job.next = &j2->job;
        job->job.crc_store = false;
        job->job.data_len -= SAR_BRGBUG_SECOND_JOB_LENGTH;
    }
#if CONFIG_SAR_BRG_JOB_ERROR
    job->job.mf_header1 = 0xdeaddead;
#endif

    /* If the pb_mf_ends does not have a MAC Frame start, MFS's head should
     * point to the next PB. */
    if (!pb_mf_ends->header.mfbf)
        mfs->head = pb_mf_ends->next;
    else
    {
        sar_mf_type_t type =
            sar_mf_header_get_type (pb_mf_ends, pb_mf_ends->header.mfbo);
        if (type != SAR_MF_TYPE_NONE)
        {
            mfs->head = pb_mf_ends;
            blk_addref_desc ((blk_t *) pb_mf_ends);
        }
        else
            mfs->head = pb_mf_ends->next;
    }
    blk_addref ((blk_t *) mfs);

    return job;
}

static inline bool
sar_rx_mfs_enough_data (pb_t * head, u16 ssn_min)
{
    if ((u16)(head->header.ssn + 1) != ssn_min)
        return true;
    if (head->header.mfbo < BLK_SIZE - SAR_MF_LENGTH)
        return true;
    return false;
}

/**
 * Try to find a MF in the chained PBs in the MFS.
 * \param  mfs  the MFS to use.
 *
 * This should try to detect and reconstitute all the MF in the chained PBs
 * from the MFS head to the last contiguous PB.
 */
sar_job_mfs_t *
sar_rx_mfs_detect_and_reconstitute_mf (sar_t *ctx, mfs_rx_t *mfs)
{
    sar_job_mfs_t *job = NULL;
    sar_mf_t sar_mf;
    uint pb_missing = 0;
    dbg_assert (mfs);
    /* Try to reassembly Frames. */
    while (mfs->head
           && sar_rx_mfs_enough_data (mfs->head, mfs->ssn_min)
           && lesseq_mod2p16 (mfs->head->header.ssn, mfs->ssn_min))
    {
        /* Verify type. */
        if (sar_rx_mfs_detect_and_reconstitute_mf__possible (
                ctx, mfs, mfs->head, &sar_mf))
        {
            pb_t *pb_mf_ends;
            uint qte = sar_mf.qte - 1;
            /* Verify if all the PBs necessary to reassembly the Mac Frame are
             * present. */
            for (pb_mf_ends = mfs->head;
                 qte
                 && pb_mf_ends->next
                 && (u16) (pb_mf_ends->header.ssn + 1)
                    == pb_mf_ends->next->header.ssn;
                 pb_mf_ends = pb_mf_ends->next, qte--);
            /* If no PBs are missing then launch the job creator */
            if (qte == 0)
            {
                /* Enough memory ? */
                if (blk_slack () || mfs->common.mme)
                {
                    job = sar_rx_mfs_detect_and_reconstitute_mf__create_job (
                        ctx, mfs, &sar_mf, pb_mf_ends);
                    break;
                }
                else
                {
                    SAR_TRACE (EXHAUSTED_MEMORY, mfs->head->header.ssn,
                               pb_mf_ends->header.ssn);
                    /* The whole mac frame is present in this PB, in the mean
                     * time, no blocks will be released, so it can be fully
                     * released. */
                    if (sar_mf.qte == 1)
                        mfs->head = sar_pb_release (mfs->head);
                    else
                    {
                        pb_t *pb = mfs->head;
                        blk_addref_desc (&pb_mf_ends->blk);
                        mfs->head = pb_mf_ends;
                        blk_release_desc_range (&pb->blk, &pb_mf_ends->blk);
                    }
                }
            }
            /* The segments are not contiguous and the missing PBs are outside
             * the window. */
            if (less_mod2p16 (pb_mf_ends->header.ssn + 1, mfs->ssn_min))
            {
                /* Next PB is outside the window. */
                if (mfs->head == pb_mf_ends)
                    /* Special case when the MF in the head is on several PBs
                     * and the next PB is missing and ouside the window.
                     * This will compute the gap between the PB's SSN and the
                     * MFS SSN min. */
                    pb_missing += sar_stats_rx_gap_between_pb_ssn_min (
                        mfs, pb_mf_ends);
                SAR_TRACE (MF_PB_OUTSIDE_WIN, mfs->ssn_min,
                           mfs->window_size, mfs->head->header.ssn,
                           mfs->head->header.mfbo);
                mfs->head = sar_pb_release (mfs->head);
            }
            /* The MAC Frame starts in a PB before the SSN min (still present
             * in the MFS) and ends with a missing PB which SSN is in the
             * Window. */
            else
                /* Stop the loop. */
                break;
        }
        /* Impossible to reassembly the Mac Frame i.e. the PB is corrupt. */
        else
        {
            /* Next PB is outside the window. */
            SAR_TRACE (PB_EMPTY, mfs->head->header.ssn,
                       mfs->head->header.mfbo);
            pb_missing += sar_stats_rx_gap_between_pb_ssn_min (
                mfs, mfs->head);
            mfs->head = sar_pb_release (mfs->head);
        }
    }
    sar_mfs_stats_missing_pbs (mfs, pb_missing);
    return job;
}

void
sar_rx_mfs_process (sar_t *ctx, mfs_rx_t * mfs, sar_reassembly_ctx_t *rea_ctx)
{
    sar_job_mfs_t *job;
    dbg_claim (mfs);
    dbg_claim (rea_ctx);

    while ((job = sar_rx_mfs_detect_and_reconstitute_mf (ctx, mfs)))
    {
        if (!slist_empty (rea_ctx->buffer_list., bare))
        {
            u8 *buffer =
                (u8*) slist_pop_front (rea_ctx->buffer_list., bare);
            job->job.data_addr = buffer;
            /* Workaround for maria bug #905 */
            if (job->job.next)
            {
                job->job.next->data_addr = buffer + job->job.data_len;
                phy_bridgedma_start (
                    ctx->bridgedma_ctx, &job->job, job->job.next);
            }
            else
                phy_bridgedma_start (
                    ctx->bridgedma_ctx, &job->job, &job->job);
        }
        else
        {
            if (job->next)
                slist_push_back_range (rea_ctx->jobs_pending_list., job,
                                       job->next, bare);
            else
                slist_push_back (rea_ctx->jobs_pending_list., job, bare);
        }
    }
}

void
sar_rx_upper_layer_transmit_data (sar_t *sar_ctx, sar_reassembly_ctx_t *ctx)
{
    sar_job_mfs_t *job_head = NULL;
    sar_job_mfs_t *job_tail = NULL;
    sar_job_mfs_t *job_current;
    u8 *buffer;
    dbg_assert (sar_ctx);
    dbg_assert (ctx);

    /* Get the head of the list. */
    job_current = ctx->jobs_pending_list.head;
    while (job_current && !slist_empty(ctx->buffer_list., bare))
    {
        if (job_head == NULL)
            job_head = job_current;
        buffer = (u8*) slist_pop_front (ctx->buffer_list., bare);
        job_current->job.data_addr = buffer;
        /* Work around maria:#905 */
        if (job_current->job.crc_store == false)
        {
            sar_job_mfs_t *j = job_current->next;
            dbg_assert (j);
            j->job.data_addr = buffer + job_current->job.data_len;
            job_current = j;
        }
        job_tail = job_current;
        job_current = job_current->next;
    }

    /* No more buffers available or no more job to unchain. */
    if (job_head)
    {
        /* Unchain the jobs from the list. */
        slist_slice (ctx->jobs_pending_list., job_tail, bare);
        job_tail->next = NULL;
        /* Provide the jobs to the bridgedma list. */
        phy_bridgedma_start (sar_ctx->bridgedma_ctx, &job_head->job,
                             &job_tail->job);
    }
}

void
sar_tx_mac_framing (sar_t *ctx, sar_msdu_t *md_data)
{
    dbg_claim (ctx);
    dbg_claim (md_data);
    dbg_claim (md_data->buffer_address);
    dbg_claim (md_data->mfs);
    dbg_claim ((md_data->length >= ETH_PACKET_MIN_SIZE_ALLOWED)
               && (md_data->length <= ETH_PACKET_MAX_SIZE));
    /* initialise the job descriptor. */
    ctx->job_tx->mfs = (mfs_t *) md_data->mfs;
    ctx->job_tx->user_data = md_data->user_data;
    ctx->job_tx->pb_last_taken = false;
    /* Take the last PB from the MFS if possible. */
    if ((ctx->job_tx->job.first_pb_desc =
        (blk_t*) pbproc_mfs_extract_tail (md_data->mfs)))
    {
        ctx->job_tx->pb_last_taken = true;
        /* Add a reference on the PB. */
        blk_addref_desc (ctx->job_tx->job.first_pb_desc);
        ((pb_t*) ctx->job_tx->job.first_pb_desc)->expiration_ntb =
            md_data->arrival_ntb + md_data->mfs->common.expiration_delay_tck;
    }
    dbg_assert ((ctx->job_tx->job.first_pb_desc == NULL
                 && ctx->job_tx->mfs->tx.last_seg_offset == 0)
                || (ctx->job_tx->job.first_pb_desc
                    && ctx->job_tx->mfs->tx.last_seg_offset != 0));
    /* Create the job for the Bridge DMA
     * Fill the job and create allocate the PBs necessary to stock the MF
     * contained in the md_data
     */
    ctx->job_tx->tail = sar_tx_job_desc_create (ctx, md_data, md_data->mfs,
                                                ctx->job_tx);
    phy_bridgedma_start (ctx->bridgedma_ctx, &ctx->job_tx->job,
                         &ctx->job_tx->job);
}

pb_t * ARCH_ILRAM_PRIO (1)
sar_tx_job_desc_create (sar_t *ctx, sar_msdu_t *md_data, mfs_tx_t * mfs,
                        sar_job_mfs_t *job_mfs)
{
    u16 ssn;
    u16 mf_complete_length = 0;
    u16 missing_size;
    u16 available_size;
    uint pb_nb_allocated;
    uint last_seg_offset;
    pb_t *pb_first;
    pb_t *pb_last;
    phy_bridgedma_job_t *job;

    dbg_claim (ctx);
    dbg_claim (mfs);
    dbg_claim (job_mfs);

    job = &job_mfs->job;
    job->data_addr = md_data->buffer_address;
    job->data_len = md_data->length;

    if (mfs->common.mme || mfs->common.ats)
    {
        job->header_len = SAR_MF_MFH_SIZE + SAR_MF_ATS_SIZE;
        job->mf_header1 = (mfs->common.mme ? SAR_MF_TYPE_MME :
            SAR_MF_TYPE_DATA_ATS)
            | ((md_data->length - 1 + SAR_MF_ATS_SIZE) << 2)
            | (md_data->ats_confounder << 16);
        job->mf_header2 = md_data->ats_confounder >> 16;
        mf_complete_length = SAR_MF_MFH_SIZE + SAR_MF_ATS_SIZE
           + md_data->length + SAR_MF_ICV_SIZE;
    }
    else
    {
        job->header_len = SAR_MF_MFH_SIZE;
        job->mf_header1 = (SAR_MF_TYPE_DATA) | ((md_data->length -1) << 2);
        job->mf_header2 = 0;
        mf_complete_length = SAR_MF_MFH_SIZE + md_data->length
            + SAR_MF_ICV_SIZE;
    }

    /* We have the last PB of the MFS and the offset is different form 0. */
    if (job->first_pb_desc)
    {
        available_size = BLK_SIZE - mfs->last_seg_offset;

        if (available_size < mf_complete_length)
            missing_size = mf_complete_length - available_size;
        else
            missing_size = 0;
    }
    else
    {
        missing_size = mf_complete_length;
        available_size = 0;
    }

    /* Create the list of PBs */
    ssn = mfs->next_ssn;
    job->first_pb_offset = mfs->last_seg_offset;
    /* Compute the next offset. */
    last_seg_offset =
        (mfs->last_seg_offset + mf_complete_length) % BLK_SIZE;
    /* Reset append zero if no more bytes are available in PB. */
    job->append_zero = last_seg_offset != 0;
    /* Need to allocate new PBs. */
    if (missing_size)
    {
        pb_nb_allocated = sar_tx_job_desc_create_complete_list (
            missing_size, ssn, mfs->common.mme, &pb_first, &pb_last,
            md_data->arrival_ntb + mfs->common.expiration_delay_tck);
        /* Store the SSN in the MFS. */
        mfs->next_ssn = ssn + pb_nb_allocated;

        /* Chain the PBs allocated to the PB in the job if the job already
         * contains the last PB of the MFS. */
        if (job->first_pb_desc)
        {
            job_mfs->pb_quantity = 1 + pb_nb_allocated;
            ((pb_t*) job->first_pb_desc)->next = pb_first;
        }
        else
        {
            job->first_pb_desc = (blk_t *) pb_first;
            /* Store the MFBF. */
            pb_first->header.mfbf = true;
            job_mfs->pb_quantity = pb_nb_allocated;
        }

        /* Add the PB to the MFS */
        pbproc_mfs_insert (md_data->mfs, pb_first, pb_last, pb_nb_allocated);
        /* Avoid compiler to change this order. This protect the last offset
         * variable to not be changed by the PBProc if the compiler change the
         * instruction order. */
        arch_reorder_barrier ();
        mfs->last_seg_offset = last_seg_offset;
        /* Store the mac frame boundary in the last PB. */
        if (!pb_last->header.mfbf && mfs->last_seg_offset)
        {
            pb_last->header.mfbf = true;
            pb_last->header.mfbo = mfs->last_seg_offset;
        }

        return pb_last;
    }
    /* Enough space available in the PB present in the job. */
    else
    {
        job_mfs->pb_quantity = 1;
        mfs->last_seg_offset = last_seg_offset;
        return (pb_t*) job->first_pb_desc;
    }
}

/**
 * Process the MFS to release it or destroy in function of the MFS_CMD state.
 * \param  ctx  the SAR context.
 * \param  mfs  the MFS to process.
 */
void
sar_mfs_cmd_process (sar_t *ctx, mfs_tx_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);

    if (mfs->fsm_state != MFS_FSM_CMD_RELEASE)
    {
        mfs->common.expiration_ntb = mac_ntb()
            + MAC_MS_TO_TCK (MFS_RELEASE_DELAY_MS);
        if (mfs->fsm_state != MFS_FSM_CMD_SPC_FAIL)
            mfs->fsm_state = MFS_FSM_CMD_RELEASE;
        else
            ca_mfs_remove (ctx->ca, mfs);
        pbproc_mfs_remove_all (mfs);
    }
    else if (mfs->fsm_state == MFS_FSM_CMD_RELEASE)
        sar_mfs_free_tx (ctx, mfs);
}

void
sar_launch (sar_t *ctx)
{
    dbg_assert (ctx);
    cyg_thread_delay (SAR_THREAD_DELAY_RTC);
    sar_expiration_mfs (ctx);
    if (ctx->pbs_missing_for_pbproc)
    {
        /* Refill the PB pool if missing block were registered. */
        arch_dsr_lock ();
        sar_pb_pool_refill (ctx, 0);
        arch_dsr_unlock ();
    }
}

void
sar_process (cyg_addrword_t data)
{
    while (true)
        sar_launch ((sar_t *) data);
}

void
sar_init_beacon_cb (sar_t *sar, void *user_data, sar_beacon_cb_t uf)
{
    dbg_assert (sar);

    sar->beacon_user_data = user_data;
    sar->beacon_function_cb = uf;
}

void
sar_beacon_add (void *sar, pb_beacon_t *pb,
                pbproc_rx_beacon_params_t *params)
{
    sar_t *ctx;
    dbg_assert (sar);
    dbg_assert (pb);
    dbg_assert (params);
    dbg_assert (((sar_t *)sar)->beacon_user_data);

    ctx = (sar_t *) sar;

    sar_pb_pool_refill (ctx, 1);
    (*ctx->beacon_function_cb) (ctx->beacon_user_data, pb, params);
}

void
sar_beacon_send (sar_t *ctx, pb_beacon_t *beacon, mfs_tx_t *beacon_mfs,
                 void *bto_bpsto)
{
    dbg_assert (ctx);
    dbg_assert (beacon);
    dbg_assert (beacon_mfs);
    dbg_assert (bto_bpsto);

    dbg_assert (ctx->pbproc_ctx);


    pbproc_mfs_beacon_prepare (ctx->pbproc_ctx, beacon_mfs,
                               (pb_beacon_t *) beacon,
                               bto_bpsto);
    ca_mfs_update (ctx->ca, beacon_mfs);
}

/**
 * Clean a MFS.
 * \param  mac_store  the mac store.
 * \param  mfs  the MFS concerned.
 * \param  ctx  the callback context.
 */
static void
sar_cleanup__mfs_remove (mac_store_t *mac_store, mfs_t *mfs, void *ctx)
{
    sar_t *sar = ctx;
    dbg_assert (ctx);
    dbg_assert (mfs);
    arch_dsr_lock ();
    if ((mfs->common.tx && (!mfs->tx.beacon))
        || (!mfs->common.tx))
    {
        /* If the MFS has not been release before, case of the clean up. */
        if (mfs->common.tx)
        {
            if (mfs->tx.fsm_state != MFS_FSM_CMD_RELEASE)
                sar_mfs_remove (sar, mfs);
            sar_mfs_free_tx (sar, (mfs_tx_t *) mfs);
        }
        else if (mfs->common.tx == false)
            sar_mfs_free_rx (sar, (mfs_rx_t *) mfs);
    }
    arch_dsr_unlock ();
}

/**
 * Release the pending jobs present in the list.
 * \param  ctx  the SAR context.
 * \param  rctx  the reassembly context to process.
 */
static inline void
sar_cleanup_pending_jobs (sar_t *ctx, sar_reassembly_ctx_t *rctx)
{
    sar_job_mfs_t *job;
    while (!slist_empty (rctx->jobs_pending_list., bare))
    {
        job = slist_pop_front (rctx->jobs_pending_list., bare);
        sar_bridge_dma_free_header_not_activate (ctx, job);
        /* The pointer can stay in an unknown state, the job in RX will be
         * freed and in TX it will be initialised at the correct MFS address.
         */
        blk_release (job->mfs);
        /* Release the JOB only for RX jobs. TX is static. */
        if (job->job.direction)
            blk_release (job);
    }
}

void
sar_cleanup (sar_t *ctx)
{
    uint i;
    dbg_assert (ctx);
    sar_cleanup_pending_jobs (ctx, &ctx->data_ctx);
    sar_cleanup_pending_jobs (ctx, &ctx->mme_ctx);
    /* Remove all the stations from the store. */
    for (i = MAC_TEI_STA_MIN; i <= MAC_TEI_STA_MAX; i++)
        sar_sta_remove (ctx, i);
    /* Remove the others MFS. */
    mac_store_mfs_travel (ctx->mac_store,
                          sar_cleanup__mfs_remove,
                          ctx);
}

void
sar_sta_remove (sar_t *ctx, u8 tei)
{
    sta_t *sta;
    dbg_assert (ctx);
    dbg_assert (tei);
    dbg_assert (ctx->mac_store);
    dbg_assert (ctx->ca);
    arch_dsr_lock ();
    sta = mac_store_sta_get (ctx->mac_store, tei);
    if (sta)
    {
        bool res;
        mac_store_mfs_travel_by_tei (ctx->mac_store, tei,
                                     sar_cleanup__mfs_remove,
                                     ctx);

        // Remove the station.
        res = mac_store_sta_remove (ctx->mac_store, tei);
        dbg_check (res);
        blk_release (sta);
    }
    arch_dsr_unlock ();
}

void
sar_activate (sar_t *ctx, bool activate)
{
    dbg_assert (ctx);
    ctx->activate = activate;
}

void
sar_mfs_cmd (sar_t *ctx, mfs_tx_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    sar_mfs_cmd_process (ctx, mfs);
}

void
sar_mfs_free_tx (sar_t *ctx, mfs_tx_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    dbg_assert (mfs->fsm_state == MFS_FSM_CMD_RELEASE);
    SAR_TRACE (MFS_TX_FREE, phy_date (), mfs);
#if CONFIG_MAC_SAR_EOC_PERMANENT_MFS
    pbproc_mfs_remove_all (mfs);
#else
    dbg_assert (mfs->head == NULL);
#endif
    mac_store_mfs_remove (ctx->mac_store, PARENT_OF (mfs_t, tx, mfs));
}

void
sar_mfs_free_rx (sar_t *ctx, mfs_rx_t *mfs)
{
    dbg_assert (ctx);
    dbg_assert (mfs);
    while (mfs->head)
        mfs->head = sar_pb_release (mfs->head);
    SAR_TRACE (MFS_RX_FREE, phy_date (), mfs);
    mac_store_mfs_remove (ctx->mac_store, PARENT_OF (mfs_t, rx, mfs));
}