DragonFlyBSD Kernel Audit
sys/netgraph7/bluetooth/socket/ng_btsocket_rfcomm.c
← back
   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
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
/*
 * ng_btsocket_rfcomm.c
 */

/*-
 * Copyright (c) 2001-2003 Maksim Yevmenkin <m_evmenkin@yahoo.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: ng_btsocket_rfcomm.c,v 1.28 2003/09/14 23:29:06 max Exp $
 * $FreeBSD: src/sys/netgraph/bluetooth/socket/ng_btsocket_rfcomm.c,v 1.27 2007/10/29 19:06:47 emax Exp $
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bitstring.h>
#include <sys/domain.h>
#include <sys/endian.h>
#include <sys/errno.h>
#include <sys/filedesc.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/proc.h>
#include <sys/protosw.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sysctl.h>
#include <sys/taskqueue.h>
#include <sys/uio.h>
#include <sys/msgport2.h>
#include <sys/fcntl.h>
#include <sys/socketvar2.h>
#include <net/netmsg2.h>
#include <netgraph7/ng_message.h>
#include <netgraph7/netgraph.h>
#include <netgraph7/bluetooth/include/ng_bluetooth.h>
#include <netgraph7/bluetooth/include/ng_hci.h>
#include <netgraph7/bluetooth/include/ng_l2cap.h>
#include <netgraph7/bluetooth/include/ng_btsocket.h>
#include <netgraph7/bluetooth/include/ng_btsocket_l2cap.h>
#include <netgraph7/bluetooth/include/ng_btsocket_rfcomm.h>

/* MALLOC define */
#ifdef NG_SEPARATE_MALLOC
MALLOC_DEFINE(M_NETGRAPH_BTSOCKET_RFCOMM, "netgraph_btsocks_rfcomm",
		"Netgraph Bluetooth RFCOMM sockets");
#else
#define M_NETGRAPH_BTSOCKET_RFCOMM M_NETGRAPH
#endif /* NG_SEPARATE_MALLOC */

/* Debug */
#define NG_BTSOCKET_RFCOMM_INFO \
	if (ng_btsocket_rfcomm_debug_level >= NG_BTSOCKET_INFO_LEVEL) \
		kprintf

#define NG_BTSOCKET_RFCOMM_WARN \
	if (ng_btsocket_rfcomm_debug_level >= NG_BTSOCKET_WARN_LEVEL) \
		kprintf

#define NG_BTSOCKET_RFCOMM_ERR \
	if (ng_btsocket_rfcomm_debug_level >= NG_BTSOCKET_ERR_LEVEL) \
		kprintf

#define NG_BTSOCKET_RFCOMM_ALERT \
	if (ng_btsocket_rfcomm_debug_level >= NG_BTSOCKET_ALERT_LEVEL) \
		kprintf

#define	ALOT	0x7fff

/* Local prototypes */
static void ng_btsocket_rfcomm_upcall
	(struct socket *so, void *arg, int waitflag);
static void ng_btsocket_rfcomm_sessions_task
	(void *ctx, int pending);
static void ng_btsocket_rfcomm_session_task
	(ng_btsocket_rfcomm_session_p s);
#define ng_btsocket_rfcomm_task_wakeup() \
	taskqueue_enqueue(taskqueue_swi, &ng_btsocket_rfcomm_task)

static ng_btsocket_rfcomm_pcb_p ng_btsocket_rfcomm_connect_ind
	(ng_btsocket_rfcomm_session_p s, int channel);
static void ng_btsocket_rfcomm_connect_cfm
	(ng_btsocket_rfcomm_session_p s);

static int ng_btsocket_rfcomm_session_create
	(ng_btsocket_rfcomm_session_p *sp, struct socket *l2so,
	 bdaddr_p src, bdaddr_p dst, struct thread *td);
static int ng_btsocket_rfcomm_session_accept
	(ng_btsocket_rfcomm_session_p s0);
static int ng_btsocket_rfcomm_session_connect
	(ng_btsocket_rfcomm_session_p s);
static int ng_btsocket_rfcomm_session_receive
	(ng_btsocket_rfcomm_session_p s);
static int ng_btsocket_rfcomm_session_send
	(ng_btsocket_rfcomm_session_p s);
static void ng_btsocket_rfcomm_session_clean
	(ng_btsocket_rfcomm_session_p s);
static void ng_btsocket_rfcomm_session_process_pcb
	(ng_btsocket_rfcomm_session_p s);
static ng_btsocket_rfcomm_session_p ng_btsocket_rfcomm_session_by_addr
	(bdaddr_p src, bdaddr_p dst);

static int ng_btsocket_rfcomm_receive_frame
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_sabm
	(ng_btsocket_rfcomm_session_p s, int dlci);
static int ng_btsocket_rfcomm_receive_disc
	(ng_btsocket_rfcomm_session_p s, int dlci);
static int ng_btsocket_rfcomm_receive_ua
	(ng_btsocket_rfcomm_session_p s, int dlci);
static int ng_btsocket_rfcomm_receive_dm
	(ng_btsocket_rfcomm_session_p s, int dlci);
static int ng_btsocket_rfcomm_receive_uih
	(ng_btsocket_rfcomm_session_p s, int dlci, int pf, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_mcc
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_test
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_fc
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_msc
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_rpn
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_rls
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static int ng_btsocket_rfcomm_receive_pn
	(ng_btsocket_rfcomm_session_p s, struct mbuf *m0);
static void ng_btsocket_rfcomm_set_pn
	(ng_btsocket_rfcomm_pcb_p pcb, u_int8_t cr, u_int8_t flow_control, 
	 u_int8_t credits, u_int16_t mtu);

static int ng_btsocket_rfcomm_send_command
	(ng_btsocket_rfcomm_session_p s, u_int8_t type, u_int8_t dlci);
static int ng_btsocket_rfcomm_send_uih
	(ng_btsocket_rfcomm_session_p s, u_int8_t address, u_int8_t pf, 
	 u_int8_t credits, struct mbuf *data);
static int ng_btsocket_rfcomm_send_msc
	(ng_btsocket_rfcomm_pcb_p pcb);
static int ng_btsocket_rfcomm_send_pn
	(ng_btsocket_rfcomm_pcb_p pcb);
static int ng_btsocket_rfcomm_send_credits
	(ng_btsocket_rfcomm_pcb_p pcb);

static int ng_btsocket_rfcomm_pcb_send
	(ng_btsocket_rfcomm_pcb_p pcb, int limit);
static void ng_btsocket_rfcomm_pcb_kill
	(ng_btsocket_rfcomm_pcb_p pcb, int error);
static ng_btsocket_rfcomm_pcb_p ng_btsocket_rfcomm_pcb_by_dlci
	(ng_btsocket_rfcomm_session_p s, int dlci);
static ng_btsocket_rfcomm_pcb_p ng_btsocket_rfcomm_pcb_listener
	(bdaddr_p src, int channel);

static void ng_btsocket_rfcomm_timeout
	(ng_btsocket_rfcomm_pcb_p pcb);
static void ng_btsocket_rfcomm_untimeout
	(ng_btsocket_rfcomm_pcb_p pcb);
static void ng_btsocket_rfcomm_process_timeout
	(void *xpcb);

static struct mbuf * ng_btsocket_rfcomm_prepare_packet
	(struct sockbuf *sb, int length);

/* Globals */
extern int					ifqmaxlen;
static u_int32_t				ng_btsocket_rfcomm_debug_level;
static u_int32_t				ng_btsocket_rfcomm_timo;
struct task					ng_btsocket_rfcomm_task;
static LIST_HEAD(, ng_btsocket_rfcomm_session)	ng_btsocket_rfcomm_sessions;
static struct lock				ng_btsocket_rfcomm_sessions_lock;
static LIST_HEAD(, ng_btsocket_rfcomm_pcb)	ng_btsocket_rfcomm_sockets;
static struct lock				ng_btsocket_rfcomm_sockets_lock;

/* Sysctl tree */
SYSCTL_DECL(_net_bluetooth_rfcomm_sockets);
SYSCTL_NODE(_net_bluetooth_rfcomm_sockets, OID_AUTO, stream, CTLFLAG_RW,
	0, "Bluetooth STREAM RFCOMM sockets family");
SYSCTL_INT(_net_bluetooth_rfcomm_sockets_stream, OID_AUTO, debug_level,
	CTLFLAG_RW,
	&ng_btsocket_rfcomm_debug_level, NG_BTSOCKET_INFO_LEVEL,
	"Bluetooth STREAM RFCOMM sockets debug level");
SYSCTL_INT(_net_bluetooth_rfcomm_sockets_stream, OID_AUTO, timeout,
	CTLFLAG_RW,
	&ng_btsocket_rfcomm_timo, 60,
	"Bluetooth STREAM RFCOMM sockets timeout");

/*****************************************************************************
 *****************************************************************************
 **                              RFCOMM CRC
 *****************************************************************************
 *****************************************************************************/

static u_int8_t	ng_btsocket_rfcomm_crc_table[256] = {
	0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75,
	0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b,
	0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69,
	0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67,

	0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d,
	0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43,
	0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51,
	0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f,

	0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05,
	0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b,
	0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19,
	0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17,

	0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d,
	0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33,
	0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21,
	0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f,

	0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95,
	0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b,
	0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89,
	0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87,

	0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad,
	0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3,
	0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1,
	0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf,

	0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5,
	0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb,
	0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9,
	0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7,

	0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd,
	0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3,
	0xb4, 0x25, 0x57, 0xc6, 0xb3, 0x22, 0x50, 0xc1,
	0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf
};

/* CRC */
static u_int8_t
ng_btsocket_rfcomm_crc(u_int8_t *data, int length)
{
	u_int8_t	crc = 0xff;

	while (length --)
		crc = ng_btsocket_rfcomm_crc_table[crc ^ *data++];

	return (crc);
} /* ng_btsocket_rfcomm_crc */

/* FCS on 2 bytes */
static u_int8_t
ng_btsocket_rfcomm_fcs2(u_int8_t *data)
{
	return (0xff - ng_btsocket_rfcomm_crc(data, 2));
} /* ng_btsocket_rfcomm_fcs2 */
  
/* FCS on 3 bytes */
static u_int8_t
ng_btsocket_rfcomm_fcs3(u_int8_t *data)
{
	return (0xff - ng_btsocket_rfcomm_crc(data, 3));
} /* ng_btsocket_rfcomm_fcs3 */

/* 
 * Check FCS
 *
 * From Bluetooth spec
 *
 * "... In 07.10, the frame check sequence (FCS) is calculated on different 
 * sets of fields for different frame types. These are the fields that the 
 * FCS are calculated on:
 *
 * For SABM, DISC, UA, DM frames: on Address, Control and length field.
 * For UIH frames: on Address and Control field.
 *
 * (This is stated here for clarification, and to set the standard for RFCOMM;
 * the fields included in FCS calculation have actually changed in version
 * 7.0.0 of TS 07.10, but RFCOMM will not change the FCS calculation scheme
 * from the one above.) ..."
 */

static int
ng_btsocket_rfcomm_check_fcs(u_int8_t *data, int type, u_int8_t fcs)
{
	if (type != RFCOMM_FRAME_UIH)
		return (ng_btsocket_rfcomm_fcs3(data) != fcs);

	return (ng_btsocket_rfcomm_fcs2(data) != fcs);
} /* ng_btsocket_rfcomm_check_fcs */

/*****************************************************************************
 *****************************************************************************
 **                              Socket interface
 *****************************************************************************
 *****************************************************************************/

/* 
 * Initialize everything
 */

void
ng_btsocket_rfcomm_init(void)
{
	ng_btsocket_rfcomm_debug_level = NG_BTSOCKET_WARN_LEVEL;
	ng_btsocket_rfcomm_timo = 60;

	/* RFCOMM task */
	TASK_INIT(&ng_btsocket_rfcomm_task, 0,
		ng_btsocket_rfcomm_sessions_task, NULL);

	/* RFCOMM sessions list */
	LIST_INIT(&ng_btsocket_rfcomm_sessions);
	lockinit(&ng_btsocket_rfcomm_sessions_lock,
		"btsocks_rfcomm_sessions_lock", 0, 0);

	/* RFCOMM sockets list */
	LIST_INIT(&ng_btsocket_rfcomm_sockets);
	lockinit(&ng_btsocket_rfcomm_sockets_lock,
		"btsocks_rfcomm_sockets_lock", 0, 0);
} /* ng_btsocket_rfcomm_init */

/*
 * Abort connection on socket
 */

void
ng_btsocket_rfcomm_abort(netmsg_t msg)
{
	struct socket			*so = msg->abort.base.nm_so;

	so->so_error = ECONNABORTED;
	ng_btsocket_rfcomm_disconnect(msg);
} /* ng_btsocket_rfcomm_abort */

#if 0 /* XXX */
void
ng_btsocket_rfcomm_close(struct socket *so)
{

	(void)ng_btsocket_rfcomm_disconnect(so);
} /* ng_btsocket_rfcomm_close */
#endif

/*
 * Accept connection on socket. Nothing to do here, socket must be connected
 * and ready, so just return peer address and be done with it.
 */

void
ng_btsocket_rfcomm_accept(netmsg_t msg)
{
	ng_btsocket_rfcomm_peeraddr(msg);
} /* ng_btsocket_rfcomm_accept */

/*
 * Create and attach new socket
 */

void
ng_btsocket_rfcomm_attach(netmsg_t msg)
{
	struct socket			*so = msg->attach.base.nm_so;
	ng_btsocket_rfcomm_pcb_p	 pcb = so2rfcomm_pcb(so);
	int				 error = 0;

	/* Check socket and protocol */
	if (so->so_type != SOCK_STREAM) {
		error = ESOCKTNOSUPPORT;
		goto out;
	}

#if 0 /* XXX sonewconn() calls "pru_attach" with proto == 0 */
	if (proto != 0) 
		if (proto != BLUETOOTH_PROTO_RFCOMM) {
			error = EPROTONOSUPPORT;
			goto out;
		}
#endif /* XXX */

	if (pcb != NULL) {
		error = EISCONN;
		goto out;
	}

	/* Reserve send and receive space if it is not reserved yet */
	if ((so->so_snd.ssb_hiwat == 0) || (so->so_rcv.ssb_hiwat == 0)) {
		error = soreserve(so, NG_BTSOCKET_RFCOMM_SENDSPACE,
					NG_BTSOCKET_RFCOMM_RECVSPACE, NULL);
		if (error != 0)
			goto out;
	}

	/* Allocate the PCB */
        pcb = kmalloc(sizeof(*pcb), M_NETGRAPH_BTSOCKET_RFCOMM,
		      M_WAITOK | M_NULLOK | M_ZERO);
        if (pcb == NULL) {
		error = ENOMEM;
		goto out;
	}

	/* Link the PCB and the socket */
	so->so_pcb = (caddr_t) pcb;
	pcb->so = so;

	/* Initialize PCB */
	pcb->state = NG_BTSOCKET_RFCOMM_DLC_CLOSED;
	pcb->flags = NG_BTSOCKET_RFCOMM_DLC_CFC;

	pcb->lmodem =
	pcb->rmodem = (RFCOMM_MODEM_RTC | RFCOMM_MODEM_RTR | RFCOMM_MODEM_DV);

	pcb->mtu = RFCOMM_DEFAULT_MTU;
	pcb->tx_cred = 0;
	pcb->rx_cred = RFCOMM_DEFAULT_CREDITS;

	lockinit(&pcb->pcb_lock, "btsocks_rfcomm_pcb_lock", 0, 0);
	callout_init_mp(&pcb->timo);

	/* Add the PCB to the list */
	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_EXCLUSIVE);
	LIST_INSERT_HEAD(&ng_btsocket_rfcomm_sockets, pcb, next);
	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);

out:
	lwkt_replymsg(&msg->attach.base.lmsg, error);
} /* ng_btsocket_rfcomm_attach */

/*
 * Bind socket
 */

void
ng_btsocket_rfcomm_bind(netmsg_t msg)
{
	struct socket			*so = msg->bind.base.nm_so;
	struct sockaddr			*nam = msg->bind.nm_nam;
	ng_btsocket_rfcomm_pcb_t	*pcb = so2rfcomm_pcb(so), *pcb1;
	struct sockaddr_rfcomm		*sa = (struct sockaddr_rfcomm *) nam;
	int				 error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}

	/* Verify address */
	if (sa == NULL) {
		error = EINVAL;
		goto out;
	}
	if (sa->rfcomm_family != AF_BLUETOOTH) {
		error = EAFNOSUPPORT;
		goto out;
	}
	if (sa->rfcomm_len != sizeof(*sa)) {
		error = EINVAL;
		goto out;
	}
	if (sa->rfcomm_channel > 30) {
		error = EINVAL;
		goto out;
	}

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	if (sa->rfcomm_channel != 0) {
		lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_EXCLUSIVE);

		LIST_FOREACH(pcb1, &ng_btsocket_rfcomm_sockets, next) {
			if (pcb1->channel == sa->rfcomm_channel &&
			    bcmp(&pcb1->src, &sa->rfcomm_bdaddr,
					sizeof(pcb1->src)) == 0) {
				lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);
				lockmgr(&pcb->pcb_lock, LK_RELEASE);

				error = EADDRINUSE;
				goto out;
			}
		}

		lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);
	}

	bcopy(&sa->rfcomm_bdaddr, &pcb->src, sizeof(pcb->src));
	pcb->channel = sa->rfcomm_channel;

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

out:
	lwkt_replymsg(&msg->bind.base.lmsg, error);
} /* ng_btsocket_rfcomm_bind */

/*
 * Connect socket
 */

void
ng_btsocket_rfcomm_connect(netmsg_t msg)
{
	struct socket			*so = msg->connect.base.nm_so;
	struct sockaddr			*nam = msg->connect.nm_nam;
	struct thread			*td = msg->connect.nm_td;
	ng_btsocket_rfcomm_pcb_t	*pcb = so2rfcomm_pcb(so);
	struct sockaddr_rfcomm		*sa = (struct sockaddr_rfcomm *) nam;
	ng_btsocket_rfcomm_session_t	*s = NULL;
	struct socket			*l2so = NULL;
	int				 dlci, error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}

	/* Verify address */
	if (sa == NULL) {
		error = EINVAL;
		goto out;
	}
	if (sa->rfcomm_family != AF_BLUETOOTH) {
		error = EAFNOSUPPORT;
		goto out;
	}
	if (sa->rfcomm_len != sizeof(*sa)) {
		error = EINVAL;
		goto out;
	}
	if (sa->rfcomm_channel > 30) {
		error = EINVAL;
		goto out;
	}
	if (sa->rfcomm_channel == 0 ||
	    bcmp(&sa->rfcomm_bdaddr, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0) {
		error = EDESTADDRREQ;
		goto out;
	}

	/*
	 * XXX FIXME - This is FUBAR. socreate() will call soalloc(1), i.e.
	 * soalloc() is allowed to sleep in MALLOC. This creates "could sleep"
	 * WITNESS warnings. To work around this problem we will create L2CAP
	 * socket first and then check if we actually need it. Note that we 
	 * will not check for errors in socreate() because if we failed to 
	 * create L2CAP socket at this point we still might have already open
	 * session.
	 */

	error = socreate(PF_BLUETOOTH, &l2so, SOCK_SEQPACKET,
			BLUETOOTH_PROTO_L2CAP, td);

	/* 
	 * Look for session between "pcb->src" and "sa->rfcomm_bdaddr" (dst)
	 */

	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_EXCLUSIVE);

	s = ng_btsocket_rfcomm_session_by_addr(&pcb->src, &sa->rfcomm_bdaddr);
	if (s == NULL) {
		/*
		 * We need to create new RFCOMM session. Check if we have L2CAP
		 * socket. If l2so == NULL then error has the error code from
		 * socreate()
		 */

		if (l2so == NULL) {
			lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);
			goto out;
		}

		error = ng_btsocket_rfcomm_session_create(&s, l2so,
				&pcb->src, &sa->rfcomm_bdaddr, td);
		if (error != 0) {
			lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);
			soclose(l2so, FNONBLOCK);

			goto out;
		}
	} else if (l2so != NULL)
		soclose(l2so, FNONBLOCK); /* we don't need new L2CAP socket */

	/*
	 * Check if we already have the same DLCI the the same session
	 */

	lockmgr(&s->session_lock, LK_EXCLUSIVE);
	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	dlci = RFCOMM_MKDLCI(!INITIATOR(s), sa->rfcomm_channel);

	if (ng_btsocket_rfcomm_pcb_by_dlci(s, dlci) != NULL) {
		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		lockmgr(&s->session_lock, LK_RELEASE);
		lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);

		error = EBUSY;
		goto out;
	}

	/*
	 * Check session state and if its not acceptable then refuse connection
	 */

	switch (s->state) {
	case NG_BTSOCKET_RFCOMM_SESSION_CONNECTING:
	case NG_BTSOCKET_RFCOMM_SESSION_CONNECTED:
	case NG_BTSOCKET_RFCOMM_SESSION_OPEN:
		/*
		 * Update destination address and channel and attach 
		 * DLC to the session
		 */

		bcopy(&sa->rfcomm_bdaddr, &pcb->dst, sizeof(pcb->dst));
		pcb->channel = sa->rfcomm_channel;
		pcb->dlci = dlci;

		LIST_INSERT_HEAD(&s->dlcs, pcb, session_next);
		pcb->session = s;

		ng_btsocket_rfcomm_timeout(pcb);
		soisconnecting(pcb->so);

		if (s->state == NG_BTSOCKET_RFCOMM_SESSION_OPEN) {
			pcb->mtu = s->mtu;
			bcopy(&so2l2cap_pcb(s->l2so)->src, &pcb->src,
				sizeof(pcb->src));

			pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONFIGURING;

			error = ng_btsocket_rfcomm_send_pn(pcb);
			if (error == 0)
				error = ng_btsocket_rfcomm_task_wakeup();
		} else
			pcb->state = NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT;
		break;

	default:
		error = ECONNRESET;
		break;
	}

	lockmgr(&pcb->pcb_lock, LK_RELEASE);
	lockmgr(&s->session_lock, LK_RELEASE);
	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);

out:
	lwkt_replymsg(&msg->connect.base.lmsg, error);
} /* ng_btsocket_rfcomm_connect */

/*
 * Process ioctl's calls on socket.
 * XXX FIXME this should provide interface to the RFCOMM multiplexor channel
 */

void
ng_btsocket_rfcomm_control(netmsg_t msg)
{
	lwkt_replymsg(&msg->control.base.lmsg, EINVAL);
} /* ng_btsocket_rfcomm_control */

/*
 * Process getsockopt/setsockopt system calls
 */

void
ng_btsocket_rfcomm_ctloutput(netmsg_t msg)
{
	struct socket				*so = msg->ctloutput.base.nm_so;
	struct sockopt				*sopt = msg->ctloutput.nm_sopt;
	ng_btsocket_rfcomm_pcb_p		 pcb = so2rfcomm_pcb(so);
	struct ng_btsocket_rfcomm_fc_info	 fcinfo;
	int					 error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}
	if (sopt->sopt_level != SOL_RFCOMM)
		goto out;

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	switch (sopt->sopt_dir) {
	case SOPT_GET:
		switch (sopt->sopt_name) {
		case SO_RFCOMM_MTU:
			error = sooptcopyout(sopt, &pcb->mtu, sizeof(pcb->mtu));
			break;

		case SO_RFCOMM_FC_INFO:
			fcinfo.lmodem = pcb->lmodem;
			fcinfo.rmodem = pcb->rmodem;
			fcinfo.tx_cred = pcb->tx_cred;
			fcinfo.rx_cred = pcb->rx_cred;
			fcinfo.cfc = (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC)?
				1 : 0;
			fcinfo.reserved = 0;

			error = sooptcopyout(sopt, &fcinfo, sizeof(fcinfo));
			break;

		default:
			error = ENOPROTOOPT;
			break;
		}
		break;

	case SOPT_SET:
		switch (sopt->sopt_name) {
		default:
			error = ENOPROTOOPT;
			break;
		}
		break;

	default:
		error = EINVAL;
		break;
	}

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

out:
	lwkt_replymsg(&msg->ctloutput.base.lmsg, error);
} /* ng_btsocket_rfcomm_ctloutput */

/*
 * Detach and destroy socket
 */

void
ng_btsocket_rfcomm_detach(netmsg_t msg)
{
	struct socket			*so = msg->detach.base.nm_so;
	ng_btsocket_rfcomm_pcb_p	 pcb = so2rfcomm_pcb(so);
	int			 	 error = 0;

	KASSERT(pcb != NULL, ("ng_btsocket_rfcomm_detach: pcb == NULL"));

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	so->so_pcb = NULL;

	switch (pcb->state) {
	case NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT:
	case NG_BTSOCKET_RFCOMM_DLC_CONFIGURING:
	case NG_BTSOCKET_RFCOMM_DLC_CONNECTING:
	case NG_BTSOCKET_RFCOMM_DLC_CONNECTED:
		/* XXX What to do with pending request? */
		if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)
			ng_btsocket_rfcomm_untimeout(pcb);

		if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT)
			pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_DETACHED;
		else
			pcb->state = NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING;

		ng_btsocket_rfcomm_task_wakeup();
		break;

	case NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING:
		ng_btsocket_rfcomm_task_wakeup();
		break;
	}
	
	while (pcb->state != NG_BTSOCKET_RFCOMM_DLC_CLOSED)
		lksleep(&pcb->state, &pcb->pcb_lock, 0, "rf_det", 0);

	if (pcb->session != NULL)
		panic("%s: pcb->session != NULL", __func__);
	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)
		panic("%s: timeout on closed DLC, flags=%#x",
			__func__, pcb->flags);

	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_EXCLUSIVE);
	LIST_REMOVE(pcb, next);
	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

	lockuninit(&pcb->pcb_lock);
	bzero(pcb, sizeof(*pcb));
	kfree(pcb, M_NETGRAPH_BTSOCKET_RFCOMM);

	soisdisconnected(so);
	sofree(so);		/* for so_pcb = NULL */

	lwkt_replymsg(&msg->detach.base.lmsg, error);
} /* ng_btsocket_rfcomm_detach */

/*
 * Disconnect socket
 */

void
ng_btsocket_rfcomm_disconnect(netmsg_t msg)
{
	struct socket			*so = msg->disconnect.base.nm_so;
	ng_btsocket_rfcomm_pcb_p	 pcb = so2rfcomm_pcb(so);
	int				 error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING) {
		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		error = EINPROGRESS;
		goto out;
	}

	/* XXX What to do with pending request? */
	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)
		ng_btsocket_rfcomm_untimeout(pcb);

	switch (pcb->state) {
	case NG_BTSOCKET_RFCOMM_DLC_CONFIGURING: /* XXX can we get here? */
	case NG_BTSOCKET_RFCOMM_DLC_CONNECTING: /* XXX can we get here? */
	case NG_BTSOCKET_RFCOMM_DLC_CONNECTED:

		/*
		 * Just change DLC state and enqueue RFCOMM task. It will
		 * queue and send DISC on the DLC.
		 */ 

		pcb->state = NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING;
		soisdisconnecting(so);

		ng_btsocket_rfcomm_task_wakeup();
		break;

	case NG_BTSOCKET_RFCOMM_DLC_CLOSED:
	case NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT:
		break;

	default:
		panic("%s: Invalid DLC state=%d, flags=%#x",
			__func__, pcb->state, pcb->flags);
		break;
	}

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

out:
	lwkt_replymsg(&msg->disconnect.base.lmsg, error);
} /* ng_btsocket_rfcomm_disconnect */

/*
 * Listen on socket. First call to listen() will create listening RFCOMM session
 */

void
ng_btsocket_rfcomm_listen(netmsg_t msg)
{
	struct socket			*so = msg->listen.base.nm_so;
	struct thread			*td = msg->listen.nm_td;
	int			 	 backlog = msg->listen.nm_flags; /* XXX */
	ng_btsocket_rfcomm_pcb_p	 pcb = so2rfcomm_pcb(so), pcb1;
	ng_btsocket_rfcomm_session_p	 s = NULL;
	struct socket			*l2so = NULL;
	int				 error = 0, socreate_error, usedchannels;

	if (pcb == NULL) {
		error = EINVAL;
		goto out2;
	}
	if (pcb->channel > 30) {
		error = EADDRNOTAVAIL;
		goto out2;
	}

	usedchannels = 0;

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	if (pcb->channel == 0) {
		lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_EXCLUSIVE);

		LIST_FOREACH(pcb1, &ng_btsocket_rfcomm_sockets, next)
			if (pcb1->channel != 0 &&
			    bcmp(&pcb1->src, &pcb->src, sizeof(pcb->src)) == 0)
				usedchannels |= (1 << (pcb1->channel - 1));

		for (pcb->channel = 30; pcb->channel > 0; pcb->channel --)
			if (!(usedchannels & (1 << (pcb->channel - 1))))
				break;

		if (pcb->channel == 0) {
			lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);
			lockmgr(&pcb->pcb_lock, LK_RELEASE);

			error = EADDRNOTAVAIL;
			goto out2;
		}

		lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);
	}

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

	/*
	 * XXX FIXME - This is FUBAR. socreate() will call soalloc(1), i.e.
	 * soalloc() is allowed to sleep in MALLOC. This creates "could sleep"
	 * WITNESS warnings. To work around this problem we will create L2CAP
	 * socket first and then check if we actually need it. Note that we 
	 * will not check for errors in socreate() because if we failed to 
	 * create L2CAP socket at this point we still might have already open
	 * session.
	 */

	socreate_error = socreate(PF_BLUETOOTH, &l2so, SOCK_SEQPACKET,
			BLUETOOTH_PROTO_L2CAP, td);

	/*
	 * Transition the socket and session into the LISTENING state.  Check
	 * for collisions first, as there can only be one.
	 */
	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_EXCLUSIVE);
	if (so->so_state &
	    (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) {
		error = EINVAL;
		goto out;
	}

	LIST_FOREACH(s, &ng_btsocket_rfcomm_sessions, next)
		if (s->state == NG_BTSOCKET_RFCOMM_SESSION_LISTENING)
			break;

	if (s == NULL) {
		/*
		 * We need to create default RFCOMM session. Check if we have 
		 * L2CAP socket. If l2so == NULL then error has the error code 
		 * from socreate()
		 */
		if (l2so == NULL) {
			error = socreate_error;
			goto out;
		}

		/* 
		 * Create default listen RFCOMM session. The default RFCOMM 
		 * session will listen on ANY address.
		 *
		 * XXX FIXME Note that currently there is no way to adjust MTU
		 * for the default session.
		 */
		error = ng_btsocket_rfcomm_session_create(&s, l2so,
					NG_HCI_BDADDR_ANY, NULL, td);
		if (error != 0)
			goto out;
		l2so = NULL;
	}
	solisten(so, backlog, td);

out:
	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);
	/*
	 * If we still have an l2so reference here, it's unneeded, so release
	 * it.
	 */
	if (l2so != NULL)
		soclose(l2so, FNONBLOCK);

out2:
	lwkt_replymsg(&msg->listen.base.lmsg, error);
} /* ng_btsocket_listen */

/*
 * Get peer address
 */

void
ng_btsocket_rfcomm_peeraddr(netmsg_t msg)
{
	struct socket			 *so = msg->peeraddr.base.nm_so;
	struct sockaddr			**nam = msg->peeraddr.nm_nam;
	ng_btsocket_rfcomm_pcb_p	  pcb = so2rfcomm_pcb(so);
	struct sockaddr_rfcomm		  sa;
	int				  error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}

	bcopy(&pcb->dst, &sa.rfcomm_bdaddr, sizeof(sa.rfcomm_bdaddr));
	sa.rfcomm_channel = pcb->channel;
	sa.rfcomm_len = sizeof(sa);
	sa.rfcomm_family = AF_BLUETOOTH;

	*nam = dup_sockaddr((struct sockaddr *) &sa);

	if (*nam == NULL)
		error = ENOMEM;

out:
	lwkt_replymsg(&msg->peeraddr.base.lmsg, error);
} /* ng_btsocket_rfcomm_peeraddr */

/*
 * Send data to socket
 */

void
ng_btsocket_rfcomm_send(netmsg_t msg)
{
	struct socket			*so = msg->send.base.nm_so;
	struct mbuf			*m = msg->send.nm_m;
	struct mbuf			*control = msg->send.nm_control;
	ng_btsocket_rfcomm_pcb_t	*pcb = so2rfcomm_pcb(so);
	int				 error = 0;

	/* Check socket and input */
	if (pcb == NULL || m == NULL || control != NULL) {
		error = EINVAL;
		goto drop;
	}

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	/* Make sure DLC is connected */
	if (pcb->state != NG_BTSOCKET_RFCOMM_DLC_CONNECTED) {
		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		error = ENOTCONN;
		goto drop;
	}

	/* Put the packet on the socket's send queue and wakeup RFCOMM task */
	sbappend(&pcb->so->so_snd.sb, m);
	m = NULL;
	
	if (!(pcb->flags & NG_BTSOCKET_RFCOMM_DLC_SENDING)) {
		pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_SENDING;
		error = ng_btsocket_rfcomm_task_wakeup();
	}

	lockmgr(&pcb->pcb_lock, LK_RELEASE);
drop:
	NG_FREE_M(m); /* checks for != NULL */
	NG_FREE_M(control);

	lwkt_replymsg(&msg->send.base.lmsg, error);
} /* ng_btsocket_rfcomm_send */

/*
 * Get socket address
 */

void
ng_btsocket_rfcomm_sockaddr(netmsg_t msg)
{
	struct socket			 *so = msg->sockaddr.base.nm_so;
	struct sockaddr			**nam = msg->sockaddr.nm_nam;
	ng_btsocket_rfcomm_pcb_p	  pcb = so2rfcomm_pcb(so);
	struct sockaddr_rfcomm		  sa;
	int				  error = 0;

	if (pcb == NULL) {
		error = EINVAL;
		goto out;
	}

	bcopy(&pcb->src, &sa.rfcomm_bdaddr, sizeof(sa.rfcomm_bdaddr));
	sa.rfcomm_channel = pcb->channel;
	sa.rfcomm_len = sizeof(sa);
	sa.rfcomm_family = AF_BLUETOOTH;

	*nam = dup_sockaddr((struct sockaddr *) &sa);

	if (*nam == NULL)
		error = ENOMEM;

out:
	lwkt_replymsg(&msg->sockaddr.base.lmsg, error);
} /* ng_btsocket_rfcomm_sockaddr */

/*
 * Upcall function for L2CAP sockets. Enqueue RFCOMM task.
 */

static void
ng_btsocket_rfcomm_upcall(struct socket *so, void *arg, int waitflag)
{
	int	error;

	if (so == NULL)
		panic("%s: so == NULL", __func__);

	if ((error = ng_btsocket_rfcomm_task_wakeup()) != 0)
		NG_BTSOCKET_RFCOMM_ALERT(
"%s: Could not enqueue RFCOMM task, error=%d\n", __func__, error);
} /* ng_btsocket_rfcomm_upcall */

/*
 * RFCOMM task. Will handle all RFCOMM sessions in one pass.
 * XXX FIXME does not scale very well
 */

static void
ng_btsocket_rfcomm_sessions_task(void *ctx, int pending)
{
	ng_btsocket_rfcomm_session_p	s = NULL, s_next = NULL;

	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_EXCLUSIVE);

	for (s = LIST_FIRST(&ng_btsocket_rfcomm_sessions); s != NULL; ) {
		lockmgr(&s->session_lock, LK_EXCLUSIVE);
		s_next = LIST_NEXT(s, next);

		ng_btsocket_rfcomm_session_task(s);

		if (s->state == NG_BTSOCKET_RFCOMM_SESSION_CLOSED) {
			/* Unlink and clean the session */
			LIST_REMOVE(s, next);

			NG_BT_MBUFQ_DRAIN(&s->outq);
			if (!LIST_EMPTY(&s->dlcs))
				panic("%s: DLC list is not empty", __func__);

			/* Close L2CAP socket */
			s->l2so->so_upcallarg = NULL;
			s->l2so->so_upcall = NULL;
			atomic_clear_int(&s->l2so->so_rcv.ssb_flags, SSB_UPCALL);
			atomic_clear_int(&s->l2so->so_snd.ssb_flags, SSB_UPCALL);
			soclose(s->l2so, FNONBLOCK);

			lockmgr(&s->session_lock, LK_RELEASE);

			lockuninit(&s->session_lock);
			bzero(s, sizeof(*s));
			kfree(s, M_NETGRAPH_BTSOCKET_RFCOMM);
		} else
			lockmgr(&s->session_lock, LK_RELEASE);

		s = s_next;
	}

	lockmgr(&ng_btsocket_rfcomm_sessions_lock, LK_RELEASE);
} /* ng_btsocket_rfcomm_sessions_task */

/*
 * Process RFCOMM session. Will handle all RFCOMM sockets in one pass.
 */

static void
ng_btsocket_rfcomm_session_task(ng_btsocket_rfcomm_session_p s)
{
	KKASSERT(lockowned(&s->session_lock) != 0);

	if (s->l2so->so_state & SS_CANTRCVMORE) {
		NG_BTSOCKET_RFCOMM_INFO(
"%s: L2CAP connection has been terminated, so=%p, so_state=%#x, " \
"state=%d, flags=%#x\n", __func__, s->l2so, s->l2so->so_state, 
			s->state, s->flags);

		s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
		ng_btsocket_rfcomm_session_clean(s);
	}

	/* Now process upcall */
	switch (s->state) {
	/* Try to accept new L2CAP connection(s) */
	case NG_BTSOCKET_RFCOMM_SESSION_LISTENING:
		while (ng_btsocket_rfcomm_session_accept(s) == 0)
			;
		break;

	/* Process the results of the L2CAP connect */
	case NG_BTSOCKET_RFCOMM_SESSION_CONNECTING:
		ng_btsocket_rfcomm_session_process_pcb(s);

		if (ng_btsocket_rfcomm_session_connect(s) != 0) {
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
			ng_btsocket_rfcomm_session_clean(s);
		} 
		break;

	/* Try to receive/send more data */
	case NG_BTSOCKET_RFCOMM_SESSION_CONNECTED:
	case NG_BTSOCKET_RFCOMM_SESSION_OPEN:
	case NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING:
		ng_btsocket_rfcomm_session_process_pcb(s);

		if (ng_btsocket_rfcomm_session_receive(s) != 0) {
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
			ng_btsocket_rfcomm_session_clean(s);
		} else if (ng_btsocket_rfcomm_session_send(s) != 0) {
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
			ng_btsocket_rfcomm_session_clean(s);
		}
		break;

	case NG_BTSOCKET_RFCOMM_SESSION_CLOSED:
		break;

	default:
		panic("%s: Invalid session state=%d, flags=%#x",
			__func__, s->state, s->flags);
		break;
	}
} /* ng_btsocket_rfcomm_session_task */

/*
 * Process RFCOMM connection indicator. Caller must hold s->session_mtx
 */

static ng_btsocket_rfcomm_pcb_p
ng_btsocket_rfcomm_connect_ind(ng_btsocket_rfcomm_session_p s, int channel)
{
	ng_btsocket_rfcomm_pcb_p	 pcb = NULL, pcb1 = NULL;
	ng_btsocket_l2cap_pcb_p		 l2pcb = NULL;
	struct socket			*so1 = NULL;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * Try to find RFCOMM socket that listens on given source address 
	 * and channel. This will return the best possible match.
	 */

	l2pcb = so2l2cap_pcb(s->l2so);
	pcb = ng_btsocket_rfcomm_pcb_listener(&l2pcb->src, channel);
	if (pcb == NULL)
		return (NULL);

	/*
	 * Check the pending connections queue and if we have space then 
	 * create new socket and set proper source and destination address,
	 * and channel.
	 */

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	if (pcb->so->so_qlen <= pcb->so->so_qlimit)
		so1 = sonewconn(pcb->so, 0);

	lockmgr(&pcb->pcb_lock, LK_RELEASE);

	if (so1 == NULL)
		return (NULL);

	/*
	 * If we got here than we have created new socket. So complete the 
	 * connection. Set source and destination address from the session.
	 */

	pcb1 = so2rfcomm_pcb(so1);
	if (pcb1 == NULL)
		panic("%s: pcb1 == NULL", __func__);

	lockmgr(&pcb1->pcb_lock, LK_EXCLUSIVE);

	bcopy(&l2pcb->src, &pcb1->src, sizeof(pcb1->src));
	bcopy(&l2pcb->dst, &pcb1->dst, sizeof(pcb1->dst));
	pcb1->channel = channel;

	/* Link new DLC to the session. We already hold s->session_mtx */
	LIST_INSERT_HEAD(&s->dlcs, pcb1, session_next);
	pcb1->session = s;
			
	lockmgr(&pcb1->pcb_lock, LK_RELEASE);

	return (pcb1);
} /* ng_btsocket_rfcomm_connect_ind */

/*
 * Process RFCOMM connect confirmation. Caller must hold s->session_mtx.
 */

static void
ng_btsocket_rfcomm_connect_cfm(ng_btsocket_rfcomm_session_p s)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL, pcb_next = NULL;
	int				error;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * Wake up all waiting sockets and send PN request for each of them. 
	 * Note that timeout already been set in ng_btsocket_rfcomm_connect()
	 *
	 * Note: cannot use LIST_FOREACH because ng_btsocket_rfcomm_pcb_kill
	 * will unlink DLC from the session
	 */

	for (pcb = LIST_FIRST(&s->dlcs); pcb != NULL; ) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);
		pcb_next = LIST_NEXT(pcb, session_next);

		if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT) {
			pcb->mtu = s->mtu;
			bcopy(&so2l2cap_pcb(s->l2so)->src, &pcb->src,
				sizeof(pcb->src));

			error = ng_btsocket_rfcomm_send_pn(pcb);
			if (error == 0)
				pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONFIGURING;
			else
				ng_btsocket_rfcomm_pcb_kill(pcb, error);
		}

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		pcb = pcb_next;
	}
} /* ng_btsocket_rfcomm_connect_cfm */

/*****************************************************************************
 *****************************************************************************
 **                              RFCOMM sessions
 *****************************************************************************
 *****************************************************************************/

/*
 * Create new RFCOMM session. That function WILL NOT take ownership over l2so.
 * Caller MUST free l2so if function failed.
 */

static int
ng_btsocket_rfcomm_session_create(ng_btsocket_rfcomm_session_p *sp,
		struct socket *l2so, bdaddr_p src, bdaddr_p dst,
		struct thread *td)
{
	ng_btsocket_rfcomm_session_p	s = NULL;
	struct sockaddr_l2cap		l2sa;
	struct sockopt			l2sopt;
	int				error;
	u_int16_t			mtu;

	KKASSERT(lockowned(&ng_btsocket_rfcomm_sessions_lock) != 0);

	/* Allocate the RFCOMM session */
        s = kmalloc(sizeof(*s), M_NETGRAPH_BTSOCKET_RFCOMM,
		    M_WAITOK | M_NULLOK | M_ZERO);
        if (s == NULL)
                return (ENOMEM);

	/* Set defaults */
	s->mtu = RFCOMM_DEFAULT_MTU;
	s->flags = 0;
	s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
	NG_BT_MBUFQ_INIT(&s->outq, ifqmaxlen);

	/*
	 * XXX Mark session mutex as DUPOK to prevent "duplicated lock of 
	 * the same type" message. When accepting new L2CAP connection
	 * ng_btsocket_rfcomm_session_accept() holds both session mutexes 
	 * for "old" (accepting) session and "new" (created) session.
	 */

	lockinit(&s->session_lock, "btsocks_rfcomm_session_lock", 0,
	    LK_CANRECURSE);

	LIST_INIT(&s->dlcs);

	/* Prepare L2CAP socket */
	l2so->so_upcallarg = NULL;
	l2so->so_upcall = ng_btsocket_rfcomm_upcall;
	atomic_set_int(&l2so->so_rcv.ssb_flags, SSB_UPCALL);
	atomic_set_int(&l2so->so_snd.ssb_flags, SSB_UPCALL);
	s->l2so = l2so;

	lockmgr(&s->session_lock, LK_EXCLUSIVE);

	/*
	 * "src" == NULL and "dst" == NULL means just create session.
	 * caller must do the rest
	 */

	if (src == NULL && dst == NULL)
		goto done;

	/*
	 * Set incoming MTU on L2CAP socket. It is RFCOMM session default MTU 
	 * plus 5 bytes: RFCOMM frame header, one extra byte for length and one
	 * extra byte for credits.
	 */

	mtu = s->mtu + sizeof(struct rfcomm_frame_hdr) + 1 + 1;

	l2sopt.sopt_dir = SOPT_SET;
	l2sopt.sopt_level = SOL_L2CAP;
	l2sopt.sopt_name = SO_L2CAP_IMTU;
	l2sopt.sopt_val = (void *) &mtu;
	l2sopt.sopt_valsize = sizeof(mtu);
	l2sopt.sopt_td = NULL;

	error = sosetopt(s->l2so, &l2sopt);
	if (error != 0)
		goto bad;

	/* Bind socket to "src" address */
	l2sa.l2cap_len = sizeof(l2sa);
	l2sa.l2cap_family = AF_BLUETOOTH;
	l2sa.l2cap_psm = (dst == NULL)? htole16(NG_L2CAP_PSM_RFCOMM) : 0;
	bcopy(src, &l2sa.l2cap_bdaddr, sizeof(l2sa.l2cap_bdaddr));

	error = sobind(s->l2so, (struct sockaddr *) &l2sa, td);
	if (error != 0)
		goto bad;

	/* If "dst" is not NULL then initiate connect(), otherwise listen() */
	if (dst == NULL) {
		s->flags = 0;
		s->state = NG_BTSOCKET_RFCOMM_SESSION_LISTENING;

		error = solisten(s->l2so, 10, td);
		if (error != 0)
			goto bad;
	} else {
		s->flags = NG_BTSOCKET_RFCOMM_SESSION_INITIATOR;
		s->state = NG_BTSOCKET_RFCOMM_SESSION_CONNECTING;

		l2sa.l2cap_len = sizeof(l2sa);   
		l2sa.l2cap_family = AF_BLUETOOTH;
		l2sa.l2cap_psm = htole16(NG_L2CAP_PSM_RFCOMM);
	        bcopy(dst, &l2sa.l2cap_bdaddr, sizeof(l2sa.l2cap_bdaddr));

		error = soconnect(s->l2so, (struct sockaddr *) &l2sa, td, TRUE);
		if (error != 0)
			goto bad;
	}

done:
	LIST_INSERT_HEAD(&ng_btsocket_rfcomm_sessions, s, next);
	*sp = s;

	lockmgr(&s->session_lock, LK_RELEASE);

	return (0);

bad:
	lockmgr(&s->session_lock, LK_RELEASE);

	/* Return L2CAP socket back to its original state */
	l2so->so_upcallarg = NULL;
	l2so->so_upcall = NULL;
	atomic_clear_int(&l2so->so_rcv.ssb_flags, SSB_UPCALL);
	atomic_clear_int(&l2so->so_snd.ssb_flags, SSB_UPCALL);

	lockuninit(&s->session_lock);
	bzero(s, sizeof(*s));
	kfree(s, M_NETGRAPH_BTSOCKET_RFCOMM);

	return (error);
} /* ng_btsocket_rfcomm_session_create */

/*
 * Process accept() on RFCOMM session
 * XXX FIXME locking for "l2so"?
 */

static int
ng_btsocket_rfcomm_session_accept(ng_btsocket_rfcomm_session_p s0)
{
	struct socket			*l2so = NULL;
	struct sockaddr_l2cap		*l2sa = NULL;
	ng_btsocket_l2cap_pcb_t		*l2pcb = NULL;
	ng_btsocket_rfcomm_session_p	 s = NULL;
	int				 error = 0;

	KKASSERT(lockowned(&ng_btsocket_rfcomm_sessions_lock) != 0);
	KKASSERT(lockowned(&s0->session_lock) != 0);

	/* Check if there is a complete L2CAP connection in the queue */
	if ((error = s0->l2so->so_error) != 0) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not accept connection on L2CAP socket, error=%d\n", __func__, error);
		s0->l2so->so_error = 0;

		return (error);
	}

	if (TAILQ_EMPTY(&s0->l2so->so_comp)) {
		if (s0->l2so->so_state & SS_CANTRCVMORE)
			return (ECONNABORTED);
		return (EWOULDBLOCK);
	}

	/* Accept incoming L2CAP connection */
	l2so = TAILQ_FIRST(&s0->l2so->so_comp);
	if (l2so == NULL)
		panic("%s: l2so == NULL", __func__);

	TAILQ_REMOVE(&s0->l2so->so_comp, l2so, so_list);
	s0->l2so->so_qlen --;
	l2so->so_head = NULL;
	soreference(l2so);

	error = soaccept(l2so, (struct sockaddr **) &l2sa);
	if (error != 0) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: soaccept() on L2CAP socket failed, error=%d\n", __func__, error);
		soclose(l2so, FNONBLOCK);

		return (error);
	}

	/*
	 * Check if there is already active RFCOMM session between two devices.
	 * If so then close L2CAP connection. We only support one RFCOMM session
	 * between each pair of devices. Note that here we assume session in any
	 * state. The session even could be in the middle of disconnecting.
	 */

	l2pcb = so2l2cap_pcb(l2so);
	s = ng_btsocket_rfcomm_session_by_addr(&l2pcb->src, &l2pcb->dst);
	if (s == NULL) {
		/* Create a new RFCOMM session */
		error = ng_btsocket_rfcomm_session_create(&s, l2so, NULL, NULL,
				curthread /* XXX */);
		if (error == 0) {
			lockmgr(&s->session_lock, LK_EXCLUSIVE);

			s->flags = 0;
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CONNECTED;

			/*
			 * Adjust MTU on incomming connection. Reserve 5 bytes:
			 * RFCOMM frame header, one extra byte for length and 
			 * one extra byte for credits.
			 */

			s->mtu = min(l2pcb->imtu, l2pcb->omtu) -
					sizeof(struct rfcomm_frame_hdr) - 1 - 1;

			lockmgr(&s->session_lock, LK_RELEASE);
		} else {
			NG_BTSOCKET_RFCOMM_ALERT(
"%s: Failed to create new RFCOMM session, error=%d\n", __func__, error);

			soclose(l2so, FNONBLOCK);
		}
	} else {
		NG_BTSOCKET_RFCOMM_WARN(
"%s: Rejecting duplicating RFCOMM session between src=%x:%x:%x:%x:%x:%x and " \
"dst=%x:%x:%x:%x:%x:%x, state=%d, flags=%#x\n",	__func__,
			l2pcb->src.b[5], l2pcb->src.b[4], l2pcb->src.b[3],
			l2pcb->src.b[2], l2pcb->src.b[1], l2pcb->src.b[0],
			l2pcb->dst.b[5], l2pcb->dst.b[4], l2pcb->dst.b[3],
			l2pcb->dst.b[2], l2pcb->dst.b[1], l2pcb->dst.b[0],
			s->state, s->flags);

		error = EBUSY;
		soclose(l2so, FNONBLOCK);
	}

	return (error);
} /* ng_btsocket_rfcomm_session_accept */

/*
 * Process connect() on RFCOMM session
 * XXX FIXME locking for "l2so"?
 */

static int
ng_btsocket_rfcomm_session_connect(ng_btsocket_rfcomm_session_p s)
{
	ng_btsocket_l2cap_pcb_p	l2pcb = so2l2cap_pcb(s->l2so);
	int			error;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/* First check if connection has failed */
	if ((error = s->l2so->so_error) != 0) {
		s->l2so->so_error = 0;

		NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not connect RFCOMM session, error=%d, state=%d, flags=%#x\n",
			__func__, error, s->state, s->flags);

		return (error);
	}

	/* Is connection still in progress? */
	if (s->l2so->so_state & SS_ISCONNECTING)
		return (0); 

	/* 
	 * If we got here then we are connected. Send SABM on DLCI 0 to 
	 * open multiplexor channel.
	 */

	if (error == 0) {
		s->state = NG_BTSOCKET_RFCOMM_SESSION_CONNECTED;

		/*
		 * Adjust MTU on outgoing connection. Reserve 5 bytes: RFCOMM 
		 * frame header, one extra byte for length and one extra byte 
		 * for credits.
		 */

		s->mtu = min(l2pcb->imtu, l2pcb->omtu) -
				sizeof(struct rfcomm_frame_hdr) - 1 - 1;

		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_SABM,0);
		if (error == 0)
			error = ng_btsocket_rfcomm_task_wakeup();
	}

	return (error);
}/* ng_btsocket_rfcomm_session_connect */

/*
 * Receive data on RFCOMM session
 * XXX FIXME locking for "l2so"?
 */

static int
ng_btsocket_rfcomm_session_receive(ng_btsocket_rfcomm_session_p s)
{
	struct sockbuf	 sio;
	int		 more, error, rcvflg, savelen = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/* Can we read from the L2CAP socket? */
	if (!soreadable(s->l2so))
		return (0);

	/* First check for error on L2CAP socket */
	if ((error = s->l2so->so_error) != 0) {
		s->l2so->so_error = 0;

		NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not receive data from L2CAP socket, error=%d, state=%d, flags=%#x\n",
			__func__, error, s->state, s->flags);

		return (error);
	}

	/*
	 * Read all packets from the L2CAP socket. 
	 * XXX FIXME/VERIFY is that correct? For now use m->m_nextpkt as
	 * indication that there is more packets on the socket's buffer.
	 * Also what should we use in uio.uio_resid?
	 * May be s->mtu + sizeof(struct rfcomm_frame_hdr) + 1 + 1?
	 */

	sbinit(&sio, 0);
	for (more = 1; more; ) {
		/* Try to get next packet from socket */
		sbinit(&sio, savelen);
		rcvflg = MSG_WAITALL;
		error = soreceive(s->l2so, NULL, NULL, &sio, NULL, &rcvflg);
		if (error != 0) {
			if (error == EWOULDBLOCK)
				return (0); /* XXX can happen? */

			NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not receive data from L2CAP socket, error=%d\n", __func__, error);

			return (error);
		}
	
		more = (sio.sb_mb->m_nextpkt != NULL);
		sio.sb_mb->m_nextpkt = NULL;

		ng_btsocket_rfcomm_receive_frame(s, sio.sb_mb);
	}

	return (0);
} /* ng_btsocket_rfcomm_session_receive */

/*
 * Send data on RFCOMM session
 * XXX FIXME locking for "l2so"?
 */

static int
ng_btsocket_rfcomm_session_send(ng_btsocket_rfcomm_session_p s)
{
	struct mbuf	*m = NULL;
	int		 error;
	struct netmsg_pru_send msg;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/* Send as much as we can from the session queue */
	while (sowriteable(s->l2so)) {
		/* Check if socket still OK */
		if ((error = s->l2so->so_error) != 0) {
			s->l2so->so_error = 0;

			NG_BTSOCKET_RFCOMM_ERR(
"%s: Detected error=%d on L2CAP socket, state=%d, flags=%#x\n",
				__func__, error, s->state, s->flags);

			return (error);
		}

		NG_BT_MBUFQ_DEQUEUE(&s->outq, m);
		if (m == NULL)
			return (0); /* we are done */

		/* Call send function on the L2CAP socket */
		netmsg_init(&msg.base, s->l2so, &curthread->td_msgport,
		    0, s->l2so->so_proto->pr_usrreqs->pru_send);
		msg.nm_flags = 0;
		msg.nm_m = m;
		msg.nm_addr = NULL;
		msg.nm_control = NULL;
		msg.nm_td = curthread; /* XXX */
		error = lwkt_domsg(s->l2so->so_port, &msg.base.lmsg, 0);
		if (error != 0) {
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not send data to L2CAP socket, error=%d\n", __func__, error);

			return (error);
		}
	}

	return (0);
} /* ng_btsocket_rfcomm_session_send */

/*
 * Close and disconnect all DLCs for the given session. Caller must hold 
 * s->sesson_mtx. Will wakeup session.
 */

static void
ng_btsocket_rfcomm_session_clean(ng_btsocket_rfcomm_session_p s)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL, pcb_next = NULL;
	int				error;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * Note: cannot use LIST_FOREACH because ng_btsocket_rfcomm_pcb_kill
	 * will unlink DLC from the session
	 */

	for (pcb = LIST_FIRST(&s->dlcs); pcb != NULL; ) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);
		pcb_next = LIST_NEXT(pcb, session_next);

		NG_BTSOCKET_RFCOMM_INFO(
"%s: Disconnecting dlci=%d, state=%d, flags=%#x\n",
			__func__, pcb->dlci, pcb->state, pcb->flags);

		if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_CONNECTED)
			error = ECONNRESET;
		else
			error = ECONNREFUSED;

		ng_btsocket_rfcomm_pcb_kill(pcb, error);

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		pcb = pcb_next;
	}
} /* ng_btsocket_rfcomm_session_clean */

/*
 * Process all DLCs on the session. Caller MUST hold s->session_mtx.
 */

static void
ng_btsocket_rfcomm_session_process_pcb(ng_btsocket_rfcomm_session_p s)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL, pcb_next = NULL;
	int				error;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * Note: cannot use LIST_FOREACH because ng_btsocket_rfcomm_pcb_kill
	 * will unlink DLC from the session
	 */

	for (pcb = LIST_FIRST(&s->dlcs); pcb != NULL; ) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);
		pcb_next = LIST_NEXT(pcb, session_next);

		switch (pcb->state) {

		/*
		 * If DLC in W4_CONNECT state then we should check for both
		 * timeout and detach.
		 */

		case NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT:
			if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_DETACHED)
				ng_btsocket_rfcomm_pcb_kill(pcb, 0);
			else if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT)
				ng_btsocket_rfcomm_pcb_kill(pcb, ETIMEDOUT);
			break;

		/*
		 * If DLC in CONFIGURING or CONNECTING state then we only
		 * should check for timeout. If detach() was called then
		 * DLC will be moved into DISCONNECTING state.
		 */

		case NG_BTSOCKET_RFCOMM_DLC_CONFIGURING:
		case NG_BTSOCKET_RFCOMM_DLC_CONNECTING:
			if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT)
				ng_btsocket_rfcomm_pcb_kill(pcb, ETIMEDOUT);
			break;

		/*
		 * If DLC in CONNECTED state then we need to send data (if any)
		 * from the socket's send queue. Note that we will send data
		 * from either all sockets or none. This may overload session's
		 * outgoing queue (but we do not check for that).
		 *
 		 * XXX FIXME need scheduler for RFCOMM sockets
		 */

		case NG_BTSOCKET_RFCOMM_DLC_CONNECTED:
			error = ng_btsocket_rfcomm_pcb_send(pcb, ALOT);
			if (error != 0)
				ng_btsocket_rfcomm_pcb_kill(pcb, error);
			break;

		/*
		 * If DLC in DISCONNECTING state then we must send DISC frame.
		 * Note that if DLC has timeout set then we do not need to 
		 * resend DISC frame.
		 *
		 * XXX FIXME need to drain all data from the socket's queue
		 * if LINGER option was set
		 */

		case NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING:
			if (!(pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)) {
				error = ng_btsocket_rfcomm_send_command(
						pcb->session, RFCOMM_FRAME_DISC,
						pcb->dlci);
				if (error == 0)
					ng_btsocket_rfcomm_timeout(pcb);
				else
					ng_btsocket_rfcomm_pcb_kill(pcb, error);
			} else if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT)
				ng_btsocket_rfcomm_pcb_kill(pcb, ETIMEDOUT);
			break;
		
/*		case NG_BTSOCKET_RFCOMM_DLC_CLOSED: */
		default:
			panic("%s: Invalid DLC state=%d, flags=%#x",
				__func__, pcb->state, pcb->flags);
			break;
		}

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
		pcb = pcb_next;
	}
} /* ng_btsocket_rfcomm_session_process_pcb */

/*
 * Find RFCOMM session between "src" and "dst".
 * Caller MUST hold ng_btsocket_rfcomm_sessions_mtx.
 */

static ng_btsocket_rfcomm_session_p
ng_btsocket_rfcomm_session_by_addr(bdaddr_p src, bdaddr_p dst)
{
	ng_btsocket_rfcomm_session_p	s = NULL;
	ng_btsocket_l2cap_pcb_p		l2pcb = NULL;
	int				any_src;

	KKASSERT(lockowned(&ng_btsocket_rfcomm_sessions_lock) != 0);

	any_src = (bcmp(src, NG_HCI_BDADDR_ANY, sizeof(*src)) == 0);

	LIST_FOREACH(s, &ng_btsocket_rfcomm_sessions, next) {
		l2pcb = so2l2cap_pcb(s->l2so);

		if ((any_src || bcmp(&l2pcb->src, src, sizeof(*src)) == 0) &&
		    bcmp(&l2pcb->dst, dst, sizeof(*dst)) == 0)
			break;
	}

	return (s);
} /* ng_btsocket_rfcomm_session_by_addr */

/*****************************************************************************
 *****************************************************************************
 **                                  RFCOMM 
 *****************************************************************************
 *****************************************************************************/

/*
 * Process incoming RFCOMM frame. Caller must hold s->session_mtx.
 * XXX FIXME check frame length
 */

static int
ng_btsocket_rfcomm_receive_frame(ng_btsocket_rfcomm_session_p s,
		struct mbuf *m0)
{
	struct rfcomm_frame_hdr	*hdr = NULL;
	struct mbuf		*m = NULL;
	u_int16_t		 length;
	u_int8_t		 dlci, type;
	int			 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/* Pullup as much as we can into first mbuf (for direct access) */
	length = min(m0->m_pkthdr.len, MHLEN);
	if (m0->m_len < length) {
		if ((m0 = m_pullup(m0, length)) == NULL) {
			NG_BTSOCKET_RFCOMM_ALERT(
"%s: m_pullup(%d) failed\n", __func__, length);

			return (ENOBUFS);
		}
	}

	hdr = mtod(m0, struct rfcomm_frame_hdr *);
	dlci = RFCOMM_DLCI(hdr->address);
	type = RFCOMM_TYPE(hdr->control);

	/* Test EA bit in length. If not set then we have 2 bytes of length */
	if (!RFCOMM_EA(hdr->length)) {
		bcopy(&hdr->length, &length, sizeof(length));
		length = le16toh(length) >> 1;
		m_adj(m0, sizeof(*hdr) + 1);
	} else {
		length = hdr->length >> 1;
		m_adj(m0, sizeof(*hdr));
	}

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got frame type=%#x, dlci=%d, length=%d, cr=%d, pf=%d, len=%d\n",
		__func__, type, dlci, length, RFCOMM_CR(hdr->address),
		RFCOMM_PF(hdr->control), m0->m_pkthdr.len);

	/*
	 * Get FCS (the last byte in the frame)
	 * XXX this will not work if mbuf chain ends with empty mbuf.
	 * XXX let's hope it never happens :)
	 */

	for (m = m0; m->m_next != NULL; m = m->m_next)
		;
	if (m->m_len <= 0)
		panic("%s: Empty mbuf at the end of the chain, len=%d",
			__func__, m->m_len);

	/*
	 * Check FCS. We only need to calculate FCS on first 2 or 3 bytes
	 * and already m_pullup'ed mbuf chain, so it should be safe.
	 */

	if (ng_btsocket_rfcomm_check_fcs((u_int8_t *) hdr, type, m->m_data[m->m_len - 1])) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Invalid RFCOMM packet. Bad checksum\n", __func__);
		NG_FREE_M(m0);

		return (EINVAL);
	}

	m_adj(m0, -1); /* Trim FCS byte */

	/*
	 * Process RFCOMM frame.
	 *
	 * From TS 07.10 spec
	 * 
	 * "... In the case where a SABM or DISC command with the P bit set
	 * to 0 is received then the received frame shall be discarded..."
 	 *
	 * "... If a unsolicited DM response is received then the frame shall
	 * be processed irrespective of the P/F setting... "
	 *
	 * "... The station may transmit response frames with the F bit set 
	 * to 0 at any opportunity on an asynchronous basis. However, in the 
	 * case where a UA response is received with the F bit set to 0 then 
	 * the received frame shall be discarded..."
	 *
	 * From Bluetooth spec
	 *
	 * "... When credit based flow control is being used, the meaning of
	 * the P/F bit in the control field of the RFCOMM header is redefined
	 * for UIH frames..."
	 */

	switch (type) {
	case RFCOMM_FRAME_SABM:
		if (RFCOMM_PF(hdr->control))
			error = ng_btsocket_rfcomm_receive_sabm(s, dlci);
		break;

	case RFCOMM_FRAME_DISC:
		if (RFCOMM_PF(hdr->control))
			error = ng_btsocket_rfcomm_receive_disc(s, dlci);
		break;

	case RFCOMM_FRAME_UA:
		if (RFCOMM_PF(hdr->control))
			error = ng_btsocket_rfcomm_receive_ua(s, dlci);
		break;

	case RFCOMM_FRAME_DM:
		error = ng_btsocket_rfcomm_receive_dm(s, dlci);
		break;

	case RFCOMM_FRAME_UIH:
		if (dlci == 0)
			error = ng_btsocket_rfcomm_receive_mcc(s, m0);
		else
			error = ng_btsocket_rfcomm_receive_uih(s, dlci,
					RFCOMM_PF(hdr->control), m0);

		return (error);
		/* NOT REACHED */

	default:
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Invalid RFCOMM packet. Unknown type=%#x\n", __func__, type);
		error = EINVAL;
		break;
	}

	NG_FREE_M(m0);

	return (error);
} /* ng_btsocket_rfcomm_receive_frame */

/*
 * Process RFCOMM SABM frame
 */

static int
ng_btsocket_rfcomm_receive_sabm(ng_btsocket_rfcomm_session_p s, int dlci)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;
	int				error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got SABM, session state=%d, flags=%#x, mtu=%d, dlci=%d\n",
		__func__, s->state, s->flags, s->mtu, dlci);

	/* DLCI == 0 means open multiplexor channel */
	if (dlci == 0) {
		switch (s->state) {
		case NG_BTSOCKET_RFCOMM_SESSION_CONNECTED:
		case NG_BTSOCKET_RFCOMM_SESSION_OPEN:
			error = ng_btsocket_rfcomm_send_command(s,
					RFCOMM_FRAME_UA, dlci);
			if (error == 0) {
				s->state = NG_BTSOCKET_RFCOMM_SESSION_OPEN;
				ng_btsocket_rfcomm_connect_cfm(s);
			} else {
				s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
				ng_btsocket_rfcomm_session_clean(s);
			}
			break;

		default:
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got SABM for session in invalid state state=%d, flags=%#x\n",
				__func__, s->state, s->flags);
			error = EINVAL;
			break;
		}

		return (error);
	}

	/* Make sure multiplexor channel is open */
	if (s->state != NG_BTSOCKET_RFCOMM_SESSION_OPEN) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Got SABM for dlci=%d with mulitplexor channel closed, state=%d, " \
"flags=%#x\n",		__func__, dlci, s->state, s->flags);

		return (EINVAL);
	}

	/*
	 * Check if we have this DLCI. This might happen when remote
	 * peer uses PN command before actual open (SABM) happens.
	 */

	pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, dlci);
	if (pcb != NULL) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

		if (pcb->state != NG_BTSOCKET_RFCOMM_DLC_CONNECTING) {
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Got SABM for dlci=%d in invalid state=%d, flags=%#x\n",
				__func__, dlci, pcb->state, pcb->flags);
			lockmgr(&pcb->pcb_lock, LK_RELEASE);

			return (ENOENT);
		}

		ng_btsocket_rfcomm_untimeout(pcb);

		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_UA,dlci);
		if (error == 0)
			error = ng_btsocket_rfcomm_send_msc(pcb);

		if (error == 0) {
			pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONNECTED;
			soisconnected(pcb->so);
		} else
			ng_btsocket_rfcomm_pcb_kill(pcb, error);

		lockmgr(&pcb->pcb_lock, LK_RELEASE);

		return (error);
	}

	/*
	 * We do not have requested DLCI, so it must be an incoming connection
	 * with default parameters. Try to accept it.
	 */ 

	pcb = ng_btsocket_rfcomm_connect_ind(s, RFCOMM_SRVCHANNEL(dlci));
	if (pcb != NULL) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

		pcb->dlci = dlci;

		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_UA,dlci);
		if (error == 0)
			error = ng_btsocket_rfcomm_send_msc(pcb);

		if (error == 0) {
			pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONNECTED;
			soisconnected(pcb->so);
		} else
			ng_btsocket_rfcomm_pcb_kill(pcb, error);

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
	} else
		/* Nobody is listen()ing on the requested DLCI */
		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_DM,dlci);

	return (error);
} /* ng_btsocket_rfcomm_receive_sabm */

/*
 * Process RFCOMM DISC frame
 */

static int
ng_btsocket_rfcomm_receive_disc(ng_btsocket_rfcomm_session_p s, int dlci)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;
	int				error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got DISC, session state=%d, flags=%#x, mtu=%d, dlci=%d\n",
		__func__, s->state, s->flags, s->mtu, dlci);

	/* DLCI == 0 means close multiplexor channel */
	if (dlci == 0) {
		/* XXX FIXME assume that remote side will close the socket */
		error = ng_btsocket_rfcomm_send_command(s, RFCOMM_FRAME_UA, 0);
		if (error == 0) {
			if (s->state == NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING)
				s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED; /* XXX */
			else
				s->state = NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING;
		} else
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED; /* XXX */

		ng_btsocket_rfcomm_session_clean(s);
	} else {
		pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, dlci);
		if (pcb != NULL) {
			int	err;

			lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

			NG_BTSOCKET_RFCOMM_INFO(
"%s: Got DISC for dlci=%d, state=%d, flags=%#x\n",
				__func__, dlci, pcb->state, pcb->flags);

			error = ng_btsocket_rfcomm_send_command(s,
					RFCOMM_FRAME_UA, dlci);

			if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_CONNECTED)
				err = 0;
			else
				err = ECONNREFUSED;

			ng_btsocket_rfcomm_pcb_kill(pcb, err);

			lockmgr(&pcb->pcb_lock, LK_RELEASE);
		} else {
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got DISC for non-existing dlci=%d\n", __func__, dlci);

			error = ng_btsocket_rfcomm_send_command(s,
					RFCOMM_FRAME_DM, dlci);
		}
	}

	return (error);
} /* ng_btsocket_rfcomm_receive_disc */

/*
 * Process RFCOMM UA frame
 */

static int
ng_btsocket_rfcomm_receive_ua(ng_btsocket_rfcomm_session_p s, int dlci)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;
	int				error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got UA, session state=%d, flags=%#x, mtu=%d, dlci=%d\n",
		__func__, s->state, s->flags, s->mtu, dlci);

	/* dlci == 0 means multiplexor channel */
	if (dlci == 0) {
		switch (s->state) {
		case NG_BTSOCKET_RFCOMM_SESSION_CONNECTED:
			s->state = NG_BTSOCKET_RFCOMM_SESSION_OPEN;
			ng_btsocket_rfcomm_connect_cfm(s);
			break;

		case NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING:
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
			ng_btsocket_rfcomm_session_clean(s);
			break;

		default:
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UA for session in invalid state=%d(%d), flags=%#x, mtu=%d\n",
				__func__, s->state, INITIATOR(s), s->flags,
				s->mtu);
			error = ENOENT;
			break;
		}

		return (error);
	}

	/* Check if we have this DLCI */
	pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, dlci);
	if (pcb != NULL) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

		NG_BTSOCKET_RFCOMM_INFO(
"%s: Got UA for dlci=%d, state=%d, flags=%#x\n",
			__func__, dlci, pcb->state, pcb->flags);

		switch (pcb->state) {
		case NG_BTSOCKET_RFCOMM_DLC_CONNECTING:
			ng_btsocket_rfcomm_untimeout(pcb);

			error = ng_btsocket_rfcomm_send_msc(pcb);
			if (error == 0) {
				pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONNECTED;
				soisconnected(pcb->so);
			}
			break;

		case NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING:
			ng_btsocket_rfcomm_pcb_kill(pcb, 0);
			break;

		default:
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UA for dlci=%d in invalid state=%d, flags=%#x\n",
				__func__, dlci, pcb->state, pcb->flags);
			error = ENOENT;
			break;
		}

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
	} else {
		NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UA for non-existing dlci=%d\n", __func__, dlci);

		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_DM,dlci);
	}

	return (error);
} /* ng_btsocket_rfcomm_receive_ua */

/*
 * Process RFCOMM DM frame
 */

static int
ng_btsocket_rfcomm_receive_dm(ng_btsocket_rfcomm_session_p s, int dlci)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;
	int				error;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got DM, session state=%d, flags=%#x, mtu=%d, dlci=%d\n",
		__func__, s->state, s->flags, s->mtu, dlci);

	/* DLCI == 0 means multiplexor channel */
	if (dlci == 0) {
		/* Disconnect all dlc's on the session */
		s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
		ng_btsocket_rfcomm_session_clean(s);
	} else {
		pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, dlci);
		if (pcb != NULL) {
			lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

			NG_BTSOCKET_RFCOMM_INFO(
"%s: Got DM for dlci=%d, state=%d, flags=%#x\n",
				__func__, dlci, pcb->state, pcb->flags);

			if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_CONNECTED)
				error = ECONNRESET;
			else
				error = ECONNREFUSED;

			ng_btsocket_rfcomm_pcb_kill(pcb, error);

			lockmgr(&pcb->pcb_lock, LK_RELEASE);
		} else
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got DM for non-existing dlci=%d\n", __func__, dlci);
	}

	return (0);
} /* ng_btsocket_rfcomm_receive_dm */

/*
 * Process RFCOMM UIH frame (data)
 */

static int
ng_btsocket_rfcomm_receive_uih(ng_btsocket_rfcomm_session_p s, int dlci,
		int pf, struct mbuf *m0)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;
	int				error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got UIH, session state=%d, flags=%#x, mtu=%d, dlci=%d, pf=%d, len=%d\n",
		__func__, s->state, s->flags, s->mtu, dlci, pf,
		m0->m_pkthdr.len);

	/* XXX should we do it here? Check for session flow control */
	if (s->flags & NG_BTSOCKET_RFCOMM_SESSION_LFC) {
		NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UIH with session flow control asserted, state=%d, flags=%#x\n",
			__func__, s->state, s->flags);
		goto drop;
	}

	/* Check if we have this dlci */
	pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, dlci);
	if (pcb == NULL) {
		NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UIH for non-existing dlci=%d\n", __func__, dlci);
		error = ng_btsocket_rfcomm_send_command(s,RFCOMM_FRAME_DM,dlci);
		goto drop;
	}

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	/* Check dlci state */	
	if (pcb->state != NG_BTSOCKET_RFCOMM_DLC_CONNECTED) {
		NG_BTSOCKET_RFCOMM_WARN(
"%s: Got UIH for dlci=%d in invalid state=%d, flags=%#x\n",
			__func__, dlci, pcb->state, pcb->flags);
		error = EINVAL;
		goto drop1;
	}

	/* Check dlci flow control */
	if (((pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) && pcb->rx_cred <= 0) ||
	     (pcb->lmodem & RFCOMM_MODEM_FC)) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Got UIH for dlci=%d with asserted flow control, state=%d, " \
"flags=%#x, rx_cred=%d, lmodem=%#x\n",
			__func__, dlci, pcb->state, pcb->flags,
			pcb->rx_cred, pcb->lmodem);
		goto drop1;
	}

	/* Did we get any credits? */
	if ((pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) && pf) {
		NG_BTSOCKET_RFCOMM_INFO(
"%s: Got %d more credits for dlci=%d, state=%d, flags=%#x, " \
"rx_cred=%d, tx_cred=%d\n",
			__func__, *mtod(m0, u_int8_t *), dlci, pcb->state, 
			pcb->flags, pcb->rx_cred, pcb->tx_cred);

		pcb->tx_cred += *mtod(m0, u_int8_t *);
		m_adj(m0, 1);

		/* Send more from the DLC. XXX check for errors? */
		ng_btsocket_rfcomm_pcb_send(pcb, ALOT);
	} 

	/* OK the of the rest of the mbuf is the data */
	if (m0->m_pkthdr.len > 0) {
		/* If we are using credit flow control decrease rx_cred here */
		if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) {
			/* Give remote peer more credits (if needed) */
			if (-- pcb->rx_cred <= RFCOMM_MAX_CREDITS / 2)
				ng_btsocket_rfcomm_send_credits(pcb);
			else
				NG_BTSOCKET_RFCOMM_INFO(
"%s: Remote side still has credits, dlci=%d, state=%d, flags=%#x, " \
"rx_cred=%d, tx_cred=%d\n",		__func__, dlci, pcb->state, pcb->flags,
					pcb->rx_cred, pcb->tx_cred);
		}
		
		/* Check packet against mtu on dlci */
		if (m0->m_pkthdr.len > pcb->mtu) {
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Got oversized UIH for dlci=%d, state=%d, flags=%#x, mtu=%d, len=%d\n",
				__func__, dlci, pcb->state, pcb->flags,
				pcb->mtu, m0->m_pkthdr.len);

			error = EMSGSIZE;
		} else if (m0->m_pkthdr.len > ssb_space(&pcb->so->so_rcv)) {
 
			/*
			 * This is really bad. Receive queue on socket does
			 * not have enough space for the packet. We do not
			 * have any other choice but drop the packet. 
			 */
 
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Not enough space in socket receive queue. Dropping UIH for dlci=%d, " \
"state=%d, flags=%#x, len=%d, space=%ld\n",
				__func__, dlci, pcb->state, pcb->flags,
				m0->m_pkthdr.len, ssb_space(&pcb->so->so_rcv));

			error = ENOBUFS;
		} else {
			/* Append packet to the socket receive queue */
			sbappend(&pcb->so->so_rcv.sb, m0);
			m0 = NULL;

			sorwakeup(pcb->so);
		}
	}
drop1:
	lockmgr(&pcb->pcb_lock, LK_RELEASE);
drop:
	NG_FREE_M(m0); /* checks for != NULL */

	return (error);
} /* ng_btsocket_rfcomm_receive_uih */

/*
 * Process RFCOMM MCC command (Multiplexor)
 * 
 * From TS 07.10 spec
 *
 * "5.4.3.1 Information Data
 * 
 *  ...The frames (UIH) sent by the initiating station have the C/R bit set 
 *  to 1 and those sent by the responding station have the C/R bit set to 0..."
 *
 * "5.4.6.2 Operating procedures
 *
 *  Messages always exist in pairs; a command message and a corresponding 
 *  response message. If the C/R bit is set to 1 the message is a command, 
 *  if it is set to 0 the message is a response...
 *
 *  ...
 * 
 *  NOTE: Notice that when UIH frames are used to convey information on DLCI 0
 *  there are at least two different fields that contain a C/R bit, and the 
 *  bits are set of different form. The C/R bit in the Type field shall be set
 *  as it is stated above, while the C/R bit in the Address field (see subclause
 *  5.2.1.2) shall be set as it is described in subclause 5.4.3.1."
 */

static int
ng_btsocket_rfcomm_receive_mcc(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr	*hdr = NULL;
	u_int8_t		 cr, type, length;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * We can access data directly in the first mbuf, because we have
	 * m_pullup()'ed mbuf chain in ng_btsocket_rfcomm_receive_frame().
	 * All MCC commands should fit into single mbuf (except probably TEST).
	 */

	hdr = mtod(m0, struct rfcomm_mcc_hdr *);
	cr = RFCOMM_CR(hdr->type);
	type = RFCOMM_MCC_TYPE(hdr->type);
	length = RFCOMM_MCC_LENGTH(hdr->length);

	/* Check MCC frame length */
	if (sizeof(*hdr) + length != m0->m_pkthdr.len) {
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Invalid MCC frame length=%d, len=%d\n",
			__func__, length, m0->m_pkthdr.len);
		NG_FREE_M(m0);

		return (EMSGSIZE);
	}

	switch (type) {
	case RFCOMM_MCC_TEST:
		return (ng_btsocket_rfcomm_receive_test(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_FCON:
	case RFCOMM_MCC_FCOFF:
		return (ng_btsocket_rfcomm_receive_fc(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_MSC:
		return (ng_btsocket_rfcomm_receive_msc(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_RPN:
		return (ng_btsocket_rfcomm_receive_rpn(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_RLS:
		return (ng_btsocket_rfcomm_receive_rls(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_PN:
		return (ng_btsocket_rfcomm_receive_pn(s, m0));
		/* NOT REACHED */

	case RFCOMM_MCC_NSC:
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Got MCC NSC, type=%#x, cr=%d, length=%d, session state=%d, flags=%#x, " \
"mtu=%d, len=%d\n",	__func__, RFCOMM_MCC_TYPE(*((u_int8_t *)(hdr + 1))), cr,
			 length, s->state, s->flags, s->mtu, m0->m_pkthdr.len);
		NG_FREE_M(m0);
		break;

	default:
		NG_BTSOCKET_RFCOMM_ERR(
"%s: Got unknown MCC, type=%#x, cr=%d, length=%d, session state=%d, " \
"flags=%#x, mtu=%d, len=%d\n",
			__func__, type, cr, length, s->state, s->flags,
			s->mtu, m0->m_pkthdr.len);

		/* Reuse mbuf to send NSC */
		hdr = mtod(m0, struct rfcomm_mcc_hdr *);
		m0->m_pkthdr.len = m0->m_len = sizeof(*hdr);

		/* Create MCC NSC header */
		hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_NSC);
		hdr->length = RFCOMM_MKLEN8(1);

		/* Put back MCC command type we did not like */
		m0->m_data[m0->m_len] = RFCOMM_MKMCC_TYPE(cr, type);
		m0->m_pkthdr.len ++;
		m0->m_len ++;

		/* Send UIH frame */
		return (ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0));
		/* NOT REACHED */
	}

	return (0);
} /* ng_btsocket_rfcomm_receive_mcc */

/*
 * Receive RFCOMM TEST MCC command
 */

static int
ng_btsocket_rfcomm_receive_test(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr	*hdr = mtod(m0, struct rfcomm_mcc_hdr *);
	int			 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC TEST, cr=%d, length=%d, session state=%d, flags=%#x, mtu=%d, " \
"len=%d\n",	__func__, RFCOMM_CR(hdr->type), RFCOMM_MCC_LENGTH(hdr->length),
		s->state, s->flags, s->mtu, m0->m_pkthdr.len);

	if (RFCOMM_CR(hdr->type)) {
		hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_TEST);
		error = ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0);
	} else
		NG_FREE_M(m0); /* XXX ignore response */

	return (error);
} /* ng_btsocket_rfcomm_receive_test */

/*
 * Receive RFCOMM FCON/FCOFF MCC command
 */

static int
ng_btsocket_rfcomm_receive_fc(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr	*hdr = mtod(m0, struct rfcomm_mcc_hdr *);
	u_int8_t		 type = RFCOMM_MCC_TYPE(hdr->type);
	int			 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * Turn ON/OFF aggregate flow on the entire session. When remote peer 
	 * asserted flow control no transmission shall occur except on dlci 0
	 * (control channel).
	 */

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC FC%s, cr=%d, length=%d, session state=%d, flags=%#x, mtu=%d, " \
"len=%d\n",	__func__, (type == RFCOMM_MCC_FCON)? "ON" : "OFF",
		RFCOMM_CR(hdr->type), RFCOMM_MCC_LENGTH(hdr->length),
		s->state, s->flags, s->mtu, m0->m_pkthdr.len);

	if (RFCOMM_CR(hdr->type)) {
		if (type == RFCOMM_MCC_FCON)
			s->flags &= ~NG_BTSOCKET_RFCOMM_SESSION_RFC;
		else
			s->flags |= NG_BTSOCKET_RFCOMM_SESSION_RFC;

		hdr->type = RFCOMM_MKMCC_TYPE(0, type);
		error = ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0);
	} else
		NG_FREE_M(m0); /* XXX ignore response */

	return (error);
} /* ng_btsocket_rfcomm_receive_fc  */

/*
 * Receive RFCOMM MSC MCC command
 */

static int
ng_btsocket_rfcomm_receive_msc(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr		*hdr = mtod(m0, struct rfcomm_mcc_hdr*);
	struct rfcomm_mcc_msc		*msc = (struct rfcomm_mcc_msc *)(hdr+1);
	ng_btsocket_rfcomm_pcb_t	*pcb = NULL;
	int				 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC MSC, dlci=%d, cr=%d, length=%d, session state=%d, flags=%#x, " \
"mtu=%d, len=%d\n",
		__func__,  RFCOMM_DLCI(msc->address), RFCOMM_CR(hdr->type),
		RFCOMM_MCC_LENGTH(hdr->length), s->state, s->flags,
		s->mtu, m0->m_pkthdr.len);

	if (RFCOMM_CR(hdr->type)) {
		pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, RFCOMM_DLCI(msc->address));
		if (pcb == NULL) {
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got MSC command for non-existing dlci=%d\n",
				__func__, RFCOMM_DLCI(msc->address));
			NG_FREE_M(m0);

			return (ENOENT);
		}

		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

		if (pcb->state != NG_BTSOCKET_RFCOMM_DLC_CONNECTING &&
		    pcb->state != NG_BTSOCKET_RFCOMM_DLC_CONNECTED) {
			NG_BTSOCKET_RFCOMM_WARN(
"%s: Got MSC on dlci=%d in invalid state=%d\n",
				__func__, RFCOMM_DLCI(msc->address),
				pcb->state);

			lockmgr(&pcb->pcb_lock, LK_RELEASE);
			NG_FREE_M(m0);

			return (EINVAL);
		}

		pcb->rmodem = msc->modem; /* Update remote port signals */

		hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_MSC);
		error = ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0);

#if 0 /* YYY */
		/* Send more data from DLC. XXX check for errors? */
		if (!(pcb->rmodem & RFCOMM_MODEM_FC) &&
		    !(pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC))
			ng_btsocket_rfcomm_pcb_send(pcb, ALOT);
#endif /* YYY */

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
	} else
		NG_FREE_M(m0); /* XXX ignore response */

	return (error);
} /* ng_btsocket_rfcomm_receive_msc */

/*
 * Receive RFCOMM RPN MCC command
 * XXX FIXME do we need htole16/le16toh for RPN param_mask?
 */

static int
ng_btsocket_rfcomm_receive_rpn(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr	*hdr = mtod(m0, struct rfcomm_mcc_hdr *);
	struct rfcomm_mcc_rpn	*rpn = (struct rfcomm_mcc_rpn *)(hdr + 1);
	int			 error = 0;
	u_int16_t		 param_mask;
	u_int8_t		 bit_rate, data_bits, stop_bits, parity,
				 flow_control, xon_char, xoff_char;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC RPN, dlci=%d, cr=%d, length=%d, session state=%d, flags=%#x, " \
"mtu=%d, len=%d\n",
		__func__, RFCOMM_DLCI(rpn->dlci), RFCOMM_CR(hdr->type),
		RFCOMM_MCC_LENGTH(hdr->length), s->state, s->flags,
		s->mtu, m0->m_pkthdr.len);

	if (RFCOMM_CR(hdr->type)) {
		param_mask = RFCOMM_RPN_PM_ALL;

		if (RFCOMM_MCC_LENGTH(hdr->length) == 1) {
			/* Request - return default setting */
			bit_rate = RFCOMM_RPN_BR_115200;
			data_bits = RFCOMM_RPN_DATA_8;
			stop_bits = RFCOMM_RPN_STOP_1;
			parity = RFCOMM_RPN_PARITY_NONE;
			flow_control = RFCOMM_RPN_FLOW_NONE;
			xon_char = RFCOMM_RPN_XON_CHAR;
			xoff_char = RFCOMM_RPN_XOFF_CHAR;
                } else {
			/*
			 * Ignore/accept bit_rate, 8 bits, 1 stop bit, no 
			 * parity, no flow control lines, default XON/XOFF 
			 * chars.
			 */

			bit_rate = rpn->bit_rate;
			rpn->param_mask = le16toh(rpn->param_mask); /* XXX */

			data_bits = RFCOMM_RPN_DATA_BITS(rpn->line_settings);
			if (rpn->param_mask & RFCOMM_RPN_PM_DATA &&
			    data_bits != RFCOMM_RPN_DATA_8) {
				data_bits = RFCOMM_RPN_DATA_8;
				param_mask ^= RFCOMM_RPN_PM_DATA;
			}

			stop_bits = RFCOMM_RPN_STOP_BITS(rpn->line_settings);
			if (rpn->param_mask & RFCOMM_RPN_PM_STOP &&
			    stop_bits != RFCOMM_RPN_STOP_1) {
				stop_bits = RFCOMM_RPN_STOP_1;
				param_mask ^= RFCOMM_RPN_PM_STOP;
			}

			parity = RFCOMM_RPN_PARITY(rpn->line_settings);
			if (rpn->param_mask & RFCOMM_RPN_PM_PARITY &&
			    parity != RFCOMM_RPN_PARITY_NONE) {
				parity = RFCOMM_RPN_PARITY_NONE;
				param_mask ^= RFCOMM_RPN_PM_PARITY;
			}

			flow_control = rpn->flow_control;
			if (rpn->param_mask & RFCOMM_RPN_PM_FLOW &&
			    flow_control != RFCOMM_RPN_FLOW_NONE) {
				flow_control = RFCOMM_RPN_FLOW_NONE;
				param_mask ^= RFCOMM_RPN_PM_FLOW;
			}

			xon_char = rpn->xon_char;
			if (rpn->param_mask & RFCOMM_RPN_PM_XON &&
			    xon_char != RFCOMM_RPN_XON_CHAR) {
				xon_char = RFCOMM_RPN_XON_CHAR;
				param_mask ^= RFCOMM_RPN_PM_XON;
			}

			xoff_char = rpn->xoff_char;
			if (rpn->param_mask & RFCOMM_RPN_PM_XOFF &&
			    xoff_char != RFCOMM_RPN_XOFF_CHAR) {
				xoff_char = RFCOMM_RPN_XOFF_CHAR;
				param_mask ^= RFCOMM_RPN_PM_XOFF;
			}
		}

		rpn->bit_rate = bit_rate;
		rpn->line_settings = RFCOMM_MKRPN_LINE_SETTINGS(data_bits, 
						stop_bits, parity);
		rpn->flow_control = flow_control;
		rpn->xon_char = xon_char;
		rpn->xoff_char = xoff_char;
		rpn->param_mask = htole16(param_mask); /* XXX */

		m0->m_pkthdr.len = m0->m_len = sizeof(*hdr) + sizeof(*rpn);

		hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_RPN);
		error = ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0);
	} else
		NG_FREE_M(m0); /* XXX ignore response */

	return (error);
} /* ng_btsocket_rfcomm_receive_rpn */

/*
 * Receive RFCOMM RLS MCC command
 */

static int
ng_btsocket_rfcomm_receive_rls(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr	*hdr = mtod(m0, struct rfcomm_mcc_hdr *);
	struct rfcomm_mcc_rls	*rls = (struct rfcomm_mcc_rls *)(hdr + 1);
	int			 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	/*
	 * XXX FIXME Do we have to do anything else here? Remote peer tries to 
	 * tell us something about DLCI. Just report what we have received and
	 * return back received values as required by TS 07.10 spec.
	 */

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC RLS, dlci=%d, status=%#x, cr=%d, length=%d, session state=%d, " \
"flags=%#x, mtu=%d, len=%d\n",
		__func__, RFCOMM_DLCI(rls->address), rls->status,
		RFCOMM_CR(hdr->type), RFCOMM_MCC_LENGTH(hdr->length),
		s->state, s->flags, s->mtu, m0->m_pkthdr.len);

	if (RFCOMM_CR(hdr->type)) {
		if (rls->status & 0x1)
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Got RLS dlci=%d, error=%#x\n", __func__, RFCOMM_DLCI(rls->address),
				rls->status >> 1);

		hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_RLS);
		error = ng_btsocket_rfcomm_send_uih(s,
				RFCOMM_MKADDRESS(INITIATOR(s), 0), 0, 0, m0);
	} else
		NG_FREE_M(m0); /* XXX ignore responses */

	return (error);
} /* ng_btsocket_rfcomm_receive_rls */

/*
 * Receive RFCOMM PN MCC command
 */

static int
ng_btsocket_rfcomm_receive_pn(ng_btsocket_rfcomm_session_p s, struct mbuf *m0)
{
	struct rfcomm_mcc_hdr		*hdr = mtod(m0, struct rfcomm_mcc_hdr*);
	struct rfcomm_mcc_pn		*pn = (struct rfcomm_mcc_pn *)(hdr+1);
	ng_btsocket_rfcomm_pcb_t	*pcb = NULL;
	int				 error = 0;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Got MCC PN, dlci=%d, cr=%d, length=%d, flow_control=%#x, priority=%d, " \
"ack_timer=%d, mtu=%d, max_retrans=%d, credits=%d, session state=%d, " \
"flags=%#x, session mtu=%d, len=%d\n",
		__func__, pn->dlci, RFCOMM_CR(hdr->type),
		RFCOMM_MCC_LENGTH(hdr->length), pn->flow_control, pn->priority,
		pn->ack_timer, le16toh(pn->mtu), pn->max_retrans, pn->credits,
		s->state, s->flags, s->mtu, m0->m_pkthdr.len);

	if (pn->dlci == 0) {
		NG_BTSOCKET_RFCOMM_ERR("%s: Zero dlci in MCC PN\n", __func__);
		NG_FREE_M(m0);

		return (EINVAL);
	}

	/* Check if we have this dlci */
	pcb = ng_btsocket_rfcomm_pcb_by_dlci(s, pn->dlci);
	if (pcb != NULL) {
		lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

		if (RFCOMM_CR(hdr->type)) {
			/* PN Request */
			ng_btsocket_rfcomm_set_pn(pcb, 1, pn->flow_control,
				pn->credits, pn->mtu);

			if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) {
				pn->flow_control = 0xe0;
				pn->credits = RFCOMM_DEFAULT_CREDITS;
			} else {
				pn->flow_control = 0;
				pn->credits = 0;
			}

			hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_PN);
			error = ng_btsocket_rfcomm_send_uih(s, 
					RFCOMM_MKADDRESS(INITIATOR(s), 0),
					0, 0, m0);
		} else {
			/* PN Response - proceed with SABM. Timeout still set */
			if (pcb->state == NG_BTSOCKET_RFCOMM_DLC_CONFIGURING) {
				ng_btsocket_rfcomm_set_pn(pcb, 0,
					pn->flow_control, pn->credits, pn->mtu);

				pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONNECTING;
				error = ng_btsocket_rfcomm_send_command(s,
						RFCOMM_FRAME_SABM, pn->dlci);
			} else
				NG_BTSOCKET_RFCOMM_WARN(
"%s: Got PN response for dlci=%d in invalid state=%d\n",
					__func__, pn->dlci, pcb->state);

			NG_FREE_M(m0);
		}

		lockmgr(&pcb->pcb_lock, LK_RELEASE);
	} else if (RFCOMM_CR(hdr->type)) {
		/* PN request to non-existing dlci - incomming connection */
		pcb = ng_btsocket_rfcomm_connect_ind(s,
				RFCOMM_SRVCHANNEL(pn->dlci));
		if (pcb != NULL) {
			lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

			pcb->dlci = pn->dlci;

			ng_btsocket_rfcomm_set_pn(pcb, 1, pn->flow_control,
				pn->credits, pn->mtu);

			if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) {
				pn->flow_control = 0xe0;
				pn->credits = RFCOMM_DEFAULT_CREDITS;
			} else {
				pn->flow_control = 0;
				pn->credits = 0;
			}

			hdr->type = RFCOMM_MKMCC_TYPE(0, RFCOMM_MCC_PN);
			error = ng_btsocket_rfcomm_send_uih(s, 
					RFCOMM_MKADDRESS(INITIATOR(s), 0),
					0, 0, m0);

			if (error == 0) {
				ng_btsocket_rfcomm_timeout(pcb);
				pcb->state = NG_BTSOCKET_RFCOMM_DLC_CONNECTING;
				soisconnecting(pcb->so);
			} else
				ng_btsocket_rfcomm_pcb_kill(pcb, error);

			lockmgr(&pcb->pcb_lock, LK_RELEASE);
		} else {
			/* Nobody is listen()ing on this channel */
			error = ng_btsocket_rfcomm_send_command(s,
					RFCOMM_FRAME_DM, pn->dlci);
			NG_FREE_M(m0);
		}
	} else
		NG_FREE_M(m0); /* XXX ignore response to non-existing dlci */

	return (error);
} /* ng_btsocket_rfcomm_receive_pn */

/*
 * Set PN parameters for dlci. Caller must hold pcb->pcb_mtx.
 * 
 * From Bluetooth spec.
 * 
 * "... The CL1 - CL4 field is completely redefined. (In TS07.10 this defines 
 *  the convergence layer to use, which is not applicable to RFCOMM. In RFCOMM,
 *  in Bluetooth versions up to 1.0B, this field was forced to 0).
 *
 *  In the PN request sent prior to a DLC establishment, this field must contain
 *  the value 15 (0xF), indicating support of credit based flow control in the 
 *  sender. See Table 5.3 below. If the PN response contains any other value 
 *  than 14 (0xE) in this field, it is inferred that the peer RFCOMM entity is 
 *  not supporting the credit based flow control feature. (This is only possible
 *  if the peer RFCOMM implementation is only conforming to Bluetooth version 
 *  1.0B.) If a PN request is sent on an already open DLC, then this field must
 *  contain the value zero; it is not possible to set initial credits  more 
 *  than once per DLC activation. A responding implementation must set this 
 *  field in the PN response to 14 (0xE), if (and only if) the value in the PN 
 *  request was 15..."
 */

static void
ng_btsocket_rfcomm_set_pn(ng_btsocket_rfcomm_pcb_p pcb, u_int8_t cr,
		u_int8_t flow_control, u_int8_t credits, u_int16_t mtu)
{
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	pcb->mtu = le16toh(mtu);

	if (cr) {
		if (flow_control == 0xf0) {
			pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_CFC;
			pcb->tx_cred = credits;
		} else {
			pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_CFC;
			pcb->tx_cred = 0;
		}
	} else {
		if (flow_control == 0xe0) {
			pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_CFC;
			pcb->tx_cred = credits;
		} else {
			pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_CFC;
			pcb->tx_cred = 0;
		}
	}

	NG_BTSOCKET_RFCOMM_INFO(
"%s: cr=%d, dlci=%d, state=%d, flags=%#x, mtu=%d, rx_cred=%d, tx_cred=%d\n",
		__func__, cr, pcb->dlci, pcb->state, pcb->flags, pcb->mtu,
		pcb->rx_cred, pcb->tx_cred);
} /* ng_btsocket_rfcomm_set_pn */

/*
 * Send RFCOMM SABM/DISC/UA/DM frames. Caller must hold s->session_mtx
 */

static int
ng_btsocket_rfcomm_send_command(ng_btsocket_rfcomm_session_p s,
		u_int8_t type, u_int8_t dlci)
{
	struct rfcomm_cmd_hdr	*hdr = NULL;
	struct mbuf		*m = NULL;
	int			 cr;

	KKASSERT(lockowned(&s->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Sending command type %#x, session state=%d, flags=%#x, mtu=%d, dlci=%d\n",
		__func__, type, s->state, s->flags, s->mtu, dlci);

	switch (type) {
	case RFCOMM_FRAME_SABM:
	case RFCOMM_FRAME_DISC:
		cr = INITIATOR(s);
		break;

	case RFCOMM_FRAME_UA:
	case RFCOMM_FRAME_DM:
		cr = !INITIATOR(s);
		break;

	default:
		panic("%s: Invalid frame type=%#x", __func__, type);
		return (EINVAL);
		/* NOT REACHED */
	}

	MGETHDR(m, M_NOWAIT, MT_DATA);
	if (m == NULL)
		return (ENOBUFS);

	m->m_pkthdr.len = m->m_len = sizeof(*hdr);

	hdr = mtod(m, struct rfcomm_cmd_hdr *);
	hdr->address = RFCOMM_MKADDRESS(cr, dlci);
	hdr->control = RFCOMM_MKCONTROL(type, 1);
	hdr->length = RFCOMM_MKLEN8(0);
	hdr->fcs = ng_btsocket_rfcomm_fcs3((u_int8_t *) hdr);

	NG_BT_MBUFQ_ENQUEUE(&s->outq, m);

	return (0);
} /* ng_btsocket_rfcomm_send_command */

/*
 * Send RFCOMM UIH frame. Caller must hold s->session_mtx
 */

static int
ng_btsocket_rfcomm_send_uih(ng_btsocket_rfcomm_session_p s, u_int8_t address,
		u_int8_t pf, u_int8_t credits, struct mbuf *data)
{
	struct rfcomm_frame_hdr	*hdr = NULL;
	struct mbuf		*m = NULL, *mcrc = NULL;
	u_int16_t		 length;

	KKASSERT(lockowned(&s->session_lock) != 0);

	MGETHDR(m, M_NOWAIT, MT_DATA);
	if (m == NULL) {
		NG_FREE_M(data);
		return (ENOBUFS);
	}
	m->m_pkthdr.len = m->m_len = sizeof(*hdr);

	MGET(mcrc, M_NOWAIT, MT_DATA);
	if (mcrc == NULL) {
		NG_FREE_M(data);
		return (ENOBUFS);
	}
	mcrc->m_len = 1;

	/* Fill UIH frame header */
	hdr = mtod(m, struct rfcomm_frame_hdr *);
	hdr->address = address;
	hdr->control = RFCOMM_MKCONTROL(RFCOMM_FRAME_UIH, pf);

	/* Calculate FCS */
	mcrc->m_data[0] = ng_btsocket_rfcomm_fcs2((u_int8_t *) hdr);

	/* Put length back */
	length = (data != NULL)? data->m_pkthdr.len : 0;
	if (length > 127) {
		u_int16_t	l = htole16(RFCOMM_MKLEN16(length));

		bcopy(&l, &hdr->length, sizeof(l));
		m->m_pkthdr.len ++;
		m->m_len ++;
	} else
		hdr->length = RFCOMM_MKLEN8(length);

	if (pf) {
		m->m_data[m->m_len] = credits;
		m->m_pkthdr.len ++;
		m->m_len ++;
	}

	/* Add payload */
	if (data != NULL) {
		m_cat(m, data);
		m->m_pkthdr.len += length;
	}

	/* Put FCS back */
	m_cat(m, mcrc);
	m->m_pkthdr.len ++;

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Sending UIH state=%d, flags=%#x, address=%d, length=%d, pf=%d, " \
"credits=%d, len=%d\n",
		__func__, s->state, s->flags, address, length, pf, credits,
		m->m_pkthdr.len);

	NG_BT_MBUFQ_ENQUEUE(&s->outq, m);

	return (0);
} /* ng_btsocket_rfcomm_send_uih */

/*
 * Send MSC request. Caller must hold pcb->pcb_mtx and pcb->session->session_mtx
 */

static int
ng_btsocket_rfcomm_send_msc(ng_btsocket_rfcomm_pcb_p pcb)
{
	struct mbuf		*m = NULL;
	struct rfcomm_mcc_hdr	*hdr = NULL;
	struct rfcomm_mcc_msc	*msc = NULL;

	KKASSERT(lockowned(&pcb->session->session_lock) != 0);
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	MGETHDR(m, M_NOWAIT, MT_DATA);
	if (m == NULL)
		return (ENOBUFS);

	m->m_pkthdr.len = m->m_len = sizeof(*hdr) + sizeof(*msc);

	hdr = mtod(m, struct rfcomm_mcc_hdr *);
	msc = (struct rfcomm_mcc_msc *)(hdr + 1);

	hdr->type = RFCOMM_MKMCC_TYPE(1, RFCOMM_MCC_MSC);
	hdr->length = RFCOMM_MKLEN8(sizeof(*msc));

	msc->address = RFCOMM_MKADDRESS(1, pcb->dlci);
	msc->modem = pcb->lmodem;

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Sending MSC dlci=%d, state=%d, flags=%#x, address=%d, modem=%#x\n",
		__func__, pcb->dlci, pcb->state, pcb->flags, msc->address,
		msc->modem);

	return (ng_btsocket_rfcomm_send_uih(pcb->session,
			RFCOMM_MKADDRESS(INITIATOR(pcb->session), 0), 0, 0, m));
} /* ng_btsocket_rfcomm_send_msc */

/*
 * Send PN request. Caller must hold pcb->pcb_mtx and pcb->session->session_mtx
 */

static int
ng_btsocket_rfcomm_send_pn(ng_btsocket_rfcomm_pcb_p pcb)
{
	struct mbuf		*m = NULL;
	struct rfcomm_mcc_hdr	*hdr = NULL;
	struct rfcomm_mcc_pn	*pn = NULL;

	KKASSERT(lockowned(&pcb->session->session_lock) != 0);
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	MGETHDR(m, M_NOWAIT, MT_DATA);
	if (m == NULL)
		return (ENOBUFS);

	m->m_pkthdr.len = m->m_len = sizeof(*hdr) + sizeof(*pn);

	hdr = mtod(m, struct rfcomm_mcc_hdr *);
	pn = (struct rfcomm_mcc_pn *)(hdr + 1);

	hdr->type = RFCOMM_MKMCC_TYPE(1, RFCOMM_MCC_PN);
	hdr->length = RFCOMM_MKLEN8(sizeof(*pn));

	pn->dlci = pcb->dlci;

	/*
	 * Set default DLCI priority as described in GSM 07.10
	 * (ETSI TS 101 369) clause 5.6 page 42
	 */

	pn->priority = (pcb->dlci < 56)? (((pcb->dlci >> 3) << 3) + 7) : 61;
	pn->ack_timer = 0;
	pn->mtu = htole16(pcb->mtu);
	pn->max_retrans = 0;

	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC) {
		pn->flow_control = 0xf0;
		pn->credits = pcb->rx_cred;
	} else {
		pn->flow_control = 0;
		pn->credits = 0;
	}

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Sending PN dlci=%d, state=%d, flags=%#x, mtu=%d, flow_control=%#x, " \
"credits=%d\n",	__func__, pcb->dlci, pcb->state, pcb->flags, pcb->mtu,
		pn->flow_control, pn->credits);

	return (ng_btsocket_rfcomm_send_uih(pcb->session,
			RFCOMM_MKADDRESS(INITIATOR(pcb->session), 0), 0, 0, m));
} /* ng_btsocket_rfcomm_send_pn */

/*
 * Calculate and send credits based on available space in receive buffer
 */

static int
ng_btsocket_rfcomm_send_credits(ng_btsocket_rfcomm_pcb_p pcb)
{
	int		error = 0;
	u_int8_t	credits;

	KKASSERT(lockowned(&pcb->pcb_lock) != 0);
	KKASSERT(lockowned(&pcb->session->session_lock) != 0);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Sending more credits, dlci=%d, state=%d, flags=%#x, mtu=%d, " \
"space=%ld, tx_cred=%d, rx_cred=%d\n",
		__func__, pcb->dlci, pcb->state, pcb->flags, pcb->mtu,
		ssb_space(&pcb->so->so_rcv), pcb->tx_cred, pcb->rx_cred);

	credits = ssb_space(&pcb->so->so_rcv) / pcb->mtu;
	if (credits > 0) {
		if (pcb->rx_cred + credits > RFCOMM_MAX_CREDITS)
			credits = RFCOMM_MAX_CREDITS - pcb->rx_cred;

		error = ng_btsocket_rfcomm_send_uih(
				pcb->session,
				RFCOMM_MKADDRESS(INITIATOR(pcb->session),
					pcb->dlci), 1, credits, NULL);
		if (error == 0) {
			pcb->rx_cred += credits;

			NG_BTSOCKET_RFCOMM_INFO(
"%s: Gave remote side %d more credits, dlci=%d, state=%d, flags=%#x, " \
"rx_cred=%d, tx_cred=%d\n",	__func__, credits, pcb->dlci, pcb->state,
				pcb->flags, pcb->rx_cred, pcb->tx_cred);
		} else
			NG_BTSOCKET_RFCOMM_ERR(
"%s: Could not send credits, error=%d, dlci=%d, state=%d, flags=%#x, " \
"mtu=%d, space=%ld, tx_cred=%d, rx_cred=%d\n",
				__func__, error, pcb->dlci, pcb->state,
				pcb->flags, pcb->mtu, ssb_space(&pcb->so->so_rcv),
				pcb->tx_cred, pcb->rx_cred);
	}

	return (error);
} /* ng_btsocket_rfcomm_send_credits */

/*****************************************************************************
 *****************************************************************************
 **                              RFCOMM DLCs
 *****************************************************************************
 *****************************************************************************/

/*
 * Send data from socket send buffer
 * Caller must hold pcb->pcb_mtx and pcb->session->session_mtx
 */

static int
ng_btsocket_rfcomm_pcb_send(ng_btsocket_rfcomm_pcb_p pcb, int limit)
{
	struct mbuf	*m = NULL;
	int		 sent, length, error;

	KKASSERT(lockowned(&pcb->session->session_lock) != 0);
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC)
		limit = min(limit, pcb->tx_cred);
	else if (!(pcb->rmodem & RFCOMM_MODEM_FC))
		limit = min(limit, RFCOMM_MAX_CREDITS); /* XXX ??? */
	else
		limit = 0;

	if (limit == 0) {
		NG_BTSOCKET_RFCOMM_INFO(
"%s: Could not send - remote flow control asserted, dlci=%d, flags=%#x, " \
"rmodem=%#x, tx_cred=%d\n",
			__func__, pcb->dlci, pcb->flags, pcb->rmodem,
			pcb->tx_cred);

		return (0);
	}

	for (error = 0, sent = 0; sent < limit; sent ++) { 
		length = min(pcb->mtu, pcb->so->so_snd.sb.sb_cc);
		if (length == 0)
			break;

		/* Get the chunk from the socket's send buffer */
		m = ng_btsocket_rfcomm_prepare_packet(&pcb->so->so_snd.sb,
		    length);
		if (m == NULL) {
			error = ENOBUFS;
			break;
		}

		sbdrop(&pcb->so->so_snd.sb, length);

		error = ng_btsocket_rfcomm_send_uih(pcb->session,
				RFCOMM_MKADDRESS(INITIATOR(pcb->session),
					pcb->dlci), 0, 0, m);
		if (error != 0)
			break;
	}

	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_CFC)
		pcb->tx_cred -= sent;

	if (error == 0 && sent > 0) {
		pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_SENDING;
		sowwakeup(pcb->so);
	}

	return (error);
} /* ng_btsocket_rfcomm_pcb_send */

/*
 * Unlink and disconnect DLC. If ng_btsocket_rfcomm_pcb_kill() returns
 * non zero value than socket has no reference and has to be detached.
 * Caller must hold pcb->pcb_mtx and pcb->session->session_mtx
 */

static void
ng_btsocket_rfcomm_pcb_kill(ng_btsocket_rfcomm_pcb_p pcb, int error)
{
	ng_btsocket_rfcomm_session_p	s = pcb->session;

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Killing DLC, so=%p, dlci=%d, state=%d, flags=%#x, error=%d\n",
		__func__, pcb->so, pcb->dlci, pcb->state, pcb->flags, error);

	if (pcb->session == NULL)
		panic("%s: DLC without session, pcb=%p, state=%d, flags=%#x",
			__func__, pcb, pcb->state, pcb->flags);

	KKASSERT(lockowned(&pcb->session->session_lock) != 0);
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)
		ng_btsocket_rfcomm_untimeout(pcb);

	/* Detach DLC from the session. Does not matter which state DLC in */
	LIST_REMOVE(pcb, session_next);
	pcb->session = NULL;

	/* Change DLC state and wakeup all sleepers */
	pcb->state = NG_BTSOCKET_RFCOMM_DLC_CLOSED;
	pcb->so->so_error = error;
	soisdisconnected(pcb->so);
	wakeup(&pcb->state);

	/* Check if we have any DLCs left on the session */
	if (LIST_EMPTY(&s->dlcs) && INITIATOR(s)) {
		NG_BTSOCKET_RFCOMM_INFO(
"%s: Disconnecting session, state=%d, flags=%#x, mtu=%d\n",
			__func__, s->state, s->flags, s->mtu);

		switch (s->state) {
		case NG_BTSOCKET_RFCOMM_SESSION_CLOSED:
		case NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING:
			/*
			 * Do not have to do anything here. We can get here
			 * when L2CAP connection was terminated or we have 
			 * received DISC on multiplexor channel
			 */
			break;

		case NG_BTSOCKET_RFCOMM_SESSION_OPEN:
			/* Send DISC on multiplexor channel */
			error = ng_btsocket_rfcomm_send_command(s,
					RFCOMM_FRAME_DISC, 0);
			if (error == 0) {
				s->state = NG_BTSOCKET_RFCOMM_SESSION_DISCONNECTING;
				break;
			}
			/* FALL THROUGH */

		case NG_BTSOCKET_RFCOMM_SESSION_CONNECTING:
		case NG_BTSOCKET_RFCOMM_SESSION_CONNECTED:
			s->state = NG_BTSOCKET_RFCOMM_SESSION_CLOSED;
			break;

/*		case NG_BTSOCKET_RFCOMM_SESSION_LISTENING: */
		default:
			panic("%s: Invalid session state=%d, flags=%#x",
				__func__, s->state, s->flags);
			break;
		}

		ng_btsocket_rfcomm_task_wakeup();
	}
} /* ng_btsocket_rfcomm_pcb_kill */

/*
 * Look for given dlci for given RFCOMM session. Caller must hold s->session_mtx
 */

static ng_btsocket_rfcomm_pcb_p
ng_btsocket_rfcomm_pcb_by_dlci(ng_btsocket_rfcomm_session_p s, int dlci)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL;

	KKASSERT(lockowned(&s->session_lock) != 0);

	LIST_FOREACH(pcb, &s->dlcs, session_next)
		if (pcb->dlci == dlci)
			break;

	return (pcb);
} /* ng_btsocket_rfcomm_pcb_by_dlci */

/*
 * Look for socket that listens on given src address and given channel
 */

static ng_btsocket_rfcomm_pcb_p
ng_btsocket_rfcomm_pcb_listener(bdaddr_p src, int channel)
{
	ng_btsocket_rfcomm_pcb_p	pcb = NULL, pcb1 = NULL;

	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_EXCLUSIVE);

	LIST_FOREACH(pcb, &ng_btsocket_rfcomm_sockets, next) {
		if (pcb->channel != channel ||
		    !(pcb->so->so_options & SO_ACCEPTCONN))
			continue;

		if (bcmp(&pcb->src, src, sizeof(*src)) == 0)
			break;

		if (bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0)
			pcb1 = pcb;
	}

	lockmgr(&ng_btsocket_rfcomm_sockets_lock, LK_RELEASE);

	return ((pcb != NULL)? pcb : pcb1);
} /* ng_btsocket_rfcomm_pcb_listener */

/*****************************************************************************
 *****************************************************************************
 **                              Misc. functions 
 *****************************************************************************
 *****************************************************************************/

/*
 *  Set timeout. Caller MUST hold pcb_mtx
 */

static void
ng_btsocket_rfcomm_timeout(ng_btsocket_rfcomm_pcb_p pcb)
{
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	if (!(pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO)) {
		pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_TIMO;
		pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT;
		callout_reset(&pcb->timo, ng_btsocket_rfcomm_timo * hz,
		    ng_btsocket_rfcomm_process_timeout, pcb);
	} else
		panic("%s: Duplicated socket timeout?!", __func__);
} /* ng_btsocket_rfcomm_timeout */

/*
 *  Unset pcb timeout. Caller MUST hold pcb_mtx
 */

static void
ng_btsocket_rfcomm_untimeout(ng_btsocket_rfcomm_pcb_p pcb)
{
	KKASSERT(lockowned(&pcb->pcb_lock) != 0);

	if (pcb->flags & NG_BTSOCKET_RFCOMM_DLC_TIMO) {
		callout_stop(&pcb->timo);
		pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_TIMO;
		pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT;
	} else
		panic("%s: No socket timeout?!", __func__);
} /* ng_btsocket_rfcomm_timeout */

/*
 * Process pcb timeout
 */

static void
ng_btsocket_rfcomm_process_timeout(void *xpcb)
{
	ng_btsocket_rfcomm_pcb_p	pcb = (ng_btsocket_rfcomm_pcb_p) xpcb;

	lockmgr(&pcb->pcb_lock, LK_EXCLUSIVE);

	NG_BTSOCKET_RFCOMM_INFO(
"%s: Timeout, so=%p, dlci=%d, state=%d, flags=%#x\n",
		__func__, pcb->so, pcb->dlci, pcb->state, pcb->flags);

	pcb->flags &= ~NG_BTSOCKET_RFCOMM_DLC_TIMO;
	pcb->flags |= NG_BTSOCKET_RFCOMM_DLC_TIMEDOUT;

	switch (pcb->state) {
	case NG_BTSOCKET_RFCOMM_DLC_CONFIGURING:
	case NG_BTSOCKET_RFCOMM_DLC_CONNECTING:
		pcb->state = NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING;
		break;

	case NG_BTSOCKET_RFCOMM_DLC_W4_CONNECT:
	case NG_BTSOCKET_RFCOMM_DLC_DISCONNECTING:
		break;

	default:
		panic(
"%s: DLC timeout in invalid state, dlci=%d, state=%d, flags=%#x\n",
			__func__, pcb->dlci, pcb->state, pcb->flags);
		break;
	}

	ng_btsocket_rfcomm_task_wakeup();

	lockmgr(&pcb->pcb_lock, LK_RELEASE);
} /* ng_btsocket_rfcomm_process_timeout */

/*
 * Get up to length bytes from the socket buffer
 */

static struct mbuf *
ng_btsocket_rfcomm_prepare_packet(struct sockbuf *sb, int length)
{
	struct mbuf	*top = NULL, *m = NULL, *n = NULL, *nextpkt = NULL;
	int		 mlen, noff, len;

	MGETHDR(top, M_NOWAIT, MT_DATA);
	if (top == NULL)
		return (NULL);

	top->m_pkthdr.len = length;
	top->m_len = 0;
	mlen = MHLEN;

	m = top;
	n = sb->sb_mb;
	nextpkt = n->m_nextpkt;
	noff = 0;

	while (length > 0 && n != NULL) {
		len = min(mlen - m->m_len, n->m_len - noff);
		if (len > length)
			len = length;

		bcopy(mtod(n, caddr_t)+noff, mtod(m, caddr_t)+m->m_len, len);
		m->m_len += len;
		noff += len;
		length -= len;

		if (length > 0 && m->m_len == mlen) {
			MGET(m->m_next, M_NOWAIT, MT_DATA);
			if (m->m_next == NULL) {
				NG_FREE_M(top);
				return (NULL);
			}

			m = m->m_next;
			m->m_len = 0;
			mlen = MLEN;
		}

		if (noff == n->m_len) {
			noff = 0;
			n = n->m_next;

			if (n == NULL)
				n = nextpkt;

			nextpkt = (n != NULL)? n->m_nextpkt : NULL;
		}
	}

	if (length < 0)
		panic("%s: length=%d", __func__, length);
	if (length > 0 && n == NULL)
		panic("%s: bogus length=%d, n=%p", __func__, length, n);

	return (top);
} /* ng_btsocket_rfcomm_prepare_packet */