summaryrefslogtreecommitdiff
path: root/net/nimble/controller/src/ble_ll_conn.c
blob: 65f60372c607fd8409f9e6ab91480e1229e4f2d0 (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
/**
 * Copyright (c) 2015 Runtime Inc.
 *
 * 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.
 */

#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "bsp/bsp.h"
#include "os/os.h"
#include "nimble/ble.h"
#include "nimble/hci_common.h"
#include "controller/ble_ll.h"
#include "controller/ble_ll_hci.h"
#include "controller/ble_ll_scan.h"
#include "controller/ble_ll_whitelist.h"
#include "controller/ble_ll_sched.h"
#include "controller/ble_ll_ctrl.h"
#include "controller/ble_phy.h"
#include "ble_ll_conn_priv.h"
#include "hal/hal_cputime.h"
#include "hal/hal_gpio.h"

/* 
 * XXX: looks like the current code will allow the 1st packet in a
 * connection to extend past the end of the allocated connection end
 * time. That is not good. Need to deal with that. Need to extend connection
 * end time.
 */

/* XXX TODO
 * 1) Add set channel map command and implement channel change procedure.
 * 2) I think if we are initiating and we already have a connection with
 * a device that we will still try and connect to it. Fix this.
 * 3) Make sure we check incoming data packets for size and all that. You
 * know, supported octets and all that. For both rx and tx.
 * 4) Make sure we are setting the schedule end time properly for both slave
 * and master. We should just set this to the end of the connection event.
 * We might want to guarantee a IFS time as well since the next event needs
 * to be scheduled prior to the start of the event to account for the time it
 * takes to get a frame ready (which is pretty much the IFS time).
 * 5) Do we need to check the terminate timeout inside the connection event?
 * I think we do.
 * 6) Use error code 0x3E correctly! Connection failed to establish. If you
 * read the LE connection complete event, it says that if the connection
 * fails to be established that the connection complete event gets sent to
 * the host that issued the create connection.
 * 7) How does peer address get set if we are using whitelist? Look at filter
 * policy and make sure you are doing this correctly.
 * 8) Right now I use a fixed definition for required slots. CHange this.
 * 9) Use output compare for transmit.
 */

/* 
 * XXX: How should we deal with a late connection event? We need to determine
 * what we want to do under the following cases:
 *  1) The current connection event has not ended but a schedule item starts
 *  2) The connection event start cb is called but we are later than we
 *  expected. What to do? If we cant transmit at correct point in slot we
 *  are hosed. Well, anchor point can get really messed up!
 */

/* XXX: this does not belong here! Move to transport? */
extern int ble_hs_rx_data(struct os_mbuf *om);

/* 
 * XXX: Possible improvements
 * 1) See what connection state machine elements are purely master and
 * purely slave. We can make a union of them.
 */

/* 
 * The amount of time that we will wait to hear the start of a receive
 * packet after we have transmitted a packet. This time is at least
 * an IFS time plus the time to receive the preamble and access address. We
 * add an additional 32 usecs just to be safe.
 * 
 * XXX: move this definition and figure out how we determine the worst-case
 * jitter (spec. should have this).
 */
#define BLE_LL_WFR_USECS                    (BLE_LL_IFS + 40 + 32)

/* Configuration parameters */
#define BLE_LL_CFG_CONN_TX_WIN_SIZE         (1)
#define BLE_LL_CFG_CONN_TX_WIN_OFF          (0)
#define BLE_LL_CFG_CONN_MASTER_SCA          (BLE_MASTER_SCA_51_75_PPM << 5)
#define BLE_LL_CFG_CONN_MAX_CONNS           (4)
#define BLE_LL_CFG_CONN_OUR_SCA             (60)    /* in ppm */
#define BLE_LL_CFG_CONN_INIT_SLOTS          (4)

/* We cannot have more than 254 connections given our current implementation */
#if (BLE_LL_CFG_CONN_MAX_CONNS >= 255)
    #error "Maximum # of connections is 254"
#endif

/* LL configuration definitions */
#define BLE_LL_CFG_SUPP_MAX_RX_BYTES        (251)
#define BLE_LL_CFG_SUPP_MAX_TX_BYTES        (251)
#define BLE_LL_CFG_CONN_INIT_MAX_TX_BYTES   (251)

/* Sleep clock accuracy table (in ppm) */
static const uint16_t g_ble_sca_ppm_tbl[8] =
{
    500, 250, 150, 100, 75, 50, 30, 20
};

/* Global Link Layer connection parameters */
struct ble_ll_conn_global_params
{
    uint8_t supp_max_tx_octets;
    uint8_t supp_max_rx_octets;
    uint8_t conn_init_max_tx_octets;
    uint16_t conn_init_max_tx_time;
    uint16_t supp_max_tx_time;
    uint16_t supp_max_rx_time;
};
struct ble_ll_conn_global_params g_ble_ll_conn_params;

/* Pointer to connection state machine we are trying to create */
struct ble_ll_conn_sm *g_ble_ll_conn_create_sm;

/* Pointer to current connection */
struct ble_ll_conn_sm *g_ble_ll_conn_cur_sm;

/* Connection state machine array */
bssnz_t struct ble_ll_conn_sm g_ble_ll_conn_sm[BLE_LL_CFG_CONN_MAX_CONNS];

/* List of active connections */
struct ble_ll_conn_active_list g_ble_ll_conn_active_list;

/* List of free connections */
struct ble_ll_conn_free_list g_ble_ll_conn_free_list;

/* Statistics */
struct ble_ll_conn_stats
{
    uint32_t cant_set_sched;
    uint32_t conn_ev_late;
    uint32_t wfr_expirations;
    uint32_t handle_not_found;
    uint32_t no_tx_pdu;
    uint32_t no_conn_sm;
    uint32_t no_free_conn_sm;
    uint32_t rx_data_pdu_no_conn;
    uint32_t rx_data_pdu_bad_aa;
    uint32_t slave_rxd_bad_conn_req_params;
    uint32_t slave_ce_failures;
    uint32_t rx_resent_pdus;
    uint32_t data_pdu_rx_dup;
    uint32_t data_pdu_txg;
    uint32_t data_pdu_txf;
    uint32_t conn_req_txd;
    uint32_t l2cap_enqueued;
};
struct ble_ll_conn_stats g_ble_ll_conn_stats;

/* Some helpful macros */
#define BLE_IS_RETRY_M(ble_hdr) ((ble_hdr)->txinfo.flags & BLE_MBUF_HDR_F_TXD)

int 
ble_ll_conn_is_lru(struct ble_ll_conn_sm *s1, struct ble_ll_conn_sm *s2)
{
    int rc;

    /* Set time that we last serviced the schedule */
    if ((int32_t)(s1->last_scheduled - s2->last_scheduled) < 0) {
        rc = 1;
    } else {
        rc = 0;
    }

    return rc;
}

/**
 * Called to return the currently running connection state machine end time. 
 * Always called when interrupts are disabled.
 * 
 * @return uint32_t 
 */
uint32_t
ble_ll_conn_get_ce_end_time(void)
{
    uint32_t ce_end_time;

    if (g_ble_ll_conn_cur_sm) {
        ce_end_time = g_ble_ll_conn_cur_sm->ce_end_time;
    } else {
        ce_end_time = cputime_get32();
    }
    return ce_end_time;
}

/**
 * Checks if pdu is a L2CAP pdu, meaning it is not a control pdu nor an empty 
 * pdu. Called only for transmit PDU's.
 * 
 * @return int 
 */
static int
ble_ll_conn_is_l2cap_pdu(struct ble_mbuf_hdr *ble_hdr)
{
    int rc;
    uint8_t llid;

    llid = ble_hdr->txinfo.hdr_byte & BLE_LL_DATA_HDR_LLID_MASK;
    if ((llid != BLE_LL_LLID_CTRL) && (ble_hdr->txinfo.pyld_len != 0)) {
        rc = 1;
    } else {
        rc = 0;
    }
    return rc;
}

/**
 * Called when the current connection state machine is no longer being used. 
 * This function will: 
 *  -> Disable the PHY, which will prevent any transmit/receive interrupts.
 *  -> Disable the wait for response timer, if running.
 *  -> Remove the connection state machine from the scheduler.
 *  -> Sets the Link Layer state to standby.
 *  -> Sets the current state machine to NULL.
 *  
 *  NOTE: the ordering of these function calls is important! We have to stop
 *  the PHY and remove the schedule item before we can set the state to
 *  standby and set the current state machine pointer to NULL.
 */
static void
ble_ll_conn_current_sm_over(void)
{
    /* Disable the PHY */
    ble_phy_disable();

    /* Disable the wfr timer */
    ble_ll_wfr_disable();

    /* Link-layer is in standby state now */
    ble_ll_state_set(BLE_LL_STATE_STANDBY);

    /* Set current LL connection to NULL */
    g_ble_ll_conn_cur_sm = NULL;
}

/**
 * Given a handle, find an active connection matching the handle
 * 
 * @param handle 
 * 
 * @return struct ble_ll_conn_sm* 
 */
struct ble_ll_conn_sm *
ble_ll_conn_find_active_conn(uint16_t handle)
{
    struct ble_ll_conn_sm *connsm;

    connsm = NULL;
    if ((handle != 0) && (handle <= BLE_LL_CFG_CONN_MAX_CONNS)) {
        connsm = &g_ble_ll_conn_sm[handle - 1];
        if (connsm->conn_state == BLE_LL_CONN_STATE_IDLE) {
            connsm = NULL;
        }
    }
    return connsm;
}

/**
 * Get a connection state machine.
 */
struct ble_ll_conn_sm *
ble_ll_conn_sm_get(void)
{
    struct ble_ll_conn_sm *connsm;

    connsm = STAILQ_FIRST(&g_ble_ll_conn_free_list);
    if (connsm) {
        STAILQ_REMOVE_HEAD(&g_ble_ll_conn_free_list, free_stqe);
    } else {
        ++g_ble_ll_conn_stats.no_free_conn_sm;
    }

    return connsm;
}

/**
 * Calculate the amount of window widening for a given connection event. This 
 * is the amount of time that a slave has to account for when listening for 
 * the start of a connection event. 
 * 
 * @param connsm Pointer to connection state machine.
 * 
 * @return uint32_t The current window widening amount (in microseconds)
 */
uint32_t
ble_ll_conn_calc_window_widening(struct ble_ll_conn_sm *connsm)
{
    uint32_t total_sca_ppm;
    uint32_t window_widening;
    int32_t time_since_last_anchor;
    uint32_t delta_msec;

    window_widening = 0;

    time_since_last_anchor = (int32_t)(connsm->anchor_point - 
                                       connsm->last_anchor_point);
    if (time_since_last_anchor > 0) {
        delta_msec = cputime_ticks_to_usecs(time_since_last_anchor) / 1000;
        total_sca_ppm = g_ble_sca_ppm_tbl[connsm->master_sca] + 
                        BLE_LL_CFG_CONN_OUR_SCA;
        window_widening = (total_sca_ppm * delta_msec) / 1000;
    }

    /* XXX: spec gives 16 usecs error btw. Probably should add that in */
    return window_widening;
}

/**
 * Calculates the number of used channels in the channel map 
 * 
 * @param chmap 
 * 
 * @return uint8_t Number of used channels
 */
uint8_t
ble_ll_conn_calc_used_chans(uint8_t *chmap)
{
    int i;
    int j;
    uint8_t mask;
    uint8_t chanbyte;
    uint8_t used_channels;

    used_channels = 0;
    for (i = 0; i < BLE_LL_CONN_CHMAP_LEN; ++i) {
        chanbyte = chmap[i];
        if (chanbyte) {
            if (chanbyte == 0xff) {
                used_channels += 8;
            } else {
                mask = 0x01;
                for (j = 0; j < 8; ++j) {
                    if (chanbyte & mask) {
                        ++used_channels;
                    }
                    mask <<= 1;
                }
            }
        }
    }
    return used_channels;
}

static uint32_t
ble_ll_conn_calc_access_addr(void)
{
    uint32_t aa;
    uint16_t aa_low;
    uint16_t aa_high;
    uint32_t temp;
    uint32_t mask;
    uint32_t prev_bit;
    uint8_t bits_diff;
    uint8_t consecutive;
    uint8_t transitions;

    /* Calculate a random access address */
    aa = 0;
    while (1) {
        /* Get two, 16-bit random numbers */
        aa_low = rand() & 0xFFFF;
        aa_high = rand() & 0xFFFF;

        /* All four bytes cannot be equal */
        if (aa_low == aa_high) {
            continue;
        }

        /* Upper 6 bits must have 2 transitions */
        temp = aa_high & 0xFC00;
        if ((temp == 0) || (temp == 0xFC00)) {
            continue;
        }

        /* Cannot be access address or be 1 bit different */
        aa = aa_high;
        aa = (aa << 16) | aa_low;
        bits_diff = 0;
        temp = aa ^ BLE_ACCESS_ADDR_ADV;
        for (mask = 0x00000001; mask != 0; mask <<= 1) {
            if (mask & temp) {
                ++bits_diff;
                if (bits_diff > 1) {
                    break;
                }
            }
        }
        if (bits_diff <= 1) {
            continue;
        }

        /* Cannot have more than 24 transitions */
        transitions = 0;
        consecutive = 0;
        mask = 0x00000001;
        prev_bit = aa & mask;
        while (mask < 0x80000000) {
            mask <<= 1;
            if (mask & aa) {
                if (prev_bit == 0) {
                    ++transitions;
                    consecutive = 0;
                } else {
                    ++consecutive;
                }
            } else {
                if (prev_bit == 0) {
                    ++consecutive;
                } else {
                    ++transitions;
                    consecutive = 0;
                }
            }

            /* This is invalid! */
            if (consecutive > 6) {
                break;
            }
        }

        /* Cannot be more than 24 transitions */
        if ((consecutive > 6) || (transitions > 24)) {
            continue;
        }

        /* We have a valid access address */
        break;
    }
    return aa;
}

/**
 * Determine data channel index to be used for the upcoming/current 
 * connection event 
 * 
 * @param conn 
 * 
 * @return uint8_t 
 */
uint8_t
ble_ll_conn_calc_dci(struct ble_ll_conn_sm *conn)
{
    int     i;
    int     j;
    uint8_t curchan;
    uint8_t remap_index;
    uint8_t bitpos;
    uint8_t cntr;
    uint8_t mask;
    uint8_t usable_chans;

    /* Get next unmapped channel */
    curchan = conn->last_unmapped_chan + conn->hop_inc;
    if (curchan > BLE_PHY_NUM_DATA_CHANS) {
        curchan -= BLE_PHY_NUM_DATA_CHANS;
    }

    /* Set the current unmapped channel */
    conn->unmapped_chan = curchan;

    /* Is this a valid channel? */
    bitpos = 1 << (curchan & 0x07);
    if ((conn->chanmap[curchan >> 3] & bitpos) == 0) {

        /* Calculate remap index */
        remap_index = curchan % conn->num_used_chans;

        /* NOTE: possible to build a map but this would use memory. For now,
           we just calculate */
        /* Iterate through channel map to find this channel */
        cntr = 0;
        for (i = 0; i < BLE_LL_CONN_CHMAP_LEN; i++) {
            usable_chans = conn->chanmap[i];
            if (usable_chans != 0) {
                mask = 0x01;
                for (j = 0; j < 8; j++) {
                    if (usable_chans & mask) {
                        if (cntr == remap_index) {
                            return cntr;
                        }
                        ++cntr;
                    }
                    mask <<= 1;
                }
            }
        }
    }

    return curchan;
}

/**
 * Called when we are in the connection state and the wait for response timer
 * fires off.
 *  
 * Context: Interrupt 
 */
void
ble_ll_conn_wfr_timer_exp(void)
{
    struct ble_ll_conn_sm *connsm;

    connsm = g_ble_ll_conn_cur_sm;
    ble_ll_conn_current_sm_over();
    if (connsm) {
        ble_ll_event_send(&connsm->conn_ev_end);
        ++g_ble_ll_conn_stats.wfr_expirations;
    }
}

/**
 * Callback for slave when it transmits a data pdu and the connection event
 * ends after the transmission.
 *  
 * Context: Interrupt 
 *
 * @param sch 
 * 
 */
static void
ble_ll_conn_wait_txend(void *arg)
{
    struct ble_ll_conn_sm *connsm;

    ble_ll_conn_current_sm_over();

    connsm = (struct ble_ll_conn_sm *)arg;
    ble_ll_event_send(&connsm->conn_ev_end);
}

/**
 * Called when we want to send a data channel pdu inside a connection event. 
 *  
 * Context: interrupt 
 *  
 * @param connsm 
 * 
 * @return int 0: success; otherwise failure to transmit
 */
static int
ble_ll_conn_tx_data_pdu(struct ble_ll_conn_sm *connsm, int beg_transition)
{
    int rc;
    int tx_empty_pdu;
    uint8_t md;
    uint8_t hdr_byte;
    uint8_t end_transition;
    uint8_t cur_txlen;
    uint8_t rem_bytes;
    uint32_t ticks;
    struct os_mbuf *m;
    struct ble_mbuf_hdr *ble_hdr;
    struct os_mbuf_pkthdr *pkthdr;
    struct os_mbuf_pkthdr *nextpkthdr;
    ble_phy_tx_end_func txend_func;

    /*
     * Get packet off transmit queue. If not available, send empty PDU. Set
     * the more data bit as well. For a slave, we will set it regardless of
     * connection event end timing (master will deal with that for us or the
     * connection event will be terminated locally). For a master, we only
     * set the MD bit if we have enough time to send the current PDU, get
     * a response and send the next packet and get a response.
     */
    md = 0;
    tx_empty_pdu = 0;
    pkthdr = STAILQ_FIRST(&connsm->conn_txq);
    if (pkthdr) {
        m = OS_MBUF_PKTHDR_TO_MBUF(pkthdr);
        nextpkthdr = STAILQ_NEXT(pkthdr, omp_next);
        ble_hdr = BLE_MBUF_HDR_PTR(m);

        /* 
         * This piece of code is trying to determine if there are more bytes
         * to send in the current packet AFTER the current fragment gets sent.
         * If this is a retry we cant change the size and we use the 
         * current tx size. If not, we use effective max transmit bytes for the
         * connection.
         */
        if (BLE_IS_RETRY_M(ble_hdr)) {
            cur_txlen = ble_hdr->txinfo.pyld_len;
            hdr_byte = ble_hdr->txinfo.hdr_byte;
            hdr_byte &= ~(BLE_LL_DATA_HDR_MD_MASK | BLE_LL_DATA_HDR_NESN_MASK);
        } else {
            /* Determine packet length we will transmit */
            cur_txlen = connsm->eff_max_tx_octets;
            rem_bytes = pkthdr->omp_len - ble_hdr->txinfo.offset;
            if (cur_txlen > rem_bytes) {
                cur_txlen = rem_bytes;
            }

            /* 
             * Need to set LLID correctly if this is a fragment. Note
             * that the LLID is already set the first time it is enqueued.
             */ 
            if (ble_hdr->txinfo.offset != 0) {
                hdr_byte = BLE_LL_LLID_DATA_FRAG;
            } else {
                hdr_byte = ble_hdr->txinfo.hdr_byte;
            }
            if (connsm->tx_seqnum) {
                hdr_byte |= BLE_LL_DATA_HDR_SN_MASK;
            }
            ble_hdr->txinfo.pyld_len = cur_txlen;
        }

        if ((nextpkthdr || 
             ((ble_hdr->txinfo.offset + cur_txlen) < pkthdr->omp_len)) && 
             !connsm->csmflags.cfbit.terminate_ind_rxd) {
            md = 1;
            if (connsm->conn_role == BLE_LL_CONN_ROLE_MASTER) {
                /* 
                 * Dont bother to set the MD bit if we cannot do the following:
                 *  -> wait IFS, send the current frame.
                 *  -> wait IFS, receive a mininim size frame.
                 *  -> wait IFS, send a mininim size frame.
                 *  -> wait IFS, receive a mininim size frame.
                 */
                /* 
                 * XXX: this calculation is based on using the current time
                 * and assuming the transmission will occur an IFS time from
                 * now. This is not the most accurate especially if we have
                 * received a frame and we are replying to it.
                 */ 
                ticks = (BLE_LL_IFS * 4) + (3 * BLE_LL_CONN_SUPP_TIME_MIN) +
                    BLE_TX_DUR_USECS_M(cur_txlen);
                ticks = cputime_usecs_to_ticks(ticks);
                if ((cputime_get32() + ticks) >= connsm->ce_end_time) {
                    md = 0;
                }
            }
        }
    } else {
        /* Send empty pdu. Need to reset some items since we re-use it. */
        m = (struct os_mbuf *)&connsm->conn_empty_pdu;
        ble_hdr = BLE_MBUF_HDR_PTR(m);
        ble_hdr->txinfo.flags = 0;
        pkthdr = OS_MBUF_PKTHDR(m);
        STAILQ_INSERT_HEAD(&connsm->conn_txq, pkthdr, omp_next);

        /* Set header of empty pdu */
        hdr_byte = BLE_LL_LLID_DATA_FRAG;
        if (connsm->tx_seqnum) {
            hdr_byte |= BLE_LL_DATA_HDR_SN_MASK;
        }
        tx_empty_pdu = 1;
    }

    /* Set transmitted flag */
    ble_hdr->txinfo.flags |= BLE_MBUF_HDR_F_TXD;

    /* If we have more data, set the bit */
    if (md) {
        hdr_byte |= BLE_LL_DATA_HDR_MD_MASK;
    }

    /* Set NESN (next expected sequence number) bit */
    if (connsm->next_exp_seqnum) {
        hdr_byte |= BLE_LL_DATA_HDR_NESN_MASK;
    }

    /* Set the header byte in the outgoing frame */
    ble_hdr->txinfo.hdr_byte = hdr_byte;

    /* 
     * If we are a slave, check to see if this transmission will end the
     * connection event. We will end the connection event if we have
     * received a valid frame with the more data bit set to 0 and we dont
     * have more data.
     */
    if ((connsm->csmflags.cfbit.terminate_ind_rxd) ||
        ((connsm->conn_role == BLE_LL_CONN_ROLE_SLAVE) && (md == 0) &&
         (connsm->cons_rxd_bad_crc == 0) &&
         ((connsm->last_rxd_hdr_byte & BLE_LL_DATA_HDR_MD_MASK) == 0) &&
         !ble_ll_ctrl_is_terminate_ind(hdr_byte, m->om_data[0]))) {
        /* We will end the connection event */
        end_transition = BLE_PHY_TRANSITION_NONE;
        txend_func = ble_ll_conn_wait_txend;
    } else {
        /* Wait for a response here */
        end_transition = BLE_PHY_TRANSITION_TX_RX;
        txend_func = NULL;
    }

    /* Set transmit end callback */
    ble_phy_set_txend_cb(txend_func, connsm);
    rc = ble_phy_tx(m, beg_transition, end_transition);
    if (!rc) {
        /* Log transmit on connection state */
        ble_ll_log(BLE_LL_LOG_ID_CONN_TX, 
                   hdr_byte, 
                   ((uint16_t)ble_hdr->txinfo.offset << 8) | 
                              ble_hdr->txinfo.pyld_len,
                   (uint32_t)m);

        /* Set flag denoting we transmitted a pdu */
        connsm->csmflags.cfbit.pdu_txd = 1;

        /* Set last transmitted MD bit */
        connsm->last_txd_md = md;

        /* Increment packets transmitted */
        if (tx_empty_pdu) {
            ++g_ble_ll_stats.tx_empty_pdus;
        } else if ((hdr_byte & BLE_LL_DATA_HDR_LLID_MASK) == BLE_LL_LLID_CTRL) {
            ++g_ble_ll_stats.tx_ctrl_pdus;
            g_ble_ll_stats.tx_ctrl_bytes += ble_hdr->txinfo.pyld_len; 
        } else {
            ++g_ble_ll_stats.tx_l2cap_pdus;
            g_ble_ll_stats.tx_l2cap_bytes += ble_hdr->txinfo.pyld_len;
        }
    }

    return rc;
}

/**
 * Schedule callback for start of connection event 
 *  
 * Context: Interrupt 
 * 
 * @param sch 
 * 
 * @return int 0: scheduled item is still running. 1: schedule item is done.
 */
static int
ble_ll_conn_event_start_cb(struct ble_ll_sched_item *sch)
{
    int rc;
    uint32_t usecs;
    uint32_t wfr_time;
    struct ble_ll_conn_sm *connsm;

    /* XXX: note that we can extend end time here if we want. Look at this */

    /* Set current connection state machine */
    connsm = (struct ble_ll_conn_sm *)sch->cb_arg;
    g_ble_ll_conn_cur_sm = connsm;
    assert(connsm);

    /* Set LL state */
    ble_ll_state_set(BLE_LL_STATE_CONNECTION);

    /* Log connection event start */
    ble_ll_log(BLE_LL_LOG_ID_CONN_EV_START, connsm->data_chan_index, 
               connsm->conn_handle, connsm->ce_end_time);

    /* Set channel */
    rc = ble_phy_setchan(connsm->data_chan_index, connsm->access_addr, 
                         connsm->crcinit);
    assert(rc == 0);

    if (connsm->conn_role == BLE_LL_CONN_ROLE_MASTER) {
        rc = ble_ll_conn_tx_data_pdu(connsm, BLE_PHY_TRANSITION_NONE);
        if (!rc) {
            rc = BLE_LL_SCHED_STATE_RUNNING;
        } else {
            /* Inform LL task of connection event end */
            rc = BLE_LL_SCHED_STATE_DONE;
        }
    } else {
        rc = ble_phy_rx();
        if (rc) {
            /* End the connection event as we have no more buffers */
            ++g_ble_ll_conn_stats.slave_ce_failures;
            rc = BLE_LL_SCHED_STATE_DONE;
        } else {
            /* 
             * Set flag that tells slave to set last anchor point if a packet
             * has been received.
             */ 
            connsm->csmflags.cfbit.slave_set_last_anchor = 1;

            /* 
             * Set the wait for response time. The anchor point is when we
             * expect the master to start transmitting. Worst-case, we expect
             * to hear a reply within the anchor point plus:
             *  -> the current tx window size
             *  -> The current window widening amount
             *  -> Amount of time it takes to detect packet start.
             */
            usecs = connsm->slave_cur_tx_win_usecs + BLE_LL_WFR_USECS +
                connsm->slave_cur_window_widening;
            wfr_time = connsm->anchor_point + cputime_usecs_to_ticks(usecs);
            ble_ll_wfr_enable(wfr_time);

            /* Set next wakeup time to connection event end time */
            rc = BLE_LL_SCHED_STATE_RUNNING;
        }
    }

    if (rc == BLE_LL_SCHED_STATE_DONE) {
        ble_ll_event_send(&connsm->conn_ev_end);
        ble_ll_state_set(BLE_LL_STATE_STANDBY);
        g_ble_ll_conn_cur_sm = NULL;
    }

    /* Set time that we last serviced the schedule */
    connsm->last_scheduled = cputime_get32();
    return rc;
}

/**
 * Called to determine if the device is allowed to send the next pdu in the 
 * connection event. This will always return 'true' if we are a slave. If we 
 * are a master, we must be able to send the next fragment and get a minimum 
 * sized response from the slave. 
 *  
 * Context: Interrupt context (rx end isr). 
 * 
 * @param connsm 
 * @param begtime   Time at which IFS before pdu transmission starts 
 * 
 * @return int 0: not allowed to send 1: allowed to send
 */
static int
ble_ll_conn_can_send_next_pdu(struct ble_ll_conn_sm *connsm, uint32_t begtime)
{
    int rc;
    uint8_t rem_bytes;
    uint32_t ticks;
    struct os_mbuf *txpdu;
    struct os_mbuf_pkthdr *pkthdr;
    struct ble_mbuf_hdr *txhdr;

    rc = 1;
    if (connsm->conn_role == BLE_LL_CONN_ROLE_MASTER) {
        pkthdr = STAILQ_FIRST(&connsm->conn_txq);
        if (pkthdr) {
            txpdu = OS_MBUF_PKTHDR_TO_MBUF(pkthdr);
            txhdr = BLE_MBUF_HDR_PTR(txpdu);
            rem_bytes = pkthdr->omp_len - txhdr->txinfo.offset;
            if (rem_bytes > connsm->eff_max_tx_octets) {
                rem_bytes = connsm->eff_max_tx_octets;
            }
            ticks = BLE_TX_DUR_USECS_M(rem_bytes);
        } else {
            /* We will send empty pdu (just a LL header) */
            ticks = BLE_TX_DUR_USECS_M(0);
        }
        ticks += (BLE_LL_IFS * 2) + BLE_LL_CONN_SUPP_TIME_MIN;
        ticks = cputime_usecs_to_ticks(ticks);
        if ((begtime + ticks) >= connsm->ce_end_time) {
            rc = 0;
        }
    }

    return rc;
}

/**
 * Connection supervision timer callback; means that the connection supervision
 * timeout has been reached and we should perform the appropriate actions. 
 *  
 * Context: Interrupt (cputimer)
 * 
 * @param arg Pointer to connection state machine.
 */
void
ble_ll_conn_spvn_timer_cb(void *arg)
{
    struct ble_ll_conn_sm *connsm;

    connsm = (struct ble_ll_conn_sm *)arg;
    ble_ll_event_send(&connsm->conn_spvn_ev);
}

/**
 * Called when a create connection command has been received. This initializes 
 * a connection state machine in the master role. 
 *  
 * NOTE: Must be called before the state machine is started 
 * 
 * @param connsm 
 * @param hcc 
 */
void
ble_ll_conn_master_init(struct ble_ll_conn_sm *connsm, 
                        struct hci_create_conn *hcc)
{
    /* Set master role */
    connsm->conn_role = BLE_LL_CONN_ROLE_MASTER;

    /* Set default ce parameters */
    connsm->tx_win_size = BLE_LL_CFG_CONN_TX_WIN_SIZE;
    connsm->tx_win_off = BLE_LL_CFG_CONN_TX_WIN_OFF;
    connsm->master_sca = BLE_LL_CFG_CONN_MASTER_SCA;

    /* Hop increment is a random value between 5 and 16. */
    connsm->hop_inc = (rand() % 12) + 5;

    /* Set slave latency and supervision timeout */
    connsm->slave_latency = hcc->conn_latency;
    connsm->supervision_tmo = hcc->supervision_timeout;

    /* Set own address type and peer address if needed */
    connsm->own_addr_type = hcc->own_addr_type;
    if (hcc->filter_policy == 0) {
        memcpy(&connsm->peer_addr, &hcc->peer_addr, BLE_DEV_ADDR_LEN);
        connsm->peer_addr_type = hcc->peer_addr_type;
    }

    /* XXX: for now, just make connection interval equal to max */
    connsm->conn_itvl_min = hcc->conn_itvl_min;
    connsm->conn_itvl_max = hcc->conn_itvl_max;
    connsm->conn_itvl = hcc->conn_itvl_max;

    /* Check the min/max CE lengths are less than connection interval */
    if (hcc->min_ce_len > (connsm->conn_itvl * 2)) {
        connsm->min_ce_len = connsm->conn_itvl * 2;
    } else {
        connsm->min_ce_len = hcc->min_ce_len;
    }

    if (hcc->max_ce_len > (connsm->conn_itvl * 2)) {
        connsm->max_ce_len = connsm->conn_itvl * 2;
    } else {
        connsm->max_ce_len = hcc->max_ce_len;
    }

    /* 
     * XXX: for now, just set the channel map to all 1's. Needs to get
     * set to default or initialized or something
     */ 
    connsm->num_used_chans = BLE_PHY_NUM_DATA_CHANS;
    memset(connsm->chanmap, 0xff, BLE_LL_CONN_CHMAP_LEN - 1);
    connsm->chanmap[4] = 0x1f;

    /*  Calculate random access address and crc initialization value */
    connsm->access_addr = ble_ll_conn_calc_access_addr();
    connsm->crcinit = rand() & 0xffffff;

    /* Set initial schedule callback */
    connsm->conn_sch.sched_cb = ble_ll_conn_event_start_cb;
}

/**
 * Create a new connection state machine. This is done once per 
 * connection when the HCI command "create connection" is issued to the 
 * controller or when a slave receives a connect request. 
 *  
 * Context: Link Layer task 
 * 
 * @param connsm 
 */
void
ble_ll_conn_sm_new(struct ble_ll_conn_sm *connsm)
{
    struct ble_ll_conn_global_params *conn_params;

    /* Reset following elements */
    connsm->csmflags.conn_flags = 0;
    connsm->event_cntr = 0;
    connsm->conn_state = BLE_LL_CONN_STATE_IDLE;
    connsm->disconnect_reason = 0;
    connsm->common_features = 0;
    connsm->vers_nr = 0;
    connsm->comp_id = 0;
    connsm->sub_vers_nr = 0;
    connsm->reject_reason = BLE_ERR_SUCCESS;

    /* Reset current control procedure */
    connsm->cur_ctrl_proc = BLE_LL_CTRL_PROC_IDLE;
    connsm->pending_ctrl_procs = 0;

    /* 
     * Set handle in connection update procedure to 0. If the handle
     * is non-zero it means that the host initiated the connection
     * parameter update request and the rest of the parameters are valid.
     */
    connsm->conn_param_req.handle = 0;

    /* Initialize connection supervision timer */
    cputime_timer_init(&connsm->conn_spvn_timer, ble_ll_conn_spvn_timer_cb, 
                       connsm);

    /* Calculate the next data channel */
    connsm->last_unmapped_chan = 0;
    connsm->data_chan_index = ble_ll_conn_calc_dci(connsm);

    /* Initialize event */
    connsm->conn_spvn_ev.ev_arg = connsm;
    connsm->conn_spvn_ev.ev_queued = 0;
    connsm->conn_spvn_ev.ev_type = BLE_LL_EVENT_CONN_SPVN_TMO;

    /* Connection end event */
    connsm->conn_ev_end.ev_arg = connsm;
    connsm->conn_ev_end.ev_queued = 0;
    connsm->conn_ev_end.ev_type = BLE_LL_EVENT_CONN_EV_END;

    /* Initialize transmit queue and ack/flow control elements */
    STAILQ_INIT(&connsm->conn_txq);
    connsm->tx_seqnum = 0;
    connsm->next_exp_seqnum = 0;
    connsm->last_txd_md = 0;
    connsm->cons_rxd_bad_crc = 0;
    connsm->last_rxd_sn = 1;
    connsm->completed_pkts = 0;

    /* initialize data length mgmt */
    conn_params = &g_ble_ll_conn_params;
    connsm->max_tx_octets = conn_params->conn_init_max_tx_octets;
    connsm->max_rx_octets = conn_params->supp_max_rx_octets;
    connsm->max_tx_time = conn_params->conn_init_max_tx_time;
    connsm->max_rx_time = conn_params->supp_max_rx_time;
    connsm->rem_max_tx_time = BLE_LL_CONN_SUPP_TIME_MIN;
    connsm->rem_max_rx_time = BLE_LL_CONN_SUPP_TIME_MIN;
    connsm->eff_max_tx_time = BLE_LL_CONN_SUPP_TIME_MIN;
    connsm->eff_max_rx_time = BLE_LL_CONN_SUPP_TIME_MIN;
    connsm->rem_max_tx_octets = BLE_LL_CONN_SUPP_BYTES_MIN;
    connsm->rem_max_rx_octets = BLE_LL_CONN_SUPP_BYTES_MIN;
    connsm->eff_max_tx_octets = BLE_LL_CONN_SUPP_BYTES_MIN;
    connsm->eff_max_rx_octets = BLE_LL_CONN_SUPP_BYTES_MIN;

    /* Add to list of active connections */
    SLIST_INSERT_HEAD(&g_ble_ll_conn_active_list, connsm, act_sle);
}

/**
 * Called when a remotes data length parameters change. 
 *  
 * Context: Link Layer task 
 *  
 * @param connsm 
 * @param req 
 */
void
ble_ll_conn_datalen_update(struct ble_ll_conn_sm *connsm, 
                           struct ble_ll_len_req *req)
{
    int send_event;
    uint16_t eff_time;
    uint16_t eff_bytes;

    /* Update parameters */
    connsm->rem_max_rx_time = req->max_rx_time;
    connsm->rem_max_tx_time = req->max_tx_time;
    connsm->rem_max_rx_octets = req->max_rx_bytes;
    connsm->rem_max_tx_octets = req->max_tx_bytes;

    /* Assume no event sent */
    send_event = 0;

    /* See if effective times have changed */
    eff_time = min(connsm->rem_max_tx_time, connsm->max_rx_time);
    if (eff_time != connsm->eff_max_rx_time) {
        connsm->eff_max_rx_time = eff_time;
        send_event = 1;
    }
    eff_time = min(connsm->rem_max_rx_time, connsm->max_tx_time);
    if (eff_time != connsm->eff_max_tx_time) {
        connsm->eff_max_tx_time = eff_time;
        send_event = 1;
    }
    eff_bytes = min(connsm->rem_max_tx_octets, connsm->max_rx_octets);
    if (eff_bytes != connsm->eff_max_rx_octets) {
        connsm->eff_max_rx_octets = eff_bytes;
        send_event = 1;
    }
    eff_bytes = min(connsm->rem_max_rx_octets, connsm->max_tx_octets);
    if (eff_bytes != connsm->eff_max_tx_octets) {
        connsm->eff_max_tx_octets = eff_bytes;
        send_event = 1;
    }

    if (send_event) {
        ble_ll_hci_ev_datalen_chg(connsm);
    }
}

/**
 * Called when a connection is terminated 
 *  
 * Context: Link Layer task. 
 * 
 * @param connsm 
 * @param ble_err 
 */
void
ble_ll_conn_end(struct ble_ll_conn_sm *connsm, uint8_t ble_err)
{
    struct os_mbuf *m;
    struct os_mbuf_pkthdr *pkthdr;

    /* Remove scheduler events just in case */
    ble_ll_sched_rmv_elem(&connsm->conn_sch);

    /* Stop supervision timer */
    cputime_timer_stop(&connsm->conn_spvn_timer);

    /* Stop any control procedures that might be running */
    os_callout_stop(&connsm->ctrl_proc_rsp_timer.cf_c);

    /* Remove from the active connection list */
    SLIST_REMOVE(&g_ble_ll_conn_active_list, connsm, ble_ll_conn_sm, act_sle);

    /* Free all packets on transmit queue */
    while (1) {
        /* Get mbuf pointer from packet header pointer */
        pkthdr = STAILQ_FIRST(&connsm->conn_txq);
        if (!pkthdr) {
            break;
        }
        STAILQ_REMOVE_HEAD(&connsm->conn_txq, omp_next);

        m = (struct os_mbuf *)((uint8_t *)pkthdr - sizeof(struct os_mbuf));
        os_mbuf_free(m);
    }

    /* Make sure events off queue */
    os_eventq_remove(&g_ble_ll_data.ll_evq, &connsm->conn_spvn_ev);
    os_eventq_remove(&g_ble_ll_data.ll_evq, &connsm->conn_ev_end);

    /* Connection state machine is now idle */
    connsm->conn_state = BLE_LL_CONN_STATE_IDLE;

    /* 
     * We need to send a disconnection complete event or a connection complete
     * event when the connection ends. We send a connection complete event
     * only when we were told to cancel the connection creation. If the
     * ble error is "success" it means that the reset command was received
     * and we should not send an event 
     */ 
    if (ble_err) {
        if (ble_err == BLE_ERR_UNK_CONN_ID) {
            ble_ll_conn_comp_event_send(connsm, ble_err);
        } else {
            ble_ll_disconn_comp_event_send(connsm, ble_err);
        }
    }

    /* Put connection state machine back on free list */
    STAILQ_INSERT_TAIL(&g_ble_ll_conn_free_list, connsm, free_stqe);

    /* Log connection end */
    ble_ll_log(BLE_LL_LOG_ID_CONN_END,connsm->conn_handle,0,connsm->event_cntr);
}

/**
 * Called to move to the next connection event. 
 * 
 * @param connsm 
 * 
 * @return int 
 */
static int
ble_ll_conn_next_event(struct ble_ll_conn_sm *connsm)
{
    uint8_t update_status;
    uint16_t latency;
    uint32_t itvl;
    uint32_t tmo;
    uint32_t cur_ww;
    uint32_t max_ww;
    struct ble_ll_conn_upd_req *upd;

    /* 
     * XXX: we could send the connection update event a bit earlier. The
     * way this is coded is that we will generally send it when the
     * connection event corresponding to the instant ends. We can send
     * it when it begins if we want.
     */

    /* XXX: deal with connection request procedure here as well */

    /* 
     * There are two cases where this flag gets set:
     * 1) A connection update procedure was started and the event counter
     * has passed the instant.
     * 2) We successfully sent the reject reason.
     */
    if (connsm->csmflags.cfbit.host_expects_upd_event) {
        update_status = BLE_ERR_SUCCESS;
        if (IS_PENDING_CTRL_PROC(connsm, BLE_LL_CTRL_PROC_CONN_UPDATE)) {
            ble_ll_ctrl_proc_stop(connsm, BLE_LL_CTRL_PROC_CONN_UPDATE);
        } else {
            if (IS_PENDING_CTRL_PROC(connsm, BLE_LL_CTRL_PROC_CONN_PARAM_REQ)) {
                ble_ll_ctrl_proc_stop(connsm, BLE_LL_CTRL_PROC_CONN_PARAM_REQ);
                update_status = connsm->reject_reason;
            }
        }
        ble_ll_hci_ev_conn_update(connsm, update_status);
        connsm->csmflags.cfbit.host_expects_upd_event = 0;
    }

    /* 
     * XXX: not quite sure I am interpreting slave latency correctly here.
     * The spec says if you applied slave latency and you dont hear a packet,
     * you dont apply slave latency. Does that mean you dont apply slave
     * latency until you hear a packet or on the next interval if you listen
     * and dont hear anything, can you apply slave latency?
     */
    /* Set event counter to the next connection event that we will tx/rx in */
    itvl = connsm->conn_itvl * BLE_LL_CONN_ITVL_USECS;
    latency = 1;
    if (connsm->csmflags.cfbit.allow_slave_latency && 
        !connsm->csmflags.cfbit.conn_update_scheduled) {
        if (connsm->csmflags.cfbit.pkt_rxd) {
            latency += connsm->slave_latency;
            itvl = itvl * latency;
        }
    }
    connsm->event_cntr += latency;

    /* Set next connection event start time */
    connsm->anchor_point += cputime_usecs_to_ticks(itvl);

    /* 
     * If a connection update has been scheduled and the event counter
     * is now equal to the instant, we need to adjust the start of the
     * connection by the the transmit window offset. We also copy in the
     * update parameters as they now should take effect.
     */
    if (connsm->csmflags.cfbit.conn_update_scheduled && 
        (connsm->event_cntr == connsm->conn_update_req.instant)) {

        /* Set flag so we send connection update event */
        upd = &connsm->conn_update_req;
        if ((connsm->conn_role == BLE_LL_CONN_ROLE_MASTER)  ||
            (connsm->conn_itvl != upd->interval)            ||
            (connsm->slave_latency != upd->latency)         || 
            (connsm->supervision_tmo != upd->timeout)) {
            connsm->csmflags.cfbit.host_expects_upd_event = 1;
        }

        connsm->conn_itvl = upd->interval;
        connsm->supervision_tmo = upd->timeout;
        connsm->slave_latency = upd->latency;
        connsm->tx_win_size = upd->winsize;
        connsm->slave_cur_tx_win_usecs =  
            connsm->tx_win_size * BLE_LL_CONN_TX_WIN_USECS;
        connsm->tx_win_off = upd->winoffset;
        connsm->anchor_point += 
            cputime_usecs_to_ticks(upd->winoffset * BLE_LL_CONN_ITVL_USECS);

        /* Reset the connection supervision timeout */
        cputime_timer_stop(&connsm->conn_spvn_timer);
        tmo = connsm->supervision_tmo;
        tmo = tmo * BLE_HCI_CONN_SPVN_TMO_UNITS * 1000;
        tmo = cputime_usecs_to_ticks(tmo);
        cputime_timer_start(&connsm->conn_spvn_timer, connsm->anchor_point+tmo);

        /* Reset update scheduled flag */
        connsm->csmflags.cfbit.conn_update_scheduled = 0;
    }

    /* Calculate data channel index of next connection event */
    while (latency > 0) {
        connsm->last_unmapped_chan = connsm->unmapped_chan;
        connsm->data_chan_index = ble_ll_conn_calc_dci(connsm);
        --latency;
    }

    /* 
     * If we are trying to terminate connection, check if next wake time is
     * passed the termination timeout. If so, no need to continue with
     * connection as we will time out anyway.
     */
    if (connsm->pending_ctrl_procs & (1 << BLE_LL_CTRL_PROC_TERMINATE)) {
        if ((int32_t)(connsm->terminate_timeout - connsm->anchor_point) <= 0) {
            return -1;
        }
    }

    /* 
     * Calculate ce end time. For a slave, we need to add window widening and
     * the transmit window if we still have one.
     */
    itvl = BLE_LL_CFG_CONN_INIT_SLOTS * BLE_LL_SCHED_USECS_PER_SLOT;
    if (connsm->conn_role == BLE_LL_CONN_ROLE_SLAVE) {
        cur_ww = ble_ll_conn_calc_window_widening(connsm);
        max_ww = (connsm->conn_itvl * (BLE_LL_CONN_ITVL_USECS/2)) - BLE_LL_IFS;
        if (cur_ww >= max_ww) {
            return -1;
        }
        connsm->slave_cur_window_widening = cur_ww;
        itvl += cur_ww + connsm->slave_cur_tx_win_usecs;
    } else {
        /* We adjust end time for connection to end of time slot */
        itvl -= XCVR_TX_SCHED_DELAY_USECS;
    }
    connsm->ce_end_time = connsm->anchor_point + cputime_usecs_to_ticks(itvl);

    return 0;
}

/**
 * Called when a connection has been created. This function will 
 *  -> Set the connection state to created.
 *  -> Start the connection supervision timer
 *  -> Set the Link Layer state to connection.
 *  -> Send a connection complete event.
 *  
 *  See Section 4.5.2 Vol 6 Part B
 *  
 *  Context: Link Layer
 * 
 * @param connsm 
 *  
 * @ return 0: connection NOT created. 1: connection created 
 */
static int
ble_ll_conn_created(struct ble_ll_conn_sm *connsm, uint32_t endtime)
{
    int rc;
    uint32_t usecs;

    /* Set state to created */
    connsm->conn_state = BLE_LL_CONN_STATE_CREATED;

    /* Set supervision timeout */
    usecs = connsm->conn_itvl * BLE_LL_CONN_ITVL_USECS * 6;
    cputime_timer_relative(&connsm->conn_spvn_timer, usecs);

    /* Clear packet received flag */
    connsm->csmflags.cfbit.pkt_rxd = 0;

    /* Consider time created the last scheduled time */
    connsm->last_scheduled = cputime_get32();

    /* 
     * Set first connection event time. If slave the endtime is the receive end
     * time of the connect request. The actual connection starts 1.25 msecs plus
     * the transmit window offset from the end of the connection request.
     */
    rc = 1;
    connsm->last_anchor_point = endtime;
    if (connsm->conn_role == BLE_LL_CONN_ROLE_SLAVE) {
        connsm->slave_cur_tx_win_usecs = 
            connsm->tx_win_size * BLE_LL_CONN_TX_WIN_USECS;
        usecs = 1250 + (connsm->tx_win_off * BLE_LL_CONN_TX_WIN_USECS);
        connsm->anchor_point = endtime + cputime_usecs_to_ticks(usecs);
        usecs = connsm->slave_cur_tx_win_usecs + (BLE_LL_CFG_CONN_INIT_SLOTS *
                                                  BLE_LL_SCHED_USECS_PER_SLOT);
        connsm->ce_end_time = connsm->anchor_point + 
            cputime_usecs_to_ticks(usecs);
        connsm->slave_cur_window_widening = 0;

        /* Start the scheduler for the first connection event */
        while (ble_ll_sched_slave_new(connsm)) {
            if (ble_ll_conn_next_event(connsm)) {
                ++g_ble_ll_conn_stats.cant_set_sched;
                rc = 0;
                break;
            }
        }
    }

    /* Send connection complete event to inform host of connection */
    if (rc) {
        /* 
         * Section 4.5.10 Vol 6 PART B. If the max tx/rx time or octets
         * exceeds the minimum, data length procedure needs to occur
         */
        if ((connsm->max_tx_octets > BLE_LL_CONN_SUPP_BYTES_MIN) ||
            (connsm->max_rx_octets > BLE_LL_CONN_SUPP_BYTES_MIN) ||
            (connsm->max_tx_time > BLE_LL_CONN_SUPP_TIME_MIN) ||
            (connsm->max_rx_time > BLE_LL_CONN_SUPP_TIME_MIN)) {
            /* Start the data length update procedure */
            if (ble_ll_read_supp_features() & BLE_LL_FEAT_DATA_LEN_EXT) {
                ble_ll_ctrl_proc_start(connsm, BLE_LL_CTRL_PROC_DATA_LEN_UPD);
            }
        }
        ble_ll_conn_comp_event_send(connsm, BLE_ERR_SUCCESS);
    }

    return rc;
}

/**
 * Called upon end of connection event
 *  
 * Context: Link-layer task 
 * 
 * @param void *arg Pointer to connection state machine
 * 
 */
void
ble_ll_conn_event_end(void *arg)
{
    uint8_t ble_err;
    struct ble_ll_conn_sm *connsm;

    /* Better be a connection state machine! */
    connsm = (struct ble_ll_conn_sm *)arg;
    assert(connsm);

    /* Check if we need to resume scanning */
    ble_ll_scan_chk_resume();

    /* Log event end */
    ble_ll_log(BLE_LL_LOG_ID_CONN_EV_END, 0, connsm->event_cntr, 
               connsm->ce_end_time);

    /* If we have transmitted the terminate IND successfully, we are done */
    if ((connsm->csmflags.cfbit.terminate_ind_txd) || 
        (connsm->csmflags.cfbit.terminate_ind_rxd)) {
        if (connsm->csmflags.cfbit.terminate_ind_txd) {
            ble_err = BLE_ERR_CONN_TERM_LOCAL;
        } else {
            /* Make sure the disconnect reason is valid! */
            ble_err = connsm->rxd_disconnect_reason;
            if (ble_err == 0) {
                ble_err = BLE_ERR_REM_USER_CONN_TERM;
            } 
        }
        ble_ll_conn_end(connsm, ble_err);
        return;
    }

    /* Remove any connection end events that might be enqueued */
    os_eventq_remove(&g_ble_ll_data.ll_evq, &connsm->conn_ev_end);

    /* 
     * If we have received a packet, we can set the current transmit window
     * usecs to 0 since we dont need to listen in the transmit window.
     */
    if (connsm->csmflags.cfbit.pkt_rxd) {
        connsm->slave_cur_tx_win_usecs = 0;
    }

    /* Move to next connection event */
    if (ble_ll_conn_next_event(connsm)) {
        ble_ll_conn_end(connsm, BLE_ERR_CONN_TERM_LOCAL);
        return;
    }

    /* Reset "per connection event" variables */
    connsm->cons_rxd_bad_crc = 0;
    connsm->csmflags.cfbit.pkt_rxd = 0;

    /* See if we need to start any control procedures */
    ble_ll_ctrl_chk_proc_start(connsm);

    /* Set initial schedule callback */
    connsm->conn_sch.sched_cb = ble_ll_conn_event_start_cb;

    /* XXX: I think all this fine for when we do connection updates, but
       we may want to force the first event to be scheduled. Not sure */
    /* Schedule the next connection event */
    while (ble_ll_sched_conn_reschedule(connsm)) {
        if (ble_ll_conn_next_event(connsm)) {
            ble_ll_conn_end(connsm, BLE_ERR_CONN_TERM_LOCAL);
            return;
        }
    }

    /* If we have completed packets, send an event */
    if (connsm->completed_pkts) {
        ble_ll_conn_num_comp_pkts_event_send();
    }
}

/**
 * Update the connection request PDU with the address type and address of 
 * advertiser we are going to send connect request to. 
 * 
 * @param m 
 * @param adva 
 * @param addr_type 
 * @param txoffset      The tx window offset for this connection 
 */
static void
ble_ll_conn_req_pdu_update(struct os_mbuf *m, uint8_t *adva, uint8_t addr_type,
                           uint16_t txoffset)
{
    uint8_t pdu_type;
    uint8_t *dptr;
    struct ble_mbuf_hdr *ble_hdr;

    assert(m != NULL);

    ble_hdr = BLE_MBUF_HDR_PTR(m);
    pdu_type = ble_hdr->txinfo.hdr_byte;
    if (addr_type) {
        /* Set random address */
        pdu_type |= BLE_ADV_PDU_HDR_RXADD_MASK;
    } else {
        /* Set public device address */
        pdu_type &= ~BLE_ADV_PDU_HDR_RXADD_MASK;
    }

    /* Set BLE transmit header */
    ble_hdr->txinfo.hdr_byte = pdu_type;

    dptr = m->om_data;
    memcpy(dptr + BLE_DEV_ADDR_LEN, adva, BLE_DEV_ADDR_LEN);
    htole16(dptr + 20, txoffset);
}

/* Returns true if the address matches the connection peer address */
static int
ble_ll_conn_is_peer_adv(uint8_t addr_type, uint8_t *adva)
{
    int rc;
    struct ble_ll_conn_sm *connsm;

    /* XXX: Deal with different types of random addresses here! */
    connsm = g_ble_ll_conn_create_sm;
    if (connsm && (connsm->peer_addr_type == addr_type) &&
        !memcmp(adva, connsm->peer_addr, BLE_DEV_ADDR_LEN)) {
        rc = 1;
    } else {
        rc = 0;
    }

    return rc;
}

/**
 * Called when a connect request transmission is done. 
 *  
 * Context: ISR 
 * 
 * @param arg 
 */
static void
ble_ll_conn_req_txend(void *arg)
{
    ble_ll_state_set(BLE_LL_STATE_STANDBY);
}

/**
 * Send a connection requestion to an advertiser 
 *  
 * Context: Interrupt 
 * 
 * @param addr_type Address type of advertiser
 * @param adva Address of advertiser
 */
static int
ble_ll_conn_request_send(uint8_t addr_type, uint8_t *adva, uint16_t txoffset)
{
    int rc;
    struct os_mbuf *m;

    m = ble_ll_scan_get_pdu();
    ble_ll_conn_req_pdu_update(m, adva, addr_type, txoffset);
    ble_phy_set_txend_cb(ble_ll_conn_req_txend, NULL);
    rc = ble_phy_tx(m, BLE_PHY_TRANSITION_RX_TX, BLE_PHY_TRANSITION_NONE);
    return rc;
}

/**
 * Called when a schedule item overlaps the currently running connection 
 * event. This generally should not happen, but if it does we stop the 
 * current connection event to let the schedule item run. 
 *  
 * NOTE: the phy has been disabled as well as the wfr timer before this is 
 * called. 
 */
void
ble_ll_conn_event_halt(void)
{
    ble_ll_state_set(BLE_LL_STATE_STANDBY);
    if (g_ble_ll_conn_cur_sm) {
        g_ble_ll_conn_cur_sm->csmflags.cfbit.pkt_rxd = 0;
        ble_ll_event_send(&g_ble_ll_conn_cur_sm->conn_ev_end);
        g_ble_ll_conn_cur_sm = NULL;
    }
}

/**
 * Process a received PDU while in the initiating state.
 *  
 * Context: Link Layer task. 
 * 
 * @param pdu_type 
 * @param rxbuf 
 */
void
ble_ll_init_rx_pkt_in(uint8_t *rxbuf, struct ble_mbuf_hdr *ble_hdr)
{
    uint8_t addr_type;
    struct ble_ll_conn_sm *connsm;

    /* Get the connection state machine we are trying to create */
    connsm = g_ble_ll_conn_create_sm;

    /* If we have sent a connect request, we need to enter CONNECTION state*/
    if (connsm && BLE_MBUF_HDR_CRC_OK(ble_hdr) && 
        (ble_hdr->rxinfo.flags & BLE_MBUF_HDR_F_CONN_REQ_TXD)) {
        /* Set address of advertiser to which we are connecting. */
        if (ble_ll_scan_whitelist_enabled()) {
            /* 
             * XXX: need to see if the whitelist tells us exactly what peer
             * addr type we should use? Not sure it matters. If whitelisting
             * is not used the peer addr and type already set
             */ 
            /* Get address type of advertiser */
            if (rxbuf[0] & BLE_ADV_PDU_HDR_TXADD_MASK) {
                addr_type = BLE_HCI_CONN_PEER_ADDR_RANDOM;
            } else {
                addr_type = BLE_HCI_CONN_PEER_ADDR_PUBLIC;
            }

            connsm->peer_addr_type = addr_type;
            memcpy(connsm->peer_addr, rxbuf + BLE_LL_PDU_HDR_LEN, 
                   BLE_DEV_ADDR_LEN);
        }

        /* Connection has been created. Stop scanning */
        g_ble_ll_conn_create_sm = NULL;
        ble_ll_scan_sm_stop(0);
        ble_ll_conn_created(connsm, ble_hdr->end_cputime);
    } else {
        ble_ll_scan_chk_resume();
    }
}

/**
 * Called when a receive PDU has ended and we are in the initiating state.
 *  
 * Context: Interrupt 
 * 
 * @param rxpdu 
 * 
 * @return int 
 *       < 0: Disable the phy after reception.
 *      == 0: Success. Do not disable the PHY.
 *       > 0: Do not disable PHY as that has already been done.
 */
int
ble_ll_init_rx_isr_end(struct os_mbuf *rxpdu, uint8_t crcok)
{
    int rc;
    int chk_send_req;
    uint8_t pdu_type;
    uint8_t addr_type;
    uint8_t *adv_addr;
    uint8_t *init_addr;
    uint8_t *rxbuf;
    struct ble_mbuf_hdr *ble_hdr;

    /* 
     * We have to restart receive if we cant hand up pdu. We return 0 so that
     * the phy does not get disabled.
     */
    if (!rxpdu) {
        ble_phy_rx();
        return 0;
    }

    rc = -1;
    if (!crcok) {
        goto init_rx_isr_exit;
    }

    /* Only interested in ADV IND or ADV DIRECT IND */
    rxbuf = rxpdu->om_data;
    pdu_type = rxbuf[0] & BLE_ADV_PDU_HDR_TYPE_MASK;

    switch (pdu_type) {
    case BLE_ADV_PDU_TYPE_ADV_IND:
        chk_send_req = 1;
        break;
    case BLE_ADV_PDU_TYPE_ADV_DIRECT_IND:
        init_addr = rxbuf + BLE_LL_PDU_HDR_LEN + BLE_DEV_ADDR_LEN;
        addr_type = rxbuf[0] & BLE_ADV_PDU_HDR_RXADD_MASK;
        if (ble_ll_is_our_devaddr(init_addr, addr_type)) {
            chk_send_req = 1;
        } else {
            chk_send_req = 0;
        }
        break;
    default:
        chk_send_req = 0;
        break;
    }

    /* Should we send a connect request? */
    if (chk_send_req) {
        /* Check filter policy */
        adv_addr = rxbuf + BLE_LL_PDU_HDR_LEN;
        if (rxbuf[0] & BLE_ADV_PDU_HDR_TXADD_MASK) {
            addr_type = BLE_HCI_CONN_PEER_ADDR_RANDOM;
        } else {
            addr_type = BLE_HCI_CONN_PEER_ADDR_PUBLIC;
        }

        /* Check filter policy */
        ble_hdr = BLE_MBUF_HDR_PTR(rxpdu);
        if (ble_ll_scan_whitelist_enabled()) {
            /* Check if device is on whitelist. If not, leave */
            if (!ble_ll_whitelist_match(adv_addr, addr_type)) {
                return -1;
            }

            /* Set BLE mbuf header flags */
            ble_hdr->rxinfo.flags |= BLE_MBUF_HDR_F_DEVMATCH;
        } else {
            /* XXX: Resolvable? Deal with those */
            /* XXX: HW device matching? If so, implement */
            /* Must match the connection address */
            if (!ble_ll_conn_is_peer_adv(addr_type, adv_addr)) {
                return -1;
            }
        }

        /* XXX: note: this crashed during interop testing! conn_create_sm=NULL*/
        /* Attempt to schedule new connection. Possible that this might fail */
        if (!ble_ll_sched_master_new(g_ble_ll_conn_create_sm, 
                                   ble_hdr->end_cputime,
                                   BLE_LL_CFG_CONN_INIT_SLOTS)) {
            /* Setup to transmit the connect request */
            rc = ble_ll_conn_request_send(addr_type, adv_addr, 
                                          g_ble_ll_conn_create_sm->tx_win_off);
            if (!rc) {
                ble_hdr->rxinfo.flags |= BLE_MBUF_HDR_F_CONN_REQ_TXD;
                ++g_ble_ll_conn_stats.conn_req_txd;
            }
        } else {
            /* Count # of times we could not set schedule */
            ++g_ble_ll_conn_stats.cant_set_sched;
        }
    }

init_rx_isr_exit:
    if (rc) {
        ble_ll_state_set(BLE_LL_STATE_STANDBY);
    }
    return rc;
}

/**
 * Function called when a timeout has occurred for a connection. There are 
 * two types of timeouts: a connection supervision timeout and control 
 * procedure timeout. 
 *  
 * Context: Link Layer task 
 * 
 * @param connsm 
 * @param ble_err 
 */
void
ble_ll_conn_timeout(struct ble_ll_conn_sm *connsm, uint8_t ble_err)
{
    int was_current;
    os_sr_t sr;

    was_current = 0;
    OS_ENTER_CRITICAL(sr);
    if (g_ble_ll_conn_cur_sm == connsm) {
        ble_ll_conn_current_sm_over();
        was_current = 1;
    }
    OS_EXIT_CRITICAL(sr);

    /* Check if we need to resume scanning */
    if (was_current) {
        ble_ll_scan_chk_resume();
    }

    ble_ll_conn_end(connsm, ble_err);
}

/**
 * Connection supervision timeout. When called, it means that the connection 
 * supervision timeout has been reached. If reached, we end the connection. 
 *  
 * Context: Link Layer 
 * 
 * @param arg Pointer to connection state machine.
 */
void
ble_ll_conn_spvn_timeout(void *arg)
{
    ble_ll_conn_timeout((struct ble_ll_conn_sm *)arg, BLE_ERR_CONN_SPVN_TMO);
}

/**
 * Called when a data channel PDU has started that matches the access 
 * address of the current connection. Note that the CRC of the PDU has not 
 * been checked yet. 
 *  
 * Context: Interrupt 
 */
void
ble_ll_conn_rx_isr_start(void)
{
    struct ble_ll_conn_sm *connsm;

    /* 
     * Disable wait for response timer since we receive a response. We dont
     * care if this is the response we were waiting for or not; the code
     * called at receive end will deal with ending the connection event
     * if needed
     */ 
    ble_ll_wfr_disable();
    connsm = g_ble_ll_conn_cur_sm;
    if (connsm) {
        connsm->csmflags.cfbit.pkt_rxd = 1;
    }
}

/**
 * Called from the Link Layer task when a data PDU has been received
 *  
 * Context: Link layer task 
 * 
 * @param rxpdu Pointer to received pdu
 * @param rxpdu Pointer to ble mbuf header of received pdu
 */
void
ble_ll_conn_rx_data_pdu(struct os_mbuf *rxpdu, struct ble_mbuf_hdr *hdr)
{
    uint8_t hdr_byte;
    uint8_t rxd_sn;
    uint8_t *rxbuf;
    uint16_t acl_len;
    uint16_t acl_hdr;
    uint32_t tmo;
    struct ble_ll_conn_sm *connsm;
    
    if (BLE_MBUF_HDR_CRC_OK(hdr)) {
        /* Count valid received data pdus */
        ++g_ble_ll_stats.rx_valid_data_pdus;

        /* XXX: there is a chance that the connection was thrown away and
           re-used before processing packets here. Fix this. */
        /* We better have a connection state machine */
        connsm = ble_ll_conn_find_active_conn(hdr->rxinfo.handle);
        if (connsm) {
            /* Reset the connection supervision timeout */
            cputime_timer_stop(&connsm->conn_spvn_timer);
            tmo = connsm->supervision_tmo * BLE_HCI_CONN_SPVN_TMO_UNITS * 1000;
            cputime_timer_relative(&connsm->conn_spvn_timer, tmo);

            rxbuf = rxpdu->om_data;
            hdr_byte = rxbuf[0];
            acl_len = rxbuf[1];
            acl_hdr = hdr_byte & BLE_LL_DATA_HDR_LLID_MASK;

            /* Check that the LLID is reasonable */
            if ((acl_hdr == 0) || 
                ((acl_hdr == BLE_LL_LLID_DATA_START) && (acl_len == 0))) {
                ++g_ble_ll_stats.rx_bad_llid;
                goto conn_rx_data_pdu_end;
            }

            /* 
             * If we are a slave, we can only start to use slave latency
             * once we have received a NESN of 1 from the master
             */ 
            if (connsm->conn_role == BLE_LL_CONN_ROLE_SLAVE) {
                if (hdr_byte & BLE_LL_DATA_HDR_NESN_MASK) {
                    connsm->csmflags.cfbit.allow_slave_latency = 1;
                }
            }

            /* 
             * Discard the received PDU if the sequence number is the same
             * as the last received sequence number
             */ 
            rxd_sn = hdr_byte & BLE_LL_DATA_HDR_SN_MASK;
            if (rxd_sn != connsm->last_rxd_sn) {
                /* Update last rxd sn */
                connsm->last_rxd_sn = rxd_sn;

                /* No need to do anything if empty pdu */
                if ((acl_hdr == BLE_LL_LLID_DATA_FRAG) && (acl_len == 0)) {
                    goto conn_rx_data_pdu_end;
                }

                if (acl_hdr == BLE_LL_LLID_CTRL) {
                    /* Process control frame! For now just free */
                    ++g_ble_ll_stats.rx_ctrl_pdus;
                    ble_ll_ctrl_rx_pdu(connsm, rxpdu);
                } else {
                    /* Count # of data frames */
                    ++g_ble_ll_stats.rx_l2cap_pdus;

                    /* NOTE: there should be at least two bytes available */
                    assert(OS_MBUF_LEADINGSPACE(rxpdu) >= 2);
                    os_mbuf_prepend(rxpdu, 2);
                    rxbuf = rxpdu->om_data;

                    acl_hdr = (acl_hdr << 12) | connsm->conn_handle;
                    htole16(rxbuf, acl_hdr);
                    htole16(rxbuf + 2, acl_len);
                    ble_hs_rx_data(rxpdu);
                }

                /* NOTE: we dont free the mbuf since we handed it off! */
                return;
            } else {
                ++g_ble_ll_conn_stats.data_pdu_rx_dup;
            }
        } else {
            ++g_ble_ll_conn_stats.no_conn_sm;
        }
    } else {
        ++g_ble_ll_stats.rx_invalid_data_pdus;
    }

    /* Free buffer */
conn_rx_data_pdu_end:
    os_mbuf_free(rxpdu);
}

/**
 * Called when a packet has been received while in the connection state.
 *  
 * Context: Interrupt
 * 
 * @param rxpdu 
 * @param crcok 
 * 
 * @return int 
 *       < 0: Disable the phy after reception.
 *      == 0: Success. Do not disable the PHY.
 *       > 0: Do not disable PHY as that has already been done.
 */
int
ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu, uint32_t aa)
{
    int rc;
    uint8_t hdr_byte;
    uint8_t hdr_sn;
    uint8_t hdr_nesn;
    uint8_t conn_sn;
    uint8_t conn_nesn;
    uint8_t reply;
    uint32_t ticks;
    struct os_mbuf *txpdu;
    struct os_mbuf_pkthdr *pkthdr;
    struct ble_ll_conn_sm *connsm;
    struct ble_mbuf_hdr *rxhdr;
    struct ble_mbuf_hdr *txhdr;

    /* 
     * We should have a current connection state machine. If we dont, we just
     * hand the packet to the higher layer to count it.
     */
    rc = -1;
    connsm = g_ble_ll_conn_cur_sm;
    if (!connsm) {
        ++g_ble_ll_conn_stats.rx_data_pdu_no_conn;
        goto conn_exit;
    }

    /* Double check access address. Better match connection state machine! */
    if (aa != connsm->access_addr) {
        ++g_ble_ll_conn_stats.rx_data_pdu_bad_aa;
        goto conn_exit;
    }

    /* Set the handle in the ble mbuf header */
    rxhdr = BLE_MBUF_HDR_PTR(rxpdu);
    rxhdr->rxinfo.handle = connsm->conn_handle;

    /* 
     * Check the packet CRC. A connection event can continue even if the
     * received PDU does not pass the CRC check. If we receive two consecutive
     * CRC errors we end the conection event.
     */
    if (!BLE_MBUF_HDR_CRC_OK(rxhdr)) {
        /* 
         * Increment # of consecutively received CRC errors. If more than
         * one we will end the connection event.
         */ 
        ++connsm->cons_rxd_bad_crc;
        if (connsm->cons_rxd_bad_crc >= 2) {
            reply = 0;
        } else {
            if (connsm->conn_role == BLE_LL_CONN_ROLE_MASTER) {
                reply = connsm->last_txd_md;
            } else {
                /* A slave always responds with a packet */
                reply = 1;
            }
        }
    } else {
        /* Reset consecutively received bad crcs (since this one was good!) */
        connsm->cons_rxd_bad_crc = 0;

        /* Store received header byte in state machine  */
        hdr_byte = rxpdu->om_data[0];
        connsm->last_rxd_hdr_byte = hdr_byte;

        ble_ll_log(BLE_LL_LOG_ID_CONN_RX, hdr_byte, connsm->tx_seqnum,
                   connsm->next_exp_seqnum);

        /* 
         * If SN bit from header does not match NESN in connection, this is
         * a resent PDU and should be ignored.
         */ 
        hdr_sn = hdr_byte & BLE_LL_DATA_HDR_SN_MASK;
        conn_nesn = connsm->next_exp_seqnum;
        if ((hdr_sn && conn_nesn) || (!hdr_sn && !conn_nesn)) {
            connsm->next_exp_seqnum ^= 1;
        } else {
            /* Count re-sent PDUs. */
            ++g_ble_ll_conn_stats.rx_resent_pdus;
        }

        /* 
         * Check NESN bit from header. If same as tx seq num, the transmission
         * is acknowledged. Otherwise we need to resend this PDU.
         */
        if (connsm->csmflags.cfbit.pdu_txd) {
            hdr_nesn = hdr_byte & BLE_LL_DATA_HDR_NESN_MASK;
            conn_sn = connsm->tx_seqnum;
            if ((hdr_nesn && conn_sn) || (!hdr_nesn && !conn_sn)) {
                /* We did not get an ACK. Must retry the PDU */
                ++g_ble_ll_conn_stats.data_pdu_txf;
            } else {
                /* Transmit success */
                connsm->tx_seqnum ^= 1;
                ++g_ble_ll_conn_stats.data_pdu_txg;

                /* 
                 * Determine if we should remove packet from queue or if there
                 * are more fragments to send.
                 */
                pkthdr = STAILQ_FIRST(&connsm->conn_txq);
                if (pkthdr) {
                    txpdu = OS_MBUF_PKTHDR_TO_MBUF(pkthdr);
                    txhdr = BLE_MBUF_HDR_PTR(txpdu);

                    /* Did we transmit a TERMINATE_IND? If so, we are done */
                    if (ble_ll_ctrl_is_terminate_ind(txhdr->txinfo.hdr_byte, 
                                                     txpdu->om_data[0])) {
                        connsm->csmflags.cfbit.terminate_ind_txd = 1;
                        STAILQ_REMOVE_HEAD(&connsm->conn_txq, omp_next);
                        os_mbuf_free(txpdu);
                        rc = -1;
                        goto conn_rx_pdu_end;
                    }

                    /* 
                     * Did we transmit a REJECT_IND_EXT? If so we need
                     * to make sure we send the connection update event
                     */
                    if (ble_ll_ctrl_is_reject_ind_ext(txhdr->txinfo.hdr_byte,
                                                      txpdu->om_data[0])) {
                        if (connsm->cur_ctrl_proc == 
                            BLE_LL_CTRL_PROC_CONN_PARAM_REQ) {
                            connsm->reject_reason = txpdu->om_data[2];
                            connsm->csmflags.cfbit.host_expects_upd_event = 1; 
                        }
                    }

                    /* Increment offset based on number of bytes sent */
                    txhdr->txinfo.offset += txhdr->txinfo.pyld_len;
                    if (txhdr->txinfo.offset >= pkthdr->omp_len) {
                        STAILQ_REMOVE_HEAD(&connsm->conn_txq, omp_next);

                        /* If l2cap pdu, increment # of completed packets */
                        if (ble_ll_conn_is_l2cap_pdu(txhdr)) {
                            ++connsm->completed_pkts;
                        }
                        os_mbuf_free(txpdu);
                    } else {
                        /* More to go. Clear the TXD flag */
                        txhdr->txinfo.flags &= ~BLE_MBUF_HDR_F_TXD;
                    }
                } else {
                    /* No packet on queue? This is an error! */
                    ++g_ble_ll_conn_stats.no_tx_pdu;
                }
            }
        }

        /* Should we continue connection event? */
        /* If this is a TERMINATE_IND, we have to reply */
        if (ble_ll_ctrl_is_terminate_ind(rxpdu->om_data[0],rxpdu->om_data[2])) {
            connsm->csmflags.cfbit.terminate_ind_rxd = 1;
            connsm->rxd_disconnect_reason = rxpdu->om_data[3];
            reply = 1;
        } else if (connsm->conn_role == BLE_LL_CONN_ROLE_MASTER) {
            reply = connsm->last_txd_md || (hdr_byte & BLE_LL_DATA_HDR_MD_MASK);
        } else {
            /* A slave always replies */
            reply = 1;
        }
    }

    /* If reply flag set, send data pdu and continue connection event */
    rc = -1;
    if (reply && ble_ll_conn_can_send_next_pdu(connsm, rxhdr->end_cputime)) {
        /* 
         * While this is not perfect, we will just check to see if the
         * terminate timer will expire within two packet times. If it will,
         * no use sending the terminate ind. We need to get an ACK for the
         * terminate ind (master and/or slave) so that is why it is two packets.
         */ 
        if (IS_PENDING_CTRL_PROC(connsm, BLE_LL_CTRL_PROC_TERMINATE)) {
            ticks = BLE_TX_DUR_USECS_M(0) +
                BLE_TX_DUR_USECS_M(BLE_LL_CTRL_TERMINATE_IND_LEN + 1) + 
                BLE_LL_IFS;
            ticks = cputime_usecs_to_ticks(ticks) + cputime_get32();
            if ((int32_t)(connsm->terminate_timeout - ticks) < 0) {
                goto conn_rx_pdu_end;
            }
        }
        rc = ble_ll_conn_tx_data_pdu(connsm, BLE_PHY_TRANSITION_RX_TX);
    }

conn_rx_pdu_end:
    /* Set anchor point (and last) if 1st received frame in connection event */
    if (connsm->csmflags.cfbit.slave_set_last_anchor) {
        connsm->csmflags.cfbit.slave_set_last_anchor = 0;
        connsm->last_anchor_point = rxhdr->end_cputime - 
            cputime_usecs_to_ticks(BLE_TX_DUR_USECS_M(rxpdu->om_data[1]));
        connsm->anchor_point = connsm->last_anchor_point;
    }

    /* Send link layer a connection end event if over */
conn_exit:
    if (rc) {
        ble_ll_conn_current_sm_over();
        if (connsm) {
            ble_ll_event_send(&connsm->conn_ev_end);
        }
    }

    return rc;
}

/**
 * Called to enqueue a packet on the transmit queue of a connection. Should 
 * only be called by the controller. 
 *  
 * Context: Link Layer 
 * 
 * 
 * @param connsm 
 * @param om 
 */
void 
ble_ll_conn_enqueue_pkt(struct ble_ll_conn_sm *connsm, struct os_mbuf *om,
                        uint8_t hdr_byte, uint8_t length)
{
    os_sr_t sr;
    struct os_mbuf_pkthdr *pkthdr;
    struct ble_mbuf_hdr *ble_hdr;

    /* Initialize the mbuf */
    ble_ll_mbuf_init(om, length, hdr_byte);

    /* 
     * We need to set the initial payload length if the total length of the
     * PDU exceeds the maximum allowed for the connection for any single tx.
     */
    if (length > connsm->eff_max_tx_octets) {
        ble_hdr = BLE_MBUF_HDR_PTR(om);
        ble_hdr->txinfo.pyld_len = connsm->eff_max_tx_octets;
    }

    /* Add to transmit queue for the connection */
    pkthdr = OS_MBUF_PKTHDR(om);
    OS_ENTER_CRITICAL(sr);
    STAILQ_INSERT_TAIL(&connsm->conn_txq, pkthdr, omp_next);
    OS_EXIT_CRITICAL(sr);
}

/**
 * Data packet from host. 
 *  
 * Context: Link Layer task 
 * 
 * @param om 
 * @param handle 
 * @param length 
 * 
 * @return int 
 */
void
ble_ll_conn_tx_pkt_in(struct os_mbuf *om, uint16_t handle, uint16_t length)
{
    uint8_t hdr_byte;
    uint16_t conn_handle;
    uint16_t pb;
    struct ble_ll_conn_sm *connsm;

    /* See if we have an active matching connection handle */
    conn_handle = handle & 0x0FFF;
    connsm = ble_ll_conn_find_active_conn(conn_handle);
    if (connsm) {
        /* Construct LL header in buffer (NOTE: pb already checked) */
        pb = handle & 0x3000;
        if (pb == 0) {
            hdr_byte = BLE_LL_LLID_DATA_START;
        } else {
            hdr_byte = BLE_LL_LLID_DATA_FRAG;
        }

        /* Add to total l2cap pdus enqueue */
        ++g_ble_ll_conn_stats.l2cap_enqueued;

        /* Clear flags field in BLE header */
        ble_ll_conn_enqueue_pkt(connsm, om, hdr_byte, length);
    } else {
        /* No connection found! */
        ++g_ble_ll_conn_stats.handle_not_found;
        os_mbuf_free(om);
    }
}

/**
 * Called when a device has received a connect request while advertising and 
 * the connect request has passed the advertising filter policy and is for 
 * us. This will start a connection in the slave role assuming that we dont 
 * already have a connection with this device and that the connect request 
 * parameters are valid. 
 *  
 * Context: Link Layer 
 *  
 * @param rxbuf Pointer to received Connect Request PDU
 * @param conn_req_end receive end time of connect request 
 *  
 * @return 0: connection not started; 1 connecton started 
 */
int
ble_ll_conn_slave_start(uint8_t *rxbuf, uint32_t conn_req_end)
{
    int rc;
    uint32_t temp;
    uint32_t crcinit;
    uint8_t *inita;
    uint8_t *dptr;
    uint8_t addr_type;
    struct ble_ll_conn_sm *connsm;

    /* Ignore the connection request if we are already connected*/
    inita = rxbuf + BLE_LL_PDU_HDR_LEN;
    SLIST_FOREACH(connsm, &g_ble_ll_conn_active_list, act_sle) {
        if (!memcmp(&connsm->peer_addr, inita, BLE_DEV_ADDR_LEN)) {
            if (rxbuf[0] & BLE_ADV_PDU_HDR_TXADD_MASK) {
                addr_type = BLE_HCI_CONN_PEER_ADDR_RANDOM;
            } else {
                addr_type = BLE_HCI_CONN_PEER_ADDR_PUBLIC;
            }
            if (connsm->peer_addr_type == addr_type) {
                return 0;
            }
        }
    }

    /* Allocate a connection. If none available, dont do anything */
    connsm = ble_ll_conn_sm_get();
    if (connsm == NULL) {
        return 0;
    }

    /* Set the pointer at the start of the connection data */
    dptr = rxbuf + BLE_LL_CONN_REQ_ADVA_OFF + BLE_DEV_ADDR_LEN;

    /* Set connection state machine information */
    connsm->access_addr = le32toh(dptr);
    crcinit = dptr[6];
    crcinit = (crcinit << 8) | dptr[5];
    crcinit = (crcinit << 8) | dptr[4];
    connsm->crcinit = crcinit;
    connsm->tx_win_size = dptr[7];
    connsm->tx_win_off = le16toh(dptr + 8);
    connsm->conn_itvl = le16toh(dptr + 10);
    connsm->slave_latency = le16toh(dptr + 12);
    connsm->supervision_tmo = le16toh(dptr + 14);
    memcpy(&connsm->chanmap, dptr + 16, BLE_LL_CONN_CHMAP_LEN);
    connsm->hop_inc = dptr[21] & 0x1F;
    connsm->master_sca = dptr[21] >> 5;

    /* Error check parameters */
    if ((connsm->tx_win_off > connsm->conn_itvl) ||
        (connsm->conn_itvl < BLE_HCI_CONN_ITVL_MIN) ||
        (connsm->conn_itvl > BLE_HCI_CONN_ITVL_MAX) ||
        (connsm->tx_win_size < BLE_LL_CONN_TX_WIN_MIN) ||
        (connsm->slave_latency > BLE_LL_CONN_SLAVE_LATENCY_MAX)) {
        goto err_slave_start;
    }

    /* Slave latency cannot cause a supervision timeout */
    temp = (connsm->slave_latency + 1) * (connsm->conn_itvl * 2) * 
            BLE_LL_CONN_ITVL_USECS;
    if ((connsm->supervision_tmo * 10000) <= temp ) {
        goto err_slave_start;
    }

    /* 
     * The transmit window must be less than or equal to the lesser of 10 
     * msecs or the connection interval minus 1.25 msecs.
     */ 
    temp = connsm->conn_itvl - 1;
    if (temp > 8) {
        temp = 8;
    }
    if (connsm->tx_win_size > temp) {
        goto err_slave_start;
    }

    /* XXX: might want to set this differently based on adv. filter policy! */
    /* Set the address of device that we are connecting with */
    memcpy(&connsm->peer_addr, rxbuf + BLE_LL_PDU_HDR_LEN, BLE_DEV_ADDR_LEN);
    if (rxbuf[0] & BLE_ADV_PDU_HDR_TXADD_MASK) {
        connsm->peer_addr_type = BLE_HCI_CONN_PEER_ADDR_RANDOM;
    } else {
        connsm->peer_addr_type = BLE_HCI_CONN_PEER_ADDR_PUBLIC;
    }

    /* Calculate number of used channels; make sure it meets min requirement */
    connsm->num_used_chans = ble_ll_conn_calc_used_chans(connsm->chanmap);
    if (connsm->num_used_chans < 2) {
        goto err_slave_start;
    }

    /* Start the connection state machine */
    connsm->conn_role = BLE_LL_CONN_ROLE_SLAVE;
    ble_ll_conn_sm_new(connsm);

    /* Set initial schedule callback */
    connsm->conn_sch.sched_cb = ble_ll_conn_event_start_cb;

    rc = ble_ll_conn_created(connsm, conn_req_end);
    if (!rc) {
        SLIST_REMOVE(&g_ble_ll_conn_active_list, connsm, ble_ll_conn_sm, act_sle);
        STAILQ_INSERT_TAIL(&g_ble_ll_conn_free_list, connsm, free_stqe);
    }
    return rc;

err_slave_start:
    STAILQ_INSERT_TAIL(&g_ble_ll_conn_free_list, connsm, free_stqe);
    ++g_ble_ll_conn_stats.slave_rxd_bad_conn_req_params;
    return 0;
}

/**
 * Called to reset the connection module. When this function is called the 
 * scheduler has been stopped and the phy has been disabled. The LL should 
 * be in the standby state. 
 *  
 * Context: Link Layer task 
 */
void
ble_ll_conn_reset(void)
{
    struct ble_ll_conn_sm *connsm;

    /* Kill the current one first (if one is running) */
    if (g_ble_ll_conn_cur_sm) {
        connsm = g_ble_ll_conn_cur_sm;
        g_ble_ll_conn_cur_sm = NULL;
        ble_ll_conn_end(connsm, BLE_ERR_SUCCESS);
    }

    /* Now go through and end all the connections */
    while (1) {
        connsm = SLIST_FIRST(&g_ble_ll_conn_active_list);
        if (!connsm) {
            break;
        }
        ble_ll_conn_end(connsm, BLE_ERR_SUCCESS);
    }
}

/* Initialize the connection module */
void
ble_ll_conn_module_init(void)
{
    uint16_t i;
    uint16_t maxbytes;
    struct os_mbuf *m;
    struct ble_ll_conn_sm *connsm;
    struct ble_ll_conn_global_params *conn_params;

    /* Initialize list of active conections */
    SLIST_INIT(&g_ble_ll_conn_active_list);
    STAILQ_INIT(&g_ble_ll_conn_free_list);

    /* 
     * Take all the connections off the free memory pool and add them to
     * the free connection list, assigning handles in linear order. Note:
     * the specification allows a handle of zero; we just avoid using it.
     */
    connsm = &g_ble_ll_conn_sm[0];
    for (i = 0; i < BLE_LL_CFG_CONN_MAX_CONNS; ++i) {
        memset(connsm, 0, sizeof(struct ble_ll_conn_sm));

        connsm->conn_handle = i + 1;
        STAILQ_INSERT_TAIL(&g_ble_ll_conn_free_list, connsm, free_stqe);

        /* Initialize empty pdu */
        m = (struct os_mbuf *)&connsm->conn_empty_pdu;
        m->om_data = (uint8_t *)&connsm->conn_empty_pdu[0];
        m->om_data += BLE_MBUF_MEMBLOCK_OVERHEAD;
        m->om_pkthdr_len = sizeof(struct ble_mbuf_hdr) + 
            sizeof(struct os_mbuf_pkthdr);
        m->om_omp = NULL;
        m->om_flags = 0;

        ble_ll_mbuf_init(m, 0, BLE_LL_LLID_DATA_FRAG);

        /* Initialize fixed schedule elements */
        connsm->conn_sch.sched_type = BLE_LL_SCHED_TYPE_CONN;
        connsm->conn_sch.cb_arg = connsm;
        ++connsm;
    }

    /* Configure the global LL parameters */
    conn_params = &g_ble_ll_conn_params;
    maxbytes = BLE_LL_CFG_SUPP_MAX_RX_BYTES + BLE_LL_DATA_MIC_LEN;
    conn_params->supp_max_rx_time = BLE_TX_DUR_USECS_M(maxbytes);
    conn_params->supp_max_rx_octets = BLE_LL_CFG_SUPP_MAX_RX_BYTES;

    maxbytes = BLE_LL_CFG_SUPP_MAX_TX_BYTES + BLE_LL_DATA_MIC_LEN;
    conn_params->supp_max_tx_time = BLE_TX_DUR_USECS_M(maxbytes);
    conn_params->supp_max_tx_octets = BLE_LL_CFG_SUPP_MAX_TX_BYTES;

    maxbytes = BLE_LL_CFG_CONN_INIT_MAX_TX_BYTES + BLE_LL_DATA_MIC_LEN;
    conn_params->conn_init_max_tx_time = BLE_TX_DUR_USECS_M(maxbytes);
    conn_params->conn_init_max_tx_octets = BLE_LL_CFG_CONN_INIT_MAX_TX_BYTES;
}