summaryrefslogtreecommitdiffstats
path: root/stack/l2cap/l2c_fcr.c
blob: ff018c5cbcbdcc443037396a8b6bb933e59a8bf7 (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
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
/******************************************************************************
 *
 *  Copyright (C) 2004-2012 Broadcom Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 ******************************************************************************/

/******************************************************************************
 *
 *  This file contains the L2CAP 1.2 Flow Control and retransmissions
 *  functions
 *
 ******************************************************************************/

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

#include "gki.h"
#include "bt_types.h"
#include "hcimsgs.h"
#include "l2cdefs.h"
#include "l2c_int.h"
#include "l2c_api.h"
#include "btu.h"
#include "btm_api.h"
#include "btm_int.h"


/* Flag passed to retransmit_i_frames() when all packets should be retransmitted */
#define L2C_FCR_RETX_ALL_PKTS   0xFF

#if BT_TRACE_VERBOSE == TRUE
static char *SAR_types[] = { "Unsegmented", "Start", "End", "Continuation" };
static char *SUP_types[] = { "RR", "REJ", "RNR", "SREJ" };
#endif

/* Look-up table for the CRC calculation */
static const unsigned short crctab[256] = {
    0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
    0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
    0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
    0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
    0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
    0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
    0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
    0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
    0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
    0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
    0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
    0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
    0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
    0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
    0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
    0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
    0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
    0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
    0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
    0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
    0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
    0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
    0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
    0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
    0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
    0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
    0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
    0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
    0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
    0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
    0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
    0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
};


/*******************************************************************************
**  Static local functions
*/
static BOOLEAN process_reqseq (tL2C_CCB *p_ccb, UINT16 ctrl_word);
static void    process_s_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word);
static void    process_i_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word, BOOLEAN delay_ack);
static BOOLEAN retransmit_i_frames (tL2C_CCB *p_ccb, UINT8 tx_seq);
static void    prepare_I_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, BOOLEAN is_retransmission);
static void    process_stream_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf);
static BOOLEAN do_sar_reassembly (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word);

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
static BOOLEAN l2c_corrupt_the_fcr_packet (tL2C_CCB *p_ccb, BT_HDR *p_buf,
                                           BOOLEAN is_rx, UINT16 ctrl_word);
static BOOLEAN l2c_bypass_sframe_packet (tL2C_CCB *p_ccb);
#endif

#if (L2CAP_ERTM_STATS == TRUE)
static void l2c_fcr_collect_ack_delay (tL2C_CCB *p_ccb, UINT8 num_bufs_acked);
#endif

/*******************************************************************************
**
** Function         l2c_fcr_updcrc
**
** Description      This function computes the CRC using the look-up table.
**
** Returns          CRC
**
*******************************************************************************/
unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char *icp, int icnt)
{
    register unsigned short crc = icrc;
    register unsigned char  *cp = icp;
    register          int   cnt = icnt;

    while (cnt--)
    {
        crc = ((crc >> 8) & 0xff) ^ crctab[(crc & 0xff) ^ *cp++];
    }

    return(crc);
}


/*******************************************************************************
**
** Function         l2c_fcr_tx_get_fcs
**
** Description      This function computes the CRC for a frame to be TXed.
**
** Returns          CRC
**
*******************************************************************************/
UINT16 l2c_fcr_tx_get_fcs (BT_HDR *p_buf)
{
    UINT8   *p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;

    return (l2c_fcr_updcrc (L2CAP_FCR_INIT_CRC, p, p_buf->len));
}

/*******************************************************************************
**
** Function         l2c_fcr_rx_get_fcs
**
** Description      This function computes the CRC for a received frame.
**
** Returns          CRC
**
*******************************************************************************/
UINT16 l2c_fcr_rx_get_fcs (BT_HDR *p_buf)
{
    UINT8   *p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;

    /* offset points past the L2CAP header, but the CRC check includes it */
    p -= L2CAP_PKT_OVERHEAD;

    return (l2c_fcr_updcrc (L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD));
}

/*******************************************************************************
**
** Function         l2c_fcr_start_timer
**
** Description      This function starts the (monitor or retransmission) timer.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_start_timer (tL2C_CCB *p_ccb)
{
    UINT32  tout;

    /* The timers which are in milliseconds */
    if (p_ccb->fcrb.wait_ack)
    {
        tout = (UINT32)p_ccb->our_cfg.fcr.mon_tout;
    }
    else
    {
        tout = (UINT32)p_ccb->our_cfg.fcr.rtrans_tout;
    }
/*
    L2CAP_TRACE_DEBUG4 ("l2c_fcr_start_timer Tout: %u  Already Running: %u  wait_ack: %u  ack_q_count: %u",
                        tout, p_ccb->timer_entry.in_use, p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);
*/
    /* Only start a timer that was not started */
    if (p_ccb->fcrb.mon_retrans_timer.in_use == 0)
        btu_start_quick_timer (&p_ccb->fcrb.mon_retrans_timer, BTU_TTYPE_L2CAP_CHNL, tout*QUICK_TIMER_TICKS_PER_SEC/1000);
}

/*******************************************************************************
**
** Function         l2c_fcr_stop_timer
**
** Description      This function stops the (monitor or transmission) timer.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_stop_timer (tL2C_CCB *p_ccb)
{
    if (p_ccb->fcrb.mon_retrans_timer.in_use)
    {
/*
        L2CAP_TRACE_DEBUG2 ("l2c_fcr_stop_timer wait_ack: %u  ack_q_count: %u",
                            p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);
*/
        btu_stop_quick_timer (&p_ccb->fcrb.mon_retrans_timer);
    }
}

/*******************************************************************************
**
** Function         l2c_fcr_cleanup
**
** Description      This function cleans up the variable used for flow-control/retrans.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_cleanup (tL2C_CCB *p_ccb)
{
    tL2C_FCRB *p_fcrb = &p_ccb->fcrb;

    l2c_fcr_stop_timer (p_ccb);

    if (p_fcrb->p_rx_sdu)
        GKI_freebuf (p_fcrb->p_rx_sdu);

    while (p_fcrb->waiting_for_ack_q.p_first)
        GKI_freebuf (GKI_dequeue (&p_fcrb->waiting_for_ack_q));

    while (p_fcrb->srej_rcv_hold_q.p_first)
        GKI_freebuf (GKI_dequeue (&p_fcrb->srej_rcv_hold_q));

    while (p_fcrb->retrans_q.p_first)
        GKI_freebuf (GKI_dequeue (&p_fcrb->retrans_q));

    btu_stop_quick_timer (&p_fcrb->ack_timer);
    btu_stop_quick_timer (&p_ccb->fcrb.mon_retrans_timer);

#if (L2CAP_ERTM_STATS == TRUE)
    if ( (p_ccb->local_cid >= L2CAP_BASE_APPL_CID) && (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) )
    {
        UINT32  dur = GKI_get_os_tick_count() - p_ccb->fcrb.connect_tick_count;
        char    *p_str = (char *)GKI_getbuf(120);
        UINT16  i;
        UINT32  throughput_avg, ack_delay_avg, ack_q_count_avg;

        dur = GKI_OS_TICKS_TO_MS(dur);
        BT_TRACE_2(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "---  L2CAP ERTM  Stats for CID: 0x%04x   Duration: %08ums", p_ccb->local_cid, dur);
        BT_TRACE_4(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "Retransmissions:%08u Times Flow Controlled:%08u Retrans Touts:%08u Ack Touts:%08u",
                    p_ccb->fcrb.pkts_retransmitted, p_ccb->fcrb.xmit_window_closed, p_ccb->fcrb.retrans_touts, p_ccb->fcrb.xmit_ack_touts);
        BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "Times there is less than 2 packets in controller when flow controlled:%08u", p_ccb->fcrb.controller_idle);
        BT_TRACE_2(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "max_held_acks:%08u, in_cfg.fcr.tx_win_sz:%08u", p_ccb->fcrb.max_held_acks, p_ccb->peer_cfg.fcr.tx_win_sz );
        if (p_str)
        {
            sprintf(p_str, "Sent Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u SREJ:%08u",
                p_ccb->fcrb.ertm_pkt_counts[0], p_ccb->fcrb.ertm_byte_counts[0],
                (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[0] * 100) / (dur / 10) : 0),
                p_ccb->fcrb.s_frames_sent[0], p_ccb->fcrb.s_frames_sent[1], p_ccb->fcrb.s_frames_sent[2], p_ccb->fcrb.s_frames_sent[3]);

            BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC, "%s", p_str);

            sprintf(p_str, "Rcvd Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u SREJ:%08u",
                p_ccb->fcrb.ertm_pkt_counts[1], p_ccb->fcrb.ertm_byte_counts[1],
                (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[1] * 100) / (dur / 10) : 0),
                p_ccb->fcrb.s_frames_rcvd[0], p_ccb->fcrb.s_frames_rcvd[1], p_ccb->fcrb.s_frames_rcvd[2], p_ccb->fcrb.s_frames_rcvd[3]);

            BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC, "%s", p_str);

            throughput_avg  = 0;
            ack_delay_avg   = 0;
            ack_q_count_avg = 0;

            for (i = 0; i < L2CAP_ERTM_STATS_NUM_AVG; i++ )
            {
                if (i == p_ccb->fcrb.ack_delay_avg_index )
                {
                    BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                           "[%02u] collecting data ...", i );
                    continue;
                }

                sprintf(p_str, "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, ack_q_count avg:%3u, min:%3u, max:%3u",
                        i, p_ccb->fcrb.throughput[i],
                        p_ccb->fcrb.ack_delay_avg[i], p_ccb->fcrb.ack_delay_min[i], p_ccb->fcrb.ack_delay_max[i],
                        p_ccb->fcrb.ack_q_count_avg[i], p_ccb->fcrb.ack_q_count_min[i], p_ccb->fcrb.ack_q_count_max[i] );

                BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC, "%s", p_str);

                throughput_avg  += p_ccb->fcrb.throughput[i];
                ack_delay_avg   += p_ccb->fcrb.ack_delay_avg[i];
                ack_q_count_avg += p_ccb->fcrb.ack_q_count_avg[i];
            }

            throughput_avg  /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
            ack_delay_avg   /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
            ack_q_count_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);

            BT_TRACE_3(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "throughput_avg: %8u (kbytes/sec), ack_delay_avg: %8u ms, ack_q_count_avg: %8u",
                    throughput_avg, ack_delay_avg, ack_q_count_avg );

            GKI_freebuf(p_str);
        }

        BT_TRACE_0(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC,
                   "---");
    }
#endif

    memset (p_fcrb, 0, sizeof (tL2C_FCRB));
}

/*******************************************************************************
**
** Function         l2c_fcr_clone_buf
**
** Description      This function allocates and copies requested part of a buffer
**                  at a new-offset.
**
** Returns          pointer to new buffer
**
*******************************************************************************/
BT_HDR *l2c_fcr_clone_buf (BT_HDR *p_buf, UINT16 new_offset, UINT16 no_of_bytes, UINT8 pool)
{
    BT_HDR *p_buf2;

    /* If using the common pool, should be at least 10% free. */
    if ( (pool == HCI_ACL_POOL_ID) && (GKI_poolutilization (pool) > 90) )
    {
        L2CAP_TRACE_ERROR1 ("L2CAP - failed to clone buffer on HCI_ACL_POOL_ID Utilization: %u", GKI_poolutilization(pool));
        return (NULL);
    }

    if ((p_buf2 = (BT_HDR *)GKI_getpoolbuf(pool)) != NULL)
    {
        UINT16    pool_buf_size = GKI_get_pool_bufsize (pool);

        /* Make sure buffer fits into buffer pool */
        if ((no_of_bytes + sizeof(BT_HDR) + new_offset) > pool_buf_size)
        {
            L2CAP_TRACE_ERROR5("##### l2c_fcr_clone_buf (NumBytes %d) -> Exceeds poolsize %d [bytes %d + BT_HDR %d + offset %d]",
                               (no_of_bytes + sizeof(BT_HDR) + new_offset),
                               pool_buf_size, no_of_bytes, sizeof(BT_HDR),
                               new_offset);

            GKI_freebuf(p_buf2);
            return (NULL);
        }

        p_buf2->offset = new_offset;
        p_buf2->len    = no_of_bytes;

        memcpy (((UINT8 *)(p_buf2 + 1)) + p_buf2->offset,
                ((UINT8 *)(p_buf + 1))  + p_buf->offset,
                no_of_bytes);
    }
    else
    {
        L2CAP_TRACE_ERROR2 ("L2CAP - failed to clone buffer, Pool: %u  Count: %u", pool,  GKI_poolfreecount(pool));
    }

    return (p_buf2);
}

/*******************************************************************************
**
** Function         l2c_fcr_is_flow_controlled
**
** Description      This function checks if the CCB is flow controlled by peer.
**
** Returns          The control word
**
*******************************************************************************/
BOOLEAN l2c_fcr_is_flow_controlled (tL2C_CCB *p_ccb)
{
    if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
    {
        /* Check if remote side flowed us off or the transmit window is full */
        if ( (p_ccb->fcrb.remote_busy == TRUE)
         ||  (p_ccb->fcrb.waiting_for_ack_q.count >= p_ccb->peer_cfg.fcr.tx_win_sz) )
        {
#if (L2CAP_ERTM_STATS == TRUE)
            if (p_ccb->xmit_hold_q.count != 0)
            {
                p_ccb->fcrb.xmit_window_closed++;

                if ((p_ccb->p_lcb->sent_not_acked < 2)&&(l2cb.controller_xmit_window > 0))
                    p_ccb->fcrb.controller_idle++;
            }
#endif
            return (TRUE);
        }
    }
    return (FALSE);
}

/*******************************************************************************
**
** Function         prepare_I_frame
**
** Description      This function sets the FCR variables in an I-frame that is
**                  about to be sent to HCI for transmission. This may be the
**                  first time the I-frame is sent, or a retransmission
**
** Returns          -
**
*******************************************************************************/
static void prepare_I_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, BOOLEAN is_retransmission)
{
    tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
    UINT8       *p;
    UINT16      fcs;
    UINT16      ctrl_word;
    BOOLEAN     set_f_bit = p_fcrb->send_f_rsp;

    p_fcrb->send_f_rsp = FALSE;

    if (is_retransmission)
    {
        /* Get the old control word and clear out the old req_seq and F bits */
        p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;

        STREAM_TO_UINT16 (ctrl_word, p);

        ctrl_word  &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT);
    }
    else
    {
        ctrl_word  = p_buf->layer_specific & L2CAP_FCR_SEG_BITS;                /* SAR bits */
        ctrl_word |= (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT);      /* Tx Seq */

        p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
    }

    /* Set the F-bit and reqseq only if using re-transmission mode */
    if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
    {
        if (set_f_bit)
            ctrl_word |= L2CAP_FCR_F_BIT;

        ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT;

        p_fcrb->last_ack_sent = p_ccb->fcrb.next_seq_expected;

        if (p_ccb->fcrb.ack_timer.in_use)
            btu_stop_quick_timer (&p_ccb->fcrb.ack_timer);
    }

    /* Set the control word */
    p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;

    UINT16_TO_STREAM (p, ctrl_word);

    /* Compute the FCS and add to the end of the buffer if not bypassed */
    if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
    {
        /* length field in l2cap header has to include FCS length */
        p = ((UINT8 *) (p_buf+1)) + p_buf->offset;
        UINT16_TO_STREAM (p, p_buf->len + L2CAP_FCS_LEN - L2CAP_PKT_OVERHEAD);

        /* Calculate the FCS */
        fcs = l2c_fcr_tx_get_fcs(p_buf);

        /* Point to the end of the buffer and put the FCS there */
        p = ((UINT8 *) (p_buf+1)) + p_buf->offset + p_buf->len;

        UINT16_TO_STREAM (p, fcs);

        p_buf->len += L2CAP_FCS_LEN;
    }

#if BT_TRACE_VERBOSE == TRUE
    if (is_retransmission)
    {
        L2CAP_TRACE_EVENT6 ("L2CAP eRTM ReTx I-frame  CID: 0x%04x  Len: %u  SAR: %s  TxSeq: %u  ReqSeq: %u  F: %u",
                            p_ccb->local_cid, p_buf->len,
                            SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
                            (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
    }
    else
    {
        L2CAP_TRACE_EVENT6 ("L2CAP eRTM Tx I-frame CID: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  ReqSeq: %u  F: %u",
                            p_ccb->local_cid, p_buf->len,
                            SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
                            (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
    }
#endif

    /* Start the retransmission timer if not already running */
    if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
        l2c_fcr_start_timer (p_ccb);
}

/*******************************************************************************
**
** Function         l2c_fcr_send_S_frame
**
** Description      This function formats and sends an S-frame for transmission.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_send_S_frame (tL2C_CCB *p_ccb, UINT16 function_code, UINT16 pf_bit)
{
    BT_HDR      *p_buf;
    UINT8       *p;
    UINT16      ctrl_word;
    UINT16      fcs;

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
    /* Only used for conformance testing */
    if (l2c_bypass_sframe_packet (p_ccb))
        return;
#endif

    if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN))
        return;

#if (L2CAP_ERTM_STATS == TRUE)
     p_ccb->fcrb.s_frames_sent[function_code]++;
#endif

    if (pf_bit == L2CAP_FCR_P_BIT)
    {
        p_ccb->fcrb.wait_ack = TRUE;

        l2c_fcr_stop_timer (p_ccb);         /* Restart the monitor timer */
        l2c_fcr_start_timer (p_ccb);
    }

    /* Create the control word to use */
    ctrl_word = (function_code << L2CAP_FCR_SUP_SHIFT) | L2CAP_FCR_S_FRAME_BIT;
    ctrl_word |= (p_ccb->fcrb.next_seq_expected << L2CAP_FCR_REQ_SEQ_BITS_SHIFT);
    ctrl_word |= pf_bit;

    if ((p_buf = (BT_HDR *)GKI_getpoolbuf (L2CAP_CMD_POOL_ID)) != NULL)
    {
        p_buf->offset = HCI_DATA_PREAMBLE_SIZE;
        p_buf->len    = L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;

        /* Set the pointer to the beginning of the data */
        p = (UINT8 *)(p_buf + 1) + p_buf->offset;

        /* Put in the L2CAP header */
        UINT16_TO_STREAM (p, L2CAP_FCR_OVERHEAD + L2CAP_FCS_LEN);
        UINT16_TO_STREAM (p, p_ccb->remote_cid);
        UINT16_TO_STREAM (p, ctrl_word);

        /* Compute the FCS and add to the end of the buffer if not bypassed */
        if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
        {
            fcs = l2c_fcr_tx_get_fcs (p_buf);

            UINT16_TO_STREAM (p, fcs);
            p_buf->len += L2CAP_FCS_LEN;
        }
        else /* rewrite the length without FCS length */
        {
            p -= 6;
            UINT16_TO_STREAM (p, L2CAP_FCR_OVERHEAD);
        }

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
        /* Get out if packet was dropped */
        if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, FALSE, ctrl_word))
            return;
#endif
        /* Now, the HCI transport header */
        p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
        l2cu_set_acl_hci_header (p_buf, p_ccb);

#if BT_TRACE_VERBOSE == TRUE
        if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1)
         || (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3))
        {
            L2CAP_TRACE_WARNING6 ("L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  ReqSeq: %u  P: %u  F: %u",
                            p_ccb->local_cid, ctrl_word,
                            SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
            L2CAP_TRACE_WARNING1 ("                  Buf Len: %u", p_buf->len);
        }
        else
        {
            L2CAP_TRACE_EVENT6 ("L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  ReqSeq: %u  P: %u  F: %u",
                            p_ccb->local_cid, ctrl_word,
                            SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
            L2CAP_TRACE_EVENT1 ("                  Buf Len: %u", p_buf->len);
        }
#endif  /* BT_TRACE_VERBOSE */

        l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, p_buf);

        p_ccb->fcrb.last_ack_sent = p_ccb->fcrb.next_seq_expected;

        if (p_ccb->fcrb.ack_timer.in_use)
            btu_stop_quick_timer (&p_ccb->fcrb.ack_timer);
    }
    else
    {
        L2CAP_TRACE_ERROR2 ("l2c_fcr_send_S_frame(No Resources) cid 0x%04x, Type: 0x%4x",
                             p_ccb->local_cid, function_code);
    }
}


/*******************************************************************************
**
** Function         l2c_fcr_proc_pdu
**
** Description      This function is the entry point for processing of a
**                  received PDU when in flow control and/or retransmission modes.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_proc_pdu (tL2C_CCB *p_ccb, BT_HDR *p_buf)
{
    UINT8       *p;
    UINT16      fcs;
    UINT16      min_pdu_len;
    UINT16      ctrl_word;

    /* Check the length */
    min_pdu_len = (p_ccb->bypass_fcs == L2CAP_BYPASS_FCS) ?
                  (UINT16)L2CAP_FCR_OVERHEAD : (UINT16)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD);

    if (p_buf->len < min_pdu_len)
    {
        L2CAP_TRACE_WARNING2 ("Rx L2CAP PDU: CID: 0x%04x  Len too short: %u", p_ccb->local_cid, p_buf->len);
        GKI_freebuf (p_buf);
        return;
    }

    if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_STREAM_MODE)
    {
        process_stream_frame (p_ccb, p_buf);
        return;
    }

#if BT_TRACE_VERBOSE == TRUE
    /* Get the control word */
    p = ((UINT8 *)(p_buf+1)) + p_buf->offset;
    STREAM_TO_UINT16 (ctrl_word, p);

    if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
    {
        if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1)
         || (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3))
        {
            /* REJ or SREJ */
            L2CAP_TRACE_WARNING6 ("L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  P: %u  F: %u",
                            p_ccb->local_cid, p_buf->len,
                            SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
        }
        else
        {
            L2CAP_TRACE_EVENT6 ("L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  P: %u  F: %u",
                            p_ccb->local_cid, p_buf->len,
                            SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
        }
    }
    else
    {
        L2CAP_TRACE_EVENT6 ("L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  ReqSeq: %u  F: %u",
                            p_ccb->local_cid, p_buf->len,
                            SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
                            (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                            (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
    }

    L2CAP_TRACE_EVENT6 ("      eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt %u, wt_q.cnt %u, tries %u",
                        p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack, p_ccb->fcrb.next_seq_expected,
                        p_ccb->fcrb.last_ack_sent, p_ccb->fcrb.waiting_for_ack_q.count, p_ccb->fcrb.num_tries);

#endif /* BT_TRACE_VERBOSE */

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
    p = ((UINT8 *)(p_buf+1)) + p_buf->offset;
    STREAM_TO_UINT16 (ctrl_word, p);

    /* Get out if packet was dropped */
    if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, TRUE, ctrl_word))
        return;
#endif  /* L2CAP_CORRUPT_ERTM_PKTS */

    /* Verify FCS if using */
    if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
    {
        p = ((UINT8 *)(p_buf+1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;

        /* Extract and drop the FCS from the packet */
        STREAM_TO_UINT16 (fcs, p);
        p_buf->len -= L2CAP_FCS_LEN;

        if (l2c_fcr_rx_get_fcs(p_buf) != fcs)
        {
            L2CAP_TRACE_WARNING1 ("Rx L2CAP PDU: CID: 0x%04x  BAD FCS", p_ccb->local_cid);
            GKI_freebuf(p_buf);
            return;
        }
    }

    /* Get the control word */
    p = ((UINT8 *)(p_buf+1)) + p_buf->offset;

    STREAM_TO_UINT16 (ctrl_word, p);

    p_buf->len    -= L2CAP_FCR_OVERHEAD;
    p_buf->offset += L2CAP_FCR_OVERHEAD;

    /* If we had a poll bit outstanding, check if we got a final response */
    if (p_ccb->fcrb.wait_ack)
    {
        /* If final bit not set, ignore the frame unless it is a polled S-frame */
        if ( !(ctrl_word & L2CAP_FCR_F_BIT) )
        {
            if ( (ctrl_word & L2CAP_FCR_P_BIT) && (ctrl_word & L2CAP_FCR_S_FRAME_BIT) )
            {
                if (p_ccb->fcrb.srej_sent)
                    l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
                else if (p_ccb->fcrb.local_busy)
                    l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
                else
                    l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);

                /* Got a poll while in wait_ack state, so re-start our timer with 1-second */
                /* This is a small optimization... the monitor timer is 12 secs, but we saw */
                /* that if the other side sends us a poll when we are waiting for a final,  */
                /* then it speeds up recovery significantly if we poll him back soon after his poll. */
                btu_start_quick_timer (&p_ccb->fcrb.mon_retrans_timer, BTU_TTYPE_L2CAP_CHNL, QUICK_TIMER_TICKS_PER_SEC);
            }
            GKI_freebuf (p_buf);
            return;
        }

        p_ccb->fcrb.wait_ack  = FALSE;

        /* P and F are mutually exclusive */
        if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
            ctrl_word &= ~L2CAP_FCR_P_BIT;

        if (p_ccb->fcrb.waiting_for_ack_q.count == 0)
            p_ccb->fcrb.num_tries = 0;

        l2c_fcr_stop_timer (p_ccb);
    }
    else
    {
        /* Otherwise, ensure the final bit is ignored */
        ctrl_word &= ~L2CAP_FCR_F_BIT;
    }

    /* Process receive sequence number */
    if (!process_reqseq (p_ccb, ctrl_word))
    {
        GKI_freebuf (p_buf);
        return;
    }

     /* Process based on whether it is an S-frame or an I-frame */
    if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
        process_s_frame (p_ccb, p_buf, ctrl_word);
    else
        process_i_frame (p_ccb, p_buf, ctrl_word, FALSE);

    /* Return if the channel got disconnected by a bad packet or max retransmissions */
    if ( (!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN) )
        return;

    /* If we have some buffers held while doing SREJ, and SREJ has cleared, process them now */
    if ( (!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.srej_sent) && (p_ccb->fcrb.srej_rcv_hold_q.count > 0) )
    {
        BUFFER_Q temp_q = p_ccb->fcrb.srej_rcv_hold_q;

        GKI_init_q (&p_ccb->fcrb.srej_rcv_hold_q);

        while ((p_buf = (BT_HDR *)GKI_dequeue (&temp_q)) != NULL)
        {
            if (p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN))
            {
                /* Get the control word */
                p = ((UINT8 *)(p_buf+1)) + p_buf->offset - L2CAP_FCR_OVERHEAD;

                STREAM_TO_UINT16 (ctrl_word, p);

                L2CAP_TRACE_DEBUG3 ("l2c_fcr_proc_pdu() CID: 0x%04x  Process Buffer from SREJ_Hold_Q   TxSeq: %u  Expected_Seq: %u",
                                    p_ccb->local_cid, (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
                                    p_ccb->fcrb.next_seq_expected);

                /* Process the SREJ held I-frame, but do not send an RR for each individual frame */
                process_i_frame (p_ccb, p_buf, ctrl_word, TRUE);
            }
            else
                GKI_freebuf (p_buf);

            /* If more frames were lost during SREJ, send a REJ */
            if (p_ccb->fcrb.rej_after_srej)
            {
                p_ccb->fcrb.rej_after_srej = FALSE;
                p_ccb->fcrb.rej_sent       = TRUE;

                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_REJ, 0);
            }
        }

        /* Now, if needed, send one RR for the whole held queue */
        if ( (!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.rej_sent) && (!p_ccb->fcrb.srej_sent)
         &&  (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent) )
            l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, 0);
        else
        {
            L2CAP_TRACE_DEBUG6 ("l2c_fcr_proc_pdu() not sending RR CID: 0x%04x  local_busy:%d rej_sent:%d srej_sent:%d Expected_Seq:%u Last_Ack:%u",
                                p_ccb->local_cid, p_ccb->fcrb.local_busy, p_ccb->fcrb.rej_sent, p_ccb->fcrb.srej_sent, p_ccb->fcrb.next_seq_expected,
                                p_ccb->fcrb.last_ack_sent);
        }
    }

    /* If a window has opened, check if we can send any more packets */
    if ( (p_ccb->fcrb.retrans_q.count || p_ccb->xmit_hold_q.count)
      && (p_ccb->fcrb.wait_ack == FALSE)
      && (l2c_fcr_is_flow_controlled (p_ccb) == FALSE) )
    {
        l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, NULL);
    }
}

/*******************************************************************************
**
** Function         l2c_fcr_proc_tout
**
** Description      Handle a timeout. We should be in error recovery state.
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_proc_tout (tL2C_CCB *p_ccb)
{
    L2CAP_TRACE_DEBUG5 ("l2c_fcr_proc_tout:  CID: 0x%04x  num_tries: %u (max: %u)  wait_ack: %u  ack_q_count: %u",
                        p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
                        p_ccb->fcrb.wait_ack, p_ccb->fcrb.waiting_for_ack_q.count);

#if (L2CAP_ERTM_STATS == TRUE)
    p_ccb->fcrb.retrans_touts++;
#endif

    if ( (p_ccb->peer_cfg.fcr.max_transmit != 0) && (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit) )
    {
        l2cu_disconnect_chnl (p_ccb);
    }
    else
    {
        if (!p_ccb->fcrb.srej_sent && !p_ccb->fcrb.rej_sent)
        {
            if (p_ccb->fcrb.local_busy)
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_P_BIT);
            else
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
        }
    }
}


/*******************************************************************************
**
** Function         l2c_fcr_proc_ack_tout
**
** Description      Send RR/RNR if we have not acked I frame
**
** Returns          -
**
*******************************************************************************/
void l2c_fcr_proc_ack_tout (tL2C_CCB *p_ccb)
{
    L2CAP_TRACE_DEBUG5 ("l2c_fcr_proc_ack_tout:  CID: 0x%04x State: %u  Wack:%u  Rq:%d  Acked:%d", p_ccb->local_cid,
                        p_ccb->chnl_state, p_ccb->fcrb.wait_ack, p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);

    if ( (p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack)
      && (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected) )
    {
#if (L2CAP_ERTM_STATS == TRUE)
        p_ccb->fcrb.xmit_ack_touts++;
#endif
        if (p_ccb->fcrb.local_busy)
            l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, 0);
        else
            l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, 0);
    }
}


/*******************************************************************************
**
** Function         process_reqseq
**
** Description      Handle receive sequence number
**
** Returns          -
**
*******************************************************************************/
static BOOLEAN process_reqseq (tL2C_CCB *p_ccb, UINT16 ctrl_word)
{
    tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
    UINT8       req_seq, num_bufs_acked, xx;
    UINT16      ls;
    UINT16      full_sdus_xmitted;

    /* Receive sequence number does not ack anything for SREJ with P-bit set to zero */
    if ( (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
     &&  ((ctrl_word & L2CAP_FCR_SUP_BITS) == (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT))
     &&  ((ctrl_word & L2CAP_FCR_P_BIT) == 0) )
    {
        /* If anything still waiting for ack, restart the timer if it was stopped */
        if (p_fcrb->waiting_for_ack_q.count)
            l2c_fcr_start_timer (p_ccb);

        return (TRUE);
    }

    /* Extract the receive sequence number from the control word */
    req_seq = (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT;

    num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;

    /* Verify the request sequence is in range before proceeding */
    if (num_bufs_acked > p_fcrb->waiting_for_ack_q.count)
    {
        /* The channel is closed if ReqSeq is not in range */
        L2CAP_TRACE_WARNING4 ("L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x  req_seq 0x%02x  last_rx_ack: 0x%02x  QCount: %u",
                               ctrl_word, req_seq, p_fcrb->last_rx_ack, p_fcrb->waiting_for_ack_q.count);

        l2cu_disconnect_chnl (p_ccb);
        return (FALSE);
    }

/*
    L2CAP_TRACE_DEBUG3 ("L2CAP process_reqseq 0x%02x  last_rx_ack: 0x%02x  QCount: %u",
                           req_seq, p_fcrb->last_rx_ack, p_fcrb->waiting_for_ack_q.count);
*/
    p_fcrb->last_rx_ack = req_seq;

    /* Now we can release all acknowledged frames, and restart the retransmission timer if needed */
    if (num_bufs_acked != 0)
    {
        p_fcrb->num_tries = 0;
        full_sdus_xmitted = 0;

#if (L2CAP_ERTM_STATS == TRUE)
        l2c_fcr_collect_ack_delay (p_ccb, num_bufs_acked);
#endif

        for (xx = 0; xx < num_bufs_acked; xx++)
        {
            ls = ((BT_HDR *)(p_fcrb->waiting_for_ack_q.p_first))->layer_specific & L2CAP_FCR_SAR_BITS;

            if ( (ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU) )
                full_sdus_xmitted++;

            GKI_freebuf (GKI_dequeue (&p_fcrb->waiting_for_ack_q));
        }

        /* If we are still in a wait_ack state, do not mess with the timer */
        if (!p_ccb->fcrb.wait_ack)
            l2c_fcr_stop_timer (p_ccb);

        /* Check if we need to call the "packet_sent" callback */
        if ( (p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && (full_sdus_xmitted) )
        {
            /* Special case for eRTM, if all packets sent, send 0xFFFF */
            if ( (p_fcrb->waiting_for_ack_q.count == 0) && (p_ccb->xmit_hold_q.count == 0) )
                full_sdus_xmitted = 0xFFFF;

            (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, full_sdus_xmitted);
        }
    }

    /* If anything still waiting for ack, restart the timer if it was stopped */
    if (p_fcrb->waiting_for_ack_q.count)
        l2c_fcr_start_timer (p_ccb);

    return (TRUE);
}


/*******************************************************************************
**
** Function         process_s_frame
**
** Description      Process an S frame
**
** Returns          -
**
*******************************************************************************/
static void process_s_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word)
{
    tL2C_FCRB   *p_fcrb      = &p_ccb->fcrb;
    UINT16      s_frame_type = (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
    BOOLEAN     remote_was_busy;
    BOOLEAN     all_ok = TRUE;

    if (p_buf->len != 0)
    {
        L2CAP_TRACE_WARNING1 ("Incorrect S-frame Length (%d)", p_buf->len);
    }

    L2CAP_TRACE_DEBUG2 ("process_s_frame ctrl_word 0x%04x fcrb_remote_busy:%d", ctrl_word, p_fcrb->remote_busy);

#if (L2CAP_ERTM_STATS == TRUE)
    p_ccb->fcrb.s_frames_rcvd[s_frame_type]++;
#endif

    if (ctrl_word & L2CAP_FCR_P_BIT)
    {
        p_fcrb->rej_sent   = FALSE;             /* After checkpoint, we can send anoher REJ */
        p_fcrb->send_f_rsp = TRUE;              /* Set a flag in case an I-frame is pending */
    }

    switch (s_frame_type)
    {
    case L2CAP_FCR_SUP_RR:
        remote_was_busy     = p_fcrb->remote_busy;
        p_fcrb->remote_busy = FALSE;

        if ( (ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy) )
            all_ok = retransmit_i_frames (p_ccb, L2C_FCR_RETX_ALL_PKTS);
        break;

    case L2CAP_FCR_SUP_REJ:
        p_fcrb->remote_busy = FALSE;
        all_ok = retransmit_i_frames (p_ccb, L2C_FCR_RETX_ALL_PKTS);
        break;

    case L2CAP_FCR_SUP_RNR:
        p_fcrb->remote_busy = TRUE;
        l2c_fcr_stop_timer (p_ccb);
        break;

    case L2CAP_FCR_SUP_SREJ:
        p_fcrb->remote_busy = FALSE;
        all_ok = retransmit_i_frames (p_ccb, (UINT8)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT));
        break;
    }

    if (all_ok)
    {
        /* If polled, we need to respond with F-bit. Note, we may have sent a I-frame with the F-bit */
        if (p_fcrb->send_f_rsp)
        {
            if (p_fcrb->srej_sent)
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
            else if (p_fcrb->local_busy)
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
            else
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);

            p_fcrb->send_f_rsp = FALSE;
        }
    }
    else
    {
        L2CAP_TRACE_DEBUG0 ("process_s_frame hit_max_retries");
    }

    GKI_freebuf (p_buf);
}


/*******************************************************************************
**
** Function         process_i_frame
**
** Description      Process an I frame
**
** Returns          -
**
*******************************************************************************/
static void process_i_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word, BOOLEAN delay_ack)
{
    tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
    UINT8       tx_seq, num_lost, num_to_ack, next_srej;

    /* If we were doing checkpoint recovery, first retransmit all unacked I-frames */
    if (ctrl_word & L2CAP_FCR_F_BIT)
    {
        if (!retransmit_i_frames (p_ccb, L2C_FCR_RETX_ALL_PKTS))
        {
            GKI_freebuf(p_buf);
            return;
        }
    }

#if (L2CAP_ERTM_STATS == TRUE)
    p_ccb->fcrb.ertm_pkt_counts[1]++;
    p_ccb->fcrb.ertm_byte_counts[1] += p_buf->len;
#endif

    /* Extract the sequence number */
    tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;

    /* If we have flow controlled the peer, ignore any bad I-frames from him */
    if ( (tx_seq != p_fcrb->next_seq_expected) && (p_fcrb->local_busy) )
    {
        L2CAP_TRACE_WARNING1 ("Dropping bad I-Frame since we flowed off, tx_seq:%u", tx_seq);
        l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, 0);
        GKI_freebuf(p_buf);
        return;
    }

    /* If there are no free buffers in the user Rx queue, drop the  */
    /* received buffer now before we update any sequence numbers    */
    if (GKI_poolfreecount (p_ccb->ertm_info.user_rx_pool_id) == 0)
    {
        L2CAP_TRACE_WARNING4 ("L2CAP CID: 0x%04x  Dropping I-Frame seq: %u  User RX Pool: %u  (Size: %u)  has no free buffers!!",
                              p_ccb->local_cid, tx_seq, p_ccb->ertm_info.user_rx_pool_id,
                              GKI_poolcount (p_ccb->ertm_info.user_rx_pool_id));
        GKI_freebuf(p_buf);
        return;
    }

    /* Check if tx-sequence is the expected one */
    if (tx_seq != p_fcrb->next_seq_expected)
    {
        num_lost = (tx_seq - p_fcrb->next_seq_expected) & L2CAP_FCR_SEQ_MODULO;

        /* Is the frame a duplicate ? If so, just drop it */
        if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz)
        {
            /* Duplicate - simply drop it */
            L2CAP_TRACE_WARNING2 ("process_i_frame() Dropping Duplicate Frame tx_seq:%u  ExpectedTxSeq %u", tx_seq, p_fcrb->next_seq_expected);
            GKI_freebuf(p_buf);
        }
        else
        {
            L2CAP_TRACE_WARNING6 ("process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: %u  SRej: %u",
                                 p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent, p_fcrb->srej_sent);

            if (p_fcrb->srej_sent)
            {
                /* If SREJ sent, save the frame for later processing as long as it is in sequence */
                next_srej = (((BT_HDR *)p_fcrb->srej_rcv_hold_q.p_last)->layer_specific + 1) & L2CAP_FCR_SEQ_MODULO;

                if ( (tx_seq == next_srej) && (p_fcrb->srej_rcv_hold_q.count < p_ccb->our_cfg.fcr.tx_win_sz) )
                {
                    /* If user gave us a pool for held rx buffers, use that */
                    if (p_ccb->ertm_info.fcr_rx_pool_id != HCI_ACL_POOL_ID)
                    {
                        BT_HDR *p_buf2;

                        /* Adjust offset and len so that control word is copied */
                        p_buf->offset -= L2CAP_FCR_OVERHEAD;
                        p_buf->len    += L2CAP_FCR_OVERHEAD;

                        p_buf2 = l2c_fcr_clone_buf (p_buf, p_buf->offset, p_buf->len, p_ccb->ertm_info.fcr_rx_pool_id);

                        if (p_buf2)
                        {
                            GKI_freebuf (p_buf);
                            p_buf = p_buf2;
                        }
                        p_buf->offset += L2CAP_FCR_OVERHEAD;
                        p_buf->len -= L2CAP_FCR_OVERHEAD;
                    }
                    L2CAP_TRACE_DEBUG4 ("process_i_frame() Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: %u  SRej1",
                                         num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);

                    p_buf->layer_specific = tx_seq;
                    GKI_enqueue (&p_fcrb->srej_rcv_hold_q, p_buf);
                }
                else
                {
                    L2CAP_TRACE_WARNING4 ("process_i_frame() CID: 0x%04x  frame dropped in Srej Sent next_srej:%u  hold_q.count:%u  win_sz:%u",
                                         p_ccb->local_cid, next_srej, p_fcrb->srej_rcv_hold_q.count, p_ccb->our_cfg.fcr.tx_win_sz);

                    p_fcrb->rej_after_srej = TRUE;
                    GKI_freebuf (p_buf);
                }
            }
            else if (p_fcrb->rej_sent)
            {
                L2CAP_TRACE_WARNING5 ("process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: 1  SRej: %u",
                                     p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->srej_sent);

                /* If REJ sent, just drop the frame */
                GKI_freebuf (p_buf);
            }
            else
            {
                L2CAP_TRACE_DEBUG4 ("process_i_frame() CID: 0x%04x  tx_seq:%u  ExpTxSeq %u  Rej: %u",
                                     p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);

                /* If only one lost, we will send SREJ, otherwise we will send REJ */
                if (num_lost > 1)
                {
                    GKI_freebuf (p_buf);
                    p_fcrb->rej_sent = TRUE;
                    l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_REJ, 0);
                }
                else
                {
                    if (p_fcrb->srej_rcv_hold_q.count != 0)
                    {
                        L2CAP_TRACE_ERROR3 ("process_i_frame() CID: 0x%04x  sending SREJ tx_seq:%d hold_q.count:%u",
                                             p_ccb->local_cid, tx_seq, p_fcrb->srej_rcv_hold_q.count);
                    }
                    p_buf->layer_specific = tx_seq;
                    GKI_enqueue (&p_fcrb->srej_rcv_hold_q, p_buf);
                    p_fcrb->srej_sent = TRUE;
                    l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_SREJ, 0);
                }
                btu_stop_quick_timer (&p_ccb->fcrb.ack_timer);
            }
        }
        return;
    }

    /* Seq number is the next expected. Clear possible reject exception in case it occured */
    p_fcrb->rej_sent = p_fcrb->srej_sent = FALSE;

    /* Adjust the next_seq, so that if the upper layer sends more data in the callback
       context, the received frame is acked by an I-frame. */
    p_fcrb->next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;

    /* If any SAR problem in eRTM mode, spec says disconnect. */
    if (!do_sar_reassembly (p_ccb, p_buf, ctrl_word))
    {
        L2CAP_TRACE_WARNING1 ("process_i_frame() CID: 0x%04x  reassembly failed", p_ccb->local_cid);
        l2cu_disconnect_chnl (p_ccb);
        return;
    }

    /* RR optimization - if peer can still send us more, then start an ACK timer */
    num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) & L2CAP_FCR_SEQ_MODULO;

    if ( (num_to_ack < p_ccb->fcrb.max_held_acks) && (!p_fcrb->local_busy) )
        delay_ack = TRUE;

    /* We should neve never ack frame if we are not in OPEN state */
    if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN))
    {
        /* If no frames are awaiting transmission or are held, send an RR or RNR S-frame for ack */
        if (delay_ack)
        {
            /* If it is the first I frame we did not ack, start ack timer */
            if (!p_ccb->fcrb.ack_timer.in_use)
            {
                btu_start_quick_timer (&p_ccb->fcrb.ack_timer, BTU_TTYPE_L2CAP_FCR_ACK,
                                        (L2CAP_FCR_ACK_TOUT*QUICK_TIMER_TICKS_PER_SEC)/1000);
            }
        }
        else if ( ((p_ccb->xmit_hold_q.count == 0) || (l2c_fcr_is_flow_controlled (p_ccb)))
               &&  (p_ccb->fcrb.srej_rcv_hold_q.count == 0) )
        {
            if (p_fcrb->local_busy)
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RNR, 0);
            else
                l2c_fcr_send_S_frame (p_ccb, L2CAP_FCR_SUP_RR, 0);
        }
    }
}


/*******************************************************************************
**
** Function         process_stream_frame
**
** Description      This function processes frames in streaming mode
**
** Returns          -
**
*******************************************************************************/
static void process_stream_frame (tL2C_CCB *p_ccb, BT_HDR *p_buf)
{
    UINT16      ctrl_word;
    UINT16      fcs;
    UINT8       *p;
    UINT8       tx_seq;

    /* Verify FCS if using */
    if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
    {
        p = ((UINT8 *)(p_buf+1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;

        /* Extract and drop the FCS from the packet */
        STREAM_TO_UINT16 (fcs, p);
        p_buf->len -= L2CAP_FCS_LEN;

        if (l2c_fcr_rx_get_fcs(p_buf) != fcs)
        {
            L2CAP_TRACE_WARNING1 ("Rx L2CAP PDU: CID: 0x%04x  BAD FCS", p_ccb->local_cid);
            GKI_freebuf(p_buf);
            return;
        }
    }

    /* Get the control word */
    p = ((UINT8 *)(p_buf+1)) + p_buf->offset;

    STREAM_TO_UINT16 (ctrl_word, p);

    p_buf->len    -= L2CAP_FCR_OVERHEAD;
    p_buf->offset += L2CAP_FCR_OVERHEAD;

    /* Make sure it is an I-frame */
    if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
    {
        L2CAP_TRACE_WARNING2 ("Rx L2CAP PDU: CID: 0x%04x  BAD S-frame in streaming mode  ctrl_word: 0x%04x", p_ccb->local_cid, ctrl_word);
        GKI_freebuf (p_buf);
        return;
    }

#if BT_TRACE_VERBOSE == TRUE
    L2CAP_TRACE_EVENT6 ("L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  ReqSeq: %u  F: %u",
                        p_ccb->local_cid, p_buf->len,
                        SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
                        (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
                        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
                        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
#endif

    /* Extract the sequence number */
    tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;

    /* Check if tx-sequence is the expected one */
    if (tx_seq != p_ccb->fcrb.next_seq_expected)
    {
        L2CAP_TRACE_WARNING4 ("Rx L2CAP PDU: CID: 0x%04x  Lost frames Exp: %u  Got: %u  p_rx_sdu: 0x%08x",
                                p_ccb->local_cid, p_ccb->fcrb.next_seq_expected, tx_seq, p_ccb->fcrb.p_rx_sdu);

        /* Lost one or more packets, so flush the SAR queue */
        if (p_ccb->fcrb.p_rx_sdu != NULL)
        {
            GKI_freebuf (p_ccb->fcrb.p_rx_sdu);
            p_ccb->fcrb.p_rx_sdu = NULL;
        }
    }

    p_ccb->fcrb.next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;

    if (!do_sar_reassembly (p_ccb, p_buf, ctrl_word))
    {
        /* Some sort of SAR error, so flush the SAR queue */
        if (p_ccb->fcrb.p_rx_sdu != NULL)
        {
            GKI_freebuf (p_ccb->fcrb.p_rx_sdu);
            p_ccb->fcrb.p_rx_sdu = NULL;
        }
    }
}


/*******************************************************************************
**
** Function         do_sar_reassembly
**
** Description      Process SAR bits and re-assemble frame
**
** Returns          TRUE if all OK, else FALSE
**
*******************************************************************************/
static BOOLEAN do_sar_reassembly (tL2C_CCB *p_ccb, BT_HDR *p_buf, UINT16 ctrl_word)
{
    tL2C_FCRB   *p_fcrb = &p_ccb->fcrb;
    UINT16      sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
    BOOLEAN     packet_ok = TRUE;
    UINT8       *p;

    /* Check if the SAR state is correct */
    if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU))
    {
        if (p_fcrb->p_rx_sdu != NULL)
        {
            L2CAP_TRACE_WARNING2 ("SAR - got unexpected unsegmented or start SDU  Expected len: %u  Got so far: %u",
                                  p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);

            packet_ok = FALSE;
        }
        /* Check the length of the packet */
        if ( (sar_type == L2CAP_FCR_START_SDU) && (p_buf->len < L2CAP_SDU_LEN_OVERHEAD) )
        {
            L2CAP_TRACE_WARNING1 ("SAR start packet too short: %u", p_buf->len);
            packet_ok = FALSE;
        }
    }
    else
    {
        if (p_fcrb->p_rx_sdu == NULL)
        {
            L2CAP_TRACE_WARNING0 ("SAR - got unexpected cont or end SDU");
            packet_ok = FALSE;
        }
    }

    if ( (packet_ok) && (sar_type != L2CAP_FCR_UNSEG_SDU) )
    {
        p = ((UINT8 *)(p_buf + 1)) + p_buf->offset;

        /* For start SDU packet, extract the SDU length */
        if (sar_type == L2CAP_FCR_START_SDU)
        {
            /* Get the SDU length */
            STREAM_TO_UINT16 (p_fcrb->rx_sdu_len, p);
            p_buf->offset += 2;
            p_buf->len    -= 2;

            if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu)
            {
                L2CAP_TRACE_WARNING2 ("SAR - SDU len: %u  larger than MTU: %u", p_fcrb->rx_sdu_len, p_fcrb->rx_sdu_len);
                packet_ok = FALSE;
            }
            else if ((p_fcrb->p_rx_sdu = (BT_HDR *)GKI_getpoolbuf (p_ccb->ertm_info.user_rx_pool_id)) == NULL)
            {
                L2CAP_TRACE_ERROR1 ("SAR - no buffer for SDU start user_rx_pool_id:%d", p_ccb->ertm_info.user_rx_pool_id);
                packet_ok = FALSE;
            }
            else
            {
                p_fcrb->p_rx_sdu->offset = 4; /* this is the minimal offset required by OBX to process incoming packets */
                p_fcrb->p_rx_sdu->len    = 0;
            }
        }

        if (packet_ok)
        {
            if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len)
            {
                L2CAP_TRACE_ERROR4 ("SAR - SDU len exceeded  Type: %u   Lengths: %u %u %u",
                                    sar_type, p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
                packet_ok = FALSE;
            }
            else if ( (sar_type == L2CAP_FCR_END_SDU) && ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len) )
            {
                L2CAP_TRACE_WARNING3 ("SAR - SDU end rcvd but SDU incomplete: %u %u %u",
                                      p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
                packet_ok = FALSE;
            }
            else
            {
                memcpy (((UINT8 *) (p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset + p_fcrb->p_rx_sdu->len, p, p_buf->len);

                p_fcrb->p_rx_sdu->len += p_buf->len;

                GKI_freebuf (p_buf);
                p_buf = NULL;

                if (sar_type == L2CAP_FCR_END_SDU)
                {
                    p_buf            = p_fcrb->p_rx_sdu;
                    p_fcrb->p_rx_sdu = NULL;
                }
            }
        }
    }

    if (packet_ok == FALSE)
    {
        GKI_freebuf (p_buf);
    }
    else if (p_buf != NULL)
    {
#if (L2CAP_NUM_FIXED_CHNLS > 0)
        if (p_ccb->local_cid < L2CAP_BASE_APPL_CID)
            (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb)(p_ccb->p_lcb->remote_bd_addr, p_buf);
        else
#endif
            l2c_csm_execute (p_ccb, L2CEVT_L2CAP_DATA, p_buf);
    }

    return (packet_ok);
}


/*******************************************************************************
**
** Function         retransmit_i_frames
**
** Description      This function retransmits i-frames awaiting acks.
**
** Returns          BOOLEAN - TRUE if retransmitted
**
*******************************************************************************/
static BOOLEAN retransmit_i_frames (tL2C_CCB *p_ccb, UINT8 tx_seq)
{
    BT_HDR      *p_buf, *p_buf2;
    UINT8       *p;
    UINT8       buf_seq;
    UINT16      ctrl_word;

    if ( (p_ccb->fcrb.waiting_for_ack_q.p_first)
     &&  (p_ccb->peer_cfg.fcr.max_transmit != 0)
     &&  (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit) )
    {
        L2CAP_TRACE_EVENT5 ("Max Tries Exceeded:  (last_acq: %d  CID: 0x%04x  num_tries: %u (max: %u) ack_q_count: %u",
                p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
                p_ccb->fcrb.waiting_for_ack_q.count);

        l2cu_disconnect_chnl (p_ccb);
        return (FALSE);
    }

    /* tx_seq indicates whether to retransmit a specific sequence or all (if == L2C_FCR_RETX_ALL_PKTS) */
    if (tx_seq != L2C_FCR_RETX_ALL_PKTS)
    {
        /* If sending only one, the sequence number tells us which one. Look for it.
        */
        for (p_buf = (BT_HDR *)p_ccb->fcrb.waiting_for_ack_q.p_first; p_buf; p_buf = (BT_HDR *)GKI_getnext (p_buf))
        {
            /* Get the old control word */
            p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;

            STREAM_TO_UINT16 (ctrl_word, p);

            buf_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;

            L2CAP_TRACE_DEBUG2 ("retransmit_i_frames()   cur seq: %u  looking for: %u", buf_seq, tx_seq);

            if (tx_seq == buf_seq)
                break;
        }

        if (!p_buf)
        {
            L2CAP_TRACE_ERROR2 ("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u", tx_seq, p_ccb->fcrb.waiting_for_ack_q.count);
            return (TRUE);
        }
    }
    else
    {
        /* Retransmitting everything. Flush buffers we already put in the link xmit queue.
        */
        p_buf = (BT_HDR *)p_ccb->p_lcb->link_xmit_data_q.p_first;

        while (p_buf != NULL)
        {
            /* Do not flush other CIDs or partial segments */
            if ( (p_buf->layer_specific == 0) && (p_buf->event == p_ccb->local_cid) )
            {
                p_buf2 = p_buf;
                p_buf = (BT_HDR *)GKI_getnext (p_buf);

                GKI_remove_from_queue (&p_ccb->p_lcb->link_xmit_data_q, p_buf2);
                GKI_freebuf (p_buf2);
            }
            else
                p_buf = (BT_HDR *)GKI_getnext (p_buf);
        }

        /* Also flush our retransmission queue */
        while (p_ccb->fcrb.retrans_q.p_first)
            GKI_freebuf (GKI_dequeue (&p_ccb->fcrb.retrans_q));

        p_buf = (BT_HDR *)p_ccb->fcrb.waiting_for_ack_q.p_first;
    }

    while (p_buf != NULL)
    {
        p_buf2 = l2c_fcr_clone_buf (p_buf, p_buf->offset, p_buf->len, p_ccb->ertm_info.fcr_tx_pool_id);

        if (p_buf2)
        {
            p_buf2->layer_specific = p_buf->layer_specific;

            GKI_enqueue (&p_ccb->fcrb.retrans_q, p_buf2);
        }

        if ( (tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL) )
            break;
        else
            p_buf = (BT_HDR *)GKI_getnext (p_buf);
    }

    l2c_link_check_send_pkts (p_ccb->p_lcb, NULL, NULL);

    if (p_ccb->fcrb.waiting_for_ack_q.count)
    {
        p_ccb->fcrb.num_tries++;
        l2c_fcr_start_timer (p_ccb);
    }

    return (TRUE);
}


/*******************************************************************************
**
** Function         l2c_fcr_get_next_xmit_sdu_seg
**
** Description      Get the next SDU segment to transmit.
**
** Returns          pointer to buffer with segment or NULL
**
*******************************************************************************/
BT_HDR *l2c_fcr_get_next_xmit_sdu_seg (tL2C_CCB *p_ccb, UINT16 max_packet_length)
{
    BOOLEAN     first_seg    = FALSE,       /* The segment is the first part of data  */
                mid_seg      = FALSE,       /* The segment is the middle part of data */
                last_seg     = FALSE;       /* The segment is the last part of data   */
    UINT16      sdu_len;
    BT_HDR      *p_buf, *p_xmit;
    UINT8       *p;
    UINT16      max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/;

    /* If there is anything in the retransmit queue, that goes first
    */
    if (p_ccb->fcrb.retrans_q.p_first)
    {
        p_buf = (BT_HDR *)GKI_dequeue (&p_ccb->fcrb.retrans_q);

        /* Update Rx Seq and FCS if we acked some packets while this one was queued */
        prepare_I_frame (p_ccb, p_buf, TRUE);

        p_buf->event = p_ccb->local_cid;

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
        /* Use sdu_len to hold the control word */
        p = ((UINT8 *) (p_buf+1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
        STREAM_TO_UINT16 (sdu_len, p);

        /* Get out if packet was dropped; just pretend it went out */
        if (l2c_corrupt_the_fcr_packet (p_ccb, p_buf, FALSE, sdu_len))
            return (NULL);
#endif  /* L2CAP_CORRUPT_ERTM_PKTS */

#if (L2CAP_ERTM_STATS == TRUE)
        p_ccb->fcrb.pkts_retransmitted++;
        p_ccb->fcrb.ertm_pkt_counts[0]++;
        p_ccb->fcrb.ertm_byte_counts[0] += (p_buf->len - 8);
#endif
        return (p_buf);
    }

    /* For BD/EDR controller, max_packet_length is set to 0             */
    /* For AMP controller, max_packet_length is set by available blocks */
    if ( (max_packet_length > L2CAP_MAX_HEADER_FCS)
      && (max_pdu + L2CAP_MAX_HEADER_FCS > max_packet_length) )
    {
        max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
    }

    p_buf = (BT_HDR *)p_ccb->xmit_hold_q.p_first;

    /* If there is more data than the MPS, it requires segmentation */
    if (p_buf->len > max_pdu)
    {
        /* We are using the "event" field to tell is if we already started segmentation */
        if (p_buf->event == 0)
        {
            first_seg = TRUE;
            sdu_len   = p_buf->len;
        }
        else
            mid_seg = TRUE;

        /* Get a new buffer and copy the data that can be sent in a PDU */
        p_xmit = l2c_fcr_clone_buf (p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET,
                                    max_pdu, p_ccb->ertm_info.fcr_tx_pool_id);

        if (p_xmit != NULL)
        {
            p_buf->event  = p_ccb->local_cid;
            p_xmit->event = p_ccb->local_cid;

            p_buf->len    -= max_pdu;
            p_buf->offset += max_pdu;

            /* copy PBF setting */
            p_xmit->layer_specific = p_buf->layer_specific;
        }
        else /* Should never happen if the application has configured buffers correctly */
        {
            L2CAP_TRACE_ERROR1 ("L2CAP - cannot get buffer, for segmentation, pool: %u", p_ccb->ertm_info.fcr_tx_pool_id);
            return (NULL);
        }
    }
    else    /* Use the original buffer if no segmentation, or the last segment */
    {
        p_xmit = (BT_HDR *)GKI_dequeue (&p_ccb->xmit_hold_q);

        if (p_xmit->event != 0)
            last_seg = TRUE;

        p_xmit->event = p_ccb->local_cid;
    }

    /* Step back to add the L2CAP headers */
    p_xmit->offset -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD);
    p_xmit->len    += L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;

    if (first_seg)
    {
        p_xmit->offset -= L2CAP_SDU_LEN_OVERHEAD;
        p_xmit->len    += L2CAP_SDU_LEN_OVERHEAD;
    }

    /* Set the pointer to the beginning of the data */
    p = (UINT8 *)(p_xmit + 1) + p_xmit->offset;

    /* Now the L2CAP header */

    /* Note: if FCS has to be included then the length is recalculated later */
    UINT16_TO_STREAM (p, p_xmit->len - L2CAP_PKT_OVERHEAD);

    UINT16_TO_STREAM (p, p_ccb->remote_cid);

    if (first_seg)
    {
        /* Skip control word and add SDU length */
        p += 2;
        UINT16_TO_STREAM (p, sdu_len);

        /* We will store the SAR type in layer-specific */
        /* layer_specific is shared with flushable flag(bits 0-1), don't clear it */
        p_xmit->layer_specific |= L2CAP_FCR_START_SDU;

        first_seg = FALSE;
    }
    else if (mid_seg)
        p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU;
    else if (last_seg)
        p_xmit->layer_specific |= L2CAP_FCR_END_SDU;
    else
        p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU;

    prepare_I_frame (p_ccb, p_xmit, FALSE);

    if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
    {
        BT_HDR *p_wack = l2c_fcr_clone_buf (p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len, p_ccb->ertm_info.fcr_tx_pool_id);

        if (!p_wack)
        {
            L2CAP_TRACE_ERROR3 ("L2CAP - no buffer for xmit cloning, CID: 0x%04x  Pool: %u  Count: %u",
                                p_ccb->local_cid, p_ccb->ertm_info.fcr_tx_pool_id,  GKI_poolfreecount(p_ccb->ertm_info.fcr_tx_pool_id));

            /* We will not save the FCS in case we reconfigure and change options */
            if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
                p_xmit->len -= L2CAP_FCS_LEN;

            /* Pretend we sent it and it got lost */
            GKI_enqueue (&p_ccb->fcrb.waiting_for_ack_q, p_xmit);
            return (NULL);
        }
        else
        {
#if (L2CAP_ERTM_STATS == TRUE)
            /* set timestamp at the end of tx I-frame to get acking delay */
            p = ((UINT8 *) (p_wack+1)) + p_wack->offset + p_wack->len;
            UINT32_TO_STREAM (p, GKI_get_os_tick_count());
#endif
            /* We will not save the FCS in case we reconfigure and change options */
            if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
                p_wack->len -= L2CAP_FCS_LEN;

            p_wack->layer_specific = p_xmit->layer_specific;
            GKI_enqueue (&p_ccb->fcrb.waiting_for_ack_q, p_wack);
        }

#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
        {
            UINT16 ctrl_word;
            p = ((UINT8 *) (p_xmit+1)) + p_xmit->offset + L2CAP_PKT_OVERHEAD;
            STREAM_TO_UINT16 (ctrl_word, p);

            /* Get out if packet was dropped; pretend it was sent */
            if (l2c_corrupt_the_fcr_packet (p_ccb, p_xmit, FALSE, ctrl_word))
                return (NULL);
        }
#endif
#if (L2CAP_ERTM_STATS == TRUE)
        p_ccb->fcrb.ertm_pkt_counts[0]++;
        p_ccb->fcrb.ertm_byte_counts[0] += (p_xmit->len - 8);
#endif

    }

    return (p_xmit);
}


/*******************************************************************************
** Configuration negotiation functions
**
** The following functions are used in negotiating channel modes during
** configuration
********************************************************************************/

/*******************************************************************************
**
** Function         l2c_fcr_chk_chan_modes
**
** Description      Validates and adjusts if necessary, the FCR options
**                  based on remote EXT features.
**
**                  Note: This assumes peer EXT Features have been received.
**                      Basic mode is used if FCR Options have not been received
**
** Returns          UINT8 - nonzero if can continue, '0' if no compatible channels
**
*******************************************************************************/
UINT8 l2c_fcr_chk_chan_modes (tL2C_CCB *p_ccb)
{
    /* Remove nonbasic options that the peer does not support */
    if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS))
        p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_ERTM;

    if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_STREAM_MODE))
        p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_STREAM;

    /* At least one type needs to be set (Basic, ERTM, STM) to continue */
    if (!p_ccb->ertm_info.allowed_modes)
    {
        L2CAP_TRACE_WARNING0 ("L2CAP - Peer does not support our desired channel types");
    }

    return (p_ccb->ertm_info.allowed_modes);
}

/*******************************************************************************
**
** Function         l2c_fcr_adj_our_req_options
**
** Description      Validates and sets up the FCR options passed in from
**                  L2CA_ConfigReq based on remote device's features.
**
** Returns          TRUE if no errors, Otherwise FALSE
**
*******************************************************************************/
BOOLEAN l2c_fcr_adj_our_req_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
{
    tL2CAP_FCR_OPTS *p_fcr = &p_cfg->fcr;

    if (p_fcr->mode != p_ccb->ertm_info.preferred_mode)
    {
        L2CAP_TRACE_WARNING2 ("l2c_fcr_adj_our_req_options - preferred_mode (%d), does not match mode (%d)",
                            p_ccb->ertm_info.preferred_mode, p_fcr->mode);

        /* The preferred mode is passed in through tL2CAP_ERTM_INFO, so override this one */
        p_fcr->mode = p_ccb->ertm_info.preferred_mode;
    }

    /* If upper layer did not request eRTM mode, BASIC must be used */
    if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC)
    {
        if (p_cfg->fcr_present && p_fcr->mode != L2CAP_FCR_BASIC_MODE)
        {
            L2CAP_TRACE_WARNING1 ("l2c_fcr_adj_our_req_options (mode %d): ERROR: No FCR options set using BASIC mode", p_fcr->mode);
        }
        p_fcr->mode = L2CAP_FCR_BASIC_MODE;
    }

    /* Process the FCR options if initial channel bring-up (not a reconfig request)
    ** Determine initial channel mode to try based on our options and remote's features
    */
    if (p_cfg->fcr_present && !(p_ccb->config_done & RECONFIG_FLAG))
    {
        /* We need to have at least one mode type common with the peer */
        if (!l2c_fcr_chk_chan_modes(p_ccb))
        {
            /* Two channels have incompatible supported types */
            l2cu_disconnect_chnl (p_ccb);
            return (FALSE);
        }

        /* Basic is the only common channel mode between the two devices */
        else if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC)
        {
            /* We only want to try Basic, so bypass sending the FCR options entirely */
            p_cfg->fcr_present = FALSE;
            p_cfg->fcs_present = FALSE;             /* Illegal to use FCS option in basic mode */
            p_cfg->ext_flow_spec_present = FALSE;   /* Illegal to use extended flow spec in basic mode */
        }

        /* We have at least one non-basic mode available
         * Override mode from available mode options based on preference, if needed
         */
        else
        {
            /* If peer does not support STREAMING, try ERTM */
            if (p_fcr->mode == L2CAP_FCR_STREAM_MODE && !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_STREAM))
            {
                L2CAP_TRACE_DEBUG0 ("L2C CFG: mode is STREAM, but peer does not support; Try ERTM");
                p_fcr->mode = L2CAP_FCR_ERTM_MODE;
            }

            /* If peer does not support ERTM, try BASIC (will support this if made it here in the code) */
            if (p_fcr->mode == L2CAP_FCR_ERTM_MODE && !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM))
            {
                L2CAP_TRACE_DEBUG0 ("L2C CFG: mode is ERTM, but peer does not support; Try BASIC");
                p_fcr->mode = L2CAP_FCR_BASIC_MODE;
            }
        }

        if (p_fcr->mode != L2CAP_FCR_BASIC_MODE)
        {
            /* MTU must be smaller than buffer size */
            if ( (p_cfg->mtu_present) && (p_cfg->mtu > p_ccb->max_rx_mtu) )
            {
                L2CAP_TRACE_WARNING2 ("L2CAP - MTU: %u  larger than buf size: %u", p_cfg->mtu, p_ccb->max_rx_mtu);
                return (FALSE);
            }

            /* application want to use the default MPS */
            if (p_fcr->mps == L2CAP_DEFAULT_ERM_MPS)
            {
                p_fcr->mps = L2CAP_MPS_OVER_BR_EDR;
            }
            /* MPS must be less than MTU */
            else if (p_fcr->mps > p_ccb->max_rx_mtu)
            {
                L2CAP_TRACE_WARNING2 ("L2CAP - MPS  %u  invalid  MTU: %u", p_fcr->mps, p_ccb->max_rx_mtu);
                return (FALSE);
            }

            /* We always initially read into the HCI buffer pool, so make sure it fits */
            if (p_fcr->mps > (L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS))
                p_fcr->mps = L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS;
        }
        else
        {
            p_cfg->fcs_present = FALSE;             /* Illegal to use FCS option in basic mode */
            p_cfg->ext_flow_spec_present = FALSE;   /* Illegal to use extended flow spec in basic mode */
        }

        p_ccb->our_cfg.fcr = *p_fcr;
    }
    else    /* Not sure how to send a reconfiguration(??) should fcr be included? */
    {
        p_ccb->our_cfg.fcr_present = FALSE;
    }

    return (TRUE);
}


/*******************************************************************************
**
** Function         l2c_fcr_adj_monitor_retran_timeout
**
** Description      Overrides monitor/retrans timer value based on controller
**
** Returns          None
**
*******************************************************************************/
void l2c_fcr_adj_monitor_retran_timeout (tL2C_CCB *p_ccb)
{
    /* adjust our monitor/retran timeout */
    if (p_ccb->out_cfg_fcr_present)
    {
        /*
        ** if we requestd ERTM or accepted ERTM
        ** We may accept ERTM even if we didn't request ERTM, in case of requesting STREAM
        */
        if ((p_ccb->our_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
          ||(p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE))
        {
            /* upper layer setting is ignored */
            p_ccb->our_cfg.fcr.mon_tout    = L2CAP_MIN_MONITOR_TOUT;
            p_ccb->our_cfg.fcr.rtrans_tout = L2CAP_MIN_RETRANS_TOUT;
        }
        else
        {
            p_ccb->our_cfg.fcr.mon_tout    = 0;
            p_ccb->our_cfg.fcr.rtrans_tout = 0;
        }

        L2CAP_TRACE_DEBUG2 ("l2c_fcr_adj_monitor_retran_timeout: mon_tout:%d, rtrans_tout:%d",
                             p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout);
    }
}
/*******************************************************************************
**
** Function         l2c_fcr_adj_our_rsp_options
**
** Description      Overrides any neccesary FCR options passed in from
**                  L2CA_ConfigRsp based on our FCR options.
**                  Only makes adjustments if channel is in ERTM mode.
**
** Returns          None
**
*******************************************************************************/
void l2c_fcr_adj_our_rsp_options (tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
{
    /* adjust our monitor/retran timeout */
    l2c_fcr_adj_monitor_retran_timeout(p_ccb);

    p_cfg->fcr_present = p_ccb->out_cfg_fcr_present;

    if (p_cfg->fcr_present)
    {
// btla-specific ++
        /* Temporary - until a better algorithm is implemented */
        /* If peer's tx_wnd_sz requires too many buffers for us to support, then adjust it. For now, respond with our own tx_wnd_sz. */
        /* Note: peer is not guaranteed to obey our adjustment */
        if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz)
        {
            L2CAP_TRACE_DEBUG3 ("%s: adjusting requested tx_win_sz from %i to %i", __FUNCTION__, p_ccb->peer_cfg.fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz);
            p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
        }
// btla-specific --

        p_cfg->fcr.mode         = p_ccb->peer_cfg.fcr.mode;
        p_cfg->fcr.tx_win_sz    = p_ccb->peer_cfg.fcr.tx_win_sz;
        p_cfg->fcr.max_transmit = p_ccb->peer_cfg.fcr.max_transmit;
        p_cfg->fcr.mps          = p_ccb->peer_cfg.fcr.mps;
        p_cfg->fcr.rtrans_tout  = p_ccb->our_cfg.fcr.rtrans_tout;
        p_cfg->fcr.mon_tout     = p_ccb->our_cfg.fcr.mon_tout;
    }
}

/*******************************************************************************
**
** Function         l2c_fcr_renegotiate_chan
**
** Description      Called upon unsuccessful peer response to config request.
**                  If the error is because of the channel mode, it will try
**                  to resend using another supported optional channel.
**
** Returns          TRUE if resent configuration, False if channel matches or
**                  cannot match.
**
*******************************************************************************/
BOOLEAN l2c_fcr_renegotiate_chan(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
{
    UINT8   peer_mode = p_ccb->our_cfg.fcr.mode;
    BOOLEAN can_renegotiate;

    /* Skip if this is a reconfiguration from OPEN STATE or if FCR is not returned */
    if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG))
        return (FALSE);

    /* Only retry if there are more channel options to try */
    if (p_cfg->result == L2CAP_CFG_UNACCEPTABLE_PARAMS)
    {
        peer_mode = (p_cfg->fcr_present) ? p_cfg->fcr.mode : L2CAP_FCR_BASIC_MODE;

        if (p_ccb->our_cfg.fcr.mode != peer_mode)
        {

            if ((--p_ccb->fcr_cfg_tries) == 0)
            {
                p_cfg->result = L2CAP_CFG_FAILED_NO_REASON;
                L2CAP_TRACE_WARNING0 ("l2c_fcr_renegotiate_chan (Max retries exceeded)");
            }

            can_renegotiate = FALSE;

            /* Try another supported mode if available based on our last attempted channel */
            switch (p_ccb->our_cfg.fcr.mode)
            {
                /* Our Streaming mode request was unnacceptable; try ERTM or Basic */
            case L2CAP_FCR_STREAM_MODE:
                /* Peer wants ERTM and we support it */
                if ( (peer_mode == L2CAP_FCR_ERTM_MODE) && (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM) )
                {
                    L2CAP_TRACE_DEBUG0 ("l2c_fcr_renegotiate_chan(Trying ERTM)");
                    p_ccb->our_cfg.fcr.mode = L2CAP_FCR_ERTM_MODE;
                    can_renegotiate = TRUE;
                }
                else    /* Falls through */

            case L2CAP_FCR_ERTM_MODE:
                {
                    /* We can try basic for any other peer mode if we support it */
                    if (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC)
                    {
                        L2CAP_TRACE_DEBUG0 ("l2c_fcr_renegotiate_chan(Trying Basic)");
                        can_renegotiate = TRUE;
                        p_ccb->our_cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
                    }
                }
                break;

            default:
                /* All other scenarios cannot be renegotiated */
                break;
            }

            if (can_renegotiate)
            {
                p_ccb->our_cfg.fcr_present = TRUE;

                if (p_ccb->our_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE)
                {
                    p_ccb->our_cfg.fcs_present = FALSE;
                    p_ccb->our_cfg.ext_flow_spec_present = FALSE;

                    /* Basic Mode uses ACL Data Pool, make sure the MTU fits */
                    if ( (p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE) )
                    {
                        L2CAP_TRACE_WARNING1 ("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
                        p_cfg->mtu = L2CAP_MTU_SIZE;
                    }
                }

                l2cu_process_our_cfg_req (p_ccb, &p_ccb->our_cfg);
                l2cu_send_peer_config_req (p_ccb, &p_ccb->our_cfg);
                btu_start_timer (&p_ccb->timer_entry, BTU_TTYPE_L2CAP_CHNL, L2CAP_CHNL_CFG_TIMEOUT);
                return (TRUE);
            }
        }
    }

    /* Disconnect if the channels do not match */
    if (p_ccb->our_cfg.fcr.mode != peer_mode)
    {
        L2CAP_TRACE_WARNING2 ("L2C CFG:  Channels incompatible (local %d, peer %d)",
                              p_ccb->our_cfg.fcr.mode, peer_mode);
        l2cu_disconnect_chnl (p_ccb);
    }

    return (FALSE);
}


/*******************************************************************************
**
** Function         l2c_fcr_process_peer_cfg_req
**
** Description      This function is called to process the FCR options passed
**                  in the peer's configuration request.
**
** Returns          UINT8 - L2CAP_PEER_CFG_OK, L2CAP_PEER_CFG_UNACCEPTABLE,
**                          or L2CAP_PEER_CFG_DISCONNECT.
**
*******************************************************************************/
UINT8 l2c_fcr_process_peer_cfg_req(tL2C_CCB *p_ccb, tL2CAP_CFG_INFO *p_cfg)
{
    UINT16 max_retrans_size;
    UINT8  fcr_ok = L2CAP_PEER_CFG_OK;

    p_ccb->p_lcb->w4_info_rsp = FALSE;      /* Handles T61x SonyEricsson Bug in Info Request */

    L2CAP_TRACE_EVENT5 ("l2c_fcr_process_peer_cfg_req() CFG fcr_present:%d fcr.mode:%d CCB FCR mode:%d preferred: %u allowed:%u",
                        p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode, p_ccb->ertm_info.preferred_mode,
                        p_ccb->ertm_info.allowed_modes);

    /* If Peer wants basic, we are done (accept it or disconnect) */
    if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE)
    {
        /* If we do not allow basic, disconnect */
        if ( !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC) )
            fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
    }

    /* Need to negotiate if our modes are not the same */
    else if (p_cfg->fcr.mode != p_ccb->ertm_info.preferred_mode)
    {
        /* If peer wants a mode that we don't support then retry our mode (ex. rtx/flc), OR
        ** If we want ERTM and they wanted streaming retry our mode.
        ** Note: If we have already determined they support our mode previously
        **       from their EXF mask.
        */
        if ( (((1 << p_cfg->fcr.mode) & L2CAP_FCR_CHAN_OPT_ALL_MASK) == 0)
            || (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE) )
        {
            p_cfg->fcr.mode = p_ccb->our_cfg.fcr.mode;
            p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
            p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit;
            fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
        }

        /* If we wanted basic, then try to renegotiate it */
        else if (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE)
        {
            p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE;
            p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0;
            p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0;
            p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout = p_ccb->our_cfg.fcr.mps = 0;
            fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
        }

        /* Only other valid case is if they want ERTM and we wanted STM which should be
           accepted if we support it; otherwise the channel should be disconnected */
        else if ( (p_cfg->fcr.mode != L2CAP_FCR_ERTM_MODE)
              || !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM) )
        {
            fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
        }
    }

    /* Configuration for FCR channels so make any adjustments and fwd to upper layer */
    if (fcr_ok == L2CAP_PEER_CFG_OK)
    {
        /* by default don't need to send params in the response */
        p_ccb->out_cfg_fcr_present = FALSE;

        /* Make any needed adjustments for the response to the peer */
        if (p_cfg->fcr_present && p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE)
        {
            /* Peer desires to bypass FCS check, and streaming or ERTM mode */
            if (p_cfg->fcs_present)
            {
                p_ccb->peer_cfg.fcs = p_cfg->fcs;
                p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCS;
                if( p_cfg->fcs == L2CAP_CFG_FCS_BYPASS)
                    p_ccb->bypass_fcs |= L2CAP_CFG_FCS_PEER;
            }

            max_retrans_size = GKI_get_pool_bufsize (p_ccb->ertm_info.fcr_tx_pool_id) - sizeof(BT_HDR)
                                            - L2CAP_MIN_OFFSET - L2CAP_SDU_LEN_OFFSET - L2CAP_FCS_LEN;

            /* Ensure the MPS is not bigger than the MTU */
            if ( (p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu) )
            {
                p_cfg->fcr.mps = p_ccb->peer_cfg.mtu;
                p_ccb->out_cfg_fcr_present = TRUE;
            }

            /* Ensure the MPS is not bigger than our retransmission buffer */
            if (p_cfg->fcr.mps > max_retrans_size)
            {
                L2CAP_TRACE_DEBUG2("CFG: Overriding MPS to %d (orig %d)", max_retrans_size, p_cfg->fcr.mps);

                p_cfg->fcr.mps = max_retrans_size;
                p_ccb->out_cfg_fcr_present = TRUE;
            }

            if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE)
            {
                /* Always respond with FCR ERTM parameters */
                p_ccb->out_cfg_fcr_present = TRUE;
            }
        }

        /* Everything ok, so save the peer's adjusted fcr options */
        p_ccb->peer_cfg.fcr = p_cfg->fcr;

        if (p_cfg->fcr_present)
            p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCR;
    }
    else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE)
    {
        /* Allow peer only one retry for mode */
        if (p_ccb->peer_cfg_already_rejected)
            fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
        else
            p_ccb->peer_cfg_already_rejected = TRUE;
    }

    return (fcr_ok);
}


#if L2CAP_CORRUPT_ERTM_PKTS == TRUE
/*******************************************************************************
**  Functions used for testing ERTM mode
*/
/* If FALSE, will also corrupt cid, length, control word, etc. */
#ifndef L2CAP_CORR_FCS_ONLY
#define L2CAP_CORR_FCS_ONLY TRUE
#endif

#define L2C_DISP_FRAME_SIZE 16
/*******************************************************************************
**
** Function         l2c_corrupt_the_fcr_packet
**
** Description      This function is used for testing purposes only.
**                  It systematically or randomly corrupts packets used with
**                  ERTM channels.
**
** Returns          BOOLEAN   TRUE if packet was dropped,
**                            FALSE if fcs corrupted or no corruption
**
*******************************************************************************/
static BOOLEAN l2c_corrupt_the_fcr_packet (tL2C_CCB *p_ccb, BT_HDR *p_buf,
                                           BOOLEAN is_rx, UINT16 ctrl_word)
{
    tL2C_FCR_TEST_CFG *p_cfg;
    UINT32   tc;
    UINT8   *p;
    UINT32   xx;
    char     buf[L2C_DISP_FRAME_SIZE];

    if (!p_ccb || !p_ccb->fcrb.test_cb.cfg.in_use)
        return FALSE;

    /* Prepare bad FCS */
    p = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
    tc = GKI_get_os_tick_count();
    tc ^= p[p_buf->len - 1];
    xx = tc % 47;

    p_cfg = &p_ccb->fcrb.test_cb.cfg;
#if 0
    L2CAP_TRACE_DEBUG4 ("testcfg: type: %d, freq: %d (NRM-0, RDM-1), is_rx: %d, count: %d",
        p_cfg->type, p_cfg->freq, p_cfg->is_rx, p_cfg->count);
#endif
    /* If not time to corrupt get out */
    if (p_cfg->freq == L2CAP_FCR_FREQ_RANDOM)
    {
        if (xx != 0)
            return FALSE;
    }
    else    /* check test criteria before corrupting */
    {
        if ( (p_cfg->count == 0)
          || (p_cfg->is_rx != is_rx)
          || ((UINT8)(ctrl_word & L2CAP_FCR_S_FRAME_BIT) != p_cfg->type) )
        {
            return FALSE;
        }

        /* Turn off if done */
        if (--(p_cfg->count) == 0)
        {
            p_ccb->fcrb.test_cb.cfg.in_use = FALSE;
        }
    }

#if L2CAP_CORR_FCS_ONLY == TRUE
    /* Corrupt the FCS check */
    p[p_buf->len - 1] = p[p_buf->len - 2] = 0;
#else
    /* If made it this far packet needs to be corrupted */
    xx = tc % p_buf->len;

    /* Make sure the value was changed */
    if (p[xx + 1] == 0)
        p[xx + 1] = 0x5A;

    p[xx] = p[xx] ^ p[xx + 1];

#if 1   /* Enable if not wishing to corrupting frame type */
    {
        UINT8 *p_temp = ((UINT8 *) (p_buf + 1)) + p_buf->offset;
        p_temp += L2CAP_PKT_OVERHEAD;
        if ((UINT16)((*p_temp) & 0x01) != (ctrl_word & 0x0001))
        {
            (*p_temp) |= (UINT8)(ctrl_word & 0x0001);
        }
    }
#endif
#endif

    if (is_rx)
    {
        if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Rx S-Frame");
        else
            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Rx I-Frame");
    }
    else
    {
        if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Tx S-Frame");
        else
            BCM_STRCPY_S(buf, L2C_DISP_FRAME_SIZE, "Tx I-Frame");
    }

    /* Lastly, just drop packet if FCS is not being used or if Tx */
    if (!is_rx || p_ccb->bypass_fcs == L2CAP_BYPASS_FCS)
    {
        L2CAP_TRACE_ERROR6 ("-=-=-=-=-=-=-=-   Dropping %s packet (0x%04x) tc: %u  Buf Len: %u  xx: %u  count: %d",
                        buf, (UINT32)p_buf, tc, p_buf->len, xx, p_cfg->count);
        GKI_freebuf(p_buf);
        return TRUE;
    }
    else
    {
        L2CAP_TRACE_ERROR6 ("-=-=-=-=-=-=-=-   Corrupting %s packet (0x%04x) tc: %u  Buf Len: %u  xx: %u  count: %d",
                        buf, (UINT32)p_buf, tc, p_buf->len, xx, p_cfg->count);
    }

    return FALSE;
}


/*******************************************************************************
**
** Function         L2CA_SetupErtmTest
**
** Description      This function is used for testing purposes only.
**                  It corrupts or drops one or more packets used with ERTM channels.
**
** Parameters
**                  cid - channel ID  (0 uses RFCOMM PSM's CID)
**
**                  type - type of test to run (L2CAP_FCR_TTYPE_CORR_IFRAMES
**                                              L2CAP_FCR_TTYPE_CORR_SFRAME
**                                              L2CAP_FCR_TTYPE_STOP_TEST
**                                              L2CAP_FCR_TTYPE_GET_CID - returns rfcomm cid only)
**
**                  is_rx  - TRUE to corrupt Rx packet, FALSE for Tx packet)
**
**                  freq - L2CAP_FCR_FREQ_RANDOM    (turns on random corruptions/drops)
**                         L2CAP_FCR_FREQ_NORMAL    (turns on test with "count" corruptions/drops)
**
**                  count - number of packets in a row to drop or corrupt
**
** Returns          CID of channel running test
**
*******************************************************************************/
UINT16 L2CA_SetupErtmTest (UINT16 cid, UINT8 type, BOOLEAN is_rx, UINT8 freq, UINT16 count)
{
    tL2C_CCB *p_ccb = NULL;
    tL2C_CCB *p_temp_ccb;
    tL2C_FCR_TEST_CB *p_test_cb;
    UINT16 xx;

    /* If '0' tests run on top of RFCOMM CID if active */
    if (cid == 0)
    {
        p_temp_ccb = l2cb.ccb_pool;
        for (xx = 0; xx < MAX_L2CAP_CHANNELS; xx++, p_temp_ccb++)
        {
            /* Fixed channels don't have p_rcb's */
            if (p_temp_ccb->in_use && p_temp_ccb->p_rcb && p_temp_ccb->p_rcb->psm == BT_PSM_RFCOMM)
            {
                p_ccb = p_temp_ccb;
                cid = L2CAP_BASE_APPL_CID + xx;
                break;
            }
        }
    }
    else
        p_ccb = l2cu_find_ccb_by_cid (NULL, cid);

    if (!p_ccb || type == L2CAP_FCR_TTYPE_GET_CID)
    {
        if (type == L2CAP_FCR_TTYPE_GET_CID)
        {
            L2CAP_TRACE_API1 ("L2CA_SetupErtmTest (GET_CID): cid = 0x%04x", cid);
        }
        return (cid);
    }

    p_test_cb = &p_ccb->fcrb.test_cb;

    /* Turn off the current test */
    if (type == L2CAP_FCR_TTYPE_STOP_TEST)
    {
        if (p_test_cb->cfg.in_use)
        {
            L2CAP_TRACE_ERROR1 ("L2CA_SetupErtmTest (OFF): cid 0x%04x", cid);
        }
        p_test_cb->cfg.in_use = FALSE;
        p_test_cb->cfg.count = 0;
    }

    /* Process the new request */
    else if (!p_test_cb->cfg.in_use)
    {
        /* count must be positive unless random is used */
        if (!count && freq != L2CAP_FCR_FREQ_RANDOM)
        {
            L2CAP_TRACE_ERROR1 ("L2CA_SetupErtmTest (FAIL): Count = 0, freq = %d", freq);
            return (cid);
        }

        L2CAP_TRACE_ERROR5 ("L2CA_SetupErtmTest (START): cid 0x%04x, type %d, is_rx %d, freq %d, count %d",
                            cid, type, is_rx, freq, count);

        p_test_cb->cfg.in_use = TRUE;
        p_test_cb->cfg.freq = freq;
        p_test_cb->cfg.type = type;
        p_test_cb->cfg.is_rx = is_rx;
        p_test_cb->cfg.count = count;
    }
    else /* Test already in progress so ignore */
    {
        L2CAP_TRACE_ERROR5 ("L2CA_SetupErtmTest (ignoring): cid 0x%04x, type %d, is_rx %d, freq %d, count %d",
                            cid, type, is_rx, freq, count);
    }

    return (cid);
}


/*******************************************************************************
** The following routines are only used in conjunction with Conformance testing
********************************************************************************/

/*******************************************************************************
**
** Function         L2CA_SendPolledSFrame
**
** Description      This function is used for testing purposes only.
**                  It Sends a Polled RR or RNR to the peer
**
** Parameters
**                  cid - channel ID
**
**                  sup_type - (L2CAP_FCR_SUP_RR or L2CAP_FCR_SUP_RNR)
**
** Returns          void
**
*******************************************************************************/
void L2CA_SendPolledSFrame (UINT16 cid, UINT16 sup_type)
{
    tL2C_CCB *p_ccb = l2cu_find_ccb_by_cid (NULL, cid);

    if (p_ccb && (sup_type == L2CAP_FCR_SUP_RR || sup_type == L2CAP_FCR_SUP_RNR))
    {
        l2c_fcr_send_S_frame (p_ccb, sup_type, L2CAP_FCR_P_BIT);
    }
    else
    {
        L2CAP_TRACE_ERROR2 ("L2CA_SendPolledSFrame(ERROR): sup_type %u, p_ccb 0x%07x",
                            sup_type, (UINT32)p_ccb);
    }
}

/*******************************************************************************
**
** Function         l2c_bypass_sframe_packet
**
** Description      This function is used for testing purposes only.
**                  It returns TRUE if S-Frame should be bypassed.
**
** Returns          void
**
*******************************************************************************/
static BOOLEAN l2c_bypass_sframe_packet (tL2C_CCB *p_ccb)
{
    if (p_ccb && p_ccb->fcrb.test_cb.cfm.in_use)
    {
        if (p_ccb->fcrb.test_cb.cfm.skip_sframe_count > 0)
        {
            L2CAP_TRACE_ERROR1 ("l2c_bypass_sframe_packet (count %d)",
                                p_ccb->fcrb.test_cb.cfm.skip_sframe_count);

            if (--p_ccb->fcrb.test_cb.cfm.skip_sframe_count == 0)
                p_ccb->fcrb.test_cb.cfm.in_use = FALSE;

            /* Bypass sending S-Frame */
            return TRUE;
        }
        else
            p_ccb->fcrb.test_cb.cfm.in_use = FALSE;
    }

    return FALSE;
}

/*******************************************************************************
**
** Function         L2CA_BypassSFrame
**
** Description      This function is used for testing purposes only.
**                  It skips sending 'count' S-Frames.
**
** Parameters
**                  cid - channel ID
**
**                  count - Number of S-Frames to skip sending
**
** Returns          void
**
*******************************************************************************/
void L2CA_BypassSFrame (UINT16 cid, UINT8 count)
{
    tL2C_CCB *p_ccb = l2cu_find_ccb_by_cid (NULL, cid);
    tL2C_FCR_CFM_TEST_CB *p_test_cb;

    if (!p_ccb)
    {
        L2CAP_TRACE_WARNING1 ("L2CA_BypassSFrame(ERROR): no p_ccb (0x%07x)", (UINT32)p_ccb);
        return;
    }

    p_test_cb = &p_ccb->fcrb.test_cb.cfm;

    /* Initiate test if not active */
    if (!p_test_cb->in_use)
    {
        p_test_cb->in_use = TRUE;
        p_test_cb->skip_sframe_count = count;
    }
    else
    {
        L2CAP_TRACE_WARNING0 ("L2CA_BypassSFrame(ERROR): already in use (ignoring...)");
    }
}

#endif  /* L2CAP_CORRUPT_ERTM_PKTS == TRUE */

#if (L2CAP_ERTM_STATS == TRUE)
/*******************************************************************************
**
** Function         l2c_fcr_collect_ack_delay
**
** Description      collect throughput, delay, queue size of waiting ack
**
** Parameters
**                  tL2C_CCB
**
** Returns          void
**
*******************************************************************************/
static void l2c_fcr_collect_ack_delay (tL2C_CCB *p_ccb, UINT8 num_bufs_acked)
{
    UINT32  index;
    BT_HDR *p_buf;
    UINT8  *p;
    UINT32  timestamp, delay;
    UINT8   xx;
    UINT8   str[120];

    index = p_ccb->fcrb.ack_delay_avg_index;

    /* update sum, max and min of waiting for ack queue size */
    p_ccb->fcrb.ack_q_count_avg[index] += p_ccb->fcrb.waiting_for_ack_q.count;

    if ( p_ccb->fcrb.waiting_for_ack_q.count > p_ccb->fcrb.ack_q_count_max[index] )
        p_ccb->fcrb.ack_q_count_max[index] = p_ccb->fcrb.waiting_for_ack_q.count;

    if ( p_ccb->fcrb.waiting_for_ack_q.count < p_ccb->fcrb.ack_q_count_min[index] )
        p_ccb->fcrb.ack_q_count_min[index] = p_ccb->fcrb.waiting_for_ack_q.count;

    /* update sum, max and min of round trip delay of acking */
    p_buf = (BT_HDR *)(p_ccb->fcrb.waiting_for_ack_q.p_first);
    for (xx = 0; (xx < num_bufs_acked)&&(p_buf); xx++)
    {
        /* adding up length of acked I-frames to get throughput */
        p_ccb->fcrb.throughput[index] += p_buf->len - 8;

        if ( xx == num_bufs_acked - 1 )
        {
            /* get timestamp from tx I-frame that receiver is acking */
            p = ((UINT8 *) (p_buf+1)) + p_buf->offset + p_buf->len;
            if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS)
            {
                p += L2CAP_FCS_LEN;
            }

            STREAM_TO_UINT32 (timestamp, p);
            delay = GKI_get_os_tick_count() - timestamp;

            p_ccb->fcrb.ack_delay_avg[index] += delay;
            if ( delay > p_ccb->fcrb.ack_delay_max[index] )
                p_ccb->fcrb.ack_delay_max[index] = delay;
            if ( delay < p_ccb->fcrb.ack_delay_min[index] )
                p_ccb->fcrb.ack_delay_min[index] = delay;
        }

        p_buf = GKI_getnext(p_buf);
    }

    p_ccb->fcrb.ack_delay_avg_count++;

    /* calculate average and initialize next avg, min and max */
    if (p_ccb->fcrb.ack_delay_avg_count > L2CAP_ERTM_STATS_AVG_NUM_SAMPLES)
    {
        p_ccb->fcrb.ack_delay_avg_count = 0;

        p_ccb->fcrb.ack_q_count_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
        p_ccb->fcrb.ack_delay_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;

        /* calculate throughput */
        timestamp = GKI_get_os_tick_count();
        if (timestamp - p_ccb->fcrb.throughput_start > 0 )
            p_ccb->fcrb.throughput[index] /= (timestamp - p_ccb->fcrb.throughput_start);

        p_ccb->fcrb.throughput_start = timestamp;

        sprintf(str, "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, ack_q_count avg:%3u, min:%3u, max:%3u",
                index, p_ccb->fcrb.throughput[index],
                p_ccb->fcrb.ack_delay_avg[index], p_ccb->fcrb.ack_delay_min[index], p_ccb->fcrb.ack_delay_max[index],
                p_ccb->fcrb.ack_q_count_avg[index], p_ccb->fcrb.ack_q_count_min[index], p_ccb->fcrb.ack_q_count_max[index] );

        BT_TRACE_1(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI , TRACE_TYPE_GENERIC, "%s", str);

        index = (index + 1) % L2CAP_ERTM_STATS_NUM_AVG;
        p_ccb->fcrb.ack_delay_avg_index = index;

        p_ccb->fcrb.ack_q_count_max[index] = 0;
        p_ccb->fcrb.ack_q_count_min[index] = 0xFFFFFFFF;
        p_ccb->fcrb.ack_q_count_avg[index] = 0;


        p_ccb->fcrb.ack_delay_max[index] = 0;
        p_ccb->fcrb.ack_delay_min[index] = 0xFFFFFFFF;
        p_ccb->fcrb.ack_delay_avg[index] = 0;

        p_ccb->fcrb.throughput[index] = 0;
    }
}
#endif