summaryrefslogtreecommitdiffstats
path: root/netwerk/sctp/src/netinet/sctp_pcb.c
blob: ea5725c85cf095fdeac8f9437efc3bda679e0b33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
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
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
/*-
 * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
 * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
 * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * a) Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * b) 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.
 *
 * c) Neither the name of Cisco Systems, Inc. nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */

#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 355931 2019-12-20 15:25:08Z tuexen $");
#endif

#include <netinet/sctp_os.h>
#ifdef __FreeBSD__
#include <sys/proc.h>
#endif
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctputil.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_asconf.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_timer.h>
#include <netinet/sctp_bsd_addr.h>
#if defined(__FreeBSD__) && __FreeBSD_version >= 803000
#include <netinet/sctp_dtrace_define.h>
#endif
#if defined(INET) || defined(INET6)
#if !defined(__Userspace_os_Windows)
#include <netinet/udp.h>
#endif
#endif
#ifdef INET6
#if defined(__Userspace__)
#include "user_ip6_var.h"
#else
#include <netinet6/ip6_var.h>
#endif
#endif
#if defined(__FreeBSD__)
#include <sys/sched.h>
#include <sys/smp.h>
#include <sys/unistd.h>
#endif
#if defined(__Userspace__)
#include <user_socketvar.h>
#if !defined(__Userspace_os_Windows)
#include <netdb.h>
#endif
#endif

#if defined(__APPLE__)
#define APPLE_FILE_NO 4
#endif

#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
VNET_DEFINE(struct sctp_base_info, system_base_info);
#else
struct sctp_base_info system_base_info;
#endif

#if defined(__Userspace__)
#if defined(INET) || defined(INET6)
struct ifaddrs *g_interfaces;
#endif
#endif
/* FIX: we don't handle multiple link local scopes */
/* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
#ifdef INET6
int
SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b)
{
#ifdef SCTP_EMBEDDED_V6_SCOPE
#if defined(__APPLE__)
	struct in6_addr tmp_a, tmp_b;

	tmp_a = a->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
	if (in6_embedscope(&tmp_a, a, NULL, NULL) != 0) {
#else
	if (in6_embedscope(&tmp_a, a, NULL, NULL, NULL) != 0) {
#endif
		return (0);
	}
	tmp_b = b->sin6_addr;
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
	if (in6_embedscope(&tmp_b, b, NULL, NULL) != 0) {
#else
	if (in6_embedscope(&tmp_b, b, NULL, NULL, NULL) != 0) {
#endif
		return (0);
	}
	return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#elif defined(SCTP_KAME)
	struct sockaddr_in6 tmp_a, tmp_b;

	memcpy(&tmp_a, a, sizeof(struct sockaddr_in6));
	if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
		return (0);
	}
	memcpy(&tmp_b, b, sizeof(struct sockaddr_in6));
	if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
		return (0);
	}
	return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr));
#else
	struct in6_addr tmp_a, tmp_b;

	tmp_a = a->sin6_addr;
	if (in6_embedscope(&tmp_a, a) != 0) {
		return (0);
	}
	tmp_b = b->sin6_addr;
	if (in6_embedscope(&tmp_b, b) != 0) {
		return (0);
	}
	return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
#endif
#else
	return (IN6_ARE_ADDR_EQUAL(&(a->sin6_addr), &(b->sin6_addr)));
#endif /* SCTP_EMBEDDED_V6_SCOPE */
}
#endif

void
sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
{
	/*
	 * We really don't need to lock this, but I will just because it
	 * does not hurt.
	 */
	SCTP_INP_INFO_RLOCK();
	spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep);
	spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc);
	spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr);
	spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr);
	spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk);
	spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq);
	spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq);
	spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks);
	SCTP_INP_INFO_RUNLOCK();
}

/*-
 * Addresses are added to VRF's (Virtual Router's). For BSD we
 * have only the default VRF 0. We maintain a hash list of
 * VRF's. Each VRF has its own list of sctp_ifn's. Each of
 * these has a list of addresses. When we add a new address
 * to a VRF we lookup the ifn/ifn_index, if the ifn does
 * not exist we create it and add it to the list of IFN's
 * within the VRF. Once we have the sctp_ifn, we add the
 * address to the list. So we look something like:
 *
 * hash-vrf-table
 *   vrf-> ifn-> ifn -> ifn
 *   vrf    |
 *    ...   +--ifa-> ifa -> ifa
 *   vrf
 *
 * We keep these separate lists since the SCTP subsystem will
 * point to these from its source address selection nets structure.
 * When an address is deleted it does not happen right away on
 * the SCTP side, it gets scheduled. What we do when a
 * delete happens is immediately remove the address from
 * the master list and decrement the refcount. As our
 * addip iterator works through and frees the src address
 * selection pointing to the sctp_ifa, eventually the refcount
 * will reach 0 and we will delete it. Note that it is assumed
 * that any locking on system level ifn/ifa is done at the
 * caller of these functions and these routines will only
 * lock the SCTP structures as they add or delete things.
 *
 * Other notes on VRF concepts.
 *  - An endpoint can be in multiple VRF's
 *  - An association lives within a VRF and only one VRF.
 *  - Any incoming packet we can deduce the VRF for by
 *    looking at the mbuf/pak inbound (for BSD its VRF=0 :D)
 *  - Any downward send call or connect call must supply the
 *    VRF via ancillary data or via some sort of set default
 *    VRF socket option call (again for BSD no brainer since
 *    the VRF is always 0).
 *  - An endpoint may add multiple VRF's to it.
 *  - Listening sockets can accept associations in any
 *    of the VRF's they are in but the assoc will end up
 *    in only one VRF (gotten from the packet or connect/send).
 *
 */

struct sctp_vrf *
sctp_allocate_vrf(int vrf_id)
{
	struct sctp_vrf *vrf = NULL;
	struct sctp_vrflist *bucket;

	/* First allocate the VRF structure */
	vrf = sctp_find_vrf(vrf_id);
	if (vrf) {
		/* Already allocated */
		return (vrf);
	}
	SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf),
		    SCTP_M_VRF);
	if (vrf == NULL) {
		/* No memory */
#ifdef INVARIANTS
		panic("No memory for VRF:%d", vrf_id);
#endif
		return (NULL);
	}
	/* setup the VRF */
	memset(vrf, 0, sizeof(struct sctp_vrf));
	vrf->vrf_id = vrf_id;
	LIST_INIT(&vrf->ifnlist);
	vrf->total_ifa_count = 0;
	vrf->refcount = 0;
	/* now also setup table ids */
	SCTP_INIT_VRF_TABLEID(vrf);
	/* Init the HASH of addresses */
	vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE,
					    &vrf->vrf_addr_hashmark);
	if (vrf->vrf_addr_hash == NULL) {
		/* No memory */
#ifdef INVARIANTS
		panic("No memory for VRF:%d", vrf_id);
#endif
		SCTP_FREE(vrf, SCTP_M_VRF);
		return (NULL);
	}

	/* Add it to the hash table */
	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
	LIST_INSERT_HEAD(bucket, vrf, next_vrf);
	atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
	return (vrf);
}


struct sctp_ifn *
sctp_find_ifn(void *ifn, uint32_t ifn_index)
{
	struct sctp_ifn *sctp_ifnp;
	struct sctp_ifnlist *hash_ifn_head;

	/* We assume the lock is held for the addresses
	 * if that's wrong problems could occur :-)
	 */
	hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
	LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) {
		if (sctp_ifnp->ifn_index == ifn_index) {
			return (sctp_ifnp);
		}
		if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) {
			return (sctp_ifnp);
		}
	}
	return (NULL);
}


struct sctp_vrf *
sctp_find_vrf(uint32_t vrf_id)
{
	struct sctp_vrflist *bucket;
	struct sctp_vrf *liste;

	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
	LIST_FOREACH(liste, bucket, next_vrf) {
		if (vrf_id == liste->vrf_id) {
			return (liste);
		}
	}
	return (NULL);
}


void
sctp_free_vrf(struct sctp_vrf *vrf)
{
	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) {
                if (vrf->vrf_addr_hash) {
                    SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
                    vrf->vrf_addr_hash = NULL;
                }
		/* We zero'd the count */
		LIST_REMOVE(vrf, next_vrf);
		SCTP_FREE(vrf, SCTP_M_VRF);
		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
	}
}


void
sctp_free_ifn(struct sctp_ifn *sctp_ifnp)
{
	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) {
		/* We zero'd the count */
		if (sctp_ifnp->vrf) {
			sctp_free_vrf(sctp_ifnp->vrf);
		}
		SCTP_FREE(sctp_ifnp, SCTP_M_IFN);
		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
	}
}


void
sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu)
{
	struct sctp_ifn *sctp_ifnp;

	sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index);
	if (sctp_ifnp != NULL) {
		sctp_ifnp->ifn_mtu = mtu;
	}
}


void
sctp_free_ifa(struct sctp_ifa *sctp_ifap)
{
	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) {
		/* We zero'd the count */
		if (sctp_ifap->ifn_p) {
			sctp_free_ifn(sctp_ifap->ifn_p);
		}
		SCTP_FREE(sctp_ifap, SCTP_M_IFA);
		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
	}
}


static void
sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock)
{
	struct sctp_ifn *found;

	found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index);
	if (found == NULL) {
		/* Not in the list.. sorry */
		return;
	}
	if (hold_addr_lock == 0)
		SCTP_IPI_ADDR_WLOCK();
	LIST_REMOVE(sctp_ifnp, next_bucket);
	LIST_REMOVE(sctp_ifnp, next_ifn);
	SCTP_DEREGISTER_INTERFACE(sctp_ifnp->ifn_index,
				  sctp_ifnp->registered_af);
	if (hold_addr_lock == 0)
		SCTP_IPI_ADDR_WUNLOCK();
	/* Take away the reference, and possibly free it */
	sctp_free_ifn(sctp_ifnp);
}


void
sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr,
			const char *if_name, uint32_t ifn_index)
{
	struct sctp_vrf *vrf;
	struct sctp_ifa *sctp_ifap;

	SCTP_IPI_ADDR_RLOCK();
	vrf = sctp_find_vrf(vrf_id);
	if (vrf == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
		goto out;

	}
	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
	if (sctp_ifap == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
		goto out;
	}
	if (sctp_ifap->ifn_p == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unuseable\n");
		goto out;
	}
	if (if_name) {
		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
				sctp_ifap->ifn_p->ifn_name, if_name);
			goto out;
		}
	} else {
		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
				sctp_ifap->ifn_p->ifn_index, ifn_index);
			goto out;
		}
	}

	sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID);
	sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE;
 out:
	SCTP_IPI_ADDR_RUNLOCK();
}


void
sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr,
		      const char *if_name, uint32_t ifn_index)
{
	struct sctp_vrf *vrf;
	struct sctp_ifa *sctp_ifap;

	SCTP_IPI_ADDR_RLOCK();
	vrf = sctp_find_vrf(vrf_id);
	if (vrf == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
		goto out;

	}
	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
	if (sctp_ifap == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
		goto out;
	}
	if (sctp_ifap->ifn_p == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unuseable\n");
		goto out;
	}
	if (if_name) {
		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
				sctp_ifap->ifn_p->ifn_name, if_name);
			goto out;
		}
	} else {
		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
				sctp_ifap->ifn_p->ifn_index, ifn_index);
			goto out;
		}
	}

	sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE);
	sctp_ifap->localifa_flags |= SCTP_ADDR_VALID;
 out:
	SCTP_IPI_ADDR_RUNLOCK();
}


/*-
 * Add an ifa to an ifn.
 * Register the interface as necessary.
 * NOTE: ADDR write lock MUST be held.
 */
static void
sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap)
{
	int ifa_af;

	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
	sctp_ifap->ifn_p = sctp_ifnp;
	atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
	/* update address counts */
	sctp_ifnp->ifa_count++;
	ifa_af = sctp_ifap->address.sa.sa_family;
	switch (ifa_af) {
#ifdef INET
	case AF_INET:
		sctp_ifnp->num_v4++;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		sctp_ifnp->num_v6++;
		break;
#endif
	default:
		break;
	}
	if (sctp_ifnp->ifa_count == 1) {
		/* register the new interface */
		SCTP_REGISTER_INTERFACE(sctp_ifnp->ifn_index, ifa_af);
		sctp_ifnp->registered_af = ifa_af;
	}
}


/*-
 * Remove an ifa from its ifn.
 * If no more addresses exist, remove the ifn too. Otherwise, re-register
 * the interface based on the remaining address families left.
 * NOTE: ADDR write lock MUST be held.
 */
static void
sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap)
{
	LIST_REMOVE(sctp_ifap, next_ifa);
	if (sctp_ifap->ifn_p) {
		/* update address counts */
		sctp_ifap->ifn_p->ifa_count--;
		switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
		case AF_INET:
			sctp_ifap->ifn_p->num_v4--;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			sctp_ifap->ifn_p->num_v6--;
			break;
#endif
		default:
			break;
		}

		if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) {
			/* remove the ifn, possibly freeing it */
			sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED);
		} else {
			/* re-register address family type, if needed */
			if ((sctp_ifap->ifn_p->num_v6 == 0) &&
			    (sctp_ifap->ifn_p->registered_af == AF_INET6)) {
				SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
				SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
				sctp_ifap->ifn_p->registered_af = AF_INET;
			} else if ((sctp_ifap->ifn_p->num_v4 == 0) &&
				   (sctp_ifap->ifn_p->registered_af == AF_INET)) {
				SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
				SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
				sctp_ifap->ifn_p->registered_af = AF_INET6;
			}
			/* free the ifn refcount */
			sctp_free_ifn(sctp_ifap->ifn_p);
		}
		sctp_ifap->ifn_p = NULL;
	}
}


struct sctp_ifa *
sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
		     uint32_t ifn_type, const char *if_name, void *ifa,
		     struct sockaddr *addr, uint32_t ifa_flags,
		     int dynamic_add)
{
	struct sctp_vrf *vrf;
	struct sctp_ifn *sctp_ifnp = NULL;
	struct sctp_ifa *sctp_ifap = NULL;
	struct sctp_ifalist *hash_addr_head;
	struct sctp_ifnlist *hash_ifn_head;
	uint32_t hash_of_addr;
	int new_ifn_af = 0;

#ifdef SCTP_DEBUG
	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id);
	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
	SCTP_IPI_ADDR_WLOCK();
	sctp_ifnp = sctp_find_ifn(ifn, ifn_index);
	if (sctp_ifnp) {
		vrf = sctp_ifnp->vrf;
	} else {
		vrf = sctp_find_vrf(vrf_id);
		if (vrf == NULL) {
			vrf = sctp_allocate_vrf(vrf_id);
			if (vrf == NULL) {
				SCTP_IPI_ADDR_WUNLOCK();
				return (NULL);
			}
		}
	}
	if (sctp_ifnp == NULL) {
		/* build one and add it, can't hold lock
		 * until after malloc done though.
		 */
		SCTP_IPI_ADDR_WUNLOCK();
		SCTP_MALLOC(sctp_ifnp, struct sctp_ifn *,
			    sizeof(struct sctp_ifn), SCTP_M_IFN);
		if (sctp_ifnp == NULL) {
#ifdef INVARIANTS
			panic("No memory for IFN");
#endif
			return (NULL);
		}
		memset(sctp_ifnp, 0, sizeof(struct sctp_ifn));
		sctp_ifnp->ifn_index = ifn_index;
		sctp_ifnp->ifn_p = ifn;
		sctp_ifnp->ifn_type = ifn_type;
		sctp_ifnp->refcount = 0;
		sctp_ifnp->vrf = vrf;
		atomic_add_int(&vrf->refcount, 1);
		sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index, addr->sa_family);
		if (if_name != NULL) {
			snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name);
		} else {
			snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown");
		}
		hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
		LIST_INIT(&sctp_ifnp->ifalist);
		SCTP_IPI_ADDR_WLOCK();
		LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket);
		LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn);
		atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
		new_ifn_af = 1;
	}
	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
	if (sctp_ifap) {
		/* Hmm, it already exists? */
		if ((sctp_ifap->ifn_p) &&
		    (sctp_ifap->ifn_p->ifn_index == ifn_index)) {
			SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n",
				sctp_ifap->ifn_p->ifn_name, ifn_index,
				(void *)sctp_ifap);
			if (new_ifn_af) {
				/* Remove the created one that we don't want */
				sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED);
			}
			if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) {
				/* easy to solve, just switch back to active */
				SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n");
				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
				sctp_ifap->ifn_p = sctp_ifnp;
				atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
			}
		exit_stage_left:
			SCTP_IPI_ADDR_WUNLOCK();
			return (sctp_ifap);
		} else {
			if (sctp_ifap->ifn_p) {
				/*
				 * The last IFN gets the address, remove the
				 * old one
				 */
				SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n",
					(void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name,
					sctp_ifap->ifn_p->ifn_index, if_name,
					ifn_index);
				/* remove the address from the old ifn */
				sctp_remove_ifa_from_ifn(sctp_ifap);
				/* move the address over to the new ifn */
				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
				goto exit_stage_left;
			} else {
				/* repair ifnp which was NULL ? */
				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
				SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n",
					(void *)sctp_ifnp, (void *)sctp_ifap);
				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
			}
			goto exit_stage_left;
		}
	}
	SCTP_IPI_ADDR_WUNLOCK();
	SCTP_MALLOC(sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA);
	if (sctp_ifap == NULL) {
#ifdef INVARIANTS
		panic("No memory for IFA");
#endif
		return (NULL);
	}
	memset(sctp_ifap, 0, sizeof(struct sctp_ifa));
	sctp_ifap->ifn_p = sctp_ifnp;
	atomic_add_int(&sctp_ifnp->refcount, 1);
	sctp_ifap->vrf_id = vrf_id;
	sctp_ifap->ifa = ifa;
#ifdef HAVE_SA_LEN
	memcpy(&sctp_ifap->address, addr, addr->sa_len);
#else
	switch (addr->sa_family) {
#ifdef INET
	case AF_INET:
		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in));
		break;
#endif
#ifdef INET6
	case AF_INET6:
		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in6));
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_conn));
		break;
#endif
	default:
		/* TSNH */
		break;
	}
#endif
	sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE;
	sctp_ifap->flags = ifa_flags;
	/* Set scope */
	switch (sctp_ifap->address.sa.sa_family) {
#ifdef INET
	case AF_INET:
	{
		struct sockaddr_in *sin;

		sin = &sctp_ifap->address.sin;
		if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
		    (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
			sctp_ifap->src_is_loop = 1;
		}
		if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
			sctp_ifap->src_is_priv = 1;
		}
		sctp_ifnp->num_v4++;
		if (new_ifn_af)
		    new_ifn_af = AF_INET;
		break;
	}
#endif
#ifdef INET6
	case AF_INET6:
	{
		/* ok to use deprecated addresses? */
		struct sockaddr_in6 *sin6;

		sin6 = &sctp_ifap->address.sin6;
		if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
		    (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
			sctp_ifap->src_is_loop = 1;
		}
		if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
			sctp_ifap->src_is_priv = 1;
		}
		sctp_ifnp->num_v6++;
		if (new_ifn_af)
			new_ifn_af = AF_INET6;
		break;
	}
#endif
#if defined(__Userspace__)
	case AF_CONN:
		if (new_ifn_af)
			new_ifn_af = AF_CONN;
		break;
#endif
	default:
		new_ifn_af = 0;
		break;
	}
	hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa);

	if ((sctp_ifap->src_is_priv == 0) &&
	    (sctp_ifap->src_is_loop == 0)) {
		sctp_ifap->src_is_glob = 1;
	}
	SCTP_IPI_ADDR_WLOCK();
	hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
	LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket);
	sctp_ifap->refcount = 1;
	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
	sctp_ifnp->ifa_count++;
	vrf->total_ifa_count++;
	atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
	if (new_ifn_af) {
		SCTP_REGISTER_INTERFACE(ifn_index, new_ifn_af);
		sctp_ifnp->registered_af = new_ifn_af;
	}
	SCTP_IPI_ADDR_WUNLOCK();
	if (dynamic_add) {
		/* Bump up the refcount so that when the timer
		 * completes it will drop back down.
		 */
		struct sctp_laddr *wi;

		atomic_add_int(&sctp_ifap->refcount, 1);
		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
		if (wi == NULL) {
			/*
			 * Gak, what can we do? We have lost an address
			 * change can you say HOSED?
			 */
			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
			/* Opps, must decrement the count */
			sctp_del_addr_from_vrf(vrf_id, addr, ifn_index,
					       if_name);
			return (NULL);
		}
		SCTP_INCR_LADDR_COUNT();
		bzero(wi, sizeof(*wi));
		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
		wi->ifa = sctp_ifap;
		wi->action = SCTP_ADD_IP_ADDRESS;

		SCTP_WQ_ADDR_LOCK();
		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
		SCTP_WQ_ADDR_UNLOCK();

		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
				 (struct sctp_inpcb *)NULL,
				 (struct sctp_tcb *)NULL,
				 (struct sctp_nets *)NULL);
	} else {
		/* it's ready for use */
		sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE;
	}
	return (sctp_ifap);
}

void
sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr,
		       uint32_t ifn_index, const char *if_name)
{
	struct sctp_vrf *vrf;
	struct sctp_ifa *sctp_ifap = NULL;

	SCTP_IPI_ADDR_WLOCK();
	vrf = sctp_find_vrf(vrf_id);
	if (vrf == NULL) {
		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
		goto out_now;
	}

#ifdef SCTP_DEBUG
	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id);
	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
#endif
	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
	if (sctp_ifap) {
		/* Validate the delete */
		if (sctp_ifap->ifn_p) {
			int valid = 0;
			/*-
			 * The name has priority over the ifn_index
			 * if its given. We do this especially for
			 * panda who might recycle indexes fast.
			 */
			if (if_name) {
				if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) {
					/* They match its a correct delete */
					valid = 1;
				}
			}
			if (!valid) {
				/* last ditch check ifn_index */
				if (ifn_index == sctp_ifap->ifn_p->ifn_index) {
					valid = 1;
				}
			}
			if (!valid) {
				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n",
					ifn_index, ((if_name == NULL) ? "NULL" : if_name));
				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n",
					sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name);
				SCTP_IPI_ADDR_WUNLOCK();
				return;
			}
		}
		SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap);
		sctp_ifap->localifa_flags &= SCTP_ADDR_VALID;
                /*
		 * We don't set the flag. This means that the structure will
		 * hang around in EP's that have bound specific to it until
		 * they close. This gives us TCP like behavior if someone
		 * removes an address (or for that matter adds it right back).
		 */
		/* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */
		vrf->total_ifa_count--;
		LIST_REMOVE(sctp_ifap, next_bucket);
		sctp_remove_ifa_from_ifn(sctp_ifap);
	}
#ifdef SCTP_DEBUG
	else {
		SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:",
			ifn_index);
		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
	}
#endif

 out_now:
	SCTP_IPI_ADDR_WUNLOCK();
	if (sctp_ifap) {
		struct sctp_laddr *wi;

		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
		if (wi == NULL) {
			/*
			 * Gak, what can we do? We have lost an address
			 * change can you say HOSED?
			 */
			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");

			/* Oops, must decrement the count */
			sctp_free_ifa(sctp_ifap);
			return;
		}
		SCTP_INCR_LADDR_COUNT();
		bzero(wi, sizeof(*wi));
		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
		wi->ifa = sctp_ifap;
		wi->action = SCTP_DEL_IP_ADDRESS;
		SCTP_WQ_ADDR_LOCK();
		/*
		 * Should this really be a tailq? As it is we will process the
		 * newest first :-0
		 */
		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
		SCTP_WQ_ADDR_UNLOCK();

		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
				 (struct sctp_inpcb *)NULL,
				 (struct sctp_tcb *)NULL,
				 (struct sctp_nets *)NULL);
	}
	return;
}


static int
sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to)
{
	int loopback_scope;
#if defined(INET)
	int ipv4_local_scope, ipv4_addr_legal;
#endif
#if defined(INET6)
	int local_scope, site_scope, ipv6_addr_legal;
#endif
#if defined(__Userspace__)
	int conn_addr_legal;
#endif
	struct sctp_vrf *vrf;
	struct sctp_ifn *sctp_ifn;
	struct sctp_ifa *sctp_ifa;

	loopback_scope = stcb->asoc.scope.loopback_scope;
#if defined(INET)
	ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
	ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
#endif
#if defined(INET6)
	local_scope = stcb->asoc.scope.local_scope;
	site_scope = stcb->asoc.scope.site_scope;
	ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
#endif
#if defined(__Userspace__)
	conn_addr_legal = stcb->asoc.scope.conn_addr_legal;
#endif

	SCTP_IPI_ADDR_RLOCK();
	vrf = sctp_find_vrf(stcb->asoc.vrf_id);
	if (vrf == NULL) {
		/* no vrf, no addresses */
		SCTP_IPI_ADDR_RUNLOCK();
		return (0);
	}

	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
		LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
			if ((loopback_scope == 0) &&
			    SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
				continue;
			}
			LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
				if (sctp_is_addr_restricted(stcb, sctp_ifa) &&
				    (!sctp_is_addr_pending(stcb, sctp_ifa))) {
					/* We allow pending addresses, where we
					 * have sent an asconf-add to be considered
					 * valid.
					 */
					continue;
				}
				if (sctp_ifa->address.sa.sa_family != to->sa_family) {
					continue;
				}
				switch (sctp_ifa->address.sa.sa_family) {
#ifdef INET
				case AF_INET:
					if (ipv4_addr_legal) {
						struct sockaddr_in *sin, *rsin;

						sin = &sctp_ifa->address.sin;
						rsin = (struct sockaddr_in *)to;
						if ((ipv4_local_scope == 0) &&
						    IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
							continue;
						}
#if defined(__FreeBSD__)
						if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
						                     &sin->sin_addr) != 0) {
							continue;
						}
#endif
						if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
							SCTP_IPI_ADDR_RUNLOCK();
							return (1);
						}
					}
					break;
#endif
#ifdef INET6
				case AF_INET6:
					if (ipv6_addr_legal) {
						struct sockaddr_in6 *sin6, *rsin6;
#if defined(SCTP_EMBEDDED_V6_SCOPE) && !defined(SCTP_KAME)
						struct sockaddr_in6 lsa6;
#endif
						sin6 = &sctp_ifa->address.sin6;
						rsin6 = (struct sockaddr_in6 *)to;
#if defined(__FreeBSD__)
						if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
						                     &sin6->sin6_addr) != 0) {
							continue;
						}
#endif
						if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
							if (local_scope == 0)
								continue;
#if defined(SCTP_EMBEDDED_V6_SCOPE)
							if (sin6->sin6_scope_id == 0) {
#ifdef SCTP_KAME
								if (sa6_recoverscope(sin6) != 0)
									continue;
#else
								lsa6 = *sin6;
								if (in6_recoverscope(&lsa6,
								                     &lsa6.sin6_addr,
								                     NULL))
									continue;
								sin6 = &lsa6;
#endif /* SCTP_KAME */
							}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
						}
						if ((site_scope == 0) &&
						    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
							continue;
						}
						if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
							SCTP_IPI_ADDR_RUNLOCK();
							return (1);
						}
					}
					break;
#endif
#if defined(__Userspace__)
				case AF_CONN:
					if (conn_addr_legal) {
						struct sockaddr_conn *sconn, *rsconn;

						sconn = &sctp_ifa->address.sconn;
						rsconn = (struct sockaddr_conn *)to;
						if (sconn->sconn_addr == rsconn->sconn_addr) {
							SCTP_IPI_ADDR_RUNLOCK();
							return (1);
						}
					}
					break;
#endif
				default:
					/* TSNH */
					break;
				}
			}
		}
	} else {
		struct sctp_laddr *laddr;

		LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) {
			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
				SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
				continue;
			}
			if (sctp_is_addr_restricted(stcb, laddr->ifa) &&
			    (!sctp_is_addr_pending(stcb, laddr->ifa))) {
				/* We allow pending addresses, where we
				 * have sent an asconf-add to be considered
				 * valid.
				 */
				continue;
			}
			if (laddr->ifa->address.sa.sa_family != to->sa_family) {
				continue;
			}
			switch (to->sa_family) {
#ifdef INET
			case AF_INET:
			{
				struct sockaddr_in *sin, *rsin;

				sin = &laddr->ifa->address.sin;
				rsin = (struct sockaddr_in *)to;
				if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
					SCTP_IPI_ADDR_RUNLOCK();
					return (1);
				}
				break;
			}
#endif
#ifdef INET6
			case AF_INET6:
			{
				struct sockaddr_in6 *sin6, *rsin6;

				sin6 = &laddr->ifa->address.sin6;
				rsin6 = (struct sockaddr_in6 *)to;
				if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
					SCTP_IPI_ADDR_RUNLOCK();
					return (1);
				}
				break;
			}

#endif
#if defined(__Userspace__)
			case AF_CONN:
			{
				struct sockaddr_conn *sconn, *rsconn;

				sconn = &laddr->ifa->address.sconn;
				rsconn = (struct sockaddr_conn *)to;
				if (sconn->sconn_addr == rsconn->sconn_addr) {
					SCTP_IPI_ADDR_RUNLOCK();
					return (1);
				}
				break;
			}
#endif
			default:
				/* TSNH */
				break;
			}

		}
	}
	SCTP_IPI_ADDR_RUNLOCK();
	return (0);
}


static struct sctp_tcb *
sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
    struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id)
{
	/**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */
	/*
	 * If we support the TCP model, then we must now dig through to see
	 * if we can find our endpoint in the list of tcp ep's.
	 */
	uint16_t lport, rport;
	struct sctppcbhead *ephead;
	struct sctp_inpcb *inp;
	struct sctp_laddr *laddr;
	struct sctp_tcb *stcb;
	struct sctp_nets *net;
#ifdef SCTP_MVRF
	int fnd, i;
#endif

	if ((to == NULL) || (from == NULL)) {
		return (NULL);
	}

	switch (to->sa_family) {
#ifdef INET
	case AF_INET:
		if (from->sa_family == AF_INET) {
			lport = ((struct sockaddr_in *)to)->sin_port;
			rport = ((struct sockaddr_in *)from)->sin_port;
		} else {
			return (NULL);
		}
		break;
#endif
#ifdef INET6
	case AF_INET6:
		if (from->sa_family == AF_INET6) {
			lport = ((struct sockaddr_in6 *)to)->sin6_port;
			rport = ((struct sockaddr_in6 *)from)->sin6_port;
		} else {
			return (NULL);
		}
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		if (from->sa_family == AF_CONN) {
			lport = ((struct sockaddr_conn *)to)->sconn_port;
			rport = ((struct sockaddr_conn *)from)->sconn_port;
		} else {
			return (NULL);
		}
		break;
#endif
	default:
		return (NULL);
	}
	ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
	/*
	 * Ok now for each of the guys in this bucket we must look and see:
	 * - Does the remote port match. - Does there single association's
	 * addresses match this address (to). If so we update p_ep to point
	 * to this ep and return the tcb from it.
	 */
	LIST_FOREACH(inp, ephead, sctp_hash) {
		SCTP_INP_RLOCK(inp);
		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if (lport != inp->sctp_lport) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
#if defined(__FreeBSD__)
		switch (to->sa_family) {
#ifdef INET
		case AF_INET:
		{
			struct sockaddr_in *sin;

			sin = (struct sockaddr_in *)to;
			if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
			                     &sin->sin_addr) != 0) {
				SCTP_INP_RUNLOCK(inp);
				continue;
			}
			break;
		}
#endif
#ifdef INET6
		case AF_INET6:
		{
			struct sockaddr_in6 *sin6;

			sin6 = (struct sockaddr_in6 *)to;
			if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
			                     &sin6->sin6_addr) != 0) {
				SCTP_INP_RUNLOCK(inp);
				continue;
			}
			break;
		}
#endif
		default:
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
#endif
#ifdef SCTP_MVRF
		fnd = 0;
		for (i = 0; i < inp->num_vrfs; i++) {
			if (inp->m_vrf_ids[i] == vrf_id) {
				fnd = 1;
				break;
			}
		}
		if (fnd == 0) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
#else
		if (inp->def_vrf_id != vrf_id) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
#endif
		/* check to see if the ep has one of the addresses */
		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
			/* We are NOT bound all, so look further */
			int match = 0;

			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {

				if (laddr->ifa == NULL) {
					SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __FUNCTION__);
					continue;
				}
				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
					SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
					continue;
				}
				if (laddr->ifa->address.sa.sa_family ==
				    to->sa_family) {
					/* see if it matches */
#ifdef INET
					if (from->sa_family == AF_INET) {
						struct sockaddr_in *intf_addr, *sin;

						intf_addr = &laddr->ifa->address.sin;
						sin = (struct sockaddr_in *)to;
						if (sin->sin_addr.s_addr ==
						    intf_addr->sin_addr.s_addr) {
							match = 1;
							break;
						}
					}
#endif
#ifdef INET6
					if (from->sa_family == AF_INET6) {
						struct sockaddr_in6 *intf_addr6;
						struct sockaddr_in6 *sin6;

						sin6 = (struct sockaddr_in6 *)
						    to;
						intf_addr6 = &laddr->ifa->address.sin6;

						if (SCTP6_ARE_ADDR_EQUAL(sin6,
						    intf_addr6)) {
							match = 1;
							break;
						}
					}
#endif
#if defined(__Userspace__)
					if (from->sa_family == AF_CONN) {
						struct sockaddr_conn *intf_addr, *sconn;

						intf_addr = &laddr->ifa->address.sconn;
						sconn = (struct sockaddr_conn *)to;
						if (sconn->sconn_addr ==
						    intf_addr->sconn_addr) {
							match = 1;
							break;
						}
					}
#endif
				}
			}
			if (match == 0) {
				/* This endpoint does not have this address */
				SCTP_INP_RUNLOCK(inp);
				continue;
			}
		}
		/*
		 * Ok if we hit here the ep has the address, does it hold
		 * the tcb?
		 */
		/* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */
		stcb = LIST_FIRST(&inp->sctp_asoc_list);
		if (stcb == NULL) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		SCTP_TCB_LOCK(stcb);
		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
			SCTP_TCB_UNLOCK(stcb);
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if (stcb->rport != rport) {
			/* remote port does not match. */
			SCTP_TCB_UNLOCK(stcb);
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
			SCTP_TCB_UNLOCK(stcb);
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
			SCTP_TCB_UNLOCK(stcb);
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		/* Does this TCB have a matching address? */
		TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {

			if (net->ro._l_addr.sa.sa_family != from->sa_family) {
				/* not the same family, can't be a match */
				continue;
			}
			switch (from->sa_family) {
#ifdef INET
			case AF_INET:
			{
				struct sockaddr_in *sin, *rsin;

				sin = (struct sockaddr_in *)&net->ro._l_addr;
				rsin = (struct sockaddr_in *)from;
				if (sin->sin_addr.s_addr ==
				    rsin->sin_addr.s_addr) {
					/* found it */
					if (netp != NULL) {
						*netp = net;
					}
					/* Update the endpoint pointer */
					*inp_p = inp;
					SCTP_INP_RUNLOCK(inp);
					return (stcb);
				}
				break;
			}
#endif
#ifdef INET6
			case AF_INET6:
			{
				struct sockaddr_in6 *sin6, *rsin6;

				sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
				rsin6 = (struct sockaddr_in6 *)from;
				if (SCTP6_ARE_ADDR_EQUAL(sin6,
				    rsin6)) {
					/* found it */
					if (netp != NULL) {
						*netp = net;
					}
					/* Update the endpoint pointer */
					*inp_p = inp;
					SCTP_INP_RUNLOCK(inp);
					return (stcb);
				}
				break;
			}
#endif
#if defined(__Userspace__)
			case AF_CONN:
			{
				struct sockaddr_conn *sconn, *rsconn;

				sconn = (struct sockaddr_conn *)&net->ro._l_addr;
				rsconn = (struct sockaddr_conn *)from;
				if (sconn->sconn_addr == rsconn->sconn_addr) {
					/* found it */
					if (netp != NULL) {
						*netp = net;
					}
					/* Update the endpoint pointer */
					*inp_p = inp;
					SCTP_INP_RUNLOCK(inp);
					return (stcb);
				}
				break;
			}
#endif
			default:
				/* TSNH */
				break;
			}
		}
		SCTP_TCB_UNLOCK(stcb);
		SCTP_INP_RUNLOCK(inp);
	}
	return (NULL);
}


/*
 * rules for use
 *
 * 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an
 * stcb, both will be locked (locked_tcb and stcb) but decrement will be done
 * (if locked == NULL). 3) Decrement happens on return ONLY if locked ==
 * NULL.
 */

struct sctp_tcb *
sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
    struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
{
	struct sctpasochead *head;
	struct sctp_inpcb *inp;
	struct sctp_tcb *stcb = NULL;
	struct sctp_nets *net;
	uint16_t rport;

	inp = *inp_p;
	switch (remote->sa_family) {
#ifdef INET
	case AF_INET:
		rport = (((struct sockaddr_in *)remote)->sin_port);
		break;
#endif
#ifdef INET6
	case AF_INET6:
		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
		break;
#endif
	default:
		return (NULL);
	}
	if (locked_tcb) {
		/*
		 * UN-lock so we can do proper locking here this occurs when
		 * called from load_addresses_from_init.
		 */
		atomic_add_int(&locked_tcb->asoc.refcnt, 1);
		SCTP_TCB_UNLOCK(locked_tcb);
	}
	SCTP_INP_INFO_RLOCK();
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
		/*-
		 * Now either this guy is our listener or it's the
		 * connector. If it is the one that issued the connect, then
		 * it's only chance is to be the first TCB in the list. If
		 * it is the acceptor, then do the special_lookup to hash
		 * and find the real inp.
		 */
		if ((inp->sctp_socket) && (inp->sctp_socket->so_qlimit)) {
			/* to is peer addr, from is my addr */
#ifndef SCTP_MVRF
			stcb = sctp_tcb_special_locate(inp_p, remote, local,
			    netp, inp->def_vrf_id);
			if ((stcb != NULL) && (locked_tcb == NULL)) {
				/* we have a locked tcb, lower refcount */
				SCTP_INP_DECR_REF(inp);
			}
			if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
				SCTP_INP_RLOCK(locked_tcb->sctp_ep);
				SCTP_TCB_LOCK(locked_tcb);
				atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
				SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
			}
#else
			/*-
			 * MVRF is tricky, we must look in every VRF
			 * the endpoint has.
			 */
			int i;

			for (i = 0; i < inp->num_vrfs; i++) {
				stcb = sctp_tcb_special_locate(inp_p, remote, local,
				                               netp, inp->m_vrf_ids[i]);
				if ((stcb != NULL) && (locked_tcb == NULL)) {
					/* we have a locked tcb, lower refcount */
					SCTP_INP_DECR_REF(inp);
					break;
				}
				if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
					SCTP_INP_RLOCK(locked_tcb->sctp_ep);
					SCTP_TCB_LOCK(locked_tcb);
					atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
					SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
					break;
				}
			}
#endif
			SCTP_INP_INFO_RUNLOCK();
			return (stcb);
		} else {
			SCTP_INP_WLOCK(inp);
			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
				goto null_return;
			}
			stcb = LIST_FIRST(&inp->sctp_asoc_list);
			if (stcb == NULL) {
				goto null_return;
			}
			SCTP_TCB_LOCK(stcb);

			if (stcb->rport != rport) {
				/* remote port does not match. */
				SCTP_TCB_UNLOCK(stcb);
				goto null_return;
			}
			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
				SCTP_TCB_UNLOCK(stcb);
				goto null_return;
			}
			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
				SCTP_TCB_UNLOCK(stcb);
				goto null_return;
			}
			/* now look at the list of remote addresses */
			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
				if (net == (TAILQ_NEXT(net, sctp_next))) {
					panic("Corrupt net list");
				}
#endif
				if (net->ro._l_addr.sa.sa_family !=
				    remote->sa_family) {
					/* not the same family */
					continue;
				}
				switch (remote->sa_family) {
#ifdef INET
				case AF_INET:
				{
					struct sockaddr_in *sin, *rsin;

					sin = (struct sockaddr_in *)
					    &net->ro._l_addr;
					rsin = (struct sockaddr_in *)remote;
					if (sin->sin_addr.s_addr ==
					    rsin->sin_addr.s_addr) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}

						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
#ifdef INET6
				case AF_INET6:
				{
					struct sockaddr_in6 *sin6, *rsin6;

					sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
					rsin6 = (struct sockaddr_in6 *)remote;
					if (SCTP6_ARE_ADDR_EQUAL(sin6,
					    rsin6)) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}
						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
#if defined(__Userspace__)
				case AF_CONN:
				{
					struct sockaddr_conn *sconn, *rsconn;

					sconn = (struct sockaddr_conn *)&net->ro._l_addr;
					rsconn = (struct sockaddr_conn *)remote;
					if (sconn->sconn_addr == rsconn->sconn_addr) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}
						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
				default:
					/* TSNH */
					break;
				}
			}
			SCTP_TCB_UNLOCK(stcb);
		}
	} else {
		SCTP_INP_WLOCK(inp);
		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			goto null_return;
		}
		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
		                                               inp->sctp_hashmark)];
		LIST_FOREACH(stcb, head, sctp_tcbhash) {
			if (stcb->rport != rport) {
				/* remote port does not match */
				continue;
			}
			SCTP_TCB_LOCK(stcb);
			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			/* now look at the list of remote addresses */
			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
#ifdef INVARIANTS
				if (net == (TAILQ_NEXT(net, sctp_next))) {
					panic("Corrupt net list");
				}
#endif
				if (net->ro._l_addr.sa.sa_family !=
				    remote->sa_family) {
					/* not the same family */
					continue;
				}
				switch (remote->sa_family) {
#ifdef INET
				case AF_INET:
				{
					struct sockaddr_in *sin, *rsin;

					sin = (struct sockaddr_in *)
					    &net->ro._l_addr;
					rsin = (struct sockaddr_in *)remote;
					if (sin->sin_addr.s_addr ==
					    rsin->sin_addr.s_addr) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}
						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
#ifdef INET6
				case AF_INET6:
				{
					struct sockaddr_in6 *sin6, *rsin6;

					sin6 = (struct sockaddr_in6 *)
					    &net->ro._l_addr;
					rsin6 = (struct sockaddr_in6 *)remote;
					if (SCTP6_ARE_ADDR_EQUAL(sin6,
					    rsin6)) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}
						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
#if defined(__Userspace__)
				case AF_CONN:
				{
					struct sockaddr_conn *sconn, *rsconn;

					sconn = (struct sockaddr_conn *)&net->ro._l_addr;
					rsconn = (struct sockaddr_conn *)remote;
					if (sconn->sconn_addr == rsconn->sconn_addr) {
						/* found it */
						if (netp != NULL) {
							*netp = net;
						}
						if (locked_tcb == NULL) {
							SCTP_INP_DECR_REF(inp);
						} else if (locked_tcb != stcb) {
							SCTP_TCB_LOCK(locked_tcb);
						}
						if (locked_tcb) {
							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
						}
						SCTP_INP_WUNLOCK(inp);
						SCTP_INP_INFO_RUNLOCK();
						return (stcb);
					}
					break;
				}
#endif
				default:
					/* TSNH */
					break;
				}
			}
			SCTP_TCB_UNLOCK(stcb);
		}
	}
null_return:
	/* clean up for returning null */
	if (locked_tcb) {
		SCTP_TCB_LOCK(locked_tcb);
		atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
	}
	SCTP_INP_WUNLOCK(inp);
	SCTP_INP_INFO_RUNLOCK();
	/* not found */
	return (NULL);
}


/*
 * Find an association for a specific endpoint using the association id given
 * out in the COMM_UP notification
 */
struct sctp_tcb *
sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
	/*
	 * Use my the assoc_id to find a endpoint
	 */
	struct sctpasochead *head;
	struct sctp_tcb *stcb;
	uint32_t id;

	if (inp == NULL) {
		SCTP_PRINTF("TSNH ep_associd\n");
		return (NULL);
	}
	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
		SCTP_PRINTF("TSNH ep_associd0\n");
		return (NULL);
	}
	id = (uint32_t)asoc_id;
	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
	if (head == NULL) {
		/* invalid id TSNH */
		SCTP_PRINTF("TSNH ep_associd1\n");
		return (NULL);
	}
	LIST_FOREACH(stcb, head, sctp_tcbasocidhash) {
		if (stcb->asoc.assoc_id == id) {
			if (inp != stcb->sctp_ep) {
				/*
				 * some other guy has the same id active (id
				 * collision ??).
				 */
				SCTP_PRINTF("TSNH ep_associd2\n");
				continue;
			}
			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
				continue;
			}
			if (want_lock) {
				SCTP_TCB_LOCK(stcb);
			}
			return (stcb);
		}
	}
	return (NULL);
}


struct sctp_tcb *
sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
{
	struct sctp_tcb *stcb;

	SCTP_INP_RLOCK(inp);
	stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock);
	SCTP_INP_RUNLOCK(inp);
	return (stcb);
}


/*
 * Endpoint probe expects that the INP_INFO is locked.
 */
static struct sctp_inpcb *
sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
		    uint16_t lport, uint32_t vrf_id)
{
	struct sctp_inpcb *inp;
	struct sctp_laddr *laddr;
#ifdef INET
	struct sockaddr_in *sin;
#endif
#ifdef INET6
	struct sockaddr_in6 *sin6;
	struct sockaddr_in6 *intf_addr6;
#endif
#if defined(__Userspace__)
	struct sockaddr_conn *sconn;
#endif
#ifdef SCTP_MVRF
	int i;
#endif
	int  fnd;

#ifdef INET
	sin = NULL;
#endif
#ifdef INET6
	sin6 = NULL;
#endif
#if defined(__Userspace__)
	sconn = NULL;
#endif
	switch (nam->sa_family) {
#ifdef INET
	case AF_INET:
		sin = (struct sockaddr_in *)nam;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		sin6 = (struct sockaddr_in6 *)nam;
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		sconn = (struct sockaddr_conn *)nam;
		break;
#endif
	default:
		/* unsupported family */
		return (NULL);
	}

	if (head == NULL)
		return (NULL);

	LIST_FOREACH(inp, head, sctp_hash) {
		SCTP_INP_RLOCK(inp);
		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
		    (inp->sctp_lport == lport)) {
			/* got it */
			switch (nam->sa_family) {
#ifdef INET
			case AF_INET:
				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
				    SCTP_IPV6_V6ONLY(inp)) {
					/* IPv4 on a IPv6 socket with ONLY IPv6 set */
					SCTP_INP_RUNLOCK(inp);
					continue;
				}
#if defined(__FreeBSD__)
				if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
				                     &sin->sin_addr) != 0) {
					SCTP_INP_RUNLOCK(inp);
					continue;
				}
#endif
				break;
#endif
#ifdef INET6
			case AF_INET6:
				/* A V6 address and the endpoint is NOT bound V6 */
				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
					SCTP_INP_RUNLOCK(inp);
					continue;
				}
#if defined(__FreeBSD__)
				if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
				                     &sin6->sin6_addr) != 0) {
					SCTP_INP_RUNLOCK(inp);
					continue;
				}
#endif
				break;
#endif
			default:
				break;
			}
			/* does a VRF id match? */
			fnd = 0;
#ifdef SCTP_MVRF
			for (i = 0; i < inp->num_vrfs; i++) {
				if (inp->m_vrf_ids[i] == vrf_id) {
					fnd = 1;
					break;
				}
			}
#else
			if (inp->def_vrf_id == vrf_id)
				fnd = 1;
#endif

			SCTP_INP_RUNLOCK(inp);
			if (!fnd)
				continue;
			return (inp);
		}
		SCTP_INP_RUNLOCK(inp);
	}
	switch (nam->sa_family) {
#ifdef INET
	case AF_INET:
		if (sin->sin_addr.s_addr == INADDR_ANY) {
			/* Can't hunt for one that has no address specified */
			return (NULL);
		}
		break;
#endif
#ifdef INET6
	case AF_INET6:
		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
			/* Can't hunt for one that has no address specified */
			return (NULL);
		}
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		if (sconn->sconn_addr == NULL) {
			return (NULL);
		}
		break;
#endif
	default:
		break;
	}
	/*
	 * ok, not bound to all so see if we can find a EP bound to this
	 * address.
	 */
	LIST_FOREACH(inp, head, sctp_hash) {
		SCTP_INP_RLOCK(inp);
		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		/*
		 * Ok this could be a likely candidate, look at all of its
		 * addresses
		 */
		if (inp->sctp_lport != lport) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		/* does a VRF id match? */
		fnd = 0;
#ifdef SCTP_MVRF
		for (i = 0; i < inp->num_vrfs; i++) {
			if (inp->m_vrf_ids[i] == vrf_id) {
				fnd = 1;
				break;
			}
		}
#else
		if (inp->def_vrf_id == vrf_id)
			fnd = 1;

#endif
		if (!fnd) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
			if (laddr->ifa == NULL) {
				SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
					__FUNCTION__);
				continue;
			}
			SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ",
				(void *)laddr->ifa);
			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
				SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n");
				continue;
			}
			if (laddr->ifa->address.sa.sa_family == nam->sa_family) {
				/* possible, see if it matches */
				switch (nam->sa_family) {
#ifdef INET
				case AF_INET:
#if defined(__APPLE__)
					if (sin == NULL) {
						/* TSNH */
						break;
					}
#endif
					if (sin->sin_addr.s_addr ==
					    laddr->ifa->address.sin.sin_addr.s_addr) {
						SCTP_INP_RUNLOCK(inp);
						return (inp);
					}
					break;
#endif
#ifdef INET6
				case AF_INET6:
					intf_addr6 = &laddr->ifa->address.sin6;
					if (SCTP6_ARE_ADDR_EQUAL(sin6,
					    intf_addr6)) {
						SCTP_INP_RUNLOCK(inp);
						return (inp);
					}
					break;
#endif
#if defined(__Userspace__)
				case AF_CONN:
					if (sconn->sconn_addr == laddr->ifa->address.sconn.sconn_addr) {
						SCTP_INP_RUNLOCK(inp);
						return (inp);
					}
					break;
#endif
				}
			}
		}
		SCTP_INP_RUNLOCK(inp);
	}
	return (NULL);
}


static struct sctp_inpcb *
sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id)
{
	struct sctppcbhead *head;
	struct sctp_inpcb *t_inp;
#ifdef SCTP_MVRF
	int i;
#endif
	int fnd;

	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
	    SCTP_BASE_INFO(hashmark))];
	LIST_FOREACH(t_inp, head, sctp_hash) {
		if (t_inp->sctp_lport != lport) {
			continue;
		}
		/* is it in the VRF in question */
		fnd = 0;
#ifdef SCTP_MVRF
		for (i = 0; i < inp->num_vrfs; i++) {
			if (t_inp->m_vrf_ids[i] == vrf_id) {
				fnd = 1;
				break;
			}
		}
#else
		if (t_inp->def_vrf_id == vrf_id)
			fnd = 1;
#endif
		if (!fnd)
			continue;

		/* This one is in use. */
		/* check the v6/v4 binding issue */
		if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
		    SCTP_IPV6_V6ONLY(t_inp)) {
			if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
				/* collision in V6 space */
				return (t_inp);
			} else {
				/* inp is BOUND_V4 no conflict */
				continue;
			}
		} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
			/* t_inp is bound v4 and v6, conflict always */
			return (t_inp);
		} else {
			/* t_inp is bound only V4 */
			if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
			    SCTP_IPV6_V6ONLY(inp)) {
				/* no conflict */
				continue;
			}
			/* else fall through to conflict */
		}
		return (t_inp);
	}
	return (NULL);
}


int
sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp)
{
	/* For 1-2-1 with port reuse */
	struct sctppcbhead *head;
	struct sctp_inpcb *tinp, *ninp;

	if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) {
		/* only works with port reuse on */
		return (-1);
	}
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
		return (0);
	}
	SCTP_INP_RUNLOCK(inp);
	SCTP_INP_INFO_WLOCK();
	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport,
	                                    SCTP_BASE_INFO(hashmark))];
	/* Kick out all non-listeners to the TCP hash */
	LIST_FOREACH_SAFE(tinp, head, sctp_hash, ninp) {
		if (tinp->sctp_lport != inp->sctp_lport) {
			continue;
		}
		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			continue;
		}
		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
			continue;
		}
		if (tinp->sctp_socket->so_qlimit) {
			continue;
		}
		SCTP_INP_WLOCK(tinp);
		LIST_REMOVE(tinp, sctp_hash);
		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))];
		tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
		LIST_INSERT_HEAD(head, tinp, sctp_hash);
		SCTP_INP_WUNLOCK(tinp);
	}
	SCTP_INP_WLOCK(inp);
	/* Pull from where he was */
	LIST_REMOVE(inp, sctp_hash);
	inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL;
	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))];
	LIST_INSERT_HEAD(head, inp, sctp_hash);
	SCTP_INP_WUNLOCK(inp);
	SCTP_INP_RLOCK(inp);
	SCTP_INP_INFO_WUNLOCK();
	return (0);
}


struct sctp_inpcb *
sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock,
		uint32_t vrf_id)
{
	/*
	 * First we check the hash table to see if someone has this port
	 * bound with just the port.
	 */
	struct sctp_inpcb *inp;
	struct sctppcbhead *head;
	int lport;
	unsigned int i;
#ifdef INET
	struct sockaddr_in *sin;
#endif
#ifdef INET6
	struct sockaddr_in6 *sin6;
#endif
#if defined(__Userspace__)
	struct sockaddr_conn *sconn;
#endif

	switch (nam->sa_family) {
#ifdef INET
	case AF_INET:
		sin = (struct sockaddr_in *)nam;
		lport = sin->sin_port;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		sin6 = (struct sockaddr_in6 *)nam;
		lport = sin6->sin6_port;
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		sconn = (struct sockaddr_conn *)nam;
		lport = sconn->sconn_port;
		break;
#endif
	default:
		return (NULL);
	}
	/*
	 * I could cheat here and just cast to one of the types but we will
	 * do it right. It also provides the check against an Unsupported
	 * type too.
	 */
	/* Find the head of the ALLADDR chain */
	if (have_lock == 0) {
		SCTP_INP_INFO_RLOCK();
	}
	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
	    SCTP_BASE_INFO(hashmark))];
	inp = sctp_endpoint_probe(nam, head, lport, vrf_id);

	/*
	 * If the TCP model exists it could be that the main listening
	 * endpoint is gone but there still exists a connected socket for this
	 * guy. If so we can return the first one that we find. This may NOT
	 * be the correct one so the caller should be wary on the returned INP.
	 * Currently the only caller that sets find_tcp_pool is in bindx where
	 * we are verifying that a user CAN bind the address. He either
	 * has bound it already, or someone else has, or its open to bind,
	 * so this is good enough.
	 */
	if (inp == NULL && find_tcp_pool) {
		for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) {
			head = &SCTP_BASE_INFO(sctp_tcpephash)[i];
			inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
			if (inp) {
				break;
			}
		}
	}
	if (inp) {
		SCTP_INP_INCR_REF(inp);
	}
	if (have_lock == 0) {
		SCTP_INP_INFO_RUNLOCK();
	}
	return (inp);
}


/*
 * Find an association for an endpoint with the pointer to whom you want to
 * send to and the endpoint pointer. The address can be IPv4 or IPv6. We may
 * need to change the *to to some other struct like a mbuf...
 */
struct sctp_tcb *
sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to,
    struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool,
    uint32_t vrf_id)
{
	struct sctp_inpcb *inp = NULL;
	struct sctp_tcb *stcb;

	SCTP_INP_INFO_RLOCK();
	if (find_tcp_pool) {
		if (inp_p != NULL) {
			stcb = sctp_tcb_special_locate(inp_p, from, to, netp,
			                               vrf_id);
		} else {
			stcb = sctp_tcb_special_locate(&inp, from, to, netp,
			                               vrf_id);
		}
		if (stcb != NULL) {
			SCTP_INP_INFO_RUNLOCK();
			return (stcb);
		}
	}
	inp = sctp_pcb_findep(to, 0, 1, vrf_id);
	if (inp_p != NULL) {
		*inp_p = inp;
	}
	SCTP_INP_INFO_RUNLOCK();
	if (inp == NULL) {
		return (NULL);
	}
	/*
	 * ok, we have an endpoint, now lets find the assoc for it (if any)
	 * we now place the source address or from in the to of the find
	 * endpoint call. Since in reality this chain is used from the
	 * inbound packet side.
	 */
	if (inp_p != NULL) {
		stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to,
		                                    NULL);
	} else {
		stcb = sctp_findassociation_ep_addr(&inp, from, netp, to,
		                                    NULL);
	}
	return (stcb);
}


/*
 * This routine will grub through the mbuf that is a INIT or INIT-ACK and
 * find all addresses that the sender has specified in any address list. Each
 * address will be used to lookup the TCB and see if one exits.
 */
static struct sctp_tcb *
sctp_findassociation_special_addr(struct mbuf *m, int offset,
    struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
    struct sockaddr *dst)
{
	struct sctp_paramhdr *phdr, parm_buf;
#if defined(INET) || defined(INET6)
	struct sctp_tcb *stcb;
	uint16_t ptype;
#endif
	uint16_t plen;
#ifdef INET
	struct sockaddr_in sin4;
#endif
#ifdef INET6
	struct sockaddr_in6 sin6;
#endif

#ifdef INET
	memset(&sin4, 0, sizeof(sin4));
#ifdef HAVE_SIN_LEN
	sin4.sin_len = sizeof(sin4);
#endif
	sin4.sin_family = AF_INET;
	sin4.sin_port = sh->src_port;
#endif
#ifdef INET6
	memset(&sin6, 0, sizeof(sin6));
#ifdef HAVE_SIN6_LEN
	sin6.sin6_len = sizeof(sin6);
#endif
	sin6.sin6_family = AF_INET6;
	sin6.sin6_port = sh->src_port;
#endif

	offset += sizeof(struct sctp_init_chunk);

	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
	while (phdr != NULL) {
		/* now we must see if we want the parameter */
#if defined(INET) || defined(INET6)
		ptype = ntohs(phdr->param_type);
#endif
		plen = ntohs(phdr->param_length);
		if (plen == 0) {
			break;
		}
#ifdef INET
		if (ptype == SCTP_IPV4_ADDRESS &&
		    plen == sizeof(struct sctp_ipv4addr_param)) {
			/* Get the rest of the address */
			struct sctp_ipv4addr_param ip4_parm, *p4;

			phdr = sctp_get_next_param(m, offset,
			    (struct sctp_paramhdr *)&ip4_parm, min(plen, sizeof(ip4_parm)));
			if (phdr == NULL) {
				return (NULL);
			}
			p4 = (struct sctp_ipv4addr_param *)phdr;
			memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
			/* look it up */
			stcb = sctp_findassociation_ep_addr(inp_p,
			    (struct sockaddr *)&sin4, netp, dst, NULL);
			if (stcb != NULL) {
				return (stcb);
			}
		}
#endif
#ifdef INET6
		if (ptype == SCTP_IPV6_ADDRESS &&
		    plen == sizeof(struct sctp_ipv6addr_param)) {
			/* Get the rest of the address */
			struct sctp_ipv6addr_param ip6_parm, *p6;

			phdr = sctp_get_next_param(m, offset,
			    (struct sctp_paramhdr *)&ip6_parm, min(plen,sizeof(ip6_parm)));
			if (phdr == NULL) {
				return (NULL);
			}
			p6 = (struct sctp_ipv6addr_param *)phdr;
			memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
			/* look it up */
			stcb = sctp_findassociation_ep_addr(inp_p,
			    (struct sockaddr *)&sin6, netp, dst, NULL);
			if (stcb != NULL) {
				return (stcb);
			}
		}
#endif
		offset += SCTP_SIZE32(plen);
		phdr = sctp_get_next_param(m, offset, &parm_buf,
					   sizeof(parm_buf));
	}
	return (NULL);
}

static struct sctp_tcb *
sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag,
		       struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
		       uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag)
{
	/*
	 * Use my vtag to hash. If we find it we then verify the source addr
	 * is in the assoc. If all goes well we save a bit on rec of a
	 * packet.
	 */
	struct sctpasochead *head;
	struct sctp_nets *net;
	struct sctp_tcb *stcb;
#ifdef SCTP_MVRF
	unsigned int i;
#endif

	SCTP_INP_INFO_RLOCK();
	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag,
	                                                        SCTP_BASE_INFO(hashasocmark))];
	LIST_FOREACH(stcb, head, sctp_asocs) {
		SCTP_INP_RLOCK(stcb->sctp_ep);
		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			SCTP_INP_RUNLOCK(stcb->sctp_ep);
			continue;
		}
#ifdef SCTP_MVRF
		for (i = 0; i < stcb->sctp_ep->num_vrfs; i++) {
			if (stcb->sctp_ep->m_vrf_ids[i] == vrf_id) {
				break;
			}
		}
		if (i == stcb->sctp_ep->num_vrfs) {
			SCTP_INP_RUNLOCK(inp);
			continue;
		}
#else
		if (stcb->sctp_ep->def_vrf_id != vrf_id) {
			SCTP_INP_RUNLOCK(stcb->sctp_ep);
			continue;
		}
#endif
		SCTP_TCB_LOCK(stcb);
		SCTP_INP_RUNLOCK(stcb->sctp_ep);
		if (stcb->asoc.my_vtag == vtag) {
			/* candidate */
			if (stcb->rport != rport) {
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			if (stcb->sctp_ep->sctp_lport != lport) {
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			/* RRS:Need toaddr check here */
			if (sctp_does_stcb_own_this_addr(stcb, to) == 0) {
			        /* Endpoint does not own this address */
				SCTP_TCB_UNLOCK(stcb);
				continue;
			}
			if (remote_tag) {
				/* If we have both vtags that's all we match on */
				if (stcb->asoc.peer_vtag == remote_tag) {
					/* If both tags match we consider it conclusive
					 * and check NO source/destination addresses
					 */
					goto conclusive;
				}
			}
			if (skip_src_check) {
			conclusive:
			        if (from) {
					*netp = sctp_findnet(stcb, from);
				} else {
					*netp = NULL;	/* unknown */
				}
				if (inp_p)
					*inp_p = stcb->sctp_ep;
				SCTP_INP_INFO_RUNLOCK();
				return (stcb);
			}
			net = sctp_findnet(stcb, from);
			if (net) {
				/* yep its him. */
				*netp = net;
				SCTP_STAT_INCR(sctps_vtagexpress);
				*inp_p = stcb->sctp_ep;
				SCTP_INP_INFO_RUNLOCK();
				return (stcb);
			} else {
				/*
				 * not him, this should only happen in rare
				 * cases so I peg it.
				 */
				SCTP_STAT_INCR(sctps_vtagbogus);
			}
		}
		SCTP_TCB_UNLOCK(stcb);
	}
	SCTP_INP_INFO_RUNLOCK();
	return (NULL);
}


/*
 * Find an association with the pointer to the inbound IP packet. This can be
 * a IPv4 or IPv6 packet.
 */
struct sctp_tcb *
sctp_findassociation_addr(struct mbuf *m, int offset,
    struct sockaddr *src, struct sockaddr *dst,
    struct sctphdr *sh, struct sctp_chunkhdr *ch,
    struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
	int find_tcp_pool;
	struct sctp_tcb *stcb;
	struct sctp_inpcb *inp;

	if (sh->v_tag) {
		/* we only go down this path if vtag is non-zero */
		stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag),
		                              inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0);
		if (stcb) {
			return (stcb);
		}
	}

	find_tcp_pool = 0;
	if ((ch->chunk_type != SCTP_INITIATION) &&
	    (ch->chunk_type != SCTP_INITIATION_ACK) &&
	    (ch->chunk_type != SCTP_COOKIE_ACK) &&
	    (ch->chunk_type != SCTP_COOKIE_ECHO)) {
		/* Other chunk types go to the tcp pool. */
		find_tcp_pool = 1;
	}
	if (inp_p) {
		stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp,
		                                    find_tcp_pool, vrf_id);
		inp = *inp_p;
	} else {
		stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp,
		                                    find_tcp_pool, vrf_id);
	}
	SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp);
	if (stcb == NULL && inp) {
		/* Found a EP but not this address */
		if ((ch->chunk_type == SCTP_INITIATION) ||
		    (ch->chunk_type == SCTP_INITIATION_ACK)) {
			/*-
			 * special hook, we do NOT return linp or an
			 * association that is linked to an existing
			 * association that is under the TCP pool (i.e. no
			 * listener exists). The endpoint finding routine
			 * will always find a listener before examining the
			 * TCP pool.
			 */
			if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
				if (inp_p) {
					*inp_p = NULL;
				}
				return (NULL);
			}
			stcb = sctp_findassociation_special_addr(m,
			    offset, sh, &inp, netp, dst);
			if (inp_p != NULL) {
				*inp_p = inp;
			}
		}
	}
	SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb);
	return (stcb);
}

/*
 * lookup an association by an ASCONF lookup address.
 * if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup
 */
struct sctp_tcb *
sctp_findassociation_ep_asconf(struct mbuf *m, int offset,
			       struct sockaddr *dst, struct sctphdr *sh,
                               struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
{
	struct sctp_tcb *stcb;
	union sctp_sockstore remote_store;
	struct sctp_paramhdr parm_buf, *phdr;
	int ptype;
	int zero_address = 0;
#ifdef INET
	struct sockaddr_in *sin;
#endif
#ifdef INET6
	struct sockaddr_in6 *sin6;
#endif

	memset(&remote_store, 0, sizeof(remote_store));
	phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
				   &parm_buf, sizeof(struct sctp_paramhdr));
	if (phdr == NULL) {
		SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n",
			__FUNCTION__);
		return NULL;
	}
	ptype = (int)((uint32_t) ntohs(phdr->param_type));
	/* get the correlation address */
	switch (ptype) {
#ifdef INET6
	case SCTP_IPV6_ADDRESS:
	{
		/* ipv6 address param */
		struct sctp_ipv6addr_param *p6, p6_buf;

		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
			return NULL;
		}
		p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
								       offset + sizeof(struct sctp_asconf_chunk),
								       &p6_buf.ph, sizeof(*p6));
		if (p6 == NULL) {
			SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n",
				__FUNCTION__);
			return (NULL);
		}
		sin6 = &remote_store.sin6;
		sin6->sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
		sin6->sin6_len = sizeof(*sin6);
#endif
		sin6->sin6_port = sh->src_port;
		memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
			zero_address = 1;
		break;
	}
#endif
#ifdef INET
	case SCTP_IPV4_ADDRESS:
	{
		/* ipv4 address param */
		struct sctp_ipv4addr_param *p4, p4_buf;

		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
			return NULL;
		}
		p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
								       offset + sizeof(struct sctp_asconf_chunk),
								       &p4_buf.ph, sizeof(*p4));
		if (p4 == NULL) {
			SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n",
				__FUNCTION__);
			return (NULL);
		}
		sin = &remote_store.sin;
		sin->sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
		sin->sin_len = sizeof(*sin);
#endif
		sin->sin_port = sh->src_port;
		memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
		if (sin->sin_addr.s_addr == INADDR_ANY)
			zero_address = 1;
		break;
	}
#endif
	default:
		/* invalid address param type */
		return NULL;
	}

	if (zero_address) {
	        stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p,
					      netp, sh->src_port, sh->dest_port, 1, vrf_id, 0);
		if (stcb != NULL) {
			SCTP_INP_DECR_REF(*inp_p);
		}
	} else {
		stcb = sctp_findassociation_ep_addr(inp_p,
		    &remote_store.sa, netp,
		    dst, NULL);
	}
	return (stcb);
}


/*
 * allocate a sctp_inpcb and setup a temporary binding to a port/all
 * addresses. This way if we don't get a bind we by default pick a ephemeral
 * port with all addresses bound.
 */
int
sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
{
	/*
	 * we get called when a new endpoint starts up. We need to allocate
	 * the sctp_inpcb structure from the zone and init it. Mark it as
	 * unbound and find a port that we can use as an ephemeral with
	 * INADDR_ANY. If the user binds later no problem we can then add in
	 * the specific addresses. And setup the default parameters for the
	 * EP.
	 */
	int i, error;
	struct sctp_inpcb *inp;
	struct sctp_pcb *m;
	struct timeval time;
	sctp_sharedkey_t *null_key;

	error = 0;

	SCTP_INP_INFO_WLOCK();
	inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb);
	if (inp == NULL) {
		SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n");
		SCTP_INP_INFO_WUNLOCK();
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
		return (ENOBUFS);
	}
	/* zap it */
	bzero(inp, sizeof(*inp));

	/* bump generations */
#if defined(__APPLE__)
	inp->ip_inp.inp.inp_state = INPCB_STATE_INUSE;
#endif
	/* setup socket pointers */
	inp->sctp_socket = so;
	inp->ip_inp.inp.inp_socket = so;
#if defined(__FreeBSD__)
	inp->ip_inp.inp.inp_cred = crhold(so->so_cred);
#endif
#ifdef INET6
#if !defined(__Userspace__) && !defined(__Windows__)
	if (INP_SOCKAF(so) == AF_INET6) {
		if (MODULE_GLOBAL(ip6_auto_flowlabel)) {
			inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL;
		}
		if (MODULE_GLOBAL(ip6_v6only)) {
			inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY;
		}
	}
#endif
#endif
	inp->sctp_associd_counter = 1;
	inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
	inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
	inp->max_cwnd = 0;
	inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
	inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable);
	inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable);
	inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable);
	inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable);
	inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable);
	inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable);
	inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable);
#if defined(__Userspace__)
	inp->ulp_info = NULL;
	inp->recv_callback = NULL;
	inp->send_callback = NULL;
	inp->send_sb_threshold = 0;
#endif
	/* init the small hash table we use to track asocid <-> tcb */
	inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
	if (inp->sctp_asocidhash == NULL) {
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		SCTP_INP_INFO_WUNLOCK();
		return (ENOBUFS);
	}
#ifdef IPSEC
#if !(defined(__APPLE__))
	{
		struct inpcbpolicy *pcb_sp = NULL;

		error = ipsec_init_policy(so, &pcb_sp);
		/* Arrange to share the policy */
		inp->ip_inp.inp.inp_sp = pcb_sp;
		((struct in6pcb *)(&inp->ip_inp.inp))->in6p_sp = pcb_sp;
	}
#else
	/* not sure what to do for openbsd here */
	error = 0;
#endif
	if (error != 0) {
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		SCTP_INP_INFO_WUNLOCK();
		return error;
	}
#endif				/* IPSEC */
	SCTP_INCR_EP_COUNT();
	inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl);
	SCTP_INP_INFO_WUNLOCK();

	so->so_pcb = (caddr_t)inp;

#if defined(__FreeBSD__) && __FreeBSD_version < 803000
	if ((SCTP_SO_TYPE(so) == SOCK_DGRAM) ||
	    (SCTP_SO_TYPE(so) == SOCK_SEQPACKET)) {
#else
	if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) {
#endif
		/* UDP style socket */
		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
		    SCTP_PCB_FLAGS_UNBOUND);
		/* Be sure it is NON-BLOCKING IO for UDP */
		/* SCTP_SET_SO_NBIO(so); */
	} else if (SCTP_SO_TYPE(so) == SOCK_STREAM) {
		/* TCP style socket */
		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
		    SCTP_PCB_FLAGS_UNBOUND);
		/* Be sure we have blocking IO by default */
		SCTP_CLEAR_SO_NBIO(so);
#if defined(__Panda__)
	} else if (SCTP_SO_TYPE(so) == SOCK_FASTSEQPACKET) {
		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
		    SCTP_PCB_FLAGS_UNBOUND);
		sctp_feature_on(inp, SCTP_PCB_FLAGS_ZERO_COPY_ACTIVE);
	} else if (SCTP_SO_TYPE(so) == SOCK_FASTSTREAM) {
		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
		    SCTP_PCB_FLAGS_UNBOUND);
		sctp_feature_on(inp, SCTP_PCB_FLAGS_ZERO_COPY_ACTIVE);
#endif
	} else {
		/*
		 * unsupported socket type (RAW, etc)- in case we missed it
		 * in protosw
		 */
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP);
		so->so_pcb = NULL;
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		return (EOPNOTSUPP);
	}
	if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) {
		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) {
		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
		sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) {
		sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
	}
	inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize),
					   &inp->sctp_hashmark);
	if (inp->sctp_tcbhash == NULL) {
		SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n");
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
		so->so_pcb = NULL;
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		return (ENOBUFS);
	}
#ifdef SCTP_MVRF
	inp->vrf_size = SCTP_DEFAULT_VRF_SIZE;
	SCTP_MALLOC(inp->m_vrf_ids, uint32_t *,
		    (sizeof(uint32_t) * inp->vrf_size), SCTP_M_MVRF);
	if (inp->m_vrf_ids == NULL) {
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
		so->so_pcb = NULL;
		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		return (ENOBUFS);
	}
	inp->m_vrf_ids[0] = vrf_id;
	inp->num_vrfs = 1;
#endif
	inp->def_vrf_id = vrf_id;

#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
	inp->ip_inp.inp.inpcb_mtx = lck_mtx_alloc_init(SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
	if (inp->ip_inp.inp.inpcb_mtx == NULL) {
		SCTP_PRINTF("in_pcballoc: can't alloc mutex! so=%p\n", (void *)so);
#ifdef SCTP_MVRF
		SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
		so->so_pcb = NULL;
#if defined(__FreeBSD__)
		crfree(inp->ip_inp.inp.inp_cred);
#endif
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
		SCTP_UNLOCK_EXC(SCTP_BASE_INFO(sctbinfo).ipi_lock);
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
		return (ENOMEM);
	}
#elif defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
	lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
	lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).ipi_lock_grp, SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
	SCTP_INP_INFO_WLOCK();
	SCTP_INP_LOCK_INIT(inp);
#if defined(__FreeBSD__)
	INP_LOCK_INIT(&inp->ip_inp.inp, "inp", "sctpinp");
#endif
	SCTP_INP_READ_INIT(inp);
	SCTP_ASOC_CREATE_LOCK_INIT(inp);
	/* lock the new ep */
	SCTP_INP_WLOCK(inp);

	/* add it to the info area */
	LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list);
#if defined(__APPLE__)
	inp->ip_inp.inp.inp_pcbinfo = &SCTP_BASE_INFO(sctbinfo);
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
	LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).listhead, &inp->ip_inp.inp, inp_list);
#else
	LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).ipi_listhead, &inp->ip_inp.inp, inp_list);
#endif
#endif
	SCTP_INP_INFO_WUNLOCK();

	TAILQ_INIT(&inp->read_queue);
	LIST_INIT(&inp->sctp_addr_list);

	LIST_INIT(&inp->sctp_asoc_list);

#ifdef SCTP_TRACK_FREED_ASOCS
	/* TEMP CODE */
	LIST_INIT(&inp->sctp_asoc_free_list);
#endif
	/* Init the timer structure for signature change */
	SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer);
	inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;

	/* now init the actual endpoint default data */
	m = &inp->sctp_ep;

	/* setup the base timeout information */
	m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC);	/* needed ? */
	m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC);	/* needed ? */
	m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default));
	m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default));
	m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default));
	m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default));
	m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default));
	/* all max/min max are in ms */
	m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default);
	m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default);
	m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default);
	m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default);
	m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default);
	m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default);
	m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default);
	m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default);
	m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold);
	m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
	m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
	m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default);
	m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default);

	m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module);
	m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module);
	m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default);
	/* number of streams to pre-open on a association */
	m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default);

	/* Add adaptation cookie */
	m->adaptation_layer_indicator = 0;
	m->adaptation_layer_indicator_provided = 0;

	/* seed random number generator */
	m->random_counter = 1;
	m->store_at = SCTP_SIGNATURE_SIZE;
	SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers));
	sctp_fill_random_store(m);

	/* Minimum cookie size */
	m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
	    sizeof(struct sctp_state_cookie);
	m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;

	/* Setup the initial secret */
	(void)SCTP_GETTIME_TIMEVAL(&time);
	m->time_of_secret_change = time.tv_sec;

	for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
		m->secret_key[0][i] = sctp_select_initial_TSN(m);
	}
	sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);

	/* How long is a cookie good for ? */
	m->def_cookie_life = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default));
	/*
	 * Initialize authentication parameters
	 */
	m->local_hmacs = sctp_default_supported_hmaclist();
	m->local_auth_chunks = sctp_alloc_chunklist();
	if (inp->asconf_supported) {
		sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks);
		sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks);
	}
	m->default_dscp = 0;
#ifdef INET6
	m->default_flowlabel = 0;
#endif
	m->port = 0; /* encapsulation disabled by default */
	LIST_INIT(&m->shared_keys);
	/* add default NULL key as key id 0 */
	null_key = sctp_alloc_sharedkey();
	sctp_insert_sharedkey(&m->shared_keys, null_key);
	SCTP_INP_WUNLOCK(inp);
#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, NULL, 12);
#endif
	return (error);
}


void
sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
    struct sctp_tcb *stcb)
{
	struct sctp_nets *net;
	uint16_t lport, rport;
	struct sctppcbhead *head;
	struct sctp_laddr *laddr, *oladdr;

	atomic_add_int(&stcb->asoc.refcnt, 1);
	SCTP_TCB_UNLOCK(stcb);
	SCTP_INP_INFO_WLOCK();
	SCTP_INP_WLOCK(old_inp);
	SCTP_INP_WLOCK(new_inp);
	SCTP_TCB_LOCK(stcb);
	atomic_subtract_int(&stcb->asoc.refcnt, 1);

	new_inp->sctp_ep.time_of_secret_change =
	    old_inp->sctp_ep.time_of_secret_change;
	memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
	    sizeof(old_inp->sctp_ep.secret_key));
	new_inp->sctp_ep.current_secret_number =
	    old_inp->sctp_ep.current_secret_number;
	new_inp->sctp_ep.last_secret_number =
	    old_inp->sctp_ep.last_secret_number;
	new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;

	/* make it so new data pours into the new socket */
	stcb->sctp_socket = new_inp->sctp_socket;
	stcb->sctp_ep = new_inp;

	/* Copy the port across */
	lport = new_inp->sctp_lport = old_inp->sctp_lport;
	rport = stcb->rport;
	/* Pull the tcb from the old association */
	LIST_REMOVE(stcb, sctp_tcbhash);
	LIST_REMOVE(stcb, sctp_tcblist);
	if (stcb->asoc.in_asocid_hash) {
		LIST_REMOVE(stcb, sctp_tcbasocidhash);
	}
	/* Now insert the new_inp into the TCP connected hash */
	head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];

	LIST_INSERT_HEAD(head, new_inp, sctp_hash);
	/* Its safe to access */
	new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;

	/* Now move the tcb into the endpoint list */
	LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
	/*
	 * Question, do we even need to worry about the ep-hash since we
	 * only have one connection? Probably not :> so lets get rid of it
	 * and not suck up any kernel memory in that.
	 */
	if (stcb->asoc.in_asocid_hash) {
		struct sctpasochead *lhd;
		lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
			new_inp->hashasocidmark)];
		LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash);
	}
	/* Ok. Let's restart timer. */
	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
		sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp,
		    stcb, net);
	}

	SCTP_INP_INFO_WUNLOCK();
	if (new_inp->sctp_tcbhash != NULL) {
		SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark);
		new_inp->sctp_tcbhash = NULL;
	}
	if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
		/* Subset bound, so copy in the laddr list from the old_inp */
		LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
			laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
			if (laddr == NULL) {
				/*
				 * Gak, what can we do? This assoc is really
				 * HOSED. We probably should send an abort
				 * here.
				 */
				SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n");
				continue;
			}
			SCTP_INCR_LADDR_COUNT();
			bzero(laddr, sizeof(*laddr));
			(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
			laddr->ifa = oladdr->ifa;
			atomic_add_int(&laddr->ifa->refcount, 1);
			LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
			    sctp_nxt_addr);
			new_inp->laddr_count++;
			if (oladdr == stcb->asoc.last_used_address) {
				stcb->asoc.last_used_address = laddr;
			}
		}
	}
	/* Now any running timers need to be adjusted
	 * since we really don't care if they are running
	 * or not just blast in the new_inp into all of
	 * them.
	 */

	stcb->asoc.dack_timer.ep = (void *)new_inp;
	stcb->asoc.asconf_timer.ep = (void *)new_inp;
	stcb->asoc.strreset_timer.ep = (void *)new_inp;
	stcb->asoc.shut_guard_timer.ep = (void *)new_inp;
	stcb->asoc.autoclose_timer.ep = (void *)new_inp;
	stcb->asoc.delayed_event_timer.ep = (void *)new_inp;
	stcb->asoc.delete_prim_timer.ep = (void *)new_inp;
	/* now what about the nets? */
	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
		net->pmtu_timer.ep = (void *)new_inp;
		net->hb_timer.ep = (void *)new_inp;
		net->rxt_timer.ep = (void *)new_inp;
	}
	SCTP_INP_WUNLOCK(new_inp);
	SCTP_INP_WUNLOCK(old_inp);
}


#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Userspace__))
/*
 * Don't know why, but without this there is an unknown reference when
 * compiling NetBSD... hmm
 */
extern void in6_sin6_2_sin(struct sockaddr_in *, struct sockaddr_in6 *sin6);
#endif


/* sctp_ifap is used to bypass normal local address validation checks */
int
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
                struct sctp_ifa *sctp_ifap, struct thread *p)
#elif defined(__Windows__)
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
                struct sctp_ifa *sctp_ifap, PKTHREAD p)
#else
sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
                struct sctp_ifa *sctp_ifap, struct proc *p)
#endif
{
	/* bind a ep to a socket address */
	struct sctppcbhead *head;
	struct sctp_inpcb *inp, *inp_tmp;
#if defined(INET) || (defined(INET6) && defined(__APPLE__)) || defined(__FreeBSD__) || defined(__APPLE__)
	struct inpcb *ip_inp;
#endif
	int port_reuse_active = 0;
	int bindall;
#ifdef SCTP_MVRF
	int i;
#endif
	uint16_t lport;
	int error;
	uint32_t vrf_id;

	lport = 0;
	bindall = 1;
	inp = (struct sctp_inpcb *)so->so_pcb;
#if defined(INET) || (defined(INET6) && defined(__APPLE__)) || defined(__FreeBSD__) || defined(__APPLE__)
	ip_inp = (struct inpcb *)so->so_pcb;
#endif
#ifdef SCTP_DEBUG
	if (addr) {
		SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n",
			ntohs(((struct sockaddr_in *)addr)->sin_port));
		SCTPDBG(SCTP_DEBUG_PCB1, "Addr: ");
		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
	}
#endif
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
		/* already did a bind, subsequent binds NOT allowed ! */
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		return (EINVAL);
	}
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
#ifdef INVARIANTS
	if (p == NULL)
		panic("null proc/thread");
#endif
#endif
	if (addr != NULL) {
		switch (addr->sa_family) {
#ifdef INET
		case AF_INET:
		{
			struct sockaddr_in *sin;

			/* IPV6_V6ONLY socket? */
			if (SCTP_IPV6_V6ONLY(ip_inp)) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
				return (EINVAL);
			}
#ifdef HAVE_SA_LEN
			if (addr->sa_len != sizeof(*sin)) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
				return (EINVAL);
			}
#endif

			sin = (struct sockaddr_in *)addr;
			lport = sin->sin_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
			/*
			 * For LOOPBACK the prison_local_ip4() call will transmute the ip address
			 * to the proper value.
			 */
			if (p && (error = prison_local_ip4(p->td_ucred, &sin->sin_addr)) != 0) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
				return (error);
			}
#endif
			if (sin->sin_addr.s_addr != INADDR_ANY) {
				bindall = 0;
			}
			break;
		}
#endif
#ifdef INET6
		case AF_INET6:
		{
			/* Only for pure IPv6 Address. (No IPv4 Mapped!) */
			struct sockaddr_in6 *sin6;

			sin6 = (struct sockaddr_in6 *)addr;

#ifdef HAVE_SA_LEN
			if (addr->sa_len != sizeof(*sin6)) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
				return (EINVAL);
			}
#endif
			lport = sin6->sin6_port;
#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
			/*
			 * For LOOPBACK the prison_local_ip6() call will transmute the ipv6 address
			 * to the proper value.
			 */
			if (p && (error = prison_local_ip6(p->td_ucred, &sin6->sin6_addr,
			    (SCTP_IPV6_V6ONLY(inp) != 0))) != 0) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
				return (error);
			}
#endif
			if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
				bindall = 0;
#ifdef SCTP_EMBEDDED_V6_SCOPE
				/* KAME hack: embed scopeid */
#if defined(SCTP_KAME)
				if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
					return (EINVAL);
				}
#elif defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
				if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL) != 0) {
#else
				if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL, NULL) != 0) {
#endif
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
					return (EINVAL);
				}
#elif defined(__FreeBSD__)
				error = scope6_check_id(sin6, MODULE_GLOBAL(ip6_use_defzone));
				if (error != 0) {
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
					return (error);
				}
#else
				if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) {
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
					return (EINVAL);
				}
#endif
#endif /* SCTP_EMBEDDED_V6_SCOPE */
			}
#ifndef SCOPEDROUTING
			/* this must be cleared for ifa_ifwithaddr() */
			sin6->sin6_scope_id = 0;
#endif /* SCOPEDROUTING */
			break;
		}
#endif
#if defined(__Userspace__)
		case AF_CONN:
		{
			struct sockaddr_conn *sconn;

#ifdef HAVE_SA_LEN
			if (addr->sa_len != sizeof(struct sockaddr_conn)) {
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
				return (EINVAL);
			}
#endif
			sconn = (struct sockaddr_conn *)addr;
			lport = sconn->sconn_port;
			if (sconn->sconn_addr != NULL) {
				bindall = 0;
			}
			break;
		}
#endif
		default:
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EAFNOSUPPORT);
			return (EAFNOSUPPORT);
		}
	}
	SCTP_INP_INFO_WLOCK();
	SCTP_INP_WLOCK(inp);
	/* Setup a vrf_id to be the default for the non-bind-all case. */
	vrf_id = inp->def_vrf_id;

	/* increase our count due to the unlock we do */
	SCTP_INP_INCR_REF(inp);
	if (lport) {
		/*
		 * Did the caller specify a port? if so we must see if an ep
		 * already has this one bound.
		 */
		/* got to be root to get at low ports */
#if !defined(__Windows__)
		if (ntohs(lport) < IPPORT_RESERVED) {
			if (p && (error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
				  priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
				  suser_cred(p->td_ucred, 0)
#else
				  suser(p)
#endif
#elif defined(__APPLE__)
				  suser(p->p_ucred, &p->p_acflag)
#elif defined(__Userspace__) /* must be true to use raw socket */
				  1
#else
				  suser(p, 0)
#endif
				    )) {
				SCTP_INP_DECR_REF(inp);
				SCTP_INP_WUNLOCK(inp);
				SCTP_INP_INFO_WUNLOCK();
				return (error);
			}
#if defined(__Panda__)
			if (!SCTP_IS_PRIVILEDGED(so)) {
				SCTP_INP_DECR_REF(inp);
				SCTP_INP_WUNLOCK(inp);
				SCTP_INP_INFO_WUNLOCK();
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EACCES);
				return (EACCES);
			}
#endif
		}
#endif /* __Windows__ */
		SCTP_INP_WUNLOCK(inp);
		if (bindall) {
#ifdef SCTP_MVRF
			for (i = 0; i < inp->num_vrfs; i++) {
				vrf_id = inp->m_vrf_ids[i];
#else
				vrf_id = inp->def_vrf_id;
#endif
				inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
				if (inp_tmp != NULL) {
					/*
					 * lock guy returned and lower count
					 * note that we are not bound so
					 * inp_tmp should NEVER be inp. And
					 * it is this inp (inp_tmp) that gets
					 * the reference bump, so we must
					 * lower it.
					 */
					SCTP_INP_DECR_REF(inp_tmp);
					/* unlock info */
					if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
					    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
						/* Ok, must be one-2-one and allowing port re-use */
						port_reuse_active = 1;
						goto continue_anyway;
					}
					SCTP_INP_DECR_REF(inp);
					SCTP_INP_INFO_WUNLOCK();
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
					return (EADDRINUSE);
				}
#ifdef SCTP_MVRF
			}
#endif
		} else {
			inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
			if (inp_tmp != NULL) {
				/*
				 * lock guy returned and lower count note
				 * that we are not bound so inp_tmp should
				 * NEVER be inp. And it is this inp (inp_tmp)
				 * that gets the reference bump, so we must
				 * lower it.
				 */
				SCTP_INP_DECR_REF(inp_tmp);
				/* unlock info */
				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
					/* Ok, must be one-2-one and allowing port re-use */
					port_reuse_active = 1;
					goto continue_anyway;
				}
				SCTP_INP_DECR_REF(inp);
				SCTP_INP_INFO_WUNLOCK();
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
				return (EADDRINUSE);
			}
		}
	continue_anyway:
		SCTP_INP_WLOCK(inp);
		if (bindall) {
			/* verify that no lport is not used by a singleton */
			if ((port_reuse_active == 0) &&
			    (inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) {
				/* Sorry someone already has this one bound */
				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
					port_reuse_active = 1;
				} else {
					SCTP_INP_DECR_REF(inp);
					SCTP_INP_WUNLOCK(inp);
					SCTP_INP_INFO_WUNLOCK();
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
					return (EADDRINUSE);
				}
			}
		}
	} else {
		uint16_t first, last, candidate;
		uint16_t count;
		int done;

#if defined(__Windows__)
		first = 1;
		last = 0xffff;
#else
#if defined(__Userspace__)
		/* TODO ensure uid is 0, etc... */
#elif defined(__FreeBSD__) || defined(__APPLE__)
		if (ip_inp->inp_flags & INP_HIGHPORT) {
			first = MODULE_GLOBAL(ipport_hifirstauto);
			last = MODULE_GLOBAL(ipport_hilastauto);
		} else if (ip_inp->inp_flags & INP_LOWPORT) {
			if (p && (error =
#ifdef __FreeBSD__
#if __FreeBSD_version > 602000
				  priv_check(p, PRIV_NETINET_RESERVEDPORT)
#elif __FreeBSD_version >= 500000
				  suser_cred(p->td_ucred, 0)
#else
				  suser(p)
#endif
#elif defined(__APPLE__)
				  suser(p->p_ucred, &p->p_acflag)
#else
				  suser(p, 0)
#endif
				    )) {
				SCTP_INP_DECR_REF(inp);
				SCTP_INP_WUNLOCK(inp);
				SCTP_INP_INFO_WUNLOCK();
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
				return (error);
			}
			first = MODULE_GLOBAL(ipport_lowfirstauto);
			last = MODULE_GLOBAL(ipport_lowlastauto);
		} else {
#endif
			first = MODULE_GLOBAL(ipport_firstauto);
			last = MODULE_GLOBAL(ipport_lastauto);
#if defined(__FreeBSD__) || defined(__APPLE__)
		}
#endif
#endif /* __Windows__ */
		if (first > last) {
			uint16_t temp;

			temp = first;
			first = last;
			last = temp;
		}
		count = last - first + 1; /* number of candidates */
		candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count);

		done = 0;
		while (!done) {
#ifdef SCTP_MVRF
			for (i = 0; i < inp->num_vrfs; i++) {
				if (sctp_isport_inuse(inp, htons(candidate), inp->m_vrf_ids[i]) != NULL) {
					break;
				}
			}
			if (i == inp->num_vrfs) {
				done = 1;
			}
#else
			if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) {
				done = 1;
			}
#endif
			if (!done) {
				if (--count == 0) {
					SCTP_INP_DECR_REF(inp);
					SCTP_INP_WUNLOCK(inp);
					SCTP_INP_INFO_WUNLOCK();
					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
					return (EADDRINUSE);
				}
				if (candidate == last)
					candidate = first;
				else
					candidate = candidate + 1;
			}
		}
		lport = htons(candidate);
	}
	SCTP_INP_DECR_REF(inp);
	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE |
			       SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
		/*
		 * this really should not happen. The guy did a non-blocking
		 * bind and then did a close at the same time.
		 */
		SCTP_INP_WUNLOCK(inp);
		SCTP_INP_INFO_WUNLOCK();
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		return (EINVAL);
	}
	/* ok we look clear to give out this port, so lets setup the binding */
	if (bindall) {
		/* binding to all addresses, so just set in the proper flags */
		inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL;
		/* set the automatic addr changes from kernel flag */
		if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) {
			sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF);
			sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
		} else {
			sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
			sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
		}
		if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) {
			sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
		} else {
			sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
		}
		/* set the automatic mobility_base from kernel
		   flag (by micchie)
		*/
		if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) {
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE);
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
		} else {
			sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE);
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
		}
		/* set the automatic mobility_fasthandoff from kernel
		   flag (by micchie)
		*/
		if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) {
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF);
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
		} else {
			sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF);
			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
		}
	} else {
		/*
		 * bind specific, make sure flags is off and add a new
		 * address structure to the sctp_addr_list inside the ep
		 * structure.
		 *
		 * We will need to allocate one and insert it at the head. The
		 * socketopt call can just insert new addresses in there as
		 * well. It will also have to do the embed scope kame hack
		 * too (before adding).
		 */
		struct sctp_ifa *ifa;
		union sctp_sockstore store;

		memset(&store, 0, sizeof(store));
		switch (addr->sa_family) {
#ifdef INET
		case AF_INET:
			memcpy(&store.sin, addr, sizeof(struct sockaddr_in));
			store.sin.sin_port = 0;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6));
			store.sin6.sin6_port = 0;
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			memcpy(&store.sconn, addr, sizeof(struct sockaddr_conn));
			store.sconn.sconn_port = 0;
			break;
#endif
		default:
			break;
		}
		/*
		 * first find the interface with the bound address need to
		 * zero out the port to find the address! yuck! can't do
		 * this earlier since need port for sctp_pcb_findep()
		 */
		if (sctp_ifap != NULL) {
			ifa = sctp_ifap;
		} else {
			/* Note for BSD we hit here always other
			 * O/S's will pass things in via the
			 * sctp_ifap argument (Panda).
			 */
			ifa = sctp_find_ifa_by_addr(&store.sa,
						    vrf_id, SCTP_ADDR_NOT_LOCKED);
		}
		if (ifa == NULL) {
			/* Can't find an interface with that address */
			SCTP_INP_WUNLOCK(inp);
			SCTP_INP_INFO_WUNLOCK();
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRNOTAVAIL);
			return (EADDRNOTAVAIL);
		}
#ifdef INET6
		if (addr->sa_family == AF_INET6) {
			/* GAK, more FIXME IFA lock? */
			if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
				/* Can't bind a non-existent addr. */
				SCTP_INP_WUNLOCK(inp);
				SCTP_INP_INFO_WUNLOCK();
				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
				return (EINVAL);
			}
		}
#endif
		/* we're not bound all */
		inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
		/* allow bindx() to send ASCONF's for binding changes */
		sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
		/* clear automatic addr changes from kernel flag */
		sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);

		/* add this address to the endpoint list */
		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0);
		if (error != 0) {
			SCTP_INP_WUNLOCK(inp);
			SCTP_INP_INFO_WUNLOCK();
			return (error);
		}
		inp->laddr_count++;
	}
	/* find the bucket */
	if (port_reuse_active) {
		/* Put it into tcp 1-2-1 hash */
		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))];
		inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
	} else {
		head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))];
	}
	/* put it in the bucket */
	LIST_INSERT_HEAD(head, inp, sctp_hash);
	SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n",
		(void *)head, ntohs(lport), port_reuse_active);
	/* set in the port */
	inp->sctp_lport = lport;

	/* turn off just the unbound flag */
	inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
	SCTP_INP_WUNLOCK(inp);
	SCTP_INP_INFO_WUNLOCK();
	return (0);
}


static void
sctp_iterator_inp_being_freed(struct sctp_inpcb *inp)
{
	struct sctp_iterator *it, *nit;

	/*
	 * We enter with the only the ITERATOR_LOCK in place and a write
	 * lock on the inp_info stuff.
	 */
	it = sctp_it_ctl.cur_it;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	if (it && (it->vn != curvnet)) {
		/* Its not looking at our VNET */
		return;
	}
#endif
	if (it && (it->inp == inp)) {
		/*
		 * This is tricky and we hold the iterator lock,
		 * but when it returns and gets the lock (when we
		 * release it) the iterator will try to operate on
		 * inp. We need to stop that from happening. But
		 * of course the iterator has a reference on the
		 * stcb and inp. We can mark it and it will stop.
		 *
		 * If its a single iterator situation, we
		 * set the end iterator flag. Otherwise
		 * we set the iterator to go to the next inp.
		 *
		 */
		if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
		} else {
			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP;
		}
	}
	/* Now go through and remove any single reference to
	 * our inp that may be still pending on the list
	 */
	SCTP_IPI_ITERATOR_WQ_LOCK();
	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
		if (it->vn != curvnet) {
			continue;
		}
#endif
		if (it->inp == inp) {
			/* This one points to me is it inp specific? */
			if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
				/* Remove and free this one */
				TAILQ_REMOVE(&sctp_it_ctl.iteratorhead,
				    it, sctp_nxt_itr);
				if (it->function_atend != NULL) {
					(*it->function_atend) (it->pointer, it->val);
				}
				SCTP_FREE(it, SCTP_M_ITER);
			} else {
				it->inp = LIST_NEXT(it->inp, sctp_list);
				if (it->inp) {
					SCTP_INP_INCR_REF(it->inp);
				}
			}
			/* When its put in the refcnt is incremented so decr it */
			SCTP_INP_DECR_REF(inp);
		}
	}
	SCTP_IPI_ITERATOR_WQ_UNLOCK();
}

/* release sctp_inpcb unbind the port */
void
sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from)
{
	/*
	 * Here we free a endpoint. We must find it (if it is in the Hash
	 * table) and remove it from there. Then we must also find it in the
	 * overall list and remove it from there. After all removals are
	 * complete then any timer has to be stopped. Then start the actual
	 * freeing. a) Any local lists. b) Any associations. c) The hash of
	 * all associations. d) finally the ep itself.
	 */
	struct sctp_tcb *asoc, *nasoc;
	struct sctp_laddr *laddr, *nladdr;
	struct inpcb *ip_pcb;
	struct socket *so;
	int being_refed = 0;
	struct sctp_queued_to_read *sq, *nsq;
#if !defined(__Panda__) && !defined(__Userspace__)
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
	sctp_rtentry_t *rt;
#endif
#endif
	int cnt;
	sctp_sharedkey_t *shared_key, *nshared_key;


#if defined(__APPLE__)
	sctp_lock_assert(SCTP_INP_SO(inp));
#endif
#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, NULL, 0);
#endif
	SCTP_ITERATOR_LOCK();
	/* mark any iterators on the list or being processed */
	sctp_iterator_inp_being_freed(inp);
	SCTP_ITERATOR_UNLOCK();
	so = inp->sctp_socket;
	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
		/* been here before.. eeks.. get out of here */
		SCTP_PRINTF("This conflict in free SHOULD not be happening! from %d, imm %d\n", from, immediate);
#ifdef SCTP_LOG_CLOSING
		sctp_log_closing(inp, NULL, 1);
#endif
		return;
	}
	SCTP_ASOC_CREATE_LOCK(inp);
	SCTP_INP_INFO_WLOCK();

	SCTP_INP_WLOCK(inp);
	if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) {
		inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP;
		/* socket is gone, so no more wakeups allowed */
		inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE;
		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT;
		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT;

	}
	/* First time through we have the socket lock, after that no more. */
	sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL,
			SCTP_FROM_SCTP_PCB+SCTP_LOC_1);

	if (inp->control) {
		sctp_m_freem(inp->control);
		inp->control = NULL;
	}
	if (inp->pkt) {
		sctp_m_freem(inp->pkt);
		inp->pkt = NULL;
	}
	ip_pcb = &inp->ip_inp.inp;	/* we could just cast the main pointer
					 * here but I will be nice :> (i.e.
					 * ip_pcb = ep;) */
	if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
		int cnt_in_sd;

		cnt_in_sd = 0;
		LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
			SCTP_TCB_LOCK(asoc);
			if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
				/* Skip guys being freed */
				cnt_in_sd++;
				if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
					/*
					 * Special case - we did not start a kill
					 * timer on the asoc due to it was not
					 * closed. So go ahead and start it now.
					 */
					asoc->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
					sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
				}
				SCTP_TCB_UNLOCK(asoc);
				continue;
			}
			if (((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_WAIT) ||
			    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_ECHOED)) &&
			    (asoc->asoc.total_output_queue_size == 0)) {
				/* If we have data in queue, we don't want to just
				 * free since the app may have done, send()/close
				 * or connect/send/close. And it wants the data
				 * to get across first.
				 */
				/* Just abandon things in the front states */
				if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE,
						   SCTP_FROM_SCTP_PCB+SCTP_LOC_2) == 0) {
					cnt_in_sd++;
				}
				continue;
			}
			/* Disconnect the socket please */
			asoc->sctp_socket = NULL;
			asoc->asoc.state |= SCTP_STATE_CLOSED_SOCKET;
			if ((asoc->asoc.size_on_reasm_queue > 0) ||
			    (asoc->asoc.control_pdapi) ||
			    (asoc->asoc.size_on_all_streams > 0) ||
			    (so && (so->so_rcv.sb_cc > 0))) {
				/* Left with Data unread */
				struct mbuf *op_err;

				op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
				asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_3;
				sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
				SCTP_STAT_INCR_COUNTER32(sctps_aborted);
				if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
				    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
				}
				if (sctp_free_assoc(inp, asoc,
						    SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB+SCTP_LOC_4) == 0) {
					cnt_in_sd++;
				}
				continue;
			} else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
			           TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
			           (asoc->asoc.stream_queue_cnt == 0)) {
				if (asoc->asoc.locked_on_sending) {
					goto abort_anyway;
				}
				if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
				    (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
					struct sctp_nets *netp;

					/*
					 * there is nothing queued to send,
					 * so I send shutdown
					 */
					if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
					    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
					}
					SCTP_SET_STATE(&asoc->asoc, SCTP_STATE_SHUTDOWN_SENT);
					SCTP_CLEAR_SUBSTATE(&asoc->asoc, SCTP_STATE_SHUTDOWN_PENDING);
					sctp_stop_timers_for_shutdown(asoc);
					if (asoc->asoc.alternate) {
						netp = asoc->asoc.alternate;
					} else {
						netp = asoc->asoc.primary_destination;
					}
					sctp_send_shutdown(asoc, netp);
					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
					    netp);
					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
					    asoc->asoc.primary_destination);
					sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED);
				}
			} else {
				/* mark into shutdown pending */
				struct sctp_stream_queue_pending *sp;

				asoc->asoc.state |= SCTP_STATE_SHUTDOWN_PENDING;
				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
						 asoc->asoc.primary_destination);
				if (asoc->asoc.locked_on_sending) {
					sp = TAILQ_LAST(&((asoc->asoc.locked_on_sending)->outqueue),
						sctp_streamhead);
					if (sp == NULL) {
						SCTP_PRINTF("Error, sp is NULL, locked on sending is %p strm:%d\n",
						       (void *)asoc->asoc.locked_on_sending,
						       asoc->asoc.locked_on_sending->stream_no);
					} else {
						if ((sp->length == 0) && (sp->msg_is_complete == 0))
							asoc->asoc.state |= SCTP_STATE_PARTIAL_MSG_LEFT;
					}
				}
				if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
				    TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
				    (asoc->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
					struct mbuf *op_err;
				abort_anyway:
					op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
					asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_5;
					sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
					SCTP_STAT_INCR_COUNTER32(sctps_aborted);
					if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
					    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
					}
					if (sctp_free_assoc(inp, asoc,
							    SCTP_PCBFREE_NOFORCE,
							    SCTP_FROM_SCTP_PCB+SCTP_LOC_6) == 0) {
						cnt_in_sd++;
					}
					continue;
				} else {
					sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED);
				}
			}
			cnt_in_sd++;
			SCTP_TCB_UNLOCK(asoc);
		}
		/* now is there some left in our SHUTDOWN state? */
		if (cnt_in_sd) {
#ifdef SCTP_LOG_CLOSING
			sctp_log_closing(inp, NULL, 2);
#endif
			inp->sctp_socket = NULL;
			SCTP_INP_WUNLOCK(inp);
			SCTP_ASOC_CREATE_UNLOCK(inp);
			SCTP_INP_INFO_WUNLOCK();
			return;
		}
	}
	inp->sctp_socket = NULL;
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
	    SCTP_PCB_FLAGS_UNBOUND) {
		/*
		 * ok, this guy has been bound. It's port is
		 * somewhere in the SCTP_BASE_INFO(hash table). Remove
		 * it!
		 */
		LIST_REMOVE(inp, sctp_hash);
		inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND;
	}

	/* If there is a timer running to kill us,
	 * forget it, since it may have a contest
	 * on the INP lock.. which would cause us
	 * to die ...
	 */
	cnt = 0;
	LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
		SCTP_TCB_LOCK(asoc);
		if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
			if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
				asoc->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
				sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
			}
		        cnt++;
			SCTP_TCB_UNLOCK(asoc);
			continue;
		}
		/* Free associations that are NOT killing us */
		if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_COOKIE_WAIT) &&
		    ((asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) {
			struct mbuf *op_err;

			op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
			asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_7;
			sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
			SCTP_STAT_INCR_COUNTER32(sctps_aborted);
		} else if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
			cnt++;
			SCTP_TCB_UNLOCK(asoc);
			continue;
		}
		if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
		    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
			SCTP_STAT_DECR_GAUGE32(sctps_currestab);
		}
		if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_FORCE, SCTP_FROM_SCTP_PCB+SCTP_LOC_8) == 0) {
			cnt++;
		}
	}
	if (cnt) {
		/* Ok we have someone out there that will kill us */
		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
		sctp_log_closing(inp, NULL, 3);
#endif
		SCTP_INP_WUNLOCK(inp);
		SCTP_ASOC_CREATE_UNLOCK(inp);
		SCTP_INP_INFO_WUNLOCK();
		return;
	}
	if (SCTP_INP_LOCK_CONTENDED(inp))
		being_refed++;
	if (SCTP_INP_READ_CONTENDED(inp))
		being_refed++;
	if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp))
		being_refed++;

	if ((inp->refcount) ||
	    (being_refed) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) {
		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
#ifdef SCTP_LOG_CLOSING
		sctp_log_closing(inp, NULL, 4);
#endif
		sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
		SCTP_INP_WUNLOCK(inp);
		SCTP_ASOC_CREATE_UNLOCK(inp);
		SCTP_INP_INFO_WUNLOCK();
		return;
	}
	inp->sctp_ep.signature_change.type = 0;
	inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
	/* Remove it from the list .. last thing we need a
	 * lock for.
	 */
	LIST_REMOVE(inp, sctp_list);
	SCTP_INP_WUNLOCK(inp);
	SCTP_ASOC_CREATE_UNLOCK(inp);
	SCTP_INP_INFO_WUNLOCK();
	/* Now we release all locks. Since this INP
	 * cannot be found anymore except possibly by the
	 * kill timer that might be running. We call
	 * the drain function here. It should hit the case
	 * were it sees the ACTIVE flag cleared and exit
	 * out freeing us to proceed and destroy everything.
	 */
	if (from != SCTP_CALLED_FROM_INPKILL_TIMER) {
		(void)SCTP_OS_TIMER_STOP_DRAIN(&inp->sctp_ep.signature_change.timer);
	} else {
		/* Probably un-needed */
		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
	}

#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, NULL, 5);
#endif

#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
	rt = ip_pcb->inp_route.ro_rt;
#endif
#endif

#if defined(__Panda__)
	if (inp->pak_to_read) {
		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.zero_copy_timer.timer);
		SCTP_RELEASE_PKT(inp->pak_to_read);
		inp->pak_to_read = NULL;
	}
	if (inp->pak_to_read_sendq) {
		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.zero_copy_sendq_timer.timer);
		SCTP_RELEASE_PKT(inp->pak_to_read_sendq);
		inp->pak_to_read_sendq = NULL;
	}
#endif
	if ((inp->sctp_asocidhash) != NULL) {
		SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark);
		inp->sctp_asocidhash = NULL;
	}
	/*sa_ignore FREED_MEMORY*/
	TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) {
		/* Its only abandoned if it had data left */
		if (sq->length)
			SCTP_STAT_INCR(sctps_left_abandon);

		TAILQ_REMOVE(&inp->read_queue, sq, next);
		sctp_free_remote_addr(sq->whoFrom);
		if (so)
			so->so_rcv.sb_cc -= sq->length;
		if (sq->data) {
			sctp_m_freem(sq->data);
			sq->data = NULL;
		}
		/*
		 * no need to free the net count, since at this point all
		 * assoc's are gone.
		 */
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), sq);
		SCTP_DECR_READQ_COUNT();
	}
	/* Now the sctp_pcb things */
	/*
	 * free each asoc if it is not already closed/free. we can't use the
	 * macro here since le_next will get freed as part of the
	 * sctp_free_assoc() call.
	 */
	if (so) {
#ifdef IPSEC
		ipsec_delete_pcbpolicy(ip_pcb);
#endif				/* IPSEC */

		/* Unlocks not needed since the socket is gone now */
	}
#ifndef __Panda__
	if (ip_pcb->inp_options) {
		(void)sctp_m_free(ip_pcb->inp_options);
		ip_pcb->inp_options = 0;
	}
#endif

#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
	if (rt) {
		RTFREE(rt);
		ip_pcb->inp_route.ro_rt = 0;
	}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version < 803000
#ifdef INET
	if (ip_pcb->inp_moptions) {
		inp_freemoptions(ip_pcb->inp_moptions);
		ip_pcb->inp_moptions = 0;
	}
#endif
#endif
#endif

#ifdef INET6
#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
#if defined(__FreeBSD__) || defined(__APPLE__)
	if (ip_pcb->inp_vflag & INP_IPV6) {
#else
	if (inp->inp_vflag & INP_IPV6) {
#endif
		struct in6pcb *in6p;

		in6p = (struct in6pcb *)inp;
		ip6_freepcbopts(in6p->in6p_outputopts);
	}
#endif
#endif				/* INET6 */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
	inp->inp_vflag = 0;
#else
	ip_pcb->inp_vflag = 0;
#endif
	/* free up authentication fields */
	if (inp->sctp_ep.local_auth_chunks != NULL)
		sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
	if (inp->sctp_ep.local_hmacs != NULL)
		sctp_free_hmaclist(inp->sctp_ep.local_hmacs);

	LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) {
		LIST_REMOVE(shared_key, next);
		sctp_free_sharedkey(shared_key);
		/*sa_ignore FREED_MEMORY*/
	}

#if defined(__APPLE__)
	inp->ip_inp.inp.inp_state = INPCB_STATE_DEAD;
	if (in_pcb_checkstate(&inp->ip_inp.inp, WNT_STOPUSING, 1) != WNT_STOPUSING) {
#ifdef INVARIANTS
		panic("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#else
		SCTP_PRINTF("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
#endif
	}
	inp->ip_inp.inp.inp_socket->so_flags |= SOF_PCBCLEARING;
#endif
	/*
	 * if we have an address list the following will free the list of
	 * ifaddr's that are set into this ep. Again macro limitations here,
	 * since the LIST_FOREACH could be a bad idea.
	 */
	LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) {
		sctp_remove_laddr(laddr);
	}

#ifdef SCTP_TRACK_FREED_ASOCS
	/* TEMP CODE */
	LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_free_list, sctp_tcblist, nasoc) {
		LIST_REMOVE(asoc, sctp_tcblist);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), asoc);
		SCTP_DECR_ASOC_COUNT();
	}
	/* *** END TEMP CODE ****/
#endif
#ifdef SCTP_MVRF
	SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
#endif
	/* Now lets see about freeing the EP hash table. */
	if (inp->sctp_tcbhash != NULL) {
		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
		inp->sctp_tcbhash = NULL;
	}
	/* Now we must put the ep memory back into the zone pool */
#if defined(__FreeBSD__)
	crfree(inp->ip_inp.inp.inp_cred);
	INP_LOCK_DESTROY(&inp->ip_inp.inp);
#endif
	SCTP_INP_LOCK_DESTROY(inp);
	SCTP_INP_READ_DESTROY(inp);
	SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
#if !defined(__APPLE__)
	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
	SCTP_DECR_EP_COUNT();
#else
	/* For Tiger, we will do this later... */
#endif
}


struct sctp_nets *
sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
{
	struct sctp_nets *net;
	/* locate the address */
	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
		if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
			return (net);
	}
	return (NULL);
}


int
sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id)
{
#ifdef __Panda__
	return (0);
#else
	struct sctp_ifa *sctp_ifa;
	sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED);
	if (sctp_ifa) {
		return (1);
	} else {
		return (0);
	}
#endif
}

/*
 * add's a remote endpoint address, done with the INIT/INIT-ACK as well as
 * when a ASCONF arrives that adds it. It will also initialize all the cwnd
 * stats of stuff.
 */
int
sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
    struct sctp_nets **netp, int set_scope, int from)
{
	/*
	 * The following is redundant to the same lines in the
	 * sctp_aloc_assoc() but is needed since others call the add
	 * address function
	 */
	struct sctp_nets *net, *netfirst;
	int addr_inscope;

	SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ",
		from);
	SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr);

	netfirst = sctp_findnet(stcb, newaddr);
	if (netfirst) {
		/*
		 * Lie and return ok, we don't want to make the association
		 * go away for this behavior. It will happen in the TCP
		 * model in a connected socket. It does not reach the hash
		 * table until after the association is built so it can't be
		 * found. Mark as reachable, since the initial creation will
		 * have been cleared and the NOT_IN_ASSOC flag will have
		 * been added... and we don't want to end up removing it
		 * back out.
		 */
		if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
			netfirst->dest_state = (SCTP_ADDR_REACHABLE |
			    SCTP_ADDR_UNCONFIRMED);
		} else {
			netfirst->dest_state = SCTP_ADDR_REACHABLE;
		}

		return (0);
	}
	addr_inscope = 1;
	switch (newaddr->sa_family) {
#ifdef INET
	case AF_INET:
	{
		struct sockaddr_in *sin;

		sin = (struct sockaddr_in *)newaddr;
		if (sin->sin_addr.s_addr == 0) {
			/* Invalid address */
			return (-1);
		}
		/* zero out the bzero area */
		memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));

		/* assure len is set */
#ifdef HAVE_SIN_LEN
		sin->sin_len = sizeof(struct sockaddr_in);
#endif
		if (set_scope) {
#ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
			stcb->asoc.scope.ipv4_local_scope = 1;
#else
			if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
				stcb->asoc.scope.ipv4_local_scope = 1;
			}
#endif				/* SCTP_DONT_DO_PRIVADDR_SCOPE */
		} else {
			/* Validate the address is in scope */
			if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
			    (stcb->asoc.scope.ipv4_local_scope == 0)) {
				addr_inscope = 0;
			}
		}
		break;
	}
#endif
#ifdef INET6
	case AF_INET6:
	{
		struct sockaddr_in6 *sin6;

		sin6 = (struct sockaddr_in6 *)newaddr;
		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
			/* Invalid address */
			return (-1);
		}
		/* assure len is set */
#ifdef HAVE_SIN6_LEN
		sin6->sin6_len = sizeof(struct sockaddr_in6);
#endif
		if (set_scope) {
			if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) {
				stcb->asoc.scope.loopback_scope = 1;
				stcb->asoc.scope.local_scope = 0;
				stcb->asoc.scope.ipv4_local_scope = 1;
				stcb->asoc.scope.site_scope = 1;
			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
				/*
				 * If the new destination is a LINK_LOCAL we
				 * must have common site scope. Don't set
				 * the local scope since we may not share
				 * all links, only loopback can do this.
				 * Links on the local network would also be
				 * on our private network for v4 too.
				 */
				stcb->asoc.scope.ipv4_local_scope = 1;
				stcb->asoc.scope.site_scope = 1;
			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
				/*
				 * If the new destination is SITE_LOCAL then
				 * we must have site scope in common.
				 */
				stcb->asoc.scope.site_scope = 1;
			}
		} else {
			/* Validate the address is in scope */
			if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
			    (stcb->asoc.scope.loopback_scope == 0)) {
				addr_inscope = 0;
			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
			    (stcb->asoc.scope.local_scope == 0)) {
				addr_inscope = 0;
			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
			    (stcb->asoc.scope.site_scope == 0)) {
				addr_inscope = 0;
			}
		}
		break;
	}
#endif
#if defined(__Userspace__)
	case AF_CONN:
	{
		struct sockaddr_conn *sconn;

		sconn = (struct sockaddr_conn *)newaddr;
		if (sconn->sconn_addr == NULL) {
			/* Invalid address */
			return (-1);
		}
#ifdef HAVE_SCONN_LEN
		sconn->sconn_len = sizeof(struct sockaddr_conn);
#endif
		break;
	}
#endif
	default:
		/* not supported family type */
		return (-1);
	}
	net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets);
	if (net == NULL) {
		return (-1);
	}
	SCTP_INCR_RADDR_COUNT();
	bzero(net, sizeof(struct sctp_nets));
	(void)SCTP_GETTIME_TIMEVAL(&net->start_time);
#ifdef HAVE_SA_LEN
	memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
#endif
	switch (newaddr->sa_family) {
#ifdef INET
	case AF_INET:
#ifndef HAVE_SA_LEN
		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in));
#endif
		((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
		break;
#endif
#ifdef INET6
	case AF_INET6:
#ifndef HAVE_SA_LEN
		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in6));
#endif
		((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
#ifndef HAVE_SA_LEN
		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_conn));
#endif
		((struct sockaddr_conn *)&net->ro._l_addr)->sconn_port = stcb->rport;
		break;
#endif
	default:
		break;
	}
	net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id);
	if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) {
		stcb->asoc.scope.loopback_scope = 1;
		stcb->asoc.scope.ipv4_local_scope = 1;
		stcb->asoc.scope.local_scope = 0;
		stcb->asoc.scope.site_scope = 1;
		addr_inscope = 1;
	}
	net->failure_threshold = stcb->asoc.def_net_failure;
	net->pf_threshold = stcb->asoc.def_net_pf_threshold;
	if (addr_inscope == 0) {
		net->dest_state = (SCTP_ADDR_REACHABLE |
		    SCTP_ADDR_OUT_OF_SCOPE);
	} else {
		if (from == SCTP_ADDR_IS_CONFIRMED)
			/* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */
			net->dest_state = SCTP_ADDR_REACHABLE;
		else
			net->dest_state = SCTP_ADDR_REACHABLE |
			    SCTP_ADDR_UNCONFIRMED;
	}
	/* We set this to 0, the timer code knows that
	 * this means its an initial value
	 */
	net->rto_needed = 1;
	net->RTO = 0;
	net->RTO_measured = 0;
	stcb->asoc.numnets++;
	net->ref_count = 1;
	net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1;
	net->port = stcb->asoc.port;
	net->dscp = stcb->asoc.default_dscp;
#ifdef INET6
	net->flowlabel = stcb->asoc.default_flowlabel;
#endif
	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) {
		net->dest_state |= SCTP_ADDR_NOHB;
	} else {
		net->dest_state &= ~SCTP_ADDR_NOHB;
	}
	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) {
		net->dest_state |= SCTP_ADDR_NO_PMTUD;
	} else {
		net->dest_state &= ~SCTP_ADDR_NO_PMTUD;
	}
	net->heart_beat_delay = stcb->asoc.heart_beat_delay;
	/* Init the timer structure */
	SCTP_OS_TIMER_INIT(&net->rxt_timer.timer);
	SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer);
	SCTP_OS_TIMER_INIT(&net->hb_timer.timer);

	/* Now generate a route for this guy */
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
	/* KAME hack: embed scopeid */
	if (newaddr->sa_family == AF_INET6) {
		struct sockaddr_in6 *sin6;

		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
		(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL);
#else
		(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL, NULL);
#endif
#elif defined(SCTP_KAME)
		(void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
#else
		(void)in6_embedscope(&sin6->sin6_addr, sin6);
#endif
#ifndef SCOPEDROUTING
		sin6->sin6_scope_id = 0;
#endif
	}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif
	SCTP_RTALLOC((sctp_route_t *)&net->ro, stcb->asoc.vrf_id);

#if defined(__Userspace__)
	net->src_addr_selected = 0;
#else
	if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) {
		/* Get source address */
		net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep,
								stcb,
								(sctp_route_t *)&net->ro,
								net,
								0,
								stcb->asoc.vrf_id);
		if (net->ro._s_addr != NULL) {
			net->src_addr_selected = 1;
			/* Now get the interface MTU */
			if (net->ro._s_addr->ifn_p != NULL) {
				net->mtu = SCTP_GATHER_MTU_FROM_INTFC(net->ro._s_addr->ifn_p);
			}
		} else {
			net->src_addr_selected = 0;
		}
		if (net->mtu > 0) {
			uint32_t rmtu;

			rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt);
			if (rmtu == 0) {
				/* Start things off to match mtu of interface please. */
				SCTP_SET_MTU_OF_ROUTE(&net->ro._l_addr.sa,
						      net->ro.ro_rt, net->mtu);
			} else {
				/* we take the route mtu over the interface, since
				 * the route may be leading out the loopback, or
				 * a different interface.
				 */
				net->mtu = rmtu;
			}
		}
	} else {
		net->src_addr_selected = 0;
	}
#endif
	if (net->mtu == 0) {
		switch (newaddr->sa_family) {
#ifdef INET
		case AF_INET:
			net->mtu = SCTP_DEFAULT_MTU;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			net->mtu = 1280;
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			net->mtu = 1280;
			break;
#endif
		default:
			break;
		}
	}
#if defined(INET) || defined(INET6)
	if (net->port) {
		net->mtu -= (uint32_t)sizeof(struct udphdr);
	}
#endif
	if (from == SCTP_ALLOC_ASOC) {
		stcb->asoc.smallest_mtu = net->mtu;
	}
	if (stcb->asoc.smallest_mtu > net->mtu) {
		stcb->asoc.smallest_mtu = net->mtu;
	}
#ifdef INET6
#ifdef SCTP_EMBEDDED_V6_SCOPE
	if (newaddr->sa_family == AF_INET6) {
		struct sockaddr_in6 *sin6;

		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
#ifdef SCTP_KAME
		(void)sa6_recoverscope(sin6);
#else
		(void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL);
#endif /* SCTP_KAME */
	}
#endif /* SCTP_EMBEDDED_V6_SCOPE */
#endif

	/* JRS - Use the congestion control given in the CC module */
	if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL)
		(*stcb->asoc.cc_functions.sctp_set_initial_cc_param)(stcb, net);

	/*
	 * CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning
	 * of assoc (2005/06/27, iyengar@cis.udel.edu)
	 */
	net->find_pseudo_cumack = 1;
	net->find_rtx_pseudo_cumack = 1;
#if defined(__FreeBSD__)
	/* Choose an initial flowid. */
	net->flowid = stcb->asoc.my_vtag ^
	              ntohs(stcb->rport) ^
	              ntohs(stcb->sctp_ep->sctp_lport);
	net->flowtype = M_HASHTYPE_OPAQUE;
#endif
	if (netp) {
		*netp = net;
	}
	netfirst = TAILQ_FIRST(&stcb->asoc.nets);
	if (net->ro.ro_rt == NULL) {
		/* Since we have no route put it at the back */
		TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
	} else if (netfirst == NULL) {
		/* We are the first one in the pool. */
		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
	} else if (netfirst->ro.ro_rt == NULL) {
		/*
		 * First one has NO route. Place this one ahead of the first
		 * one.
		 */
		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#ifndef __Panda__
	} else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) {
		/*
		 * This one has a different interface than the one at the
		 * top of the list. Place it ahead.
		 */
		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
#endif
	} else {
		/*
		 * Ok we have the same interface as the first one. Move
		 * forward until we find either a) one with a NULL route...
		 * insert ahead of that b) one with a different ifp.. insert
		 * after that. c) end of the list.. insert at the tail.
		 */
		struct sctp_nets *netlook;

		do {
			netlook = TAILQ_NEXT(netfirst, sctp_next);
			if (netlook == NULL) {
				/* End of the list */
				TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
				break;
			} else if (netlook->ro.ro_rt == NULL) {
				/* next one has NO route */
				TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
				break;
			}
#ifndef __Panda__
			else if (netlook->ro.ro_rt->rt_ifp != net->ro.ro_rt->rt_ifp)
#else
			else
#endif
			{
				TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
						   net, sctp_next);
				break;
			}
#ifndef __Panda__
			/* Shift forward */
			netfirst = netlook;
#endif
		} while (netlook != NULL);
	}

	/* got to have a primary set */
	if (stcb->asoc.primary_destination == 0) {
		stcb->asoc.primary_destination = net;
	} else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) &&
		    (net->ro.ro_rt) &&
	    ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) {
		/* No route to current primary adopt new primary */
		stcb->asoc.primary_destination = net;
	}
	/* Validate primary is first */
	net = TAILQ_FIRST(&stcb->asoc.nets);
	if ((net != stcb->asoc.primary_destination) &&
	    (stcb->asoc.primary_destination)) {
		/* first one on the list is NOT the primary
		 * sctp_cmpaddr() is much more efficient if
		 * the primary is the first on the list, make it
		 * so.
		 */
		TAILQ_REMOVE(&stcb->asoc.nets,
			     stcb->asoc.primary_destination, sctp_next);
		TAILQ_INSERT_HEAD(&stcb->asoc.nets,
				  stcb->asoc.primary_destination, sctp_next);
	}
	return (0);
}


static uint32_t
sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
	uint32_t id;
	struct sctpasochead *head;
	struct sctp_tcb *lstcb;

	SCTP_INP_WLOCK(inp);
 try_again:
	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
		/* TSNH */
		SCTP_INP_WUNLOCK(inp);
		return (0);
	}
	/*
	 * We don't allow assoc id to be one of SCTP_FUTURE_ASSOC,
	 * SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC.
	 */
	if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) {
		inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1;
	}
	id = inp->sctp_associd_counter;
	inp->sctp_associd_counter++;
	lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0);
	if (lstcb) {
		goto try_again;
	}
	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
	LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash);
	stcb->asoc.in_asocid_hash = 1;
	SCTP_INP_WUNLOCK(inp);
	return id;
}

/*
 * allocate an association and add it to the endpoint. The caller must be
 * careful to add all additional addresses once they are know right away or
 * else the assoc will be may experience a blackout scenario.
 */
struct sctp_tcb *
sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
		int *error, uint32_t override_tag, uint32_t vrf_id,
#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
		struct thread *p
#elif defined(__Windows__)
		PKTHREAD p
#else
#if defined(__Userspace__)
                /*  __Userspace__ NULL proc is going to be passed here. See sctp_lower_sosend */
#endif
		struct proc *p
#endif
)
{
	/* note the p argument is only valid in unbound sockets */

	struct sctp_tcb *stcb;
	struct sctp_association *asoc;
	struct sctpasochead *head;
	uint16_t rport;
	int err;

	/*
	 * Assumption made here: Caller has done a
	 * sctp_findassociation_ep_addr(ep, addr's); to make sure the
	 * address does not exist already.
	 */
	if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) {
		/* Hit max assoc, sorry no more */
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
		*error = ENOBUFS;
		return (NULL);
	}
	if (firstaddr == NULL) {
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		*error = EINVAL;
		return (NULL);
	}
	SCTP_INP_RLOCK(inp);
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) &&
	    ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) ||
	     (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
		/*
		 * If its in the TCP pool, its NOT allowed to create an
		 * association. The parent listener needs to call
		 * sctp_aloc_assoc.. or the one-2-many socket. If a peeled
		 * off, or connected one does this.. its an error.
		 */
		SCTP_INP_RUNLOCK(inp);
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		*error = EINVAL;
		return (NULL);
	}
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
		if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) ||
		    (inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) {
			SCTP_INP_RUNLOCK(inp);
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
			*error = EINVAL;
			return (NULL);
		}
	}
	SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:");
#ifdef SCTP_DEBUG
	if (firstaddr) {
		SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr);
		switch (firstaddr->sa_family) {
#ifdef INET
		case AF_INET:
			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
			        ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
			break;
#endif
#ifdef INET6
		case AF_INET6:
			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
			        ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port));
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
			        ntohs(((struct sockaddr_conn *)firstaddr)->sconn_port));
			break;
#endif
		default:
			break;
		}
	} else {
		SCTPDBG(SCTP_DEBUG_PCB3,"None\n");
	}
#endif				/* SCTP_DEBUG */
	switch (firstaddr->sa_family) {
#ifdef INET
	case AF_INET:
	{
		struct sockaddr_in *sin;

		sin = (struct sockaddr_in *)firstaddr;
		if ((ntohs(sin->sin_port) == 0) ||
		    (sin->sin_addr.s_addr == INADDR_ANY) ||
		    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
		    IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
			/* Invalid address */
			SCTP_INP_RUNLOCK(inp);
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
			*error = EINVAL;
			return (NULL);
		}
		rport = sin->sin_port;
		break;
	}
#endif
#ifdef INET6
	case AF_INET6:
	{
		struct sockaddr_in6 *sin6;

		sin6 = (struct sockaddr_in6 *)firstaddr;
		if ((ntohs(sin6->sin6_port) == 0) ||
		    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
		    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
			/* Invalid address */
			SCTP_INP_RUNLOCK(inp);
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
			*error = EINVAL;
			return (NULL);
		}
		rport = sin6->sin6_port;
		break;
	}
#endif
#if defined(__Userspace__)
	case AF_CONN:
	{
		struct sockaddr_conn *sconn;

		sconn = (struct sockaddr_conn *)firstaddr;
		if ((ntohs(sconn->sconn_port) == 0) ||
		    (sconn->sconn_addr == NULL)) {
			/* Invalid address */
			SCTP_INP_RUNLOCK(inp);
			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
			*error = EINVAL;
			return (NULL);
		}
		rport = sconn->sconn_port;
		break;
	}
#endif
	default:
		/* not supported family type */
		SCTP_INP_RUNLOCK(inp);
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		*error = EINVAL;
		return (NULL);
	}
	SCTP_INP_RUNLOCK(inp);
	if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
		/*
		 * If you have not performed a bind, then we need to do the
		 * ephemeral bind for you.
		 */
		if ((err = sctp_inpcb_bind(inp->sctp_socket,
		    (struct sockaddr *)NULL,
		    (struct sctp_ifa *)NULL,
#ifndef __Panda__
					   p
#else
					   (struct proc *)NULL
#endif
		    ))) {
			/* bind error, probably perm */
			*error = err;
			return (NULL);
		}
	}
	stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb);
	if (stcb == NULL) {
		/* out of memory? */
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
		*error = ENOMEM;
		return (NULL);
	}
	SCTP_INCR_ASOC_COUNT();

	bzero(stcb, sizeof(*stcb));
	asoc = &stcb->asoc;

	asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb);
	SCTP_TCB_LOCK_INIT(stcb);
	SCTP_TCB_SEND_LOCK_INIT(stcb);
	stcb->rport = rport;
	/* setup back pointer's */
	stcb->sctp_ep = inp;
	stcb->sctp_socket = inp->sctp_socket;
	if ((err = sctp_init_asoc(inp, stcb, override_tag, vrf_id))) {
		/* failed */
		SCTP_TCB_LOCK_DESTROY(stcb);
		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
		LIST_REMOVE(stcb, sctp_tcbasocidhash);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
		SCTP_DECR_ASOC_COUNT();
		*error = err;
		return (NULL);
	}
	/* and the port */
	SCTP_INP_INFO_WLOCK();
	SCTP_INP_WLOCK(inp);
	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
		/* inpcb freed while alloc going on */
		SCTP_TCB_LOCK_DESTROY(stcb);
		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
		LIST_REMOVE(stcb, sctp_tcbasocidhash);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
		SCTP_INP_WUNLOCK(inp);
		SCTP_INP_INFO_WUNLOCK();
		SCTP_DECR_ASOC_COUNT();
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		*error = EINVAL;
		return (NULL);
	}
	SCTP_TCB_LOCK(stcb);

	/* now that my_vtag is set, add it to the hash */
	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
	/* put it in the bucket in the vtag hash of assoc's for the system */
	LIST_INSERT_HEAD(head, stcb, sctp_asocs);
	SCTP_INP_INFO_WUNLOCK();

	if ((err = sctp_add_remote_addr(stcb, firstaddr, NULL, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC))) {
		/* failure.. memory error? */
		if (asoc->strmout) {
			SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
			asoc->strmout = NULL;
		}
		if (asoc->mapping_array) {
			SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
			asoc->mapping_array = NULL;
		}
		if (asoc->nr_mapping_array) {
			SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
			asoc->nr_mapping_array = NULL;
		}
		SCTP_DECR_ASOC_COUNT();
		SCTP_TCB_UNLOCK(stcb);
		SCTP_TCB_LOCK_DESTROY(stcb);
		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
		LIST_REMOVE(stcb, sctp_tcbasocidhash);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
		SCTP_INP_WUNLOCK(inp);
		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
		*error = ENOBUFS;
		return (NULL);
	}
	/* Init all the timers */
	SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->delayed_event_timer.timer);
	SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer);

	LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
	/* now file the port under the hash as well */
	if (inp->sctp_tcbhash != NULL) {
		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
		    inp->sctp_hashmark)];
		LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
	}
	SCTP_INP_WUNLOCK(inp);
	SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb);
	return (stcb);
}


void
sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net)
{
	struct sctp_association *asoc;

	asoc = &stcb->asoc;
	asoc->numnets--;
	TAILQ_REMOVE(&asoc->nets, net, sctp_next);
	if (net == asoc->primary_destination) {
		/* Reset primary */
		struct sctp_nets *lnet;

		lnet = TAILQ_FIRST(&asoc->nets);
		/* Mobility adaptation
		   Ideally, if deleted destination is the primary, it becomes
		   a fast retransmission trigger by the subsequent SET PRIMARY.
		   (by micchie)
		 */
		if (sctp_is_mobility_feature_on(stcb->sctp_ep,
		                                SCTP_MOBILITY_BASE) ||
		    sctp_is_mobility_feature_on(stcb->sctp_ep,
		                                SCTP_MOBILITY_FASTHANDOFF)) {
			SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n");
			if (asoc->deleted_primary != NULL) {
				SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n");
				goto out;
			}
			asoc->deleted_primary = net;
			atomic_add_int(&net->ref_count, 1);
			memset(&net->lastsa, 0, sizeof(net->lastsa));
			memset(&net->lastsv, 0, sizeof(net->lastsv));
			sctp_mobility_feature_on(stcb->sctp_ep,
						 SCTP_MOBILITY_PRIM_DELETED);
			sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED,
					 stcb->sctp_ep, stcb, NULL);
		}
out:
		/* Try to find a confirmed primary */
		asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0);
	}
	if (net == asoc->last_data_chunk_from) {
		/* Reset primary */
		asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets);
	}
	if (net == asoc->last_control_chunk_from) {
		/* Clear net */
		asoc->last_control_chunk_from = NULL;
	}
	if (net == stcb->asoc.alternate) {
		sctp_free_remote_addr(stcb->asoc.alternate);
		stcb->asoc.alternate = NULL;
	}
	sctp_free_remote_addr(net);
}

/*
 * remove a remote endpoint address from an association, it will fail if the
 * address does not exist.
 */
int
sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
{
	/*
	 * Here we need to remove a remote address. This is quite simple, we
	 * first find it in the list of address for the association
	 * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE
	 * on that item. Note we do not allow it to be removed if there are
	 * no other addresses.
	 */
	struct sctp_association *asoc;
	struct sctp_nets *net, *nnet;

	asoc = &stcb->asoc;

	/* locate the address */
	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
		if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
			continue;
		}
		if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
		    remaddr)) {
			/* we found the guy */
			if (asoc->numnets < 2) {
				/* Must have at LEAST two remote addresses */
				return (-1);
			} else {
				sctp_remove_net(stcb, net);
				return (0);
			}
		}
	}
	/* not found. */
	return (-2);
}

void
sctp_delete_from_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
	struct sctpvtaghead *chain;
	struct sctp_tagblock *twait_block;
	int found = 0;
	int i;

	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
		  if ((twait_block->vtag_block[i].v_tag == tag) &&
		      (twait_block->vtag_block[i].lport == lport) &&
		      (twait_block->vtag_block[i].rport == rport)) {
				twait_block->vtag_block[i].tv_sec_at_expire = 0;
				twait_block->vtag_block[i].v_tag = 0;
				twait_block->vtag_block[i].lport = 0;
				twait_block->vtag_block[i].rport = 0;
				found = 1;
				break;
			}
		}
		if (found)
			break;
	}
}

int
sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
{
	struct sctpvtaghead *chain;
	struct sctp_tagblock *twait_block;
	int found = 0;
	int i;

	SCTP_INP_INFO_WLOCK();
	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
			if ((twait_block->vtag_block[i].v_tag == tag)  &&
			    (twait_block->vtag_block[i].lport == lport)  &&
			    (twait_block->vtag_block[i].rport == rport)) {
				found = 1;
				break;
			}
		}
		if (found)
			break;
	}
	SCTP_INP_INFO_WUNLOCK();
	return (found);
}


void
sctp_add_vtag_to_timewait(uint32_t tag, uint32_t time, uint16_t lport, uint16_t rport)
{
	struct sctpvtaghead *chain;
	struct sctp_tagblock *twait_block;
	struct timeval now;
	int set, i;

	if (time == 0) {
		/* Its disabled */
		return;
	}
	(void)SCTP_GETTIME_TIMEVAL(&now);
	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
	set = 0;
	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
		/* Block(s) present, lets find space, and expire on the fly */
		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
			if ((twait_block->vtag_block[i].v_tag == 0) &&
			    !set) {
				twait_block->vtag_block[i].tv_sec_at_expire =
					now.tv_sec + time;
				twait_block->vtag_block[i].v_tag = tag;
				twait_block->vtag_block[i].lport = lport;
				twait_block->vtag_block[i].rport = rport;
				set = 1;
			} else if ((twait_block->vtag_block[i].v_tag) &&
				    ((long)twait_block->vtag_block[i].tv_sec_at_expire < now.tv_sec)) {
				/* Audit expires this guy */
				twait_block->vtag_block[i].tv_sec_at_expire = 0;
				twait_block->vtag_block[i].v_tag = 0;
				twait_block->vtag_block[i].lport = 0;
				twait_block->vtag_block[i].rport = 0;
				if (set == 0) {
					/* Reuse it for my new tag */
					twait_block->vtag_block[i].tv_sec_at_expire = now.tv_sec + time;
					twait_block->vtag_block[i].v_tag = tag;
					twait_block->vtag_block[i].lport = lport;
					twait_block->vtag_block[i].rport = rport;
					set = 1;
				}
			}
		}
		if (set) {
			/*
			 * We only do up to the block where we can
			 * place our tag for audits
			 */
			break;
		}
	}
	/* Need to add a new block to chain */
	if (!set) {
		SCTP_MALLOC(twait_block, struct sctp_tagblock *,
		    sizeof(struct sctp_tagblock), SCTP_M_TIMW);
		if (twait_block == NULL) {
#ifdef INVARIANTS
			panic("Can not alloc tagblock");
#endif
			return;
		}
		memset(twait_block, 0, sizeof(struct sctp_tagblock));
		LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
		twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + time;
		twait_block->vtag_block[0].v_tag = tag;
		twait_block->vtag_block[0].lport = lport;
		twait_block->vtag_block[0].rport = rport;
	}
}


#ifdef __Panda__
void panda_wakeup_socket(struct socket *so);
#endif

/*-
 * Free the association after un-hashing the remote port. This
 * function ALWAYS returns holding NO LOCK on the stcb. It DOES
 * expect that the input to this function IS a locked TCB.
 * It will return 0, if it did NOT destroy the association (instead
 * it unlocks it. It will return NON-zero if it either destroyed the
 * association OR the association is already destroyed.
 */
int
sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location)
{
	int i;
	struct sctp_association *asoc;
	struct sctp_nets *net, *nnet;
	struct sctp_laddr *laddr, *naddr;
	struct sctp_tmit_chunk *chk, *nchk;
	struct sctp_asconf_addr *aparam, *naparam;
	struct sctp_asconf_ack *aack, *naack;
	struct sctp_stream_reset_list *strrst, *nstrrst;
	struct sctp_queued_to_read *sq, *nsq;
	struct sctp_stream_queue_pending *sp, *nsp;
	sctp_sharedkey_t *shared_key, *nshared_key;
	struct socket *so;

	/* first, lets purge the entry from the hash table. */
#if defined(__APPLE__)
	sctp_lock_assert(SCTP_INP_SO(inp));
#endif

#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, stcb, 6);
#endif
	if (stcb->asoc.state == 0) {
#ifdef SCTP_LOG_CLOSING
		sctp_log_closing(inp, NULL, 7);
#endif
		/* there is no asoc, really TSNH :-0 */
		return (1);
	}
	if (stcb->asoc.alternate) {
		sctp_free_remote_addr(stcb->asoc.alternate);
		stcb->asoc.alternate = NULL;
	}
#if !defined(__APPLE__) /* TEMP: moved to below */
        /* TEMP CODE */
	if (stcb->freed_from_where == 0) {
		/* Only record the first place free happened from */
		stcb->freed_from_where = from_location;
	}
        /* TEMP CODE */
#endif

	asoc = &stcb->asoc;
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
		/* nothing around */
		so = NULL;
	else
		so = inp->sctp_socket;

	/*
	 * We used timer based freeing if a reader or writer is in the way.
	 * So we first check if we are actually being called from a timer,
	 * if so we abort early if a reader or writer is still in the way.
	 */
	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) &&
	    (from_inpcbfree == SCTP_NORMAL_PROC)) {
		/*
		 * is it the timer driving us? if so are the reader/writers
		 * gone?
		 */
		if (stcb->asoc.refcnt) {
			/* nope, reader or writer in the way */
			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
			/* no asoc destroyed */
			SCTP_TCB_UNLOCK(stcb);
#ifdef SCTP_LOG_CLOSING
			sctp_log_closing(inp, stcb, 8);
#endif
			return (0);
		}
	}
	/* now clean up any other timers */
	(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
	asoc->dack_timer.self = NULL;
	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
	/*-
	 * For stream reset we don't blast this unless
	 * it is a str-reset timer, it might be the
	 * free-asoc timer which we DON'T want to
	 * disturb.
	 */
	if (asoc->strreset_timer.type == SCTP_TIMER_TYPE_STRRESET)
		asoc->strreset_timer.self = NULL;
	(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
	asoc->asconf_timer.self = NULL;
	(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
	asoc->autoclose_timer.self = NULL;
	(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
	asoc->shut_guard_timer.self = NULL;
	(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
	asoc->delayed_event_timer.self = NULL;
	/* Mobility adaptation */
	(void)SCTP_OS_TIMER_STOP(&asoc->delete_prim_timer.timer);
	asoc->delete_prim_timer.self = NULL;
	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
		(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
		net->rxt_timer.self = NULL;
		(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
		net->pmtu_timer.self = NULL;
		(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
		net->hb_timer.self = NULL;
	}
	/* Now the read queue needs to be cleaned up (only once) */
	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) {
		stcb->asoc.state |= SCTP_STATE_ABOUT_TO_BE_FREED;
		SCTP_INP_READ_LOCK(inp);
		TAILQ_FOREACH(sq, &inp->read_queue, next) {
			if (sq->stcb == stcb) {
				sq->do_not_ref_stcb = 1;
				sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
				/* If there is no end, there never
				 * will be now.
				 */
				if (sq->end_added == 0) {
					/* Held for PD-API clear that. */
					sq->pdapi_aborted = 1;
					sq->held_length = 0;
					if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) {
						/*
						 * Need to add a PD-API aborted indication.
						 * Setting the control_pdapi assures that it will
						 * be added right after this msg.
						 */
						uint32_t strseq;
						stcb->asoc.control_pdapi = sq;
						strseq = (sq->sinfo_stream << 16) | sq->sinfo_ssn;
						sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
						                stcb,
						                SCTP_PARTIAL_DELIVERY_ABORTED,
						                (void *)&strseq,
						                SCTP_SO_LOCKED);
						stcb->asoc.control_pdapi = NULL;
					}
				}
				/* Add an end to wake them */
				sq->end_added = 1;
			}
		}
		SCTP_INP_READ_UNLOCK(inp);
		if (stcb->block_entry) {
			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET);
			stcb->block_entry->error = ECONNRESET;
			stcb->block_entry = NULL;
		}
	}
	if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) {
		/* Someone holds a reference OR the socket is unaccepted yet.
		*/
		if ((stcb->asoc.refcnt)  ||
		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
			stcb->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
		}
		SCTP_TCB_UNLOCK(stcb);
		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
			/* nothing around */
			so = NULL;
		if (so) {
			/* Wake any reader/writers */
			sctp_sorwakeup(inp, so);
			sctp_sowwakeup(inp, so);
		}

#ifdef SCTP_LOG_CLOSING
		sctp_log_closing(inp, stcb, 9);
#endif
		/* no asoc destroyed */
		return (0);
	}
#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, stcb, 10);
#endif
	/* When I reach here, no others want
	 * to kill the assoc yet.. and I own
	 * the lock. Now its possible an abort
	 * comes in when I do the lock exchange
	 * below to grab all the locks to do
	 * the final take out. to prevent this
	 * we increment the count, which will
	 * start a timer and blow out above thus
	 * assuring us that we hold exclusive
	 * killing of the asoc. Note that
	 * after getting back the TCB lock
	 * we will go ahead and increment the
	 * counter back up and stop any timer
	 * a passing stranger may have started :-S
	 */
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		atomic_add_int(&stcb->asoc.refcnt, 1);

		SCTP_TCB_UNLOCK(stcb);
		SCTP_INP_INFO_WLOCK();
		SCTP_INP_WLOCK(inp);
		SCTP_TCB_LOCK(stcb);
	}
	/* Double check the GONE flag */
	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
		/* nothing around */
		so = NULL;

	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
		/*
		 * For TCP type we need special handling when we are
		 * connected. We also include the peel'ed off ones to.
		 */
		if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
			inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
			inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED;
			if (so) {
				SOCK_LOCK(so);
				if (so->so_rcv.sb_cc == 0) {
					so->so_state &= ~(SS_ISCONNECTING |
							  SS_ISDISCONNECTING |
							  SS_ISCONFIRMING |
							  SS_ISCONNECTED);
				}
#if defined(__APPLE__)
				socantrcvmore(so);
#else
				socantrcvmore_locked(so);
#endif
				sctp_sowwakeup(inp, so);
				sctp_sorwakeup(inp, so);
				SCTP_SOWAKEUP(so);
			}
		}
	}

	/* Make it invalid too, that way if its
	 * about to run it will abort and return.
	 */
	/* re-increment the lock */
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		atomic_add_int(&stcb->asoc.refcnt, -1);
	}
	if (stcb->asoc.refcnt) {
		stcb->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
		sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
		if (from_inpcbfree == SCTP_NORMAL_PROC) {
			SCTP_INP_INFO_WUNLOCK();
			SCTP_INP_WUNLOCK(inp);
		}
		SCTP_TCB_UNLOCK(stcb);
		return (0);
	}
	asoc->state = 0;
	if (inp->sctp_tcbhash) {
		LIST_REMOVE(stcb, sctp_tcbhash);
	}
	if (stcb->asoc.in_asocid_hash) {
		LIST_REMOVE(stcb, sctp_tcbasocidhash);
	}
	/* Now lets remove it from the list of ALL associations in the EP */
	LIST_REMOVE(stcb, sctp_tcblist);
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		SCTP_INP_INCR_REF(inp);
		SCTP_INP_WUNLOCK(inp);
	}
	/* pull from vtag hash */
	LIST_REMOVE(stcb, sctp_asocs);
	sctp_add_vtag_to_timewait(asoc->my_vtag, SCTP_BASE_SYSCTL(sctp_vtag_time_wait),
				  inp->sctp_lport, stcb->rport);

	/* Now restop the timers to be sure
	 * this is paranoia at is finest!
	 */
	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
	(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
		(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
		(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
		(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
	}

	asoc->strreset_timer.type = SCTP_TIMER_TYPE_NONE;
	/*
	 * The chunk lists and such SHOULD be empty but we check them just
	 * in case.
	 */
	/* anything on the wheel needs to be removed */
	for (i = 0; i < asoc->streamoutcnt; i++) {
		struct sctp_stream_out *outs;

		outs = &asoc->strmout[i];
		/* now clean up any chunks here */
		TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
			TAILQ_REMOVE(&outs->outqueue, sp, next);
			sctp_free_spbufspace(stcb, asoc, sp);
			if (sp->data) {
				if (so) {
					/* Still an open socket - report */
					sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
					                0, (void *)sp, SCTP_SO_LOCKED);
				}
				if (sp->data) {
					sctp_m_freem(sp->data);
					sp->data = NULL;
					sp->tail_mbuf = NULL;
					sp->length = 0;
				}
			}
			if (sp->net) {
				sctp_free_remote_addr(sp->net);
				sp->net = NULL;
			}
			sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
		}
	}
	/*sa_ignore FREED_MEMORY*/
	TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) {
		TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp);
		SCTP_FREE(strrst, SCTP_M_STRESET);
	}
	TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) {
		TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next);
		if (sq->data) {
			sctp_m_freem(sq->data);
			sq->data = NULL;
		}
		sctp_free_remote_addr(sq->whoFrom);
		sq->whoFrom = NULL;
		sq->stcb = NULL;
		/* Free the ctl entry */
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), sq);
		SCTP_DECR_READQ_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}
	TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) {
		TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next);
		if (chk->data) {
			sctp_m_freem(chk->data);
			chk->data = NULL;
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1);
		asoc->free_chunk_cnt--;
		/*sa_ignore FREED_MEMORY*/
	}
	/* pending send queue SHOULD be empty */
	TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
		if (asoc->strmout[chk->rec.data.stream_number].chunks_on_queues > 0) {
			asoc->strmout[chk->rec.data.stream_number].chunks_on_queues--;
#ifdef INVARIANTS
		} else {
			panic("No chunks on the queues for sid %u.", chk->rec.data.stream_number);
#endif
		}
		TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
		if (chk->data) {
			if (so) {
				/* Still a socket? */
				sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
				                0, chk, SCTP_SO_LOCKED);
			}
			if (chk->data) {
				sctp_m_freem(chk->data);
				chk->data = NULL;
			}
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		if (chk->whoTo) {
			sctp_free_remote_addr(chk->whoTo);
			chk->whoTo = NULL;
		}
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}
	/* sent queue SHOULD be empty */
	TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
		if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
			if (asoc->strmout[chk->rec.data.stream_number].chunks_on_queues > 0) {
				asoc->strmout[chk->rec.data.stream_number].chunks_on_queues--;
#ifdef INVARIANTS
			} else {
				panic("No chunks on the queues for sid %u.", chk->rec.data.stream_number);
#endif
			}
		}
		TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
		if (chk->data) {
			if (so) {
				/* Still a socket? */
				sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
				                0, chk, SCTP_SO_LOCKED);
			}
			if (chk->data) {
				sctp_m_freem(chk->data);
				chk->data = NULL;
			}
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		sctp_free_remote_addr(chk->whoTo);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}
#ifdef INVARIANTS
	for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
		if (stcb->asoc.strmout[i].chunks_on_queues > 0) {
			panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i);
		}
	}
#endif
	/* control queue MAY not be empty */
	TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
		TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
		if (chk->data) {
			sctp_m_freem(chk->data);
			chk->data = NULL;
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		sctp_free_remote_addr(chk->whoTo);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}
	/* ASCONF queue MAY not be empty */
	TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
		TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
		if (chk->data) {
			sctp_m_freem(chk->data);
			chk->data = NULL;
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		sctp_free_remote_addr(chk->whoTo);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}
	TAILQ_FOREACH_SAFE(chk, &asoc->reasmqueue, sctp_next, nchk) {
		TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
		if (chk->data) {
			sctp_m_freem(chk->data);
			chk->data = NULL;
		}
		if (chk->holds_key_ref)
			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
		sctp_free_remote_addr(chk->whoTo);
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
		SCTP_DECR_CHK_COUNT();
		/*sa_ignore FREED_MEMORY*/
	}

	if (asoc->mapping_array) {
		SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
		asoc->mapping_array = NULL;
	}
	if (asoc->nr_mapping_array) {
		SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
		asoc->nr_mapping_array = NULL;
	}
	/* the stream outs */
	if (asoc->strmout) {
		SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
		asoc->strmout = NULL;
	}
	asoc->strm_realoutsize = asoc->streamoutcnt = 0;
	if (asoc->strmin) {
		struct sctp_queued_to_read *ctl, *nctl;

		for (i = 0; i < asoc->streamincnt; i++) {
			TAILQ_FOREACH_SAFE(ctl, &asoc->strmin[i].inqueue, next, nctl) {
				TAILQ_REMOVE(&asoc->strmin[i].inqueue, ctl, next);
				sctp_free_remote_addr(ctl->whoFrom);
				if (ctl->data) {
					sctp_m_freem(ctl->data);
					ctl->data = NULL;
				}
				/*
				 * We don't free the address here
				 * since all the net's were freed
				 * above.
				 */
				SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), ctl);
				SCTP_DECR_READQ_COUNT();
			}
		}
		SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
		asoc->strmin = NULL;
	}
	asoc->streamincnt = 0;
	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
#ifdef INVARIANTS
		if (SCTP_BASE_INFO(ipi_count_raddr) == 0) {
			panic("no net's left alloc'ed, or list points to itself");
		}
#endif
		TAILQ_REMOVE(&asoc->nets, net, sctp_next);
		sctp_free_remote_addr(net);
	}
	LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) {
		/*sa_ignore FREED_MEMORY*/
		sctp_remove_laddr(laddr);
	}

	/* pending asconf (address) parameters */
	TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) {
		/*sa_ignore FREED_MEMORY*/
		TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
		SCTP_FREE(aparam,SCTP_M_ASC_ADDR);
	}
	TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) {
		/*sa_ignore FREED_MEMORY*/
		TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next);
		if (aack->data != NULL) {
			sctp_m_freem(aack->data);
		}
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack);
	}
	/* clean up auth stuff */
	if (asoc->local_hmacs)
		sctp_free_hmaclist(asoc->local_hmacs);
	if (asoc->peer_hmacs)
		sctp_free_hmaclist(asoc->peer_hmacs);

	if (asoc->local_auth_chunks)
		sctp_free_chunklist(asoc->local_auth_chunks);
	if (asoc->peer_auth_chunks)
		sctp_free_chunklist(asoc->peer_auth_chunks);

	sctp_free_authinfo(&asoc->authinfo);

	LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) {
		LIST_REMOVE(shared_key, next);
		sctp_free_sharedkey(shared_key);
		/*sa_ignore FREED_MEMORY*/
	}

	/* Insert new items here :> */

	/* Get rid of LOCK */
	SCTP_TCB_UNLOCK(stcb);
	SCTP_TCB_LOCK_DESTROY(stcb);
	SCTP_TCB_SEND_LOCK_DESTROY(stcb);
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		SCTP_INP_INFO_WUNLOCK();
		SCTP_INP_RLOCK(inp);
	}
#if defined(__APPLE__) /* TEMP CODE */
	stcb->freed_from_where = from_location;
#endif
#ifdef SCTP_TRACK_FREED_ASOCS
	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
		/* now clean up the tasoc itself */
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
		SCTP_DECR_ASOC_COUNT();
	} else {
		LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist);
	}
#else
	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
	SCTP_DECR_ASOC_COUNT();
#endif
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
			/* If its NOT the inp_free calling us AND
			 * sctp_close as been called, we
			 * call back...
			 */
			SCTP_INP_RUNLOCK(inp);
			/* This will start the kill timer (if we are
			 * the last one) since we hold an increment yet. But
			 * this is the only safe way to do this
			 * since otherwise if the socket closes
			 * at the same time we are here we might
			 * collide in the cleanup.
			 */
			sctp_inpcb_free(inp,
					SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE,
					SCTP_CALLED_DIRECTLY_NOCMPSET);
			SCTP_INP_DECR_REF(inp);
			goto out_of;
		} else {
			/* The socket is still open. */
			SCTP_INP_DECR_REF(inp);
		}
	}
	if (from_inpcbfree == SCTP_NORMAL_PROC) {
		SCTP_INP_RUNLOCK(inp);
	}
 out_of:
	/* destroyed the asoc */
#ifdef SCTP_LOG_CLOSING
	sctp_log_closing(inp, NULL, 11);
#endif
	return (1);
}



/*
 * determine if a destination is "reachable" based upon the addresses bound
 * to the current endpoint (e.g. only v4 or v6 currently bound)
 */
/*
 * FIX: if we allow assoc-level bindx(), then this needs to be fixed to use
 * assoc level v4/v6 flags, as the assoc *may* not have the same address
 * types bound as its endpoint
 */
int
sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
{
	struct sctp_inpcb *inp;
	int answer;

	/*
	 * No locks here, the TCB, in all cases is already locked and an
	 * assoc is up. There is either a INP lock by the caller applied (in
	 * asconf case when deleting an address) or NOT in the HB case,
	 * however if HB then the INP increment is up and the INP will not
	 * be removed (on top of the fact that we have a TCB lock). So we
	 * only want to read the sctp_flags, which is either bound-all or
	 * not.. no protection needed since once an assoc is up you can't be
	 * changing your binding.
	 */
	inp = stcb->sctp_ep;
	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
		/* if bound all, destination is not restricted */
		/*
		 * RRS: Question during lock work: Is this correct? If you
		 * are bound-all you still might need to obey the V4--V6
		 * flags??? IMO this bound-all stuff needs to be removed!
		 */
		return (1);
	}
	/* NOTE: all "scope" checks are done when local addresses are added */
	switch (destaddr->sa_family) {
#ifdef INET6
	case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
		answer = inp->inp_vflag & INP_IPV6;
#else
		answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
#endif
		break;
#endif
#ifdef INET
	case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
		answer = inp->inp_vflag & INP_IPV4;
#else
		answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
#endif
		break;
#endif
#if defined(__Userspace__)
	case AF_CONN:
		answer = inp->ip_inp.inp.inp_vflag & INP_CONN;
		break;
#endif
	default:
		/* invalid family, so it's unreachable */
		answer = 0;
		break;
	}
	return (answer);
}

/*
 * update the inp_vflags on an endpoint
 */
static void
sctp_update_ep_vflag(struct sctp_inpcb *inp)
{
	struct sctp_laddr *laddr;

	/* first clear the flag */
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
	inp->inp_vflag = 0;
#else
	inp->ip_inp.inp.inp_vflag = 0;
#endif
	/* set the flag based on addresses on the ep list */
	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
		if (laddr->ifa == NULL) {
			SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
				__FUNCTION__);
			continue;
		}

		if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
			continue;
		}
		switch (laddr->ifa->address.sa.sa_family) {
#ifdef INET6
		case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
			inp->inp_vflag |= INP_IPV6;
#else
			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
			break;
#endif
#ifdef INET
		case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
			inp->inp_vflag |= INP_IPV4;
#else
			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			inp->ip_inp.inp.inp_vflag |= INP_CONN;
			break;
#endif
		default:
			break;
		}
	}
}

/*
 * Add the address to the endpoint local address list There is nothing to be
 * done if we are bound to all addresses
 */
void
sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action)
{
	struct sctp_laddr *laddr;
	int fnd, error = 0;

	fnd = 0;

	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
		/* You are already bound to all. You have it already */
		return;
	}
#ifdef INET6
	if (ifa->address.sa.sa_family == AF_INET6) {
		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
			/* Can't bind a non-useable addr. */
			return;
		}
	}
#endif
	/* first, is it already present? */
	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
		if (laddr->ifa == ifa) {
			fnd = 1;
			break;
		}
	}

	if (fnd == 0) {
		/* Not in the ep list */
		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action);
		if (error != 0)
			return;
		inp->laddr_count++;
		/* update inp_vflag flags */
		switch (ifa->address.sa.sa_family) {
#ifdef INET6
		case AF_INET6:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
			inp->inp_vflag |= INP_IPV6;
#else
			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
#endif
			break;
#endif
#ifdef INET
		case AF_INET:
#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
			inp->inp_vflag |= INP_IPV4;
#else
			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
#endif
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			inp->ip_inp.inp.inp_vflag |= INP_CONN;
			break;
#endif
		default:
			break;
		}
	}
	return;
}


/*
 * select a new (hopefully reachable) destination net (should only be used
 * when we deleted an ep addr that is the only usable source address to reach
 * the destination net)
 */
static void
sctp_select_primary_destination(struct sctp_tcb *stcb)
{
	struct sctp_nets *net;

	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
		/* for now, we'll just pick the first reachable one we find */
		if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
			continue;
		if (sctp_destination_is_reachable(stcb,
		    (struct sockaddr *)&net->ro._l_addr)) {
			/* found a reachable destination */
			stcb->asoc.primary_destination = net;
		}
	}
	/* I can't there from here! ...we're gonna die shortly... */
}


/*
 * Delete the address from the endpoint local address list There is nothing
 * to be done if we are bound to all addresses
 */
void
sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
{
	struct sctp_laddr *laddr;
	int fnd;

	fnd = 0;
	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
		/* You are already bound to all. You have it already */
		return;
	}
	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
		if (laddr->ifa == ifa) {
			fnd = 1;
			break;
		}
	}
	if (fnd && (inp->laddr_count < 2)) {
		/* can't delete unless there are at LEAST 2 addresses */
		return;
	}
	if (fnd) {
		/*
		 * clean up any use of this address go through our
		 * associations and clear any last_used_address that match
		 * this one for each assoc, see if a new primary_destination
		 * is needed
		 */
		struct sctp_tcb *stcb;

		/* clean up "next_addr_touse" */
		if (inp->next_addr_touse == laddr)
			/* delete this address */
			inp->next_addr_touse = NULL;

		/* clean up "last_used_address" */
		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
			struct sctp_nets *net;
			SCTP_TCB_LOCK(stcb);
			if (stcb->asoc.last_used_address == laddr)
				/* delete this address */
				stcb->asoc.last_used_address = NULL;
			/* Now spin through all the nets and purge any ref to laddr */
			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
				if (net->ro._s_addr &&
				    (net->ro._s_addr->ifa == laddr->ifa)) {
					/* Yep, purge src address selected */
					sctp_rtentry_t *rt;

					/* delete this address if cached */
					rt = net->ro.ro_rt;
					if (rt != NULL) {
						RTFREE(rt);
						net->ro.ro_rt = NULL;
					}
					sctp_free_ifa(net->ro._s_addr);
					net->ro._s_addr = NULL;
					net->src_addr_selected = 0;
				}
			}
			SCTP_TCB_UNLOCK(stcb);
		}		/* for each tcb */
		/* remove it from the ep list */
		sctp_remove_laddr(laddr);
		inp->laddr_count--;
		/* update inp_vflag flags */
		sctp_update_ep_vflag(inp);
	}
	return;
}

/*
 * Add the address to the TCB local address restricted list.
 * This is a "pending" address list (eg. addresses waiting for an
 * ASCONF-ACK response) and cannot be used as a valid source address.
 */
void
sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
	struct sctp_laddr *laddr;
	struct sctpladdr *list;

	/*
	 * Assumes TCB is locked.. and possibly the INP. May need to
	 * confirm/fix that if we need it and is not the case.
	 */
	list = &stcb->asoc.sctp_restricted_addrs;

#ifdef INET6
	if (ifa->address.sa.sa_family == AF_INET6) {
		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
			/* Can't bind a non-existent addr. */
			return;
		}
	}
#endif
	/* does the address already exist? */
	LIST_FOREACH(laddr, list, sctp_nxt_addr) {
		if (laddr->ifa == ifa) {
			return;
		}
	}

	/* add to the list */
	(void)sctp_insert_laddr(list, ifa, 0);
	return;
}

/*
 * insert an laddr entry with the given ifa for the desired list
 */
int
sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act)
{
	struct sctp_laddr *laddr;

	laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
	if (laddr == NULL) {
		/* out of memory? */
		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
		return (EINVAL);
	}
	SCTP_INCR_LADDR_COUNT();
	bzero(laddr, sizeof(*laddr));
	(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
	laddr->ifa = ifa;
	laddr->action = act;
	atomic_add_int(&ifa->refcount, 1);
	/* insert it */
	LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);

	return (0);
}

/*
 * Remove an laddr entry from the local address list (on an assoc)
 */
void
sctp_remove_laddr(struct sctp_laddr *laddr)
{

	/* remove from the list */
	LIST_REMOVE(laddr, sctp_nxt_addr);
	sctp_free_ifa(laddr->ifa);
	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr);
	SCTP_DECR_LADDR_COUNT();
}

/*
 * Remove a local address from the TCB local address restricted list
 */
void
sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
{
	struct sctp_inpcb *inp;
	struct sctp_laddr *laddr;

	/*
	 * This is called by asconf work. It is assumed that a) The TCB is
	 * locked and b) The INP is locked. This is true in as much as I can
	 * trace through the entry asconf code where I did these locks.
	 * Again, the ASCONF code is a bit different in that it does lock
	 * the INP during its work often times. This must be since we don't
	 * want other proc's looking up things while what they are looking
	 * up is changing :-D
	 */

	inp = stcb->sctp_ep;
	/* if subset bound and don't allow ASCONF's, can't delete last */
	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
	    sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) {
		if (stcb->sctp_ep->laddr_count < 2) {
			/* can't delete last address */
			return;
		}
	}
	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
		/* remove the address if it exists */
		if (laddr->ifa == NULL)
			continue;
		if (laddr->ifa == ifa) {
			sctp_remove_laddr(laddr);
			return;
		}
	}

	/* address not found! */
	return;
}

#if defined(__FreeBSD__)
/*
 * Temporarily remove for __APPLE__ until we use the Tiger equivalents
 */
/* sysctl */
static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
#endif				/* FreeBSD || APPLE */



#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
struct sctp_mcore_ctrl *sctp_mcore_workers = NULL;
int *sctp_cpuarry = NULL;
void
sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use)
{
	/* Queue a packet to a processor for the specified core */
	struct sctp_mcore_queue *qent;
	struct sctp_mcore_ctrl *wkq;
	int need_wake = 0;
	if (sctp_mcore_workers == NULL) {
		/* Something went way bad during setup */
		sctp_input_with_port(m, off, 0);
		return;
	}
	SCTP_MALLOC(qent, struct sctp_mcore_queue *,
		    (sizeof(struct sctp_mcore_queue)),
		    SCTP_M_MCORE);
	if (qent == NULL) {
		/* This is trouble  */
		sctp_input_with_port(m, off, 0);
		return;
	}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	qent->vn = curvnet;
#endif
	qent->m = m;
	qent->off = off;
	qent->v6 = 0;
	wkq = &sctp_mcore_workers[cpu_to_use];
	SCTP_MCORE_QLOCK(wkq);

	TAILQ_INSERT_TAIL(&wkq->que, qent, next);
	if (wkq->running == 0) {
		need_wake = 1;
	}
	SCTP_MCORE_QUNLOCK(wkq);
	if (need_wake) {
		wakeup(&wkq->running);
	}
}

static void
sctp_mcore_thread(void *arg)
{

	struct sctp_mcore_ctrl *wkq;
	struct sctp_mcore_queue *qent;

	wkq = (struct sctp_mcore_ctrl *)arg;
	struct mbuf *m;
	int off, v6;

	/* Wait for first tickle */
	SCTP_MCORE_LOCK(wkq);
	wkq->running = 0;
	msleep(&wkq->running,
	       &wkq->core_mtx,
	       0, "wait for pkt", 0);
	SCTP_MCORE_UNLOCK(wkq);

	/* Bind to our cpu */
	thread_lock(curthread);
	sched_bind(curthread, wkq->cpuid);
	thread_unlock(curthread);

	/* Now lets start working */
	SCTP_MCORE_LOCK(wkq);
	/* Now grab lock and go */
	for (;;) {
		SCTP_MCORE_QLOCK(wkq);
	skip_sleep:
		wkq->running = 1;
		qent = TAILQ_FIRST(&wkq->que);
		if (qent) {
			TAILQ_REMOVE(&wkq->que, qent, next);
			SCTP_MCORE_QUNLOCK(wkq);
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
			CURVNET_SET(qent->vn);
#endif
			m = qent->m;
			off = qent->off;
			v6 = qent->v6;
			SCTP_FREE(qent, SCTP_M_MCORE);
			if (v6 == 0) {
				sctp_input_with_port(m, off, 0);
			} else {
				SCTP_PRINTF("V6 not yet supported\n");
				sctp_m_freem(m);
			}
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
			CURVNET_RESTORE();
#endif
			SCTP_MCORE_QLOCK(wkq);
		}
		wkq->running = 0;
		if (!TAILQ_EMPTY(&wkq->que)) {
			goto skip_sleep;
		}
		SCTP_MCORE_QUNLOCK(wkq);
		msleep(&wkq->running,
		       &wkq->core_mtx,
		       0, "wait for pkt", 0);
	}
}

static void
sctp_startup_mcore_threads(void)
{
	int i, cpu;

	if (mp_ncpus == 1)
		return;

	if (sctp_mcore_workers != NULL) {
		/* Already been here in some previous
		 * vnet?
		 */
		return;
	}
	SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *,
		    ((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl)),
		    SCTP_M_MCORE);
	if (sctp_mcore_workers == NULL) {
		/* TSNH I hope */
		return;
	}
	memset(sctp_mcore_workers, 0 , ((mp_maxid+1) *
					sizeof(struct sctp_mcore_ctrl)));
	/* Init the structures */
	for (i = 0; i<=mp_maxid; i++) {
		TAILQ_INIT(&sctp_mcore_workers[i].que);
		SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]);
		SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]);
		sctp_mcore_workers[i].cpuid = i;
	}
	if (sctp_cpuarry == NULL) {
		SCTP_MALLOC(sctp_cpuarry, int *,
			    (mp_ncpus * sizeof(int)),
			    SCTP_M_MCORE);
		i = 0;
		CPU_FOREACH(cpu) {
			sctp_cpuarry[i] = cpu;
			i++;
		}
	}

	/* Now start them all */
	CPU_FOREACH(cpu) {
#if __FreeBSD_version <= 701000
		(void)kthread_create(sctp_mcore_thread,
				     (void *)&sctp_mcore_workers[cpu],
				     &sctp_mcore_workers[cpu].thread_proc,
				     RFPROC,
				     SCTP_KTHREAD_PAGES,
				     SCTP_MCORE_NAME);

#else
		(void)kproc_create(sctp_mcore_thread,
				   (void *)&sctp_mcore_workers[cpu],
				   &sctp_mcore_workers[cpu].thread_proc,
				   RFPROC,
				   SCTP_KTHREAD_PAGES,
				   SCTP_MCORE_NAME);
#endif

	}
}
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1200000
static struct mbuf *
sctp_netisr_hdlr(struct mbuf *m, uintptr_t source)
{
	struct ip *ip;
	struct sctphdr *sh;
	int offset;
	uint32_t flowid, tag;

	/*
	 * No flow id built by lower layers fix it so we
	 * create one.
	 */
	ip = mtod(m, struct ip *);
	offset = (ip->ip_hl << 2) + sizeof(struct sctphdr);
	if (SCTP_BUF_LEN(m) < offset) {
		if ((m = m_pullup(m, offset)) == NULL) {
			SCTP_STAT_INCR(sctps_hdrops);
			return (NULL);
		}
		ip = mtod(m, struct ip *);
	}
	sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2));
	tag = htonl(sh->v_tag);
	flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port);
	m->m_pkthdr.flowid = flowid;
	m->m_flags |= M_FLOWID;
	return (m);
}
#endif

void
sctp_pcb_init()
{
	/*
	 * SCTP initialization for the PCB structures should be called by
	 * the sctp_init() funciton.
	 */
	int i;
	struct timeval tv;

	if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) {
		/* error I was called twice */
		return;
	}
	SCTP_BASE_VAR(sctp_pcb_initialized) = 1;

#if defined(SCTP_LOCAL_TRACE_BUF)
#if defined(__Windows__)
	if (SCTP_BASE_SYSCTL(sctp_log) != NULL) {
		bzero(SCTP_BASE_SYSCTL(sctp_log), sizeof(struct sctp_log));
	}
#else
	bzero(&SCTP_BASE_SYSCTL(sctp_log), sizeof(struct sctp_log));
#endif
#endif
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
	SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *,
		    ((mp_maxid+1) * sizeof(struct sctpstat)),
		    SCTP_M_MCORE);
#endif
	(void)SCTP_GETTIME_TIMEVAL(&tv);
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
	bzero(SCTP_BASE_STATS, (sizeof(struct sctpstat) * (mp_maxid+1)));
	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec;
	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec;
#else
	bzero(&SCTP_BASE_STATS, sizeof(struct sctpstat));
	SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec;
	SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec;
#endif
	/* init the empty list of (All) Endpoints */
	LIST_INIT(&SCTP_BASE_INFO(listhead));
#if defined(__APPLE__)
	LIST_INIT(&SCTP_BASE_INFO(inplisthead));
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
	SCTP_BASE_INFO(sctbinfo).listhead = &SCTP_BASE_INFO(inplisthead);
	SCTP_BASE_INFO(sctbinfo).mtx_grp_attr = lck_grp_attr_alloc_init();
	lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
	SCTP_BASE_INFO(sctbinfo).mtx_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
	SCTP_BASE_INFO(sctbinfo).mtx_attr = lck_attr_alloc_init();
	lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
	SCTP_BASE_INFO(sctbinfo).ipi_listhead = &SCTP_BASE_INFO(inplisthead);
	SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr = lck_grp_attr_alloc_init();
	lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
	SCTP_BASE_INFO(sctbinfo).ipi_lock_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
	SCTP_BASE_INFO(sctbinfo).ipi_lock_attr = lck_attr_alloc_init();
	lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
	SCTP_BASE_INFO(sctbinfo).ipi_gc = sctp_gc;
	in_pcbinfo_attach(&SCTP_BASE_INFO(sctbinfo));
#endif
#endif


	/* init the hash table of endpoints */
#if defined(__FreeBSD__)
#if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize));
	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize));
	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale));
#else
	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
			  SCTP_BASE_SYSCTL(sctp_hashtblsize));
	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
			  SCTP_BASE_SYSCTL(sctp_pcbtblsize));
	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
			  SCTP_BASE_SYSCTL(sctp_chunkscale));
#endif
#endif
	SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31),
						       &SCTP_BASE_INFO(hashasocmark));
	SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
						     &SCTP_BASE_INFO(hashmark));
	SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
							&SCTP_BASE_INFO(hashtcpmark));
	SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize);


	SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH,
						      &SCTP_BASE_INFO(hashvrfmark));

	SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE,
						      &SCTP_BASE_INFO(vrf_ifn_hashmark));
	/* init the zones */
	/*
	 * FIX ME: Should check for NULL returns, but if it does fail we are
	 * doomed to panic anyways... add later maybe.
	 */
	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep",
		       sizeof(struct sctp_inpcb), maxsockets);

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc",
		       sizeof(struct sctp_tcb), sctp_max_number_of_assoc);

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr",
		       sizeof(struct sctp_laddr),
		       (sctp_max_number_of_assoc * sctp_scale_up_for_address));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr",
		       sizeof(struct sctp_nets),
		       (sctp_max_number_of_assoc * sctp_scale_up_for_address));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk",
		       sizeof(struct sctp_tmit_chunk),
		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq",
		       sizeof(struct sctp_queued_to_read),
		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out",
		       sizeof(struct sctp_stream_queue_pending),
		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf",
		       sizeof(struct sctp_asconf),
		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));

	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack",
		       sizeof(struct sctp_asconf_ack),
		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));


	/* Master Lock INIT for info structure */
	SCTP_INP_INFO_LOCK_INIT();
	SCTP_STATLOG_INIT_LOCK();

	SCTP_IPI_COUNT_INIT();
	SCTP_IPI_ADDR_INIT();
#ifdef SCTP_PACKET_LOGGING
	SCTP_IP_PKTLOG_INIT();
#endif
	LIST_INIT(&SCTP_BASE_INFO(addr_wq));

	SCTP_WQ_ADDR_INIT();
	/* not sure if we need all the counts */
	SCTP_BASE_INFO(ipi_count_ep) = 0;
	/* assoc/tcb zone info */
	SCTP_BASE_INFO(ipi_count_asoc) = 0;
	/* local addrlist zone info */
	SCTP_BASE_INFO(ipi_count_laddr) = 0;
	/* remote addrlist zone info */
	SCTP_BASE_INFO(ipi_count_raddr) = 0;
	/* chunk info */
	SCTP_BASE_INFO(ipi_count_chunk) = 0;

	/* socket queue zone info */
	SCTP_BASE_INFO(ipi_count_readq) = 0;

	/* stream out queue cont */
	SCTP_BASE_INFO(ipi_count_strmoq) = 0;

	SCTP_BASE_INFO(ipi_free_strmoq) = 0;
	SCTP_BASE_INFO(ipi_free_chunks) = 0;

	SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer));

	/* Init the TIMEWAIT list */
	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
		LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]);
	}
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
	InitializeConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
	(void)pthread_cond_init(&sctp_it_ctl.iterator_wakeup, NULL);
#endif
#endif
	sctp_startup_iterator();

#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
	sctp_startup_mcore_threads();
#endif

#ifndef __Panda__
	/*
	 * INIT the default VRF which for BSD is the only one, other O/S's
	 * may have more. But initially they must start with one and then
	 * add the VRF's as addresses are added.
	 */
	sctp_init_vrf_list(SCTP_DEFAULT_VRF);
#endif
#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1200000
	if (ip_register_flow_handler(sctp_netisr_hdlr, IPPROTO_SCTP)) {
		SCTP_PRINTF("***SCTP- Error can't register netisr handler***\n");
	}
#endif
#if defined(_SCTP_NEEDS_CALLOUT_) || defined(_USER_SCTP_NEEDS_CALLOUT_)
	/* allocate the lock for the callout/timer queue */
	SCTP_TIMERQ_LOCK_INIT();
	TAILQ_INIT(&SCTP_BASE_INFO(callqueue));
#endif
#if defined(__Userspace__)
	mbuf_init(NULL);
	atomic_init();
#if defined(INET) || defined(INET6)
	recv_thread_init();
#endif
#endif
}

/*
 * Assumes that the SCTP_BASE_INFO() lock is NOT held.
 */
void
sctp_pcb_finish(void)
{
	struct sctp_vrflist *vrf_bucket;
	struct sctp_vrf *vrf, *nvrf;
	struct sctp_ifn *ifn, *nifn;
	struct sctp_ifa *ifa, *nifa;
	struct sctpvtaghead *chain;
	struct sctp_tagblock *twait_block, *prev_twait_block;
	struct sctp_laddr *wi, *nwi;
	int i;
	struct sctp_iterator *it, *nit;
	
#if !defined(__FreeBSD__)
	/* Notify the iterator to exit. */
	SCTP_IPI_ITERATOR_WQ_LOCK();
	sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_MUST_EXIT;
	sctp_wakeup_iterator();
	SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__APPLE__)
#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
	in_pcbinfo_detach(&SCTP_BASE_INFO(sctbinfo));
#endif
	SCTP_IPI_ITERATOR_WQ_LOCK();
	do {
		msleep(&sctp_it_ctl.iterator_flags,
		       sctp_it_ctl.ipi_iterator_wq_mtx,
		       0, "waiting_for_work", 0);
	} while ((sctp_it_ctl.iterator_flags & SCTP_ITERATOR_EXITED) == 0);
	thread_deallocate(sctp_it_ctl.thread_proc);
	SCTP_IPI_ITERATOR_WQ_UNLOCK();
#endif
#if defined(__Windows__)
	if (sctp_it_ctl.iterator_thread_obj != NULL) {
		NTSTATUS status = STATUS_SUCCESS;

		KeSetEvent(&sctp_it_ctl.iterator_wakeup[1], IO_NO_INCREMENT, FALSE);
		status = KeWaitForSingleObject(sctp_it_ctl.iterator_thread_obj,
					       Executive,
					       KernelMode,
					       FALSE,
					       NULL);
		ObDereferenceObject(sctp_it_ctl.iterator_thread_obj);
	}
#endif
#if defined(__Userspace__)
	if (sctp_it_ctl.thread_proc) {
#if defined(__Userspace_os_Windows)
		WaitForSingleObject(sctp_it_ctl.thread_proc, INFINITE);
		CloseHandle(sctp_it_ctl.thread_proc);
		sctp_it_ctl.thread_proc = NULL;
#else
		pthread_join(sctp_it_ctl.thread_proc, NULL);
		sctp_it_ctl.thread_proc = 0;
#endif
	}
#endif
#if defined(SCTP_PROCESS_LEVEL_LOCKS)
#if defined(__Userspace_os_Windows)
	DeleteConditionVariable(&sctp_it_ctl.iterator_wakeup);
#else
	pthread_cond_destroy(&sctp_it_ctl.iterator_wakeup);
#endif
#endif
	/* In FreeBSD the iterator thread never exits
	 * but we do clean up.
	 * The only way FreeBSD reaches here is if we have VRF's
	 * but we still add the ifdef to make it compile on old versions.
	 */
	SCTP_IPI_ITERATOR_WQ_LOCK();
	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
		if (it->vn != curvnet) {
			continue;
		}
#endif
		TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
		if (it->function_atend != NULL) {
			(*it->function_atend) (it->pointer, it->val);
		}
		SCTP_FREE(it,SCTP_M_ITER);
	}
	SCTP_IPI_ITERATOR_WQ_UNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	SCTP_ITERATOR_LOCK();
	if ((sctp_it_ctl.cur_it) &&
	    (sctp_it_ctl.cur_it->vn == curvnet)) {
		sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
	}
	SCTP_ITERATOR_UNLOCK();
#endif
#if !defined(__FreeBSD__)
	SCTP_IPI_ITERATOR_WQ_DESTROY();
	SCTP_ITERATOR_LOCK_DESTROY();
#endif
	SCTP_OS_TIMER_STOP(&SCTP_BASE_INFO(addr_wq_timer.timer));
	SCTP_WQ_ADDR_LOCK();
	LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
		LIST_REMOVE(wi, sctp_nxt_addr);
		SCTP_DECR_LADDR_COUNT();
		if (wi->action == SCTP_DEL_IP_ADDRESS) {
			SCTP_FREE(wi->ifa, SCTP_M_IFA);
		}
		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi);
	}
	SCTP_WQ_ADDR_UNLOCK();

	/*
	 * free the vrf/ifn/ifa lists and hashes (be sure address monitor
	 * is destroyed first).
	 */
	vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))];
	LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) {
		LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) {
			LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) {
				/* free the ifa */
				LIST_REMOVE(ifa, next_bucket);
				LIST_REMOVE(ifa, next_ifa);
				SCTP_FREE(ifa, SCTP_M_IFA);
			}
			/* free the ifn */
			LIST_REMOVE(ifn, next_bucket);
			LIST_REMOVE(ifn, next_ifn);
			SCTP_FREE(ifn, SCTP_M_IFN);
		}
		SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
		/* free the vrf */
		LIST_REMOVE(vrf, next_vrf);
		SCTP_FREE(vrf, SCTP_M_VRF);
	}
	/* free the vrf hashes */
	SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark));
	SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark));
#if defined(__Userspace__) && !defined(__Userspace_os_Windows)
	/* free memory allocated by getifaddrs call */
#if defined(INET) || defined(INET6)
	freeifaddrs(g_interfaces);
#endif
#endif

	/* free the TIMEWAIT list elements malloc'd in the function
	 * sctp_add_vtag_to_timewait()...
	 */
	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
		chain = &SCTP_BASE_INFO(vtag_timewait)[i];
		if (!LIST_EMPTY(chain)) {
			prev_twait_block = NULL;
			LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
				if (prev_twait_block) {
					SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
				}
				prev_twait_block = twait_block;
			}
			SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
		}
	}

	/* free the locks and mutexes */
#if defined(__APPLE__)
	SCTP_TIMERQ_LOCK_DESTROY();
#endif
#ifdef SCTP_PACKET_LOGGING
	SCTP_IP_PKTLOG_DESTROY();
#endif
	SCTP_IPI_ADDR_DESTROY();
#if defined(__APPLE__)
	SCTP_IPI_COUNT_DESTROY();
#endif
	SCTP_STATLOG_DESTROY();
	SCTP_INP_INFO_LOCK_DESTROY();

	SCTP_WQ_ADDR_DESTROY();

#if defined(__APPLE__)
#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
	lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
	lck_grp_free(SCTP_BASE_INFO(sctbinfo).mtx_grp);
	lck_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_attr);
#else
	lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
	lck_grp_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp);
	lck_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
#endif
#endif
#if defined(__Userspace__)
	SCTP_TIMERQ_LOCK_DESTROY();
	SCTP_ZONE_DESTROY(zone_mbuf);
	SCTP_ZONE_DESTROY(zone_clust);
	SCTP_ZONE_DESTROY(zone_ext_refcnt);
#endif
#if defined(__Windows__) || defined(__FreeBSD__) || defined(__Userspace__)
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf));
	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack));
#endif
	/* Get rid of other stuff to */
	if (SCTP_BASE_INFO(sctp_asochash) != NULL)
		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark));
	if (SCTP_BASE_INFO(sctp_ephash) != NULL)
		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark));
	if (SCTP_BASE_INFO(sctp_tcpephash) != NULL)
		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark));
#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
	SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE);
#endif
}


int
sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
                              int offset, int limit,
                              struct sockaddr *src, struct sockaddr *dst,
                              struct sockaddr *altsa)
{
	/*
	 * grub through the INIT pulling addresses and loading them to the
	 * nets structure in the asoc. The from address in the mbuf should
	 * also be loaded (if it is not already). This routine can be called
	 * with either INIT or INIT-ACK's as long as the m points to the IP
	 * packet and the offset points to the beginning of the parameters.
	 */
	struct sctp_inpcb *inp;
	struct sctp_nets *net, *nnet, *net_tmp;
	struct sctp_paramhdr *phdr, parm_buf;
	struct sctp_tcb *stcb_tmp;
	uint16_t ptype, plen;
	struct sockaddr *sa;
	uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
	struct sctp_auth_random *p_random = NULL;
	uint16_t random_len = 0;
	uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
	struct sctp_auth_hmac_algo *hmacs = NULL;
	uint16_t hmacs_len = 0;
	uint8_t saw_asconf = 0;
	uint8_t saw_asconf_ack = 0;
	uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
	struct sctp_auth_chunk_list *chunks = NULL;
	uint16_t num_chunks = 0;
	sctp_key_t *new_key;
	uint32_t keylen;
	int got_random = 0, got_hmacs = 0, got_chklist = 0;
	uint8_t peer_supports_ecn;
	uint8_t peer_supports_prsctp;
	uint8_t peer_supports_auth;
	uint8_t peer_supports_asconf;
	uint8_t peer_supports_asconf_ack;
	uint8_t peer_supports_reconfig;
	uint8_t peer_supports_nrsack;
	uint8_t peer_supports_pktdrop;
#ifdef INET
	struct sockaddr_in sin;
#endif
#ifdef INET6
	struct sockaddr_in6 sin6;
#endif

	/* First get the destination address setup too. */
#ifdef INET
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
	sin.sin_len = sizeof(sin);
#endif
	sin.sin_port = stcb->rport;
#endif
#ifdef INET6
	memset(&sin6, 0, sizeof(sin6));
	sin6.sin6_family = AF_INET6;
#ifdef HAVE_SIN6_LEN
	sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif
	sin6.sin6_port = stcb->rport;
#endif
	if (altsa) {
		sa = altsa;
	} else {
		sa = src;
	}
	peer_supports_ecn = 0;
	peer_supports_prsctp = 0;
	peer_supports_auth = 0;
	peer_supports_asconf = 0;
	peer_supports_reconfig = 0;
	peer_supports_nrsack = 0;
	peer_supports_pktdrop = 0;
	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
		/* mark all addresses that we have currently on the list */
		net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
	}
	/* does the source address already exist? if so skip it */
	inp = stcb->sctp_ep;
	atomic_add_int(&stcb->asoc.refcnt, 1);
	stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb);
	atomic_add_int(&stcb->asoc.refcnt, -1);

	if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
		/* we must add the source address */
		/* no scope set here since we have a tcb already. */
		switch (sa->sa_family) {
#ifdef INET
		case AF_INET:
			if (stcb->asoc.scope.ipv4_addr_legal) {
				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) {
					return (-1);
				}
			}
			break;
#endif
#ifdef INET6
		case AF_INET6:
			if (stcb->asoc.scope.ipv6_addr_legal) {
				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
					return (-2);
				}
			}
			break;
#endif
#if defined(__Userspace__)
		case AF_CONN:
			if (stcb->asoc.scope.conn_addr_legal) {
				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
					return (-2);
				}
			}
			break;
#endif
		default:
			break;
		}
	} else {
		if (net_tmp != NULL && stcb_tmp == stcb) {
			net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
		} else if (stcb_tmp != stcb) {
			/* It belongs to another association? */
			if (stcb_tmp)
				SCTP_TCB_UNLOCK(stcb_tmp);
			return (-3);
		}
	}
	if (stcb->asoc.state == 0) {
		/* the assoc was freed? */
		return (-4);
	}
	/* now we must go through each of the params. */
	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
	while (phdr) {
		ptype = ntohs(phdr->param_type);
		plen = ntohs(phdr->param_length);
		/*
		 * SCTP_PRINTF("ptype => %0x, plen => %d\n", (uint32_t)ptype,
		 * (int)plen);
		 */
		if (offset + plen > limit) {
			break;
		}
		if (plen < sizeof(struct sctp_paramhdr)) {
			break;
		}
#ifdef INET
		if (ptype == SCTP_IPV4_ADDRESS) {
			if (stcb->asoc.scope.ipv4_addr_legal) {
				struct sctp_ipv4addr_param *p4, p4_buf;

				/* ok get the v4 address and check/add */
				phdr = sctp_get_next_param(m, offset,
							   (struct sctp_paramhdr *)&p4_buf,
							   sizeof(p4_buf));
				if (plen != sizeof(struct sctp_ipv4addr_param) ||
				    phdr == NULL) {
					return (-5);
				}
				p4 = (struct sctp_ipv4addr_param *)phdr;
				sin.sin_addr.s_addr = p4->addr;
				if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
					/* Skip multi-cast addresses */
					goto next_param;
				}
				if ((sin.sin_addr.s_addr == INADDR_BROADCAST) ||
				    (sin.sin_addr.s_addr == INADDR_ANY)) {
					goto next_param;
				}
				sa = (struct sockaddr *)&sin;
				inp = stcb->sctp_ep;
				atomic_add_int(&stcb->asoc.refcnt, 1);
				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
									dst, stcb);
				atomic_add_int(&stcb->asoc.refcnt, -1);

				if ((stcb_tmp == NULL && inp == stcb->sctp_ep) ||
				    inp == NULL) {
					/* we must add the source address */
					/*
					 * no scope set since we have a tcb
					 * already
					 */

					/*
					 * we must validate the state again
					 * here
					 */
				add_it_now:
					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-7);
					}
					if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) {
						return (-8);
					}
				} else if (stcb_tmp == stcb) {
					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-10);
					}
					if (net != NULL) {
						/* clear flag */
						net->dest_state &=
							~SCTP_ADDR_NOT_IN_ASSOC;
					}
				} else {
					/*
					 * strange, address is in another
					 * assoc? straighten out locks.
					 */
					if (stcb_tmp) {
						if (SCTP_GET_STATE(&stcb_tmp->asoc) & SCTP_STATE_COOKIE_WAIT) {
							/* in setup state we abort this guy */
							sctp_abort_an_association(stcb_tmp->sctp_ep,
										  stcb_tmp, NULL, SCTP_SO_NOT_LOCKED);
							goto add_it_now;
						}
						SCTP_TCB_UNLOCK(stcb_tmp);
					}

					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-12);
					}
					return (-13);
				}
			}
		} else
#endif
#ifdef INET6
		if (ptype == SCTP_IPV6_ADDRESS) {
			if (stcb->asoc.scope.ipv6_addr_legal) {
				/* ok get the v6 address and check/add */
				struct sctp_ipv6addr_param *p6, p6_buf;

				phdr = sctp_get_next_param(m, offset,
							   (struct sctp_paramhdr *)&p6_buf,
							   sizeof(p6_buf));
				if (plen != sizeof(struct sctp_ipv6addr_param) ||
				    phdr == NULL) {
					return (-14);
				}
				p6 = (struct sctp_ipv6addr_param *)phdr;
				memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
				       sizeof(p6->addr));
				if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
					/* Skip multi-cast addresses */
					goto next_param;
				}
				if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
					/* Link local make no sense without scope */
					goto next_param;
				}
				sa = (struct sockaddr *)&sin6;
				inp = stcb->sctp_ep;
				atomic_add_int(&stcb->asoc.refcnt, 1);
				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
									dst, stcb);
				atomic_add_int(&stcb->asoc.refcnt, -1);
				if (stcb_tmp == NULL &&
				    (inp == stcb->sctp_ep || inp == NULL)) {
					/*
					 * we must validate the state again
					 * here
					 */
				add_it_now6:
					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-16);
					}
					/*
					 * we must add the address, no scope
					 * set
					 */
					if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) {
						return (-17);
					}
				} else if (stcb_tmp == stcb) {
					/*
					 * we must validate the state again
					 * here
					 */
					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-19);
					}
					if (net != NULL) {
						/* clear flag */
						net->dest_state &=
							~SCTP_ADDR_NOT_IN_ASSOC;
					}
				} else {
					/*
					 * strange, address is in another
					 * assoc? straighten out locks.
					 */
					if (stcb_tmp)
						if (SCTP_GET_STATE(&stcb_tmp->asoc) & SCTP_STATE_COOKIE_WAIT) {
							/* in setup state we abort this guy */
							sctp_abort_an_association(stcb_tmp->sctp_ep,
										  stcb_tmp, NULL, SCTP_SO_NOT_LOCKED);
							goto add_it_now6;
						}
					SCTP_TCB_UNLOCK(stcb_tmp);

					if (stcb->asoc.state == 0) {
						/* the assoc was freed? */
						return (-21);
					}
					return (-22);
				}
			}
		} else
#endif
		if (ptype == SCTP_ECN_CAPABLE) {
			peer_supports_ecn = 1;
		} else if (ptype == SCTP_ULP_ADAPTATION) {
			if (stcb->asoc.state != SCTP_STATE_OPEN) {
				struct sctp_adaptation_layer_indication ai, *aip;

				phdr = sctp_get_next_param(m, offset,
							   (struct sctp_paramhdr *)&ai, sizeof(ai));
				aip = (struct sctp_adaptation_layer_indication *)phdr;
				if (aip) {
					stcb->asoc.peers_adaptation = ntohl(aip->indication);
					stcb->asoc.adaptation_needed = 1;
				}
			}
		} else if (ptype == SCTP_SET_PRIM_ADDR) {
			struct sctp_asconf_addr_param lstore, *fee;
			int lptype;
			struct sockaddr *lsa = NULL;
#ifdef INET
			struct sctp_asconf_addrv4_param *fii;
#endif

			if (stcb->asoc.asconf_supported == 0) {
				return (-100);
			}
			if (plen > sizeof(lstore)) {
				return (-23);
			}
			if (plen < sizeof(struct sctp_asconf_addrv4_param)) {
				return (-101);
			}
			phdr = sctp_get_next_param(m, offset,
						   (struct sctp_paramhdr *)&lstore,
						   min(plen,sizeof(lstore)));
			if (phdr == NULL) {
				return (-24);
			}
			fee = (struct sctp_asconf_addr_param *)phdr;
			lptype = ntohs(fee->addrp.ph.param_type);
			switch (lptype) {
#ifdef INET
			case SCTP_IPV4_ADDRESS:
				if (plen !=
				    sizeof(struct sctp_asconf_addrv4_param)) {
					SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n",
						    (int)sizeof(struct sctp_asconf_addrv4_param),
						    plen);
				} else {
					fii = (struct sctp_asconf_addrv4_param *)fee;
					sin.sin_addr.s_addr = fii->addrp.addr;
					lsa = (struct sockaddr *)&sin;
				}
				break;
#endif
#ifdef INET6
			case SCTP_IPV6_ADDRESS:
				if (plen !=
				    sizeof(struct sctp_asconf_addr_param)) {
					SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
						    (int)sizeof(struct sctp_asconf_addr_param),
						    plen);
				} else {
					memcpy(sin6.sin6_addr.s6_addr,
					       fee->addrp.addr,
					       sizeof(fee->addrp.addr));
					lsa = (struct sockaddr *)&sin6;
				}
				break;
#endif
			default:
				break;
			}
			if (lsa) {
				(void)sctp_set_primary_addr(stcb, sa, NULL);
			}
		} else if (ptype == SCTP_HAS_NAT_SUPPORT) {
			stcb->asoc.peer_supports_nat = 1;
		} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
			/* Peer supports pr-sctp */
			peer_supports_prsctp = 1;
		} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
			/* A supported extension chunk */
			struct sctp_supported_chunk_types_param *pr_supported;
			uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
			int num_ent, i;

			phdr = sctp_get_next_param(m, offset,
						   (struct sctp_paramhdr *)&local_store, min(sizeof(local_store),plen));
			if (phdr == NULL) {
				return (-25);
			}
			pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
			num_ent = plen - sizeof(struct sctp_paramhdr);
			for (i = 0; i < num_ent; i++) {
				switch (pr_supported->chunk_types[i]) {
				case SCTP_ASCONF:
					peer_supports_asconf = 1;
					break;
				case SCTP_ASCONF_ACK:
					peer_supports_asconf_ack = 1;
					break;
				case SCTP_FORWARD_CUM_TSN:
					peer_supports_prsctp = 1;
					break;
				case SCTP_PACKET_DROPPED:
					peer_supports_pktdrop = 1;
					break;
				case SCTP_NR_SELECTIVE_ACK:
					peer_supports_nrsack = 1;
					break;
				case SCTP_STREAM_RESET:
					peer_supports_reconfig = 1;
					break;
				case SCTP_AUTHENTICATION:
					peer_supports_auth = 1;
					break;
				default:
					/* one I have not learned yet */
					break;

				}
			}
		} else if (ptype == SCTP_RANDOM) {
			if (plen > sizeof(random_store))
				break;
			if (got_random) {
				/* already processed a RANDOM */
				goto next_param;
			}
			phdr = sctp_get_next_param(m, offset,
						   (struct sctp_paramhdr *)random_store,
						   min(sizeof(random_store),plen));
			if (phdr == NULL)
				return (-26);
			p_random = (struct sctp_auth_random *)phdr;
			random_len = plen - sizeof(*p_random);
			/* enforce the random length */
			if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) {
				SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n");
				return (-27);
			}
			got_random = 1;
		} else if (ptype == SCTP_HMAC_LIST) {
			uint16_t num_hmacs;
			uint16_t i;

			if (plen > sizeof(hmacs_store))
				break;
			if (got_hmacs) {
				/* already processed a HMAC list */
				goto next_param;
			}
			phdr = sctp_get_next_param(m, offset,
						   (struct sctp_paramhdr *)hmacs_store,
						   min(plen,sizeof(hmacs_store)));
			if (phdr == NULL)
				return (-28);
			hmacs = (struct sctp_auth_hmac_algo *)phdr;
			hmacs_len = plen - sizeof(*hmacs);
			num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
			/* validate the hmac list */
			if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
				return (-29);
			}
			if (stcb->asoc.peer_hmacs != NULL)
				sctp_free_hmaclist(stcb->asoc.peer_hmacs);
			stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs);
			if (stcb->asoc.peer_hmacs != NULL) {
				for (i = 0; i < num_hmacs; i++) {
					(void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs,
								   ntohs(hmacs->hmac_ids[i]));
				}
			}
			got_hmacs = 1;
		} else if (ptype == SCTP_CHUNK_LIST) {
			int i;

			if (plen > sizeof(chunks_store))
				break;
			if (got_chklist) {
				/* already processed a Chunks list */
				goto next_param;
			}
			phdr = sctp_get_next_param(m, offset,
						   (struct sctp_paramhdr *)chunks_store,
						   min(plen,sizeof(chunks_store)));
			if (phdr == NULL)
				return (-30);
			chunks = (struct sctp_auth_chunk_list *)phdr;
			num_chunks = plen - sizeof(*chunks);
			if (stcb->asoc.peer_auth_chunks != NULL)
				sctp_clear_chunklist(stcb->asoc.peer_auth_chunks);
			else
				stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist();
			for (i = 0; i < num_chunks; i++) {
				(void)sctp_auth_add_chunk(chunks->chunk_types[i],
							  stcb->asoc.peer_auth_chunks);
				/* record asconf/asconf-ack if listed */
				if (chunks->chunk_types[i] == SCTP_ASCONF)
					saw_asconf = 1;
				if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
					saw_asconf_ack = 1;

			}
			got_chklist = 1;
		} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
			   (ptype == SCTP_STATE_COOKIE) ||
			   (ptype == SCTP_UNRECOG_PARAM) ||
			   (ptype == SCTP_COOKIE_PRESERVE) ||
			   (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
			   (ptype == SCTP_ADD_IP_ADDRESS) ||
			   (ptype == SCTP_DEL_IP_ADDRESS) ||
			   (ptype == SCTP_ERROR_CAUSE_IND) ||
			   (ptype == SCTP_SUCCESS_REPORT)) {
			/* don't care */ ;
		} else {
			if ((ptype & 0x8000) == 0x0000) {
				/*
				 * must stop processing the rest of the
				 * param's. Any report bits were handled
				 * with the call to
				 * sctp_arethere_unrecognized_parameters()
				 * when the INIT or INIT-ACK was first seen.
				 */
				break;
			}
		}

	next_param:
		offset += SCTP_SIZE32(plen);
		if (offset >= limit) {
			break;
		}
		phdr = sctp_get_next_param(m, offset, &parm_buf,
					   sizeof(parm_buf));
	}
	/* Now check to see if we need to purge any addresses */
	TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) {
		if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
		    SCTP_ADDR_NOT_IN_ASSOC) {
			/* This address has been removed from the asoc */
			/* remove and free it */
			stcb->asoc.numnets--;
			TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
			sctp_free_remote_addr(net);
			if (net == stcb->asoc.primary_destination) {
				stcb->asoc.primary_destination = NULL;
				sctp_select_primary_destination(stcb);
			}
		}
	}
	if ((stcb->asoc.ecn_supported == 1) &&
	    (peer_supports_ecn == 0)) {
		stcb->asoc.ecn_supported = 0;
	}
	if ((stcb->asoc.prsctp_supported == 1) &&
	    (peer_supports_prsctp == 0)) {
		stcb->asoc.prsctp_supported = 0;
	}
	if ((stcb->asoc.auth_supported == 1) &&
	    ((peer_supports_auth == 0) ||
	     (got_random == 0) || (got_hmacs == 0))) {
		stcb->asoc.auth_supported = 0;
	}
	if ((stcb->asoc.asconf_supported == 1) &&
	    ((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) ||
	     (stcb->asoc.auth_supported == 0) ||
	     (saw_asconf == 0) || (saw_asconf_ack == 0))) {
		stcb->asoc.asconf_supported = 0;
	}
	if ((stcb->asoc.reconfig_supported == 1) &&
	    (peer_supports_reconfig == 0)) {
		stcb->asoc.reconfig_supported = 0;
	}
	if ((stcb->asoc.nrsack_supported == 1) &&
	    (peer_supports_nrsack == 0)) {
		stcb->asoc.nrsack_supported = 0;
	}
	if ((stcb->asoc.pktdrop_supported == 1) &&
	    (peer_supports_pktdrop == 0)){
		stcb->asoc.pktdrop_supported = 0;
	}
	/* validate authentication required parameters */
	if ((peer_supports_auth == 0) && (got_chklist == 1)) {
		/* peer does not support auth but sent a chunks list? */
		return (-31);
	}
	if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) {
		/* peer supports asconf but not auth? */
		return (-32);
	} else if ((peer_supports_asconf == 1) &&
	           (peer_supports_auth == 1) &&
		   ((saw_asconf == 0) || (saw_asconf_ack == 0))) {
		return (-33);
	}
	/* concatenate the full random key */
	keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
	if (chunks != NULL) {
		keylen += sizeof(*chunks) + num_chunks;
	}
	new_key = sctp_alloc_key(keylen);
	if (new_key != NULL) {
		/* copy in the RANDOM */
		if (p_random != NULL) {
			keylen = sizeof(*p_random) + random_len;
			bcopy(p_random, new_key->key, keylen);
		} else {
			keylen = 0;
		}
		/* append in the AUTH chunks */
		if (chunks != NULL) {
			bcopy(chunks, new_key->key + keylen,
			      sizeof(*chunks) + num_chunks);
			keylen += sizeof(*chunks) + num_chunks;
		}
		/* append in the HMACs */
		if (hmacs != NULL) {
			bcopy(hmacs, new_key->key + keylen,
			      sizeof(*hmacs) + hmacs_len);
		}
	} else {
		/* failed to get memory for the key */
		return (-34);
	}
	if (stcb->asoc.authinfo.peer_random != NULL)
		sctp_free_key(stcb->asoc.authinfo.peer_random);
	stcb->asoc.authinfo.peer_random = new_key;
	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);

	return (0);
}

int
sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
		      struct sctp_nets *net)
{
	/* make sure the requested primary address exists in the assoc */
	if (net == NULL && sa)
		net = sctp_findnet(stcb, sa);

	if (net == NULL) {
		/* didn't find the requested primary address! */
		return (-1);
	} else {
		/* set the primary address */
		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
			/* Must be confirmed, so queue to set */
			net->dest_state |= SCTP_ADDR_REQ_PRIMARY;
			return (0);
		}
		stcb->asoc.primary_destination = net;
		if (!(net->dest_state & SCTP_ADDR_PF) && (stcb->asoc.alternate)) {
			sctp_free_remote_addr(stcb->asoc.alternate);
			stcb->asoc.alternate = NULL;
		}
		net = TAILQ_FIRST(&stcb->asoc.nets);
		if (net != stcb->asoc.primary_destination) {
			/* first one on the list is NOT the primary
			 * sctp_cmpaddr() is much more efficient if
			 * the primary is the first on the list, make it
			 * so.
			 */
			TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
			TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
		}
		return (0);
	}
}

int
sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now)
{
	/*
	 * This function serves two purposes. It will see if a TAG can be
	 * re-used and return 1 for yes it is ok and 0 for don't use that
	 * tag. A secondary function it will do is purge out old tags that
	 * can be removed.
	 */
	struct sctpvtaghead *chain;
	struct sctp_tagblock *twait_block;
	struct sctpasochead *head;
	struct sctp_tcb *stcb;
	int i;

	SCTP_INP_INFO_RLOCK();
	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag,
								SCTP_BASE_INFO(hashasocmark))];
	LIST_FOREACH(stcb, head, sctp_asocs) {
		/* We choose not to lock anything here. TCB's can't be
		 * removed since we have the read lock, so they can't
		 * be freed on us, same thing for the INP. I may
		 * be wrong with this assumption, but we will go
		 * with it for now :-)
		 */
		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
			continue;
		}
		if (stcb->asoc.my_vtag == tag) {
			/* candidate */
			if (stcb->rport != rport) {
				continue;
			}
			if (stcb->sctp_ep->sctp_lport != lport) {
				continue;
			}
			/* Its a used tag set */
			SCTP_INP_INFO_RUNLOCK();
			return (0);
		}
	}
	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
	/* Now what about timed wait ? */
	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
		/*
		 * Block(s) are present, lets see if we have this tag in the
		 * list
		 */
		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
			if (twait_block->vtag_block[i].v_tag == 0) {
				/* not used */
				continue;
			} else if ((long)twait_block->vtag_block[i].tv_sec_at_expire  <
				   now->tv_sec) {
				/* Audit expires this guy */
				twait_block->vtag_block[i].tv_sec_at_expire = 0;
				twait_block->vtag_block[i].v_tag = 0;
				twait_block->vtag_block[i].lport = 0;
				twait_block->vtag_block[i].rport = 0;
			} else if ((twait_block->vtag_block[i].v_tag == tag) &&
				   (twait_block->vtag_block[i].lport == lport) &&
				   (twait_block->vtag_block[i].rport == rport)) {
				/* Bad tag, sorry :< */
				SCTP_INP_INFO_RUNLOCK();
				return (0);
			}
		}
	}
	SCTP_INP_INFO_RUNLOCK();
	return (1);
}

static void
sctp_drain_mbufs(struct sctp_tcb *stcb)
{
	/*
	 * We must hunt this association for MBUF's past the cumack (i.e.
	 * out of order data that we can renege on).
	 */
	struct sctp_association *asoc;
	struct sctp_tmit_chunk *chk, *nchk;
	uint32_t cumulative_tsn_p1;
	struct sctp_queued_to_read *ctl, *nctl;
	int cnt, strmat;
	uint32_t gap, i;
	int fnd = 0;

	/* We look for anything larger than the cum-ack + 1 */

	asoc = &stcb->asoc;
	if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) {
		/* none we can reneg on. */
		return;
	}
	SCTP_STAT_INCR(sctps_protocol_drains_done);
	cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
	cnt = 0;
	/* First look in the re-assembly queue */
	TAILQ_FOREACH_SAFE(chk, &asoc->reasmqueue, sctp_next, nchk) {
		if (SCTP_TSN_GT(chk->rec.data.TSN_seq, cumulative_tsn_p1)) {
			/* Yep it is above cum-ack */
			cnt++;
			SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.TSN_seq, asoc->mapping_array_base_tsn);
			asoc->size_on_reasm_queue = sctp_sbspace_sub(asoc->size_on_reasm_queue, chk->send_size);
			sctp_ucount_decr(asoc->cnt_on_reasm_queue);
			SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
			TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
			if (chk->data) {
				sctp_m_freem(chk->data);
				chk->data = NULL;
			}
			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
		}
	}
	/* Ok that was fun, now we will drain all the inbound streams? */
	for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
		TAILQ_FOREACH_SAFE(ctl, &asoc->strmin[strmat].inqueue, next, nctl) {
			if (SCTP_TSN_GT(ctl->sinfo_tsn, cumulative_tsn_p1)) {
				/* Yep it is above cum-ack */
				cnt++;
				SCTP_CALC_TSN_TO_GAP(gap, ctl->sinfo_tsn, asoc->mapping_array_base_tsn);
				asoc->size_on_all_streams = sctp_sbspace_sub(asoc->size_on_all_streams, ctl->length);
				sctp_ucount_decr(asoc->cnt_on_all_streams);
				SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
				TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, ctl, next);
				if (ctl->data) {
					sctp_m_freem(ctl->data);
					ctl->data = NULL;
				}
				sctp_free_remote_addr(ctl->whoFrom);
				SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), ctl);
				SCTP_DECR_READQ_COUNT();
			}
		}
	}
	if (cnt) {
		/* We must back down to see what the new highest is */
		for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) {
			SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn);
			if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
				asoc->highest_tsn_inside_map = i;
				fnd = 1;
				break;
			}
		}
		if (!fnd) {
			asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1;
		}

		/*
		 * Question, should we go through the delivery queue? The only
		 * reason things are on here is the app not reading OR a p-d-api up.
		 * An attacker COULD send enough in to initiate the PD-API and then
		 * send a bunch of stuff to other streams... these would wind up on
		 * the delivery queue.. and then we would not get to them. But in
		 * order to do this I then have to back-track and un-deliver
		 * sequence numbers in streams.. el-yucko. I think for now we will
		 * NOT look at the delivery queue and leave it to be something to
		 * consider later. An alternative would be to abort the P-D-API with
		 * a notification and then deliver the data.... Or another method
		 * might be to keep track of how many times the situation occurs and
		 * if we see a possible attack underway just abort the association.
		 */
#ifdef SCTP_DEBUG
		SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt);
#endif
		/*
		 * Now do we need to find a new
		 * asoc->highest_tsn_inside_map?
		 */
		asoc->last_revoke_count = cnt;
		(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
		/*sa_ignore NO_NULL_CHK*/
		sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
		sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
	}
	/*
	 * Another issue, in un-setting the TSN's in the mapping array we
	 * DID NOT adjust the highest_tsn marker.  This will cause one of two
	 * things to occur. It may cause us to do extra work in checking for
	 * our mapping array movement. More importantly it may cause us to
	 * SACK every datagram. This may not be a bad thing though since we
	 * will recover once we get our cum-ack above and all this stuff we
	 * dumped recovered.
	 */
}

void
sctp_drain()
{
	/*
	 * We must walk the PCB lists for ALL associations here. The system
	 * is LOW on MBUF's and needs help. This is where reneging will
	 * occur. We really hope this does NOT happen!
	 */
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	VNET_ITERATOR_DECL(vnet_iter);
#else
	struct sctp_inpcb *inp;
	struct sctp_tcb *stcb;

	SCTP_STAT_INCR(sctps_protocol_drain_calls);
	if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
		return;
	}
#endif
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	VNET_LIST_RLOCK_NOSLEEP();
	VNET_FOREACH(vnet_iter) {
		CURVNET_SET(vnet_iter);
		struct sctp_inpcb *inp;
		struct sctp_tcb *stcb;
#endif

#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
		SCTP_STAT_INCR(sctps_protocol_drain_calls);
		if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
#ifdef VIMAGE
			continue;
#else
			return;
#endif
		}
#endif
		SCTP_INP_INFO_RLOCK();
		LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) {
			/* For each endpoint */
			SCTP_INP_RLOCK(inp);
			LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
				/* For each association */
				SCTP_TCB_LOCK(stcb);
				sctp_drain_mbufs(stcb);
				SCTP_TCB_UNLOCK(stcb);
			}
			SCTP_INP_RUNLOCK(inp);
		}
		SCTP_INP_INFO_RUNLOCK();
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
		CURVNET_RESTORE();
	}
	VNET_LIST_RUNLOCK_NOSLEEP();
#endif
}

/*
 * start a new iterator
 * iterates through all endpoints and associations based on the pcb_state
 * flags and asoc_state.  "af" (mandatory) is executed for all matching
 * assocs and "ef" (optional) is executed when the iterator completes.
 * "inpf" (optional) is executed for each new endpoint as it is being
 * iterated through. inpe (optional) is called when the inp completes
 * its way through all the stcbs.
 */
int
sctp_initiate_iterator(inp_func inpf,
		       asoc_func af,
		       inp_func inpe,
		       uint32_t pcb_state,
		       uint32_t pcb_features,
		       uint32_t asoc_state,
		       void *argp,
		       uint32_t argi,
		       end_func ef,
		       struct sctp_inpcb *s_inp,
		       uint8_t chunk_output_off)
{
	struct sctp_iterator *it = NULL;

	if (af == NULL) {
		return (-1);
	}
	SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator),
		    SCTP_M_ITER);
	if (it == NULL) {
		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
		return (ENOMEM);
	}
	memset(it, 0, sizeof(*it));
	it->function_assoc = af;
	it->function_inp = inpf;
	if (inpf)
		it->done_current_ep = 0;
	else
		it->done_current_ep = 1;
	it->function_atend = ef;
	it->pointer = argp;
	it->val = argi;
	it->pcb_flags = pcb_state;
	it->pcb_features = pcb_features;
	it->asoc_state = asoc_state;
	it->function_inp_end = inpe;
	it->no_chunk_output = chunk_output_off;
#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
	it->vn = curvnet;
#endif
	if (s_inp) {
		/* Assume lock is held here */
		it->inp = s_inp;
		SCTP_INP_INCR_REF(it->inp);
		it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
	} else {
		SCTP_INP_INFO_RLOCK();
		it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead));
		if (it->inp) {
			SCTP_INP_INCR_REF(it->inp);
		}
		SCTP_INP_INFO_RUNLOCK();
		it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;

	}
	SCTP_IPI_ITERATOR_WQ_LOCK();

	TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
	if (sctp_it_ctl.iterator_running == 0) {
		sctp_wakeup_iterator();
	}
	SCTP_IPI_ITERATOR_WQ_UNLOCK();
	/* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */
	return (0);
}