aboutsummaryrefslogtreecommitdiff
path: root/sys/net80211/ieee80211_mesh.c
blob: 9816473b6ece42fda9c5adcd148033c34ae342e4 (plain) (blame)
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
/*- 
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2009 The FreeBSD Foundation 
 * All rights reserved. 
 * 
 * This software was developed by Rui Paulo under sponsorship from the
 * FreeBSD Foundation. 
 *  
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 1. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE. 
 */ 
#include <sys/cdefs.h>
#ifdef __FreeBSD__
__FBSDID("$FreeBSD$");
#endif

/*
 * IEEE 802.11s Mesh Point (MBSS) support.
 *
 * Based on March 2009, D3.0 802.11s draft spec.
 */
#include "opt_inet.h"
#include "opt_wlan.h"

#include <sys/param.h>
#include <sys/systm.h> 
#include <sys/mbuf.h>   
#include <sys/malloc.h>
#include <sys/kernel.h>

#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/endian.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/sysctl.h>

#include <net/bpf.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/if_media.h>
#include <net/if_llc.h>
#include <net/ethernet.h>

#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_action.h>
#ifdef IEEE80211_SUPPORT_SUPERG
#include <net80211/ieee80211_superg.h>
#endif
#include <net80211/ieee80211_input.h>
#include <net80211/ieee80211_mesh.h>

static void	mesh_rt_flush_invalid(struct ieee80211vap *);
static int	mesh_select_proto_path(struct ieee80211vap *, const char *);
static int	mesh_select_proto_metric(struct ieee80211vap *, const char *);
static void	mesh_vattach(struct ieee80211vap *);
static int	mesh_newstate(struct ieee80211vap *, enum ieee80211_state, int);
static void	mesh_rt_cleanup_cb(void *);
static void	mesh_gatemode_setup(struct ieee80211vap *);
static void	mesh_gatemode_cb(void *);
static void	mesh_linkchange(struct ieee80211_node *,
		    enum ieee80211_mesh_mlstate);
static void	mesh_checkid(void *, struct ieee80211_node *);
static uint32_t	mesh_generateid(struct ieee80211vap *);
static int	mesh_checkpseq(struct ieee80211vap *,
		    const uint8_t [IEEE80211_ADDR_LEN], uint32_t);
static void	mesh_transmit_to_gate(struct ieee80211vap *, struct mbuf *,
		    struct ieee80211_mesh_route *);
static void	mesh_forward(struct ieee80211vap *, struct mbuf *,
		    const struct ieee80211_meshcntl *);
static int	mesh_input(struct ieee80211_node *, struct mbuf *,
		    const struct ieee80211_rx_stats *rxs, int, int);
static void	mesh_recv_mgmt(struct ieee80211_node *, struct mbuf *, int,
		    const struct ieee80211_rx_stats *rxs, int, int);
static void	mesh_recv_ctl(struct ieee80211_node *, struct mbuf *, int);
static void	mesh_peer_timeout_setup(struct ieee80211_node *);
static void	mesh_peer_timeout_backoff(struct ieee80211_node *);
static void	mesh_peer_timeout_cb(void *);
static __inline void
		mesh_peer_timeout_stop(struct ieee80211_node *);
static int	mesh_verify_meshid(struct ieee80211vap *, const uint8_t *);
static int	mesh_verify_meshconf(struct ieee80211vap *, const uint8_t *);
static int	mesh_verify_meshpeer(struct ieee80211vap *, uint8_t,
    		    const uint8_t *);
uint32_t	mesh_airtime_calc(struct ieee80211_node *);

/*
 * Timeout values come from the specification and are in milliseconds.
 */
static SYSCTL_NODE(_net_wlan, OID_AUTO, mesh, CTLFLAG_RD, 0,
    "IEEE 802.11s parameters");
static int	ieee80211_mesh_gateint = -1;
SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, gateint, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_gateint, 0, ieee80211_sysctl_msecs_ticks, "I",
    "mesh gate interval (ms)");
static int ieee80211_mesh_retrytimeout = -1;
SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, retrytimeout, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_retrytimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
    "Retry timeout (msec)");
static int ieee80211_mesh_holdingtimeout = -1;

SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, holdingtimeout, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_holdingtimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
    "Holding state timeout (msec)");
static int ieee80211_mesh_confirmtimeout = -1;
SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, confirmtimeout, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_confirmtimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
    "Confirm state timeout (msec)");
static int ieee80211_mesh_backofftimeout = -1;
SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, backofftimeout, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_backofftimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
    "Backoff timeout (msec). This is to throutles peering forever when "
    "not receiving answer or is rejected by a neighbor");
static int ieee80211_mesh_maxretries = 2;
SYSCTL_INT(_net_wlan_mesh, OID_AUTO, maxretries, CTLFLAG_RW,
    &ieee80211_mesh_maxretries, 0,
    "Maximum retries during peer link establishment");
static int ieee80211_mesh_maxholding = 2;
SYSCTL_INT(_net_wlan_mesh, OID_AUTO, maxholding, CTLFLAG_RW,
    &ieee80211_mesh_maxholding, 0,
    "Maximum times we are allowed to transition to HOLDING state before "
    "backinoff during peer link establishment");

static const uint8_t broadcastaddr[IEEE80211_ADDR_LEN] =
	{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

static	ieee80211_recv_action_func mesh_recv_action_meshpeering_open;
static	ieee80211_recv_action_func mesh_recv_action_meshpeering_confirm;
static	ieee80211_recv_action_func mesh_recv_action_meshpeering_close;
static	ieee80211_recv_action_func mesh_recv_action_meshlmetric;
static	ieee80211_recv_action_func mesh_recv_action_meshgate;

static	ieee80211_send_action_func mesh_send_action_meshpeering_open;
static	ieee80211_send_action_func mesh_send_action_meshpeering_confirm;
static	ieee80211_send_action_func mesh_send_action_meshpeering_close;
static	ieee80211_send_action_func mesh_send_action_meshlmetric;
static	ieee80211_send_action_func mesh_send_action_meshgate;

static const struct ieee80211_mesh_proto_metric mesh_metric_airtime = {
	.mpm_descr	= "AIRTIME",
	.mpm_ie		= IEEE80211_MESHCONF_METRIC_AIRTIME,
	.mpm_metric	= mesh_airtime_calc,
};

static struct ieee80211_mesh_proto_path		mesh_proto_paths[4];
static struct ieee80211_mesh_proto_metric	mesh_proto_metrics[4];

MALLOC_DEFINE(M_80211_MESH_PREQ, "80211preq", "802.11 MESH Path Request frame");
MALLOC_DEFINE(M_80211_MESH_PREP, "80211prep", "802.11 MESH Path Reply frame");
MALLOC_DEFINE(M_80211_MESH_PERR, "80211perr", "802.11 MESH Path Error frame");

/* The longer one of the lifetime should be stored as new lifetime */
#define MESH_ROUTE_LIFETIME_MAX(a, b)	(a > b ? a : b)

MALLOC_DEFINE(M_80211_MESH_RT, "80211mesh_rt", "802.11s routing table");
MALLOC_DEFINE(M_80211_MESH_GT_RT, "80211mesh_gt", "802.11s known gates table");

/*
 * Helper functions to manipulate the Mesh routing table.
 */

static struct ieee80211_mesh_route *
mesh_rt_find_locked(struct ieee80211_mesh_state *ms,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_route *rt;

	MESH_RT_LOCK_ASSERT(ms);

	TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
		if (IEEE80211_ADDR_EQ(dest, rt->rt_dest))
			return rt;
	}
	return NULL;
}

static struct ieee80211_mesh_route *
mesh_rt_add_locked(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt;

	KASSERT(!IEEE80211_ADDR_EQ(broadcastaddr, dest),
	    ("%s: adding broadcast to the routing table", __func__));

	MESH_RT_LOCK_ASSERT(ms);

	rt = IEEE80211_MALLOC(ALIGN(sizeof(struct ieee80211_mesh_route)) +
	    ms->ms_ppath->mpp_privlen, M_80211_MESH_RT,
	    IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
	if (rt != NULL) {
		rt->rt_vap = vap;
		IEEE80211_ADDR_COPY(rt->rt_dest, dest);
		rt->rt_priv = (void *)ALIGN(&rt[1]);
		MESH_RT_ENTRY_LOCK_INIT(rt, "MBSS_RT");
		callout_init(&rt->rt_discovery, 1);
		rt->rt_updtime = ticks;	/* create time */
		TAILQ_INSERT_TAIL(&ms->ms_routes, rt, rt_next);
	}
	return rt;
}

struct ieee80211_mesh_route *
ieee80211_mesh_rt_find(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt;

	MESH_RT_LOCK(ms);
	rt = mesh_rt_find_locked(ms, dest);
	MESH_RT_UNLOCK(ms);
	return rt;
}

struct ieee80211_mesh_route *
ieee80211_mesh_rt_add(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt;

	KASSERT(ieee80211_mesh_rt_find(vap, dest) == NULL,
	    ("%s: duplicate entry in the routing table", __func__));
	KASSERT(!IEEE80211_ADDR_EQ(vap->iv_myaddr, dest),
	    ("%s: adding self to the routing table", __func__));

	MESH_RT_LOCK(ms);
	rt = mesh_rt_add_locked(vap, dest);
	MESH_RT_UNLOCK(ms);
	return rt;
}

/*
 * Update the route lifetime and returns the updated lifetime.
 * If new_lifetime is zero and route is timedout it will be invalidated.
 * new_lifetime is in msec
 */
int
ieee80211_mesh_rt_update(struct ieee80211_mesh_route *rt, int new_lifetime)
{
	int timesince, now;
	uint32_t lifetime = 0;

	KASSERT(rt != NULL, ("route is NULL"));

	now = ticks;
	MESH_RT_ENTRY_LOCK(rt);

	/* dont clobber a proxy entry gated by us */
	if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY && rt->rt_nhops == 0) {
		MESH_RT_ENTRY_UNLOCK(rt);
		return rt->rt_lifetime;
	}

	timesince = ticks_to_msecs(now - rt->rt_updtime);
	rt->rt_updtime = now;
	if (timesince >= rt->rt_lifetime) {
		if (new_lifetime != 0) {
			rt->rt_lifetime = new_lifetime;
		}
		else {
			rt->rt_flags &= ~IEEE80211_MESHRT_FLAGS_VALID;
			rt->rt_lifetime = 0;
		}
	} else {
		/* update what is left of lifetime */
		rt->rt_lifetime = rt->rt_lifetime - timesince;
		rt->rt_lifetime  = MESH_ROUTE_LIFETIME_MAX(
			new_lifetime, rt->rt_lifetime);
	}
	lifetime = rt->rt_lifetime;
	MESH_RT_ENTRY_UNLOCK(rt);

	return lifetime;
}

/*
 * Add a proxy route (as needed) for the specified destination.
 */
void
ieee80211_mesh_proxy_check(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt;

	MESH_RT_LOCK(ms);
	rt = mesh_rt_find_locked(ms, dest);
	if (rt == NULL) {
		rt = mesh_rt_add_locked(vap, dest);
		if (rt == NULL) {
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
			    "%s", "unable to add proxy entry");
			vap->iv_stats.is_mesh_rtaddfailed++;
		} else {
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
			    "%s", "add proxy entry");
			IEEE80211_ADDR_COPY(rt->rt_mesh_gate, vap->iv_myaddr);
			IEEE80211_ADDR_COPY(rt->rt_nexthop, vap->iv_myaddr);
			rt->rt_flags |= IEEE80211_MESHRT_FLAGS_VALID
				     |  IEEE80211_MESHRT_FLAGS_PROXY;
		}
	} else if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0) {
		KASSERT(rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY,
		    ("no proxy flag for poxy entry"));
		struct ieee80211com *ic = vap->iv_ic;
		/*
		 * Fix existing entry created by received frames from
		 * stations that have some memory of dest.  We also
		 * flush any frames held on the staging queue; delivering
		 * them is too much trouble right now.
		 */
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
		    "%s", "fix proxy entry");
		IEEE80211_ADDR_COPY(rt->rt_nexthop, vap->iv_myaddr);
		rt->rt_flags |= IEEE80211_MESHRT_FLAGS_VALID
			     |  IEEE80211_MESHRT_FLAGS_PROXY;
		/* XXX belongs in hwmp */
		ieee80211_ageq_drain_node(&ic->ic_stageq,
		   (void *)(uintptr_t) ieee80211_mac_hash(ic, dest));
		/* XXX stat? */
	}
	MESH_RT_UNLOCK(ms);
}

static __inline void
mesh_rt_del(struct ieee80211_mesh_state *ms, struct ieee80211_mesh_route *rt)
{
	TAILQ_REMOVE(&ms->ms_routes, rt, rt_next);
	/*
	 * Grab the lock before destroying it, to be sure no one else
	 * is holding the route.
	 */
	MESH_RT_ENTRY_LOCK(rt);
	callout_drain(&rt->rt_discovery);
	MESH_RT_ENTRY_LOCK_DESTROY(rt);
	IEEE80211_FREE(rt, M_80211_MESH_RT);
}

void
ieee80211_mesh_rt_del(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt, *next;

	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
		if (IEEE80211_ADDR_EQ(rt->rt_dest, dest)) {
			if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) {
				ms->ms_ppath->mpp_senderror(vap, dest, rt,
				    IEEE80211_REASON_MESH_PERR_NO_PROXY);
			} else {
				ms->ms_ppath->mpp_senderror(vap, dest, rt,
				    IEEE80211_REASON_MESH_PERR_DEST_UNREACH);
			}
			mesh_rt_del(ms, rt);
			MESH_RT_UNLOCK(ms);
			return;
		}
	}
	MESH_RT_UNLOCK(ms);
}

void
ieee80211_mesh_rt_flush(struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt, *next;

	if (ms == NULL)
		return;
	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next)
		mesh_rt_del(ms, rt);
	MESH_RT_UNLOCK(ms);
}

void
ieee80211_mesh_rt_flush_peer(struct ieee80211vap *vap,
    const uint8_t peer[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt, *next;

	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
		if (IEEE80211_ADDR_EQ(rt->rt_nexthop, peer))
			mesh_rt_del(ms, rt);
	}
	MESH_RT_UNLOCK(ms);
}

/*
 * Flush expired routing entries, i.e. those in invalid state for
 * some time.
 */
static void
mesh_rt_flush_invalid(struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt, *next;

	if (ms == NULL)
		return;
	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
		/* Discover paths will be deleted by their own callout */
		if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_DISCOVER)
			continue;
		ieee80211_mesh_rt_update(rt, 0);
		if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0)
			mesh_rt_del(ms, rt);
	}
	MESH_RT_UNLOCK(ms);
}

int
ieee80211_mesh_register_proto_path(const struct ieee80211_mesh_proto_path *mpp)
{
	int i, firstempty = -1;

	for (i = 0; i < nitems(mesh_proto_paths); i++) {
		if (strncmp(mpp->mpp_descr, mesh_proto_paths[i].mpp_descr,
		    IEEE80211_MESH_PROTO_DSZ) == 0)
			return EEXIST;
		if (!mesh_proto_paths[i].mpp_active && firstempty == -1)
			firstempty = i;
	}
	if (firstempty < 0)
		return ENOSPC;
	memcpy(&mesh_proto_paths[firstempty], mpp, sizeof(*mpp));
	mesh_proto_paths[firstempty].mpp_active = 1;
	return 0;
}

int
ieee80211_mesh_register_proto_metric(const struct
    ieee80211_mesh_proto_metric *mpm)
{
	int i, firstempty = -1;

	for (i = 0; i < nitems(mesh_proto_metrics); i++) {
		if (strncmp(mpm->mpm_descr, mesh_proto_metrics[i].mpm_descr,
		    IEEE80211_MESH_PROTO_DSZ) == 0)
			return EEXIST;
		if (!mesh_proto_metrics[i].mpm_active && firstempty == -1)
			firstempty = i;
	}
	if (firstempty < 0)
		return ENOSPC;
	memcpy(&mesh_proto_metrics[firstempty], mpm, sizeof(*mpm));
	mesh_proto_metrics[firstempty].mpm_active = 1;
	return 0;
}

static int
mesh_select_proto_path(struct ieee80211vap *vap, const char *name)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	int i;

	for (i = 0; i < nitems(mesh_proto_paths); i++) {
		if (strcasecmp(mesh_proto_paths[i].mpp_descr, name) == 0) {
			ms->ms_ppath = &mesh_proto_paths[i];
			return 0;
		}
	}
	return ENOENT;
}

static int
mesh_select_proto_metric(struct ieee80211vap *vap, const char *name)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	int i;

	for (i = 0; i < nitems(mesh_proto_metrics); i++) {
		if (strcasecmp(mesh_proto_metrics[i].mpm_descr, name) == 0) {
			ms->ms_pmetric = &mesh_proto_metrics[i];
			return 0;
		}
	}
	return ENOENT;
}

static void
mesh_gatemode_setup(struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	/*
	 * NB: When a mesh gate is running as a ROOT it shall
	 * not send out periodic GANNs but instead mark the
	 * mesh gate flag for the corresponding proactive PREQ
	 * and RANN frames.
	 */
	if (ms->ms_flags & IEEE80211_MESHFLAGS_ROOT ||
	    (ms->ms_flags & IEEE80211_MESHFLAGS_GATE) == 0) {
		callout_drain(&ms->ms_gatetimer);
		return ;
	}
	callout_reset(&ms->ms_gatetimer, ieee80211_mesh_gateint,
	    mesh_gatemode_cb, vap);
}

static void
mesh_gatemode_cb(void *arg)
{
	struct ieee80211vap *vap = (struct ieee80211vap *)arg;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_meshgann_ie gann;

	gann.gann_flags = 0; /* Reserved */
	gann.gann_hopcount = 0;
	gann.gann_ttl = ms->ms_ttl;
	IEEE80211_ADDR_COPY(gann.gann_addr, vap->iv_myaddr);
	gann.gann_seq = ms->ms_gateseq++;
	gann.gann_interval = ieee80211_mesh_gateint;

	IEEE80211_NOTE(vap, IEEE80211_MSG_MESH, vap->iv_bss,
	    "send broadcast GANN (seq %u)", gann.gann_seq);

	ieee80211_send_action(vap->iv_bss, IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_GANN, &gann);
	mesh_gatemode_setup(vap);
}

static void
ieee80211_mesh_init(void)
{

	memset(mesh_proto_paths, 0, sizeof(mesh_proto_paths));
	memset(mesh_proto_metrics, 0, sizeof(mesh_proto_metrics));

	/*
	 * Setup mesh parameters that depends on the clock frequency.
	 */
	ieee80211_mesh_gateint = msecs_to_ticks(10000);
	ieee80211_mesh_retrytimeout = msecs_to_ticks(40);
	ieee80211_mesh_holdingtimeout = msecs_to_ticks(40);
	ieee80211_mesh_confirmtimeout = msecs_to_ticks(40);
	ieee80211_mesh_backofftimeout = msecs_to_ticks(5000);

	/*
	 * Register action frame handlers.
	 */
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_OPEN,
	    mesh_recv_action_meshpeering_open);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_CONFIRM,
	    mesh_recv_action_meshpeering_confirm);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_CLOSE,
	    mesh_recv_action_meshpeering_close);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_LMETRIC, mesh_recv_action_meshlmetric);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_GANN, mesh_recv_action_meshgate);

	ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_OPEN,
	    mesh_send_action_meshpeering_open);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_CONFIRM,
	    mesh_send_action_meshpeering_confirm);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
	    IEEE80211_ACTION_MESHPEERING_CLOSE,
	    mesh_send_action_meshpeering_close);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_LMETRIC,
	    mesh_send_action_meshlmetric);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_GANN,
	    mesh_send_action_meshgate);

	/*
	 * Register Airtime Link Metric.
	 */
	ieee80211_mesh_register_proto_metric(&mesh_metric_airtime);

}
SYSINIT(wlan_mesh, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_mesh_init, NULL);

void
ieee80211_mesh_attach(struct ieee80211com *ic)
{
	ic->ic_vattach[IEEE80211_M_MBSS] = mesh_vattach;
}

void
ieee80211_mesh_detach(struct ieee80211com *ic)
{
}

static void
mesh_vdetach_peers(void *arg, struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t args[3];

	if (ni->ni_mlstate == IEEE80211_NODE_MESH_ESTABLISHED) {
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CLOSE,
		    args);
	}
	callout_drain(&ni->ni_mltimer);
	/* XXX belongs in hwmp */
	ieee80211_ageq_drain_node(&ic->ic_stageq,
	   (void *)(uintptr_t) ieee80211_mac_hash(ic, ni->ni_macaddr));
}

static void
mesh_vdetach(struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	callout_drain(&ms->ms_cleantimer);
	ieee80211_iterate_nodes(&vap->iv_ic->ic_sta, mesh_vdetach_peers,
	    NULL);
	ieee80211_mesh_rt_flush(vap);
	MESH_RT_LOCK_DESTROY(ms);
	ms->ms_ppath->mpp_vdetach(vap);
	IEEE80211_FREE(vap->iv_mesh, M_80211_VAP);
	vap->iv_mesh = NULL;
}

static void
mesh_vattach(struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms;
	vap->iv_newstate = mesh_newstate;
	vap->iv_input = mesh_input;
	vap->iv_opdetach = mesh_vdetach;
	vap->iv_recv_mgmt = mesh_recv_mgmt;
	vap->iv_recv_ctl = mesh_recv_ctl;
	ms = IEEE80211_MALLOC(sizeof(struct ieee80211_mesh_state), M_80211_VAP,
	    IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
	if (ms == NULL) {
		printf("%s: couldn't alloc MBSS state\n", __func__);
		return;
	}
	vap->iv_mesh = ms;
	ms->ms_seq = 0;
	ms->ms_flags = (IEEE80211_MESHFLAGS_AP | IEEE80211_MESHFLAGS_FWD);
	ms->ms_ttl = IEEE80211_MESH_DEFAULT_TTL;
	TAILQ_INIT(&ms->ms_known_gates);
	TAILQ_INIT(&ms->ms_routes);
	MESH_RT_LOCK_INIT(ms, "MBSS");
	callout_init(&ms->ms_cleantimer, 1);
	callout_init(&ms->ms_gatetimer, 1);
	ms->ms_gateseq = 0;
	mesh_select_proto_metric(vap, "AIRTIME");
	KASSERT(ms->ms_pmetric, ("ms_pmetric == NULL"));
	mesh_select_proto_path(vap, "HWMP");
	KASSERT(ms->ms_ppath, ("ms_ppath == NULL"));
	ms->ms_ppath->mpp_vattach(vap);
}

/*
 * IEEE80211_M_MBSS vap state machine handler.
 */
static int
mesh_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211com *ic = vap->iv_ic;
	struct ieee80211_node *ni;
	enum ieee80211_state ostate;

	IEEE80211_LOCK_ASSERT(ic);

	ostate = vap->iv_state;
	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE, "%s: %s -> %s (%d)\n",
	    __func__, ieee80211_state_name[ostate],
	    ieee80211_state_name[nstate], arg);
	vap->iv_state = nstate;		/* state transition */
	if (ostate != IEEE80211_S_SCAN)
		ieee80211_cancel_scan(vap);	/* background scan */
	ni = vap->iv_bss;			/* NB: no reference held */
	if (nstate != IEEE80211_S_RUN && ostate == IEEE80211_S_RUN) {
		callout_drain(&ms->ms_cleantimer);
		callout_drain(&ms->ms_gatetimer);
	}
	switch (nstate) {
	case IEEE80211_S_INIT:
		switch (ostate) {
		case IEEE80211_S_SCAN:
			ieee80211_cancel_scan(vap);
			break;
		case IEEE80211_S_CAC:
			ieee80211_dfs_cac_stop(vap);
			break;
		case IEEE80211_S_RUN:
			ieee80211_iterate_nodes(&ic->ic_sta,
			    mesh_vdetach_peers, NULL);
			break;
		default:
			break;
		}
		if (ostate != IEEE80211_S_INIT) {
			/* NB: optimize INIT -> INIT case */
			ieee80211_reset_bss(vap);
			ieee80211_mesh_rt_flush(vap);
		}
		break;
	case IEEE80211_S_SCAN:
		switch (ostate) {
		case IEEE80211_S_INIT:
			if (vap->iv_des_chan != IEEE80211_CHAN_ANYC &&
			    !IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan) &&
			    ms->ms_idlen != 0) {
				/*
				 * Already have a channel and a mesh ID; bypass
				 * the scan and startup immediately.
				 */
				ieee80211_create_ibss(vap, vap->iv_des_chan);
				break;
			}
			/*
			 * Initiate a scan.  We can come here as a result
			 * of an IEEE80211_IOC_SCAN_REQ too in which case
			 * the vap will be marked with IEEE80211_FEXT_SCANREQ
			 * and the scan request parameters will be present
			 * in iv_scanreq.  Otherwise we do the default.
			*/
			if (vap->iv_flags_ext & IEEE80211_FEXT_SCANREQ) {
				ieee80211_check_scan(vap,
				    vap->iv_scanreq_flags,
				    vap->iv_scanreq_duration,
				    vap->iv_scanreq_mindwell,
				    vap->iv_scanreq_maxdwell,
				    vap->iv_scanreq_nssid, vap->iv_scanreq_ssid);
				vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANREQ;
			} else
				ieee80211_check_scan_current(vap);
			break;
		default:
			break;
		}
		break;
	case IEEE80211_S_CAC:
		/*
		 * Start CAC on a DFS channel.  We come here when starting
		 * a bss on a DFS channel (see ieee80211_create_ibss).
		 */
		ieee80211_dfs_cac_start(vap);
		break;
	case IEEE80211_S_RUN:
		switch (ostate) {
		case IEEE80211_S_INIT:
			/*
			 * Already have a channel; bypass the
			 * scan and startup immediately.
			 * Note that ieee80211_create_ibss will call
			 * back to do a RUN->RUN state change.
			 */
			ieee80211_create_ibss(vap,
			    ieee80211_ht_adjust_channel(ic,
				ic->ic_curchan, vap->iv_flags_ht));
			/* NB: iv_bss is changed on return */
			break;
		case IEEE80211_S_CAC:
			/*
			 * NB: This is the normal state change when CAC
			 * expires and no radar was detected; no need to
			 * clear the CAC timer as it's already expired.
			 */
			/* fall thru... */
		case IEEE80211_S_CSA:
#if 0
			/*
			 * Shorten inactivity timer of associated stations
			 * to weed out sta's that don't follow a CSA.
			 */
			ieee80211_iterate_nodes(&ic->ic_sta, sta_csa, vap);
#endif
			/*
			 * Update bss node channel to reflect where
			 * we landed after CSA.
			 */
			ieee80211_node_set_chan(ni,
			    ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
				ieee80211_htchanflags(ni->ni_chan)));
			/* XXX bypass debug msgs */
			break;
		case IEEE80211_S_SCAN:
		case IEEE80211_S_RUN:
#ifdef IEEE80211_DEBUG
			if (ieee80211_msg_debug(vap)) {
				ieee80211_note(vap,
				    "synchronized with %s meshid ",
				    ether_sprintf(ni->ni_meshid));
				ieee80211_print_essid(ni->ni_meshid,
				    ni->ni_meshidlen);
				/* XXX MCS/HT */
				printf(" channel %d\n",
				    ieee80211_chan2ieee(ic, ic->ic_curchan));
			}
#endif
			break;
		default:
			break;
		}
		ieee80211_node_authorize(ni);
		callout_reset(&ms->ms_cleantimer, ms->ms_ppath->mpp_inact,
                    mesh_rt_cleanup_cb, vap);
		mesh_gatemode_setup(vap);
		break;
	default:
		break;
	}
	/* NB: ostate not nstate */
	ms->ms_ppath->mpp_newstate(vap, ostate, arg);
	return 0;
}

static void
mesh_rt_cleanup_cb(void *arg)
{
	struct ieee80211vap *vap = arg;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	mesh_rt_flush_invalid(vap);
	callout_reset(&ms->ms_cleantimer, ms->ms_ppath->mpp_inact,
	    mesh_rt_cleanup_cb, vap);
}

/*
 * Mark a mesh STA as gate and return a pointer to it.
 * If this is first time, we create a new gate route.
 * Always update the path route to this mesh gate.
 */
struct ieee80211_mesh_gate_route *
ieee80211_mesh_mark_gate(struct ieee80211vap *vap, const uint8_t *addr,
    struct ieee80211_mesh_route *rt)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_gate_route *gr = NULL, *next;
	int found = 0;

	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(gr, &ms->ms_known_gates, gr_next, next) {
		if (IEEE80211_ADDR_EQ(gr->gr_addr, addr)) {
			found = 1;
			break;
		}
	}

	if (!found) {
		/* New mesh gate add it to known table. */
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, addr,
		    "%s", "stored new gate information from pro-PREQ.");
		gr = IEEE80211_MALLOC(ALIGN(sizeof(struct ieee80211_mesh_gate_route)),
		    M_80211_MESH_GT_RT,
		    IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
		IEEE80211_ADDR_COPY(gr->gr_addr, addr);
		TAILQ_INSERT_TAIL(&ms->ms_known_gates, gr, gr_next);
	}
	gr->gr_route = rt;
	/* TODO: link from path route to gate route */
	MESH_RT_UNLOCK(ms);

	return gr;
}


/*
 * Helper function to note the Mesh Peer Link FSM change.
 */
static void
mesh_linkchange(struct ieee80211_node *ni, enum ieee80211_mesh_mlstate state)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
#ifdef IEEE80211_DEBUG
	static const char *meshlinkstates[] = {
		[IEEE80211_NODE_MESH_IDLE]		= "IDLE",
		[IEEE80211_NODE_MESH_OPENSNT]		= "OPEN SENT",
		[IEEE80211_NODE_MESH_OPENRCV]		= "OPEN RECEIVED",
		[IEEE80211_NODE_MESH_CONFIRMRCV]	= "CONFIRM RECEIVED",
		[IEEE80211_NODE_MESH_ESTABLISHED]	= "ESTABLISHED",
		[IEEE80211_NODE_MESH_HOLDING]		= "HOLDING"
	};
#endif
	IEEE80211_NOTE(vap, IEEE80211_MSG_MESH,
	    ni, "peer link: %s -> %s",
	    meshlinkstates[ni->ni_mlstate], meshlinkstates[state]);

	/* track neighbor count */
	if (state == IEEE80211_NODE_MESH_ESTABLISHED &&
	    ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED) {
		KASSERT(ms->ms_neighbors < 65535, ("neighbor count overflow"));
		ms->ms_neighbors++;
		ieee80211_beacon_notify(vap, IEEE80211_BEACON_MESHCONF);
	} else if (ni->ni_mlstate == IEEE80211_NODE_MESH_ESTABLISHED &&
	    state != IEEE80211_NODE_MESH_ESTABLISHED) {
		KASSERT(ms->ms_neighbors > 0, ("neighbor count 0"));
		ms->ms_neighbors--;
		ieee80211_beacon_notify(vap, IEEE80211_BEACON_MESHCONF);
	}
	ni->ni_mlstate = state;
	switch (state) {
	case IEEE80211_NODE_MESH_HOLDING:
		ms->ms_ppath->mpp_peerdown(ni);
		break;
	case IEEE80211_NODE_MESH_ESTABLISHED:
		ieee80211_mesh_discover(vap, ni->ni_macaddr, NULL);
		break;
	default:
		break;
	}
}

/*
 * Helper function to generate a unique local ID required for mesh
 * peer establishment.
 */
static void
mesh_checkid(void *arg, struct ieee80211_node *ni)
{
	uint16_t *r = arg;
	
	if (*r == ni->ni_mllid)
		*(uint16_t *)arg = 0;
}

static uint32_t
mesh_generateid(struct ieee80211vap *vap)
{
	int maxiter = 4;
	uint16_t r;

	do {
		get_random_bytes(&r, 2);
		ieee80211_iterate_nodes(&vap->iv_ic->ic_sta, mesh_checkid, &r);
		maxiter--;
	} while (r == 0 && maxiter > 0);
	return r;
}

/*
 * Verifies if we already received this packet by checking its
 * sequence number.
 * Returns 0 if the frame is to be accepted, 1 otherwise.
 */
static int
mesh_checkpseq(struct ieee80211vap *vap,
    const uint8_t source[IEEE80211_ADDR_LEN], uint32_t seq)
{
	struct ieee80211_mesh_route *rt;

	rt = ieee80211_mesh_rt_find(vap, source);
	if (rt == NULL) {
		rt = ieee80211_mesh_rt_add(vap, source);
		if (rt == NULL) {
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, source,
			    "%s", "add mcast route failed");
			vap->iv_stats.is_mesh_rtaddfailed++;
			return 1;
		}
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, source,
		    "add mcast route, mesh seqno %d", seq);
		rt->rt_lastmseq = seq;
		return 0;
	}
	if (IEEE80211_MESH_SEQ_GEQ(rt->rt_lastmseq, seq)) {
		return 1;
	} else {
		rt->rt_lastmseq = seq;
		return 0;
	}
}

/*
 * Iterate the routing table and locate the next hop.
 */
struct ieee80211_node *
ieee80211_mesh_find_txnode(struct ieee80211vap *vap,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	struct ieee80211_mesh_route *rt;

	rt = ieee80211_mesh_rt_find(vap, dest);
	if (rt == NULL)
		return NULL;
	if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0) {
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
		    "%s: !valid, flags 0x%x", __func__, rt->rt_flags);
		/* XXX stat */
		return NULL;
	}
	if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) {
		rt = ieee80211_mesh_rt_find(vap, rt->rt_mesh_gate);
		if (rt == NULL) return NULL;
		if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0) {
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
			    "%s: meshgate !valid, flags 0x%x", __func__,
			    rt->rt_flags);
			/* XXX stat */
			return NULL;
		}
	}
	return ieee80211_find_txnode(vap, rt->rt_nexthop);
}

static void
mesh_transmit_to_gate(struct ieee80211vap *vap, struct mbuf *m,
    struct ieee80211_mesh_route *rt_gate)
{
	struct ifnet *ifp = vap->iv_ifp;
	struct ieee80211_node *ni;

	IEEE80211_TX_UNLOCK_ASSERT(vap->iv_ic);

	ni = ieee80211_mesh_find_txnode(vap, rt_gate->rt_dest);
	if (ni == NULL) {
		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
		m_freem(m);
		return;
	}

	/*
	 * Send through the VAP packet transmit path.
	 * This consumes the node ref grabbed above and
	 * the mbuf, regardless of whether there's a problem
	 * or not.
	 */
	(void) ieee80211_vap_pkt_send_dest(vap, m, ni);
}

/*
 * Forward the queued frames to known valid mesh gates.
 * Assume destination to be outside the MBSS (i.e. proxy entry),
 * If no valid mesh gates are known silently discard queued frames.
 * After transmitting frames to all known valid mesh gates, this route
 * will be marked invalid, and a new path discovery will happen in the hopes
 * that (at least) one of the mesh gates have a new proxy entry for us to use.
 */
void
ieee80211_mesh_forward_to_gates(struct ieee80211vap *vap,
    struct ieee80211_mesh_route *rt_dest)
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt_gate;
	struct ieee80211_mesh_gate_route *gr = NULL, *gr_next;
	struct mbuf *m, *mcopy, *next;

	IEEE80211_TX_UNLOCK_ASSERT(ic);

	KASSERT( rt_dest->rt_flags == IEEE80211_MESHRT_FLAGS_DISCOVER,
	    ("Route is not marked with IEEE80211_MESHRT_FLAGS_DISCOVER"));

	/* XXX: send to more than one valid mash gate */
	MESH_RT_LOCK(ms);

	m = ieee80211_ageq_remove(&ic->ic_stageq,
	    (struct ieee80211_node *)(uintptr_t)
	    ieee80211_mac_hash(ic, rt_dest->rt_dest));

	TAILQ_FOREACH_SAFE(gr, &ms->ms_known_gates, gr_next, gr_next) {
		rt_gate = gr->gr_route;
		if (rt_gate == NULL) {
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_HWMP,
				rt_dest->rt_dest,
				"mesh gate with no path %6D",
				gr->gr_addr, ":");
			continue;
		}
		if ((rt_gate->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0)
			continue;
		KASSERT(rt_gate->rt_flags & IEEE80211_MESHRT_FLAGS_GATE,
		    ("route not marked as a mesh gate"));
		KASSERT((rt_gate->rt_flags &
			IEEE80211_MESHRT_FLAGS_PROXY) == 0,
			("found mesh gate that is also marked porxy"));
		/*
		 * convert route to a proxy route gated by the current
		 * mesh gate, this is needed so encap can built data
		 * frame with correct address.
		 */
		rt_dest->rt_flags = IEEE80211_MESHRT_FLAGS_PROXY |
			IEEE80211_MESHRT_FLAGS_VALID;
		rt_dest->rt_ext_seq = 1; /* random value */
		IEEE80211_ADDR_COPY(rt_dest->rt_mesh_gate, rt_gate->rt_dest);
		IEEE80211_ADDR_COPY(rt_dest->rt_nexthop, rt_gate->rt_nexthop);
		rt_dest->rt_metric = rt_gate->rt_metric;
		rt_dest->rt_nhops = rt_gate->rt_nhops;
		ieee80211_mesh_rt_update(rt_dest, ms->ms_ppath->mpp_inact);
		MESH_RT_UNLOCK(ms);
		/* XXX: lock?? */
		mcopy = m_dup(m, M_NOWAIT);
		for (; mcopy != NULL; mcopy = next) {
			next = mcopy->m_nextpkt;
			mcopy->m_nextpkt = NULL;
			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_HWMP,
			    rt_dest->rt_dest,
			    "flush queued frame %p len %d", mcopy,
			    mcopy->m_pkthdr.len);
			mesh_transmit_to_gate(vap, mcopy, rt_gate);
		}
		MESH_RT_LOCK(ms);
	}
	rt_dest->rt_flags = 0; /* Mark invalid */
	m_freem(m);
	MESH_RT_UNLOCK(ms);
}

/*
 * Forward the specified frame.
 * Decrement the TTL and set TA to our MAC address.
 */
static void
mesh_forward(struct ieee80211vap *vap, struct mbuf *m,
    const struct ieee80211_meshcntl *mc)
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ifnet *ifp = vap->iv_ifp;
	const struct ieee80211_frame *wh =
	    mtod(m, const struct ieee80211_frame *);
	struct mbuf *mcopy;
	struct ieee80211_meshcntl *mccopy;
	struct ieee80211_frame *whcopy;
	struct ieee80211_node *ni;
	int err;

	/* This is called from the RX path - don't hold this lock */
	IEEE80211_TX_UNLOCK_ASSERT(ic);

	/*
	 * mesh ttl of 1 means we are the last one receiving it,
	 * according to amendment we decrement and then check if
	 * 0, if so we dont forward.
	 */
	if (mc->mc_ttl < 1) {
		IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
		    "%s", "frame not fwd'd, ttl 1");
		vap->iv_stats.is_mesh_fwd_ttl++;
		return;
	}
	if (!(ms->ms_flags & IEEE80211_MESHFLAGS_FWD)) {
		IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
		    "%s", "frame not fwd'd, fwding disabled");
		vap->iv_stats.is_mesh_fwd_disabled++;
		return;
	}
	mcopy = m_dup(m, M_NOWAIT);
	if (mcopy == NULL) {
		IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
		    "%s", "frame not fwd'd, cannot dup");
		vap->iv_stats.is_mesh_fwd_nobuf++;
		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
		return;
	}
	mcopy = m_pullup(mcopy, ieee80211_hdrspace(ic, wh) +
	    sizeof(struct ieee80211_meshcntl));
	if (mcopy == NULL) {
		IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
		    "%s", "frame not fwd'd, too short");
		vap->iv_stats.is_mesh_fwd_tooshort++;
		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
		m_freem(mcopy);
		return;
	}
	whcopy = mtod(mcopy, struct ieee80211_frame *);
	mccopy = (struct ieee80211_meshcntl *)
	    (mtod(mcopy, uint8_t *) + ieee80211_hdrspace(ic, wh));
	/* XXX clear other bits? */
	whcopy->i_fc[1] &= ~IEEE80211_FC1_RETRY;
	IEEE80211_ADDR_COPY(whcopy->i_addr2, vap->iv_myaddr);
	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
		ni = ieee80211_ref_node(vap->iv_bss);
		mcopy->m_flags |= M_MCAST;
	} else {
		ni = ieee80211_mesh_find_txnode(vap, whcopy->i_addr3);
		if (ni == NULL) {
			/*
			 * [Optional] any of the following three actions:
			 * o silently discard
			 * o trigger a path discovery
			 * o inform TA that meshDA is unknown.
			 */
			IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
			    "%s", "frame not fwd'd, no path");
			ms->ms_ppath->mpp_senderror(vap, whcopy->i_addr3, NULL,
			    IEEE80211_REASON_MESH_PERR_NO_FI);
			vap->iv_stats.is_mesh_fwd_nopath++;
			m_freem(mcopy);
			return;
		}
		IEEE80211_ADDR_COPY(whcopy->i_addr1, ni->ni_macaddr);
	}
	KASSERT(mccopy->mc_ttl > 0, ("%s called with wrong ttl", __func__));
	mccopy->mc_ttl--;

	/* XXX calculate priority so drivers can find the tx queue */
	M_WME_SETAC(mcopy, WME_AC_BE);

	/* XXX do we know m_nextpkt is NULL? */
	MPASS((mcopy->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
	mcopy->m_pkthdr.rcvif = (void *) ni;

	/*
	 * XXX this bypasses all of the VAP TX handling; it passes frames
	 * directly to the parent interface.
	 *
	 * Because of this, there's no TX lock being held as there's no
	 * encaps state being used.
	 *
	 * Doing a direct parent transmit may not be the correct thing
	 * to do here; we'll have to re-think this soon.
	 */
	IEEE80211_TX_LOCK(ic);
	err = ieee80211_parent_xmitpkt(ic, mcopy);
	IEEE80211_TX_UNLOCK(ic);
	if (!err)
		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
}

static struct mbuf *
mesh_decap(struct ieee80211vap *vap, struct mbuf *m, int hdrlen, int meshdrlen)
{
#define	WHDIR(wh)	((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK)
#define	MC01(mc)	((const struct ieee80211_meshcntl_ae01 *)mc)
	uint8_t b[sizeof(struct ieee80211_qosframe_addr4) +
		  sizeof(struct ieee80211_meshcntl_ae10)];
	const struct ieee80211_qosframe_addr4 *wh;
	const struct ieee80211_meshcntl_ae10 *mc;
	struct ether_header *eh;
	struct llc *llc;
	int ae;

	if (m->m_len < hdrlen + sizeof(*llc) &&
	    (m = m_pullup(m, hdrlen + sizeof(*llc))) == NULL) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
		    "discard data frame: %s", "m_pullup failed");
		vap->iv_stats.is_rx_tooshort++;
		return NULL;
	}
	memcpy(b, mtod(m, caddr_t), hdrlen);
	wh = (const struct ieee80211_qosframe_addr4 *)&b[0];
	mc = (const struct ieee80211_meshcntl_ae10 *)&b[hdrlen - meshdrlen];
	KASSERT(WHDIR(wh) == IEEE80211_FC1_DIR_FROMDS ||
		WHDIR(wh) == IEEE80211_FC1_DIR_DSTODS,
	    ("bogus dir, fc 0x%x:0x%x", wh->i_fc[0], wh->i_fc[1]));

	llc = (struct llc *)(mtod(m, caddr_t) + hdrlen);
	if (llc->llc_dsap == LLC_SNAP_LSAP && llc->llc_ssap == LLC_SNAP_LSAP &&
	    llc->llc_control == LLC_UI && llc->llc_snap.org_code[0] == 0 &&
	    llc->llc_snap.org_code[1] == 0 && llc->llc_snap.org_code[2] == 0 &&
	    /* NB: preserve AppleTalk frames that have a native SNAP hdr */
	    !(llc->llc_snap.ether_type == htons(ETHERTYPE_AARP) ||
	      llc->llc_snap.ether_type == htons(ETHERTYPE_IPX))) {
		m_adj(m, hdrlen + sizeof(struct llc) - sizeof(*eh));
		llc = NULL;
	} else {
		m_adj(m, hdrlen - sizeof(*eh));
	}
	eh = mtod(m, struct ether_header *);
	ae = mc->mc_flags & IEEE80211_MESH_AE_MASK;
	if (WHDIR(wh) == IEEE80211_FC1_DIR_FROMDS) {
		IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr1);
		if (ae == IEEE80211_MESH_AE_00) {
			IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr3);
		} else if (ae == IEEE80211_MESH_AE_01) {
			IEEE80211_ADDR_COPY(eh->ether_shost,
			    MC01(mc)->mc_addr4);
		} else {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
			    (const struct ieee80211_frame *)wh, NULL,
			    "bad AE %d", ae);
			vap->iv_stats.is_mesh_badae++;
			m_freem(m);
			return NULL;
		}
	} else {
		if (ae == IEEE80211_MESH_AE_00) {
			IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr3);
			IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr4);
		} else if (ae == IEEE80211_MESH_AE_10) {
			IEEE80211_ADDR_COPY(eh->ether_dhost, mc->mc_addr5);
			IEEE80211_ADDR_COPY(eh->ether_shost, mc->mc_addr6);
		} else {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
			    (const struct ieee80211_frame *)wh, NULL,
			    "bad AE %d", ae);
			vap->iv_stats.is_mesh_badae++;
			m_freem(m);
			return NULL;
		}
	}
#ifndef __NO_STRICT_ALIGNMENT
	if (!ALIGNED_POINTER(mtod(m, caddr_t) + sizeof(*eh), uint32_t)) {
		m = ieee80211_realign(vap, m, sizeof(*eh));
		if (m == NULL)
			return NULL;
	}
#endif /* !__NO_STRICT_ALIGNMENT */
	if (llc != NULL) {
		eh = mtod(m, struct ether_header *);
		eh->ether_type = htons(m->m_pkthdr.len - sizeof(*eh));
	}
	return m;
#undef	WDIR
#undef	MC01
}

/*
 * Return non-zero if the unicast mesh data frame should be processed
 * locally.  Frames that are not proxy'd have our address, otherwise
 * we need to consult the routing table to look for a proxy entry.
 */
static __inline int
mesh_isucastforme(struct ieee80211vap *vap, const struct ieee80211_frame *wh,
    const struct ieee80211_meshcntl *mc)
{
	int ae = mc->mc_flags & 3;

	KASSERT((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS,
	    ("bad dir 0x%x:0x%x", wh->i_fc[0], wh->i_fc[1]));
	KASSERT(ae == IEEE80211_MESH_AE_00 || ae == IEEE80211_MESH_AE_10,
	    ("bad AE %d", ae));
	if (ae == IEEE80211_MESH_AE_10) {	/* ucast w/ proxy */
		const struct ieee80211_meshcntl_ae10 *mc10 =
		    (const struct ieee80211_meshcntl_ae10 *) mc;
		struct ieee80211_mesh_route *rt =
		    ieee80211_mesh_rt_find(vap, mc10->mc_addr5);
		/* check for proxy route to ourself */
		return (rt != NULL &&
		    (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY));
	} else					/* ucast w/o proxy */
		return IEEE80211_ADDR_EQ(wh->i_addr3, vap->iv_myaddr);
}

/*
 * Verifies transmitter, updates lifetime, precursor list and forwards data.
 * > 0 means we have forwarded data and no need to process locally
 * == 0 means we want to process locally (and we may have forwarded data
 * < 0 means there was an error and data should be discarded
 */
static int
mesh_recv_indiv_data_to_fwrd(struct ieee80211vap *vap, struct mbuf *m,
    struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
{
	struct ieee80211_qosframe_addr4 *qwh;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt_meshda, *rt_meshsa;

	/* This is called from the RX path - don't hold this lock */
	IEEE80211_TX_UNLOCK_ASSERT(vap->iv_ic);

	qwh = (struct ieee80211_qosframe_addr4 *)wh;

	/*
	 * TODO:
	 * o verify addr2 is  a legitimate transmitter
	 * o lifetime of precursor of addr3 (addr2) is max(init, curr)
	 * o lifetime of precursor of addr4 (nexthop) is max(init, curr)
	 */

	/* set lifetime of addr3 (meshDA) to initial value */
	rt_meshda = ieee80211_mesh_rt_find(vap, qwh->i_addr3);
	if (rt_meshda == NULL) {
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, qwh->i_addr2,
		    "no route to meshDA(%6D)", qwh->i_addr3, ":");
		/*
		 * [Optional] any of the following three actions:
		 * o silently discard 				[X]
		 * o trigger a path discovery			[ ]
		 * o inform TA that meshDA is unknown.		[ ]
		 */
		/* XXX: stats */
		return (-1);
	}

	ieee80211_mesh_rt_update(rt_meshda, ticks_to_msecs(
	    ms->ms_ppath->mpp_inact));

	/* set lifetime of addr4 (meshSA) to initial value */
	rt_meshsa = ieee80211_mesh_rt_find(vap, qwh->i_addr4);
	KASSERT(rt_meshsa != NULL, ("no route"));
	ieee80211_mesh_rt_update(rt_meshsa, ticks_to_msecs(
	    ms->ms_ppath->mpp_inact));

	mesh_forward(vap, m, mc);
	return (1); /* dont process locally */
}

/*
 * Verifies transmitter, updates lifetime, precursor list and process data
 * locally, if data is proxy with AE = 10 it could mean data should go
 * on another mesh path or data should be forwarded to the DS.
 *
 * > 0 means we have forwarded data and no need to process locally
 * == 0 means we want to process locally (and we may have forwarded data
 * < 0 means there was an error and data should be discarded
 */
static int
mesh_recv_indiv_data_to_me(struct ieee80211vap *vap, struct mbuf *m,
    struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
{
	struct ieee80211_qosframe_addr4 *qwh;
	const struct ieee80211_meshcntl_ae10 *mc10;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_route *rt;
	int ae;

	/* This is called from the RX path - don't hold this lock */
	IEEE80211_TX_UNLOCK_ASSERT(vap->iv_ic);

	qwh = (struct ieee80211_qosframe_addr4 *)wh;
	mc10 = (const struct ieee80211_meshcntl_ae10 *)mc;

	/*
	 * TODO:
	 * o verify addr2 is  a legitimate transmitter
	 * o lifetime of precursor entry is max(init, curr)
	 */

	/* set lifetime of addr4 (meshSA) to initial value */
	rt = ieee80211_mesh_rt_find(vap, qwh->i_addr4);
	KASSERT(rt != NULL, ("no route"));
	ieee80211_mesh_rt_update(rt, ticks_to_msecs(ms->ms_ppath->mpp_inact));
	rt = NULL;

	ae = mc10->mc_flags & IEEE80211_MESH_AE_MASK;
	KASSERT(ae == IEEE80211_MESH_AE_00 ||
	    ae == IEEE80211_MESH_AE_10, ("bad AE %d", ae));
	if (ae == IEEE80211_MESH_AE_10) {
		if (IEEE80211_ADDR_EQ(mc10->mc_addr5, qwh->i_addr3)) {
			return (0); /* process locally */
		}

		rt =  ieee80211_mesh_rt_find(vap, mc10->mc_addr5);
		if (rt != NULL &&
		    (rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) &&
		    (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) == 0) {
			/*
			 * Forward on another mesh-path, according to
			 * amendment as specified in 9.32.4.1
			 */
			IEEE80211_ADDR_COPY(qwh->i_addr3, mc10->mc_addr5);
			mesh_forward(vap, m,
			    (const struct ieee80211_meshcntl *)mc10);
			return (1); /* dont process locally */
		}
		/*
		 * All other cases: forward of MSDUs from the MBSS to DS indiv.
		 * addressed according to 13.11.3.2.
		 */
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT, qwh->i_addr2,
		    "forward frame to DS, SA(%6D) DA(%6D)",
		    mc10->mc_addr6, ":", mc10->mc_addr5, ":");
	}
	return (0); /* process locally */
}

/*
 * Try to forward the group addressed data on to other mesh STAs, and
 * also to the DS.
 *
 * > 0 means we have forwarded data and no need to process locally
 * == 0 means we want to process locally (and we may have forwarded data
 * < 0 means there was an error and data should be discarded
 */
static int
mesh_recv_group_data(struct ieee80211vap *vap, struct mbuf *m,
    struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
{
#define	MC01(mc)	((const struct ieee80211_meshcntl_ae01 *)mc)
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	/* This is called from the RX path - don't hold this lock */
	IEEE80211_TX_UNLOCK_ASSERT(vap->iv_ic);

	mesh_forward(vap, m, mc);

	if(mc->mc_ttl > 0) {
		if (mc->mc_flags & IEEE80211_MESH_AE_01) {
			/*
			 * Forward of MSDUs from the MBSS to DS group addressed
			 * (according to 13.11.3.2)
			 * This happens by delivering the packet, and a bridge
			 * will sent it on another port member.
			 */
			if (ms->ms_flags & IEEE80211_MESHFLAGS_GATE &&
			    ms->ms_flags & IEEE80211_MESHFLAGS_FWD) {
				IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH,
				    MC01(mc)->mc_addr4, "%s",
				    "forward from MBSS to the DS");
			}
		}
	}
	return (0); /* process locally */
#undef	MC01
}

static int
mesh_input(struct ieee80211_node *ni, struct mbuf *m,
    const struct ieee80211_rx_stats *rxs, int rssi, int nf)
{
#define	HAS_SEQ(type)	((type & 0x4) == 0)
#define	MC01(mc)	((const struct ieee80211_meshcntl_ae01 *)mc)
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	struct ifnet *ifp = vap->iv_ifp;
	struct ieee80211_frame *wh;
	const struct ieee80211_meshcntl *mc;
	int hdrspace, meshdrlen, need_tap, error;
	uint8_t dir, type, subtype, ae;
	uint32_t seq;
	const uint8_t *addr;
	uint8_t qos[2];

	KASSERT(ni != NULL, ("null node"));
	ni->ni_inact = ni->ni_inact_reload;

	need_tap = 1;			/* mbuf need to be tapped. */
	type = -1;			/* undefined */

	/* This is called from the RX path - don't hold this lock */
	IEEE80211_TX_UNLOCK_ASSERT(ic);

	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_min)) {
		IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
		    ni->ni_macaddr, NULL,
		    "too short (1): len %u", m->m_pkthdr.len);
		vap->iv_stats.is_rx_tooshort++;
		goto out;
	}
	/*
	 * Bit of a cheat here, we use a pointer for a 3-address
	 * frame format but don't reference fields past outside
	 * ieee80211_frame_min w/o first validating the data is
	 * present.
	*/
	wh = mtod(m, struct ieee80211_frame *);

	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
	    IEEE80211_FC0_VERSION_0) {
		IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
		    ni->ni_macaddr, NULL, "wrong version %x", wh->i_fc[0]);
		vap->iv_stats.is_rx_badversion++;
		goto err;
	}
	dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
		IEEE80211_RSSI_LPF(ni->ni_avgrssi, rssi);
		ni->ni_noise = nf;
		if (HAS_SEQ(type)) {
			uint8_t tid = ieee80211_gettid(wh);

			if (IEEE80211_QOS_HAS_SEQ(wh) &&
			    TID_TO_WME_AC(tid) >= WME_AC_VI)
				ic->ic_wme.wme_hipri_traffic++;
			if (! ieee80211_check_rxseq(ni, wh, wh->i_addr1, rxs))
				goto out;
		}
	}
#ifdef IEEE80211_DEBUG
	/*
	 * It's easier, but too expensive, to simulate different mesh
	 * topologies by consulting the ACL policy very early, so do this
	 * only under DEBUG.
	 *
	 * NB: this check is also done upon peering link initiation.
	 */
	if (vap->iv_acl != NULL && !vap->iv_acl->iac_check(vap, wh)) {
		IEEE80211_DISCARD(vap, IEEE80211_MSG_ACL,
		    wh, NULL, "%s", "disallowed by ACL");
		vap->iv_stats.is_rx_acl++;
		goto out;
	}
#endif
	switch (type) {
	case IEEE80211_FC0_TYPE_DATA:
		if (ni == vap->iv_bss)
			goto out;
		if (ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
			    ni->ni_macaddr, NULL,
			    "peer link not yet established (%d)",
			    ni->ni_mlstate);
			vap->iv_stats.is_mesh_nolink++;
			goto out;
		}
		if (dir != IEEE80211_FC1_DIR_FROMDS &&
		    dir != IEEE80211_FC1_DIR_DSTODS) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, "data", "incorrect dir 0x%x", dir);
			vap->iv_stats.is_rx_wrongdir++;
			goto err;
		}

		/* All Mesh data frames are QoS subtype */
		if (!HAS_SEQ(type)) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, "data", "incorrect subtype 0x%x", subtype);
			vap->iv_stats.is_rx_badsubtype++;
			goto err;
		}

		/*
		 * Next up, any fragmentation.
		 * XXX: we defrag before we even try to forward,
		 * Mesh Control field is not present in sub-sequent
		 * fragmented frames. This is in contrast to Draft 4.0.
		 */
		hdrspace = ieee80211_hdrspace(ic, wh);
		if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
			m = ieee80211_defrag(ni, m, hdrspace);
			if (m == NULL) {
				/* Fragment dropped or frame not complete yet */
				goto out;
			}
		}
		wh = mtod(m, struct ieee80211_frame *); /* NB: after defrag */

		/*
		 * Now we have a complete Mesh Data frame.
		 */

		/*
		 * Only fromDStoDS data frames use 4 address qos frames
		 * as specified in amendment. Otherwise addr4 is located
		 * in the Mesh Control field and a 3 address qos frame
		 * is used.
		 */
		*(uint16_t *)qos = *(uint16_t *)ieee80211_getqos(wh);

		/*
		 * NB: The mesh STA sets the Mesh Control Present
		 * subfield to 1 in the Mesh Data frame containing
		 * an unfragmented MSDU, an A-MSDU, or the first
		 * fragment of an MSDU.
		 * After defrag it should always be present.
		 */
		if (!(qos[1] & IEEE80211_QOS_MC)) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
			    ni->ni_macaddr, NULL,
			    "%s", "Mesh control field not present");
			vap->iv_stats.is_rx_elem_missing++; /* XXX: kinda */
			goto err;
		}

		/* pull up enough to get to the mesh control */
		if (m->m_len < hdrspace + sizeof(struct ieee80211_meshcntl) &&
		    (m = m_pullup(m, hdrspace +
		        sizeof(struct ieee80211_meshcntl))) == NULL) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
			    ni->ni_macaddr, NULL,
			    "data too short: expecting %u", hdrspace);
			vap->iv_stats.is_rx_tooshort++;
			goto out;		/* XXX */
		}
		/*
		 * Now calculate the full extent of the headers. Note
		 * mesh_decap will pull up anything we didn't get
		 * above when it strips the 802.11 headers.
		 */
		mc = (const struct ieee80211_meshcntl *)
		    (mtod(m, const uint8_t *) + hdrspace);
		ae = mc->mc_flags & IEEE80211_MESH_AE_MASK;
		meshdrlen = sizeof(struct ieee80211_meshcntl) +
		    ae * IEEE80211_ADDR_LEN;
		hdrspace += meshdrlen;

		/* pull complete hdrspace = ieee80211_hdrspace + meshcontrol */
		if ((meshdrlen > sizeof(struct ieee80211_meshcntl)) &&
		    (m->m_len < hdrspace) &&
		    ((m = m_pullup(m, hdrspace)) == NULL)) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
			    ni->ni_macaddr, NULL,
			    "data too short: expecting %u", hdrspace);
			vap->iv_stats.is_rx_tooshort++;
			goto out;		/* XXX */
		}
		/* XXX: are we sure there is no reallocating after m_pullup? */

		seq = le32dec(mc->mc_seq);
		if (IEEE80211_IS_MULTICAST(wh->i_addr1))
			addr = wh->i_addr3;
		else if (ae == IEEE80211_MESH_AE_01)
			addr = MC01(mc)->mc_addr4;
		else
			addr = ((struct ieee80211_qosframe_addr4 *)wh)->i_addr4;
		if (IEEE80211_ADDR_EQ(vap->iv_myaddr, addr)) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
			    addr, "data", "%s", "not to me");
			vap->iv_stats.is_rx_wrongbss++;	/* XXX kinda */
			goto out;
		}
		if (mesh_checkpseq(vap, addr, seq) != 0) {
			vap->iv_stats.is_rx_dup++;
			goto out;
		}

		/* This code "routes" the frame to the right control path */
		if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
			if (IEEE80211_ADDR_EQ(vap->iv_myaddr, wh->i_addr3))
				error =
				    mesh_recv_indiv_data_to_me(vap, m, wh, mc);
			else if (IEEE80211_IS_MULTICAST(wh->i_addr3))
				error = mesh_recv_group_data(vap, m, wh, mc);
			else
				error = mesh_recv_indiv_data_to_fwrd(vap, m,
				    wh, mc);
		} else
			error = mesh_recv_group_data(vap, m, wh, mc);
		if (error < 0)
			goto err;
		else if (error > 0)
			goto out;

		if (ieee80211_radiotap_active_vap(vap))
			ieee80211_radiotap_rx(vap, m);
		need_tap = 0;

		/*
		 * Finally, strip the 802.11 header.
		 */
		m = mesh_decap(vap, m, hdrspace, meshdrlen);
		if (m == NULL) {
			/* XXX mask bit to check for both */
			/* don't count Null data frames as errors */
			if (subtype == IEEE80211_FC0_SUBTYPE_NODATA ||
			    subtype == IEEE80211_FC0_SUBTYPE_QOS_NULL)
				goto out;
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
			    ni->ni_macaddr, "data", "%s", "decap error");
			vap->iv_stats.is_rx_decap++;
			IEEE80211_NODE_STAT(ni, rx_decap);
			goto err;
		}
		if (qos[0] & IEEE80211_QOS_AMSDU) {
			m = ieee80211_decap_amsdu(ni, m);
			if (m == NULL)
				return IEEE80211_FC0_TYPE_DATA;
		}
		ieee80211_deliver_data(vap, ni, m);
		return type;
	case IEEE80211_FC0_TYPE_MGT:
		vap->iv_stats.is_rx_mgmt++;
		IEEE80211_NODE_STAT(ni, rx_mgmt);
		if (dir != IEEE80211_FC1_DIR_NODS) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, "mgt", "incorrect dir 0x%x", dir);
			vap->iv_stats.is_rx_wrongdir++;
			goto err;
		}
		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame)) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
			    ni->ni_macaddr, "mgt", "too short: len %u",
			    m->m_pkthdr.len);
			vap->iv_stats.is_rx_tooshort++;
			goto out;
		}
#ifdef IEEE80211_DEBUG
		if ((ieee80211_msg_debug(vap) && 
		    (vap->iv_ic->ic_flags & IEEE80211_F_SCAN)) ||
		    ieee80211_msg_dumppkts(vap)) {
			if_printf(ifp, "received %s from %s rssi %d\n",
			    ieee80211_mgt_subtype_name(subtype),
			    ether_sprintf(wh->i_addr2), rssi);
		}
#endif
		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "%s", "WEP set but not permitted");
			vap->iv_stats.is_rx_mgtdiscard++; /* XXX */
			goto out;
		}
		vap->iv_recv_mgmt(ni, m, subtype, rxs, rssi, nf);
		goto out;
	case IEEE80211_FC0_TYPE_CTL:
		vap->iv_stats.is_rx_ctl++;
		IEEE80211_NODE_STAT(ni, rx_ctrl);
		goto out;
	default:
		IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
		    wh, "bad", "frame type 0x%x", type);
		/* should not come here */
		break;
	}
err:
	if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
out:
	if (m != NULL) {
		if (need_tap && ieee80211_radiotap_active_vap(vap))
			ieee80211_radiotap_rx(vap, m);
		m_freem(m);
	}
	return type;
#undef	HAS_SEQ
#undef	MC01
}

static void
mesh_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m0, int subtype,
    const struct ieee80211_rx_stats *rxs, int rssi, int nf)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_channel *rxchan = ic->ic_curchan;
	struct ieee80211_frame *wh;
	struct ieee80211_mesh_route *rt;
	uint8_t *frm, *efrm;

	wh = mtod(m0, struct ieee80211_frame *);
	frm = (uint8_t *)&wh[1];
	efrm = mtod(m0, uint8_t *) + m0->m_len;
	switch (subtype) {
	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
	case IEEE80211_FC0_SUBTYPE_BEACON:
	{
		struct ieee80211_scanparams scan;
		struct ieee80211_channel *c;
		/*
		 * We process beacon/probe response
		 * frames to discover neighbors.
		 */
		if (rxs != NULL) {
			c = ieee80211_lookup_channel_rxstatus(vap, rxs);
			if (c != NULL)
				rxchan = c;
		}
		if (ieee80211_parse_beacon(ni, m0, rxchan, &scan) != 0)
			return;
		/*
		 * Count frame now that we know it's to be processed.
		 */
		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
			vap->iv_stats.is_rx_beacon++;	/* XXX remove */
			IEEE80211_NODE_STAT(ni, rx_beacons);
		} else
			IEEE80211_NODE_STAT(ni, rx_proberesp);
		/*
		 * If scanning, just pass information to the scan module.
		 */
		if (ic->ic_flags & IEEE80211_F_SCAN) {
			if (ic->ic_flags_ext & IEEE80211_FEXT_PROBECHAN) {
				/*
				 * Actively scanning a channel marked passive;
				 * send a probe request now that we know there
				 * is 802.11 traffic present.
				 *
				 * XXX check if the beacon we recv'd gives
				 * us what we need and suppress the probe req
				 */
				ieee80211_probe_curchan(vap, 1);
				ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
			}
			ieee80211_add_scan(vap, rxchan, &scan, wh,
			    subtype, rssi, nf);
			return;
		}

		/* The rest of this code assumes we are running */
		if (vap->iv_state != IEEE80211_S_RUN)
			return;
		/*
		 * Ignore non-mesh STAs.
		 */
		if ((scan.capinfo &
		     (IEEE80211_CAPINFO_ESS|IEEE80211_CAPINFO_IBSS)) ||
		    scan.meshid == NULL || scan.meshconf == NULL) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, "beacon", "%s", "not a mesh sta");
			vap->iv_stats.is_mesh_wrongmesh++;
			return;
		}
		/*
		 * Ignore STAs for other mesh networks.
		 */
		if (memcmp(scan.meshid+2, ms->ms_id, ms->ms_idlen) != 0 ||
		    mesh_verify_meshconf(vap, scan.meshconf)) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, "beacon", "%s", "not for our mesh");
			vap->iv_stats.is_mesh_wrongmesh++;
			return;
		}
		/*
		 * Peer only based on the current ACL policy.
		 */
		if (vap->iv_acl != NULL && !vap->iv_acl->iac_check(vap, wh)) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_ACL,
			    wh, NULL, "%s", "disallowed by ACL");
			vap->iv_stats.is_rx_acl++;
			return;
		}
		/*
		 * Do neighbor discovery.
		 */
		if (!IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_macaddr)) {
			/*
			 * Create a new entry in the neighbor table.
			 */
			ni = ieee80211_add_neighbor(vap, wh, &scan);
		}
		/*
		 * Automatically peer with discovered nodes if possible.
		 */
		if (ni != vap->iv_bss &&
		    (ms->ms_flags & IEEE80211_MESHFLAGS_AP)) {
			switch (ni->ni_mlstate) {
			case IEEE80211_NODE_MESH_IDLE:
			{
				uint16_t args[1];

				/* Wait for backoff callout to reset counter */
				if (ni->ni_mlhcnt >= ieee80211_mesh_maxholding)
					return;

				ni->ni_mlpid = mesh_generateid(vap);
				if (ni->ni_mlpid == 0)
					return;
				mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENSNT);
				args[0] = ni->ni_mlpid;
				ieee80211_send_action(ni,
				IEEE80211_ACTION_CAT_SELF_PROT,
				IEEE80211_ACTION_MESHPEERING_OPEN, args);
				ni->ni_mlrcnt = 0;
				mesh_peer_timeout_setup(ni);
				break;
			}
			case IEEE80211_NODE_MESH_ESTABLISHED:
			{
				/*
				 * Valid beacon from a peer mesh STA
				 * bump TA lifetime
				 */
				rt = ieee80211_mesh_rt_find(vap, wh->i_addr2);
				if(rt != NULL) {
					ieee80211_mesh_rt_update(rt,
					    ticks_to_msecs(
					    ms->ms_ppath->mpp_inact));
				}
				break;
			}
			default:
				break; /* ignore */
			}
		}
		break;
	}
	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
	{
		uint8_t *ssid, *meshid, *rates, *xrates;

		if (vap->iv_state != IEEE80211_S_RUN) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "wrong state %s",
			    ieee80211_state_name[vap->iv_state]);
			vap->iv_stats.is_rx_mgtdiscard++;
			return;
		}
		if (IEEE80211_IS_MULTICAST(wh->i_addr2)) {
			/* frame must be directed */
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "%s", "not unicast");
			vap->iv_stats.is_rx_mgtdiscard++;	/* XXX stat */
			return;
		}
		/*
		 * prreq frame format
		 *      [tlv] ssid
		 *      [tlv] supported rates
		 *      [tlv] extended supported rates
		 *	[tlv] mesh id
		 */
		ssid = meshid = rates = xrates = NULL;
		while (efrm - frm > 1) {
			IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return);
			switch (*frm) {
			case IEEE80211_ELEMID_SSID:
				ssid = frm;
				break;
			case IEEE80211_ELEMID_RATES:
				rates = frm;
				break;
			case IEEE80211_ELEMID_XRATES:
				xrates = frm;
				break;
			case IEEE80211_ELEMID_MESHID:
				meshid = frm;
				break;
			}
			frm += frm[1] + 2;
		}
		IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN, return);
		IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE, return);
		if (xrates != NULL)
			IEEE80211_VERIFY_ELEMENT(xrates,
			    IEEE80211_RATE_MAXSIZE - rates[1], return);
		if (meshid != NULL) {
			IEEE80211_VERIFY_ELEMENT(meshid,
			    IEEE80211_MESHID_LEN, return);
			/* NB: meshid, not ssid */
			IEEE80211_VERIFY_SSID(vap->iv_bss, meshid, return);
		}

		/* XXX find a better class or define it's own */
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_INPUT, wh->i_addr2,
		    "%s", "recv probe req");
		/*
		 * Some legacy 11b clients cannot hack a complete
		 * probe response frame.  When the request includes
		 * only a bare-bones rate set, communicate this to
		 * the transmit side.
		 */
		ieee80211_send_proberesp(vap, wh->i_addr2, 0);
		break;
	}

	case IEEE80211_FC0_SUBTYPE_ACTION:
	case IEEE80211_FC0_SUBTYPE_ACTION_NOACK:
		if (ni == vap->iv_bss) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "%s", "unknown node");
			vap->iv_stats.is_rx_mgtdiscard++;
		} else if (!IEEE80211_ADDR_EQ(vap->iv_myaddr, wh->i_addr1) &&
		    !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "%s", "not for us");
			vap->iv_stats.is_rx_mgtdiscard++;
		} else if (vap->iv_state != IEEE80211_S_RUN) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
			    wh, NULL, "wrong state %s",
			    ieee80211_state_name[vap->iv_state]);
			vap->iv_stats.is_rx_mgtdiscard++;
		} else {
			if (ieee80211_parse_action(ni, m0) == 0)
				(void)ic->ic_recv_action(ni, wh, frm, efrm);
		}
		break;

	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
	case IEEE80211_FC0_SUBTYPE_TIMING_ADV:
	case IEEE80211_FC0_SUBTYPE_ATIM:
	case IEEE80211_FC0_SUBTYPE_DISASSOC:
	case IEEE80211_FC0_SUBTYPE_AUTH:
	case IEEE80211_FC0_SUBTYPE_DEAUTH:
		IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
		    wh, NULL, "%s", "not handled");
		vap->iv_stats.is_rx_mgtdiscard++;
		break;

	default:
		IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
		    wh, "mgt", "subtype 0x%x not handled", subtype);
		vap->iv_stats.is_rx_badsubtype++;
		break;
	}
}

static void
mesh_recv_ctl(struct ieee80211_node *ni, struct mbuf *m, int subtype)
{

	switch (subtype) {
	case IEEE80211_FC0_SUBTYPE_BAR:
		ieee80211_recv_bar(ni, m);
		break;
	}
}

/*
 * Parse meshpeering action ie's for MPM frames
 */
static const struct ieee80211_meshpeer_ie *
mesh_parse_meshpeering_action(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,	/* XXX for VERIFY_LENGTH */
	const uint8_t *frm, const uint8_t *efrm,
	struct ieee80211_meshpeer_ie *mp, uint8_t subtype)
{
	struct ieee80211vap *vap = ni->ni_vap;
	const struct ieee80211_meshpeer_ie *mpie;
	uint16_t args[3];
	const uint8_t *meshid, *meshconf;
	uint8_t sendclose = 0; /* 1 = MPM frame rejected, close will be sent */

	meshid = meshconf = NULL;
	while (efrm - frm > 1) {
		IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return NULL);
		switch (*frm) {
		case IEEE80211_ELEMID_MESHID:
			meshid = frm;
			break;
		case IEEE80211_ELEMID_MESHCONF:
			meshconf = frm;
			break;
		case IEEE80211_ELEMID_MESHPEER:
			mpie = (const struct ieee80211_meshpeer_ie *) frm;
			memset(mp, 0, sizeof(*mp));
			mp->peer_len = mpie->peer_len;
			mp->peer_proto = le16dec(&mpie->peer_proto);
			mp->peer_llinkid = le16dec(&mpie->peer_llinkid);
			switch (subtype) {
			case IEEE80211_ACTION_MESHPEERING_CONFIRM:
				mp->peer_linkid =
				    le16dec(&mpie->peer_linkid);
				break;
			case IEEE80211_ACTION_MESHPEERING_CLOSE:
				/* NB: peer link ID is optional */
				if (mpie->peer_len ==
				    (IEEE80211_MPM_BASE_SZ + 2)) {
					mp->peer_linkid = 0;
					mp->peer_rcode =
					    le16dec(&mpie->peer_linkid);
				} else {
					mp->peer_linkid =
					    le16dec(&mpie->peer_linkid);
					mp->peer_rcode =
					    le16dec(&mpie->peer_rcode);
				}
				break;
			}
			break;
		}
		frm += frm[1] + 2;
	}

	/*
	 * Verify the contents of the frame.
	 * If it fails validation, close the peer link.
	 */
	if (mesh_verify_meshpeer(vap, subtype, (const uint8_t *)mp)) {
		sendclose = 1;
		IEEE80211_DISCARD(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    wh, NULL, "%s", "MPM validation failed");
	}

	/* If meshid is not the same reject any frames type. */
	if (sendclose == 0 && mesh_verify_meshid(vap, meshid)) {
		sendclose = 1;
		IEEE80211_DISCARD(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    wh, NULL, "%s", "not for our mesh");
		if (subtype == IEEE80211_ACTION_MESHPEERING_CLOSE) {
			/*
			 * Standard not clear about this, if we dont ignore
			 * there will be an endless loop between nodes sending
			 * CLOSE frames between each other with wrong meshid.
			 * Discard and timers will bring FSM to IDLE state.
			 */
			return NULL;
		}
	}
	
	/*
	 * Close frames are accepted if meshid is the same.
	 * Verify the other two types.
	 */
	if (sendclose == 0 && subtype != IEEE80211_ACTION_MESHPEERING_CLOSE &&
	    mesh_verify_meshconf(vap, meshconf)) {
		sendclose = 1;
		IEEE80211_DISCARD(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    wh, NULL, "%s", "configuration missmatch");
	}

	if (sendclose) {
		vap->iv_stats.is_rx_mgtdiscard++;
		switch (ni->ni_mlstate) {
		case IEEE80211_NODE_MESH_IDLE:
		case IEEE80211_NODE_MESH_ESTABLISHED:
		case IEEE80211_NODE_MESH_HOLDING:
			/* ignore */
			break;
		case IEEE80211_NODE_MESH_OPENSNT:
		case IEEE80211_NODE_MESH_OPENRCV:
		case IEEE80211_NODE_MESH_CONFIRMRCV:
			args[0] = ni->ni_mlpid;
			args[1] = ni->ni_mllid;
			/* Reason codes for rejection */
			switch (subtype) {
			case IEEE80211_ACTION_MESHPEERING_OPEN:
				args[2] = IEEE80211_REASON_MESH_CPVIOLATION;
				break;
			case IEEE80211_ACTION_MESHPEERING_CONFIRM:
				args[2] = IEEE80211_REASON_MESH_INCONS_PARAMS;
				break;
			}
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
			break;
		}
		return NULL;
	}
	
	return (const struct ieee80211_meshpeer_ie *) mp;
}

static int
mesh_recv_action_meshpeering_open(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_meshpeer_ie ie;
	const struct ieee80211_meshpeer_ie *meshpeer;
	uint16_t args[3];

	/* +2+2 for action + code + capabilites */
	meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2+2, efrm, &ie,
	    IEEE80211_ACTION_MESHPEERING_OPEN);
	if (meshpeer == NULL) {
		return 0;
	}

	/* XXX move up */
	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "recv PEER OPEN, lid 0x%x", meshpeer->peer_llinkid);

	switch (ni->ni_mlstate) {
	case IEEE80211_NODE_MESH_IDLE:
		/* Reject open request if reached our maximum neighbor count */
		if (ms->ms_neighbors >= IEEE80211_MESH_MAX_NEIGHBORS) {
			args[0] = meshpeer->peer_llinkid;
			args[1] = 0;
			args[2] = IEEE80211_REASON_MESH_MAX_PEERS;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			/* stay in IDLE state */
			return (0);
		}
		/* Open frame accepted */
		mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENRCV);
		ni->ni_mllid = meshpeer->peer_llinkid;
		ni->ni_mlpid = mesh_generateid(vap);
		if (ni->ni_mlpid == 0)
			return 0;		/* XXX */
		args[0] = ni->ni_mlpid;
		/* Announce we're open too... */
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_OPEN, args);
		/* ...and confirm the link. */
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		mesh_peer_timeout_setup(ni);
		break;
	case IEEE80211_NODE_MESH_OPENRCV:
		/* Wrong Link ID */
		if (ni->ni_mllid != meshpeer->peer_llinkid) {
			args[0] = ni->ni_mllid;
			args[1] = ni->ni_mlpid;
			args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
			break;
		}
		/* Duplicate open, confirm again. */
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		break;
	case IEEE80211_NODE_MESH_OPENSNT:
		ni->ni_mllid = meshpeer->peer_llinkid;
		mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENRCV);
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		/* NB: don't setup/clear any timeout */
		break;
	case IEEE80211_NODE_MESH_CONFIRMRCV:
		if (ni->ni_mlpid != meshpeer->peer_linkid ||
		    ni->ni_mllid != meshpeer->peer_llinkid) {
			args[0] = ni->ni_mlpid;
			args[1] = ni->ni_mllid;
			args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			mesh_linkchange(ni,
			    IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
			break;
		}
		mesh_linkchange(ni, IEEE80211_NODE_MESH_ESTABLISHED);
		ni->ni_mllid = meshpeer->peer_llinkid;
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		mesh_peer_timeout_stop(ni);
		break;
	case IEEE80211_NODE_MESH_ESTABLISHED:
		if (ni->ni_mllid != meshpeer->peer_llinkid) {
			args[0] = ni->ni_mllid;
			args[1] = ni->ni_mlpid;
			args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
			break;
		}
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		args[0] = ni->ni_mlpid;
		args[1] = meshpeer->peer_llinkid;
		/* Standard not clear about what the reaason code should be */
		args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CLOSE,
		    args);
		break;
	}
	return 0;
}

static int
mesh_recv_action_meshpeering_confirm(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_meshpeer_ie ie;
	const struct ieee80211_meshpeer_ie *meshpeer;
	uint16_t args[3];

	/* +2+2+2+2 for action + code + capabilites + status code + AID */
	meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2+2+2+2, efrm, &ie,
	    IEEE80211_ACTION_MESHPEERING_CONFIRM);
	if (meshpeer == NULL) {
		return 0;
	}

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "recv PEER CONFIRM, local id 0x%x, peer id 0x%x",
	    meshpeer->peer_llinkid, meshpeer->peer_linkid);

	switch (ni->ni_mlstate) {
	case IEEE80211_NODE_MESH_OPENRCV:
		mesh_linkchange(ni, IEEE80211_NODE_MESH_ESTABLISHED);
		mesh_peer_timeout_stop(ni);
		break;
	case IEEE80211_NODE_MESH_OPENSNT:
		mesh_linkchange(ni, IEEE80211_NODE_MESH_CONFIRMRCV);
		mesh_peer_timeout_setup(ni);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		args[0] = ni->ni_mlpid;
		args[1] = meshpeer->peer_llinkid;
		/* Standard not clear about what the reaason code should be */
		args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CLOSE,
		    args);
		break;
	case IEEE80211_NODE_MESH_CONFIRMRCV:
		if (ni->ni_mllid != meshpeer->peer_llinkid) {
			args[0] = ni->ni_mlpid;
			args[1] = ni->ni_mllid;
			args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE,
			    args);
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
		}
		break;
	default:
		IEEE80211_DISCARD(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    wh, NULL, "received confirm in invalid state %d",
		    ni->ni_mlstate);
		vap->iv_stats.is_rx_mgtdiscard++;
		break;
	}
	return 0;
}

static int
mesh_recv_action_meshpeering_close(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211_meshpeer_ie ie;
	const struct ieee80211_meshpeer_ie *meshpeer;
	uint16_t args[3];

	/* +2 for action + code */
	meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2, efrm, &ie,
	    IEEE80211_ACTION_MESHPEERING_CLOSE);
	if (meshpeer == NULL) {
		return 0;
	}

	/*
	 * XXX: check reason code, for example we could receive
	 * IEEE80211_REASON_MESH_MAX_PEERS then we should not attempt
	 * to peer again.
	 */

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
	    ni, "%s", "recv PEER CLOSE");

	switch (ni->ni_mlstate) {
	case IEEE80211_NODE_MESH_IDLE:
		/* ignore */
		break;
	case IEEE80211_NODE_MESH_OPENRCV:
	case IEEE80211_NODE_MESH_OPENSNT:
	case IEEE80211_NODE_MESH_CONFIRMRCV:
	case IEEE80211_NODE_MESH_ESTABLISHED:
		args[0] = ni->ni_mlpid;
		args[1] = ni->ni_mllid;
		args[2] = IEEE80211_REASON_MESH_CLOSE_RCVD;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CLOSE,
		    args);
		mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
		mesh_peer_timeout_setup(ni);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		mesh_linkchange(ni, IEEE80211_NODE_MESH_IDLE);
		mesh_peer_timeout_stop(ni);
		break;
	}
	return 0;
}

/*
 * Link Metric handling.
 */
static int
mesh_recv_action_meshlmetric(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	const struct ieee80211_meshlmetric_ie *ie =
	    (const struct ieee80211_meshlmetric_ie *)
	    (frm+2); /* action + code */
	struct ieee80211_meshlmetric_ie lm_rep;
	
	if (ie->lm_flags & IEEE80211_MESH_LMETRIC_FLAGS_REQ) {
		lm_rep.lm_flags = 0;
		lm_rep.lm_metric = mesh_airtime_calc(ni);
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_MESH,
		    IEEE80211_ACTION_MESH_LMETRIC,
		    &lm_rep);
	}
	/* XXX: else do nothing for now */
	return 0;
}

/*
 * Parse meshgate action ie's for GANN frames.
 * Returns -1 if parsing fails, otherwise 0.
 */
static int
mesh_parse_meshgate_action(struct ieee80211_node *ni,
    const struct ieee80211_frame *wh,	/* XXX for VERIFY_LENGTH */
    struct ieee80211_meshgann_ie *ie, const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211vap *vap = ni->ni_vap;
	const struct ieee80211_meshgann_ie *gannie;

	while (efrm - frm > 1) {
		IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return -1);
		switch (*frm) {
		case IEEE80211_ELEMID_MESHGANN:
			gannie = (const struct ieee80211_meshgann_ie *) frm;
			memset(ie, 0, sizeof(*ie));
			ie->gann_ie = gannie->gann_ie;
			ie->gann_len = gannie->gann_len;
			ie->gann_flags = gannie->gann_flags;
			ie->gann_hopcount = gannie->gann_hopcount;
			ie->gann_ttl = gannie->gann_ttl;
			IEEE80211_ADDR_COPY(ie->gann_addr, gannie->gann_addr);
			ie->gann_seq = le32dec(&gannie->gann_seq);
			ie->gann_interval = le16dec(&gannie->gann_interval);
			break;
		}
		frm += frm[1] + 2;
	}

	return 0;
}

/*
 * Mesh Gate Announcement handling.
 */
static int
mesh_recv_action_meshgate(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	struct ieee80211_mesh_gate_route *gr, *next;
	struct ieee80211_mesh_route *rt_gate;
	struct ieee80211_meshgann_ie pgann;
	struct ieee80211_meshgann_ie ie;
	int found = 0;

	/* +2 for action + code */
	if (mesh_parse_meshgate_action(ni, wh, &ie, frm+2, efrm) != 0) {
		IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
		    ni->ni_macaddr, NULL, "%s",
		    "GANN parsing failed");
		vap->iv_stats.is_rx_mgtdiscard++;
		return (0);
	}

	if (IEEE80211_ADDR_EQ(vap->iv_myaddr, ie.gann_addr))
		return 0;

	IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, ni->ni_macaddr,
	    "received GANN, meshgate: %6D (seq %u)", ie.gann_addr, ":",
	    ie.gann_seq);

	if (ms == NULL)
		return (0);
	MESH_RT_LOCK(ms);
	TAILQ_FOREACH_SAFE(gr, &ms->ms_known_gates, gr_next, next) {
		if (!IEEE80211_ADDR_EQ(gr->gr_addr, ie.gann_addr))
			continue;
		if (ie.gann_seq <= gr->gr_lastseq) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
			    ni->ni_macaddr, NULL,
			    "GANN old seqno %u <= %u",
			    ie.gann_seq, gr->gr_lastseq);
			MESH_RT_UNLOCK(ms);
			return (0);
		}
		/* corresponding mesh gate found & GANN accepted */
		found = 1;
		break;

	}
	if (found == 0) {
		/* this GANN is from a new mesh Gate add it to known table. */
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, ie.gann_addr,
		    "stored new GANN information, seq %u.", ie.gann_seq);
		gr = IEEE80211_MALLOC(ALIGN(sizeof(struct ieee80211_mesh_gate_route)),
		    M_80211_MESH_GT_RT,
		    IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
		IEEE80211_ADDR_COPY(gr->gr_addr, ie.gann_addr);
		TAILQ_INSERT_TAIL(&ms->ms_known_gates, gr, gr_next);
	}
	gr->gr_lastseq = ie.gann_seq;

	/* check if we have a path to this gate */
	rt_gate = mesh_rt_find_locked(ms, gr->gr_addr);
	if (rt_gate != NULL &&
	    rt_gate->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) {
		gr->gr_route = rt_gate;
		rt_gate->rt_flags |= IEEE80211_MESHRT_FLAGS_GATE;
	}

	MESH_RT_UNLOCK(ms);

	/* popagate only if decremented ttl >= 1 && forwarding is enabled */
	if ((ie.gann_ttl - 1) < 1 && !(ms->ms_flags & IEEE80211_MESHFLAGS_FWD))
		return 0;
	pgann.gann_flags = ie.gann_flags; /* Reserved */
	pgann.gann_hopcount = ie.gann_hopcount + 1;
	pgann.gann_ttl = ie.gann_ttl - 1;
	IEEE80211_ADDR_COPY(pgann.gann_addr, ie.gann_addr);
	pgann.gann_seq = ie.gann_seq;
	pgann.gann_interval = ie.gann_interval;

	IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, ie.gann_addr,
	    "%s", "propagate GANN");

	ieee80211_send_action(vap->iv_bss, IEEE80211_ACTION_CAT_MESH,
	    IEEE80211_ACTION_MESH_GANN, &pgann);

	return 0;
}

static int
mesh_send_action(struct ieee80211_node *ni,
    const uint8_t sa[IEEE80211_ADDR_LEN],
    const uint8_t da[IEEE80211_ADDR_LEN],
    struct mbuf *m)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_bpf_params params;
	int ret;

	KASSERT(ni != NULL, ("null node"));

	if (vap->iv_state == IEEE80211_S_CAC) {
		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
		    "block %s frame in CAC state", "Mesh action");
		vap->iv_stats.is_tx_badstate++;
		ieee80211_free_node(ni);
		m_freem(m);
		return EIO;		/* XXX */
	}

	M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
	if (m == NULL) {
		ieee80211_free_node(ni);
		return ENOMEM;
	}

	IEEE80211_TX_LOCK(ic);
	ieee80211_send_setup(ni, m,
	     IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_ACTION,
	     IEEE80211_NONQOS_TID, sa, da, sa);
	m->m_flags |= M_ENCAP;		/* mark encapsulated */

	memset(&params, 0, sizeof(params));
	params.ibp_pri = WME_AC_VO;
	params.ibp_rate0 = ni->ni_txparms->mgmtrate;
	if (IEEE80211_IS_MULTICAST(da))
		params.ibp_try0 = 1;
	else
		params.ibp_try0 = ni->ni_txparms->maxretry;
	params.ibp_power = ni->ni_txpower;

	IEEE80211_NODE_STAT(ni, tx_mgmt);

	ret = ieee80211_raw_output(vap, ni, m, &params);
	IEEE80211_TX_UNLOCK(ic);
	return (ret);
}

#define	ADDSHORT(frm, v) do {			\
	frm[0] = (v) & 0xff;			\
	frm[1] = (v) >> 8;			\
	frm += 2;				\
} while (0)
#define	ADDWORD(frm, v) do {			\
	frm[0] = (v) & 0xff;			\
	frm[1] = ((v) >> 8) & 0xff;		\
	frm[2] = ((v) >> 16) & 0xff;		\
	frm[3] = ((v) >> 24) & 0xff;		\
	frm += 4;				\
} while (0)

static int
mesh_send_action_meshpeering_open(struct ieee80211_node *ni,
	int category, int action, void *args0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t *args = args0;
	const struct ieee80211_rateset *rs;
	struct mbuf *m;
	uint8_t *frm;

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "send PEER OPEN action: localid 0x%x", args[0]);

	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
	    ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t)	/* action+category */
	    + sizeof(uint16_t)	/* capabilites */
	    + 2 + IEEE80211_RATE_SIZE
	    + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
	    + 2 + IEEE80211_MESHID_LEN
	    + sizeof(struct ieee80211_meshconf_ie)
	    + sizeof(struct ieee80211_meshpeer_ie)
	);
	if (m != NULL) {
		/*
		 * mesh peer open action frame format:
		 *   [1] category
		 *   [1] action
		 *   [2] capabilities
		 *   [tlv] rates
		 *   [tlv] xrates
		 *   [tlv] mesh id
		 *   [tlv] mesh conf
		 *   [tlv] mesh peer link mgmt
		 */
		*frm++ = category;
		*frm++ = action;
		ADDSHORT(frm, ieee80211_getcapinfo(vap, ni->ni_chan));
		rs = ieee80211_get_suprates(ic, ic->ic_curchan);
		frm = ieee80211_add_rates(frm, rs);
		frm = ieee80211_add_xrates(frm, rs);
		frm = ieee80211_add_meshid(frm, vap);
		frm = ieee80211_add_meshconf(frm, vap);
		frm = ieee80211_add_meshpeer(frm, IEEE80211_ACTION_MESHPEERING_OPEN,
		    args[0], 0, 0);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, vap->iv_myaddr, ni->ni_macaddr, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static int
mesh_send_action_meshpeering_confirm(struct ieee80211_node *ni,
	int category, int action, void *args0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t *args = args0;
	const struct ieee80211_rateset *rs;
	struct mbuf *m;
	uint8_t *frm;

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "send PEER CONFIRM action: localid 0x%x, peerid 0x%x",
	    args[0], args[1]);

	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
	    ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t)	/* action+category */
	    + sizeof(uint16_t)	/* capabilites */
	    + sizeof(uint16_t)	/* status code */
	    + sizeof(uint16_t)	/* AID */
	    + 2 + IEEE80211_RATE_SIZE
	    + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
	    + 2 + IEEE80211_MESHID_LEN
	    + sizeof(struct ieee80211_meshconf_ie)
	    + sizeof(struct ieee80211_meshpeer_ie)
	);
	if (m != NULL) {
		/*
		 * mesh peer confirm action frame format:
		 *   [1] category
		 *   [1] action
		 *   [2] capabilities
		 *   [2] status code
		 *   [2] association id (peer ID)
		 *   [tlv] rates
		 *   [tlv] xrates
		 *   [tlv] mesh id
		 *   [tlv] mesh conf
		 *   [tlv] mesh peer link mgmt
		 */
		*frm++ = category;
		*frm++ = action;
		ADDSHORT(frm, ieee80211_getcapinfo(vap, ni->ni_chan));
		ADDSHORT(frm, 0);		/* status code */
		ADDSHORT(frm, args[1]);		/* AID */
		rs = ieee80211_get_suprates(ic, ic->ic_curchan);
		frm = ieee80211_add_rates(frm, rs);
		frm = ieee80211_add_xrates(frm, rs);
		frm = ieee80211_add_meshid(frm, vap);
		frm = ieee80211_add_meshconf(frm, vap);
		frm = ieee80211_add_meshpeer(frm,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args[0], args[1], 0);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, vap->iv_myaddr, ni->ni_macaddr, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static int
mesh_send_action_meshpeering_close(struct ieee80211_node *ni,
	int category, int action, void *args0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t *args = args0;
	struct mbuf *m;
	uint8_t *frm;

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "send PEER CLOSE action: localid 0x%x, peerid 0x%x reason %d (%s)",
	    args[0], args[1], args[2], ieee80211_reason_to_string(args[2]));

	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
	    ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t)	/* action+category */
	    + sizeof(uint16_t)	/* reason code */
	    + 2 + IEEE80211_MESHID_LEN
	    + sizeof(struct ieee80211_meshpeer_ie)
	);
	if (m != NULL) {
		/*
		 * mesh peer close action frame format:
		 *   [1] category
		 *   [1] action
		 *   [tlv] mesh id
		 *   [tlv] mesh peer link mgmt
		 */
		*frm++ = category;
		*frm++ = action;
		frm = ieee80211_add_meshid(frm, vap);
		frm = ieee80211_add_meshpeer(frm,
		    IEEE80211_ACTION_MESHPEERING_CLOSE,
		    args[0], args[1], args[2]);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, vap->iv_myaddr, ni->ni_macaddr, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static int
mesh_send_action_meshlmetric(struct ieee80211_node *ni,
	int category, int action, void *arg0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_meshlmetric_ie *ie = arg0;
	struct mbuf *m;
	uint8_t *frm;

	if (ie->lm_flags & IEEE80211_MESH_LMETRIC_FLAGS_REQ) {
		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    ni, "%s", "send LINK METRIC REQUEST action");
	} else {
		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    ni, "send LINK METRIC REPLY action: metric 0x%x",
		    ie->lm_metric);
	}
	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
	    ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t) +	/* action+category */
	    sizeof(struct ieee80211_meshlmetric_ie)
	);
	if (m != NULL) {
		/*
		 * mesh link metric
		 *   [1] category
		 *   [1] action
		 *   [tlv] mesh link metric
		 */
		*frm++ = category;
		*frm++ = action;
		frm = ieee80211_add_meshlmetric(frm,
		    ie->lm_flags, ie->lm_metric);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, vap->iv_myaddr, ni->ni_macaddr, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static int
mesh_send_action_meshgate(struct ieee80211_node *ni,
	int category, int action, void *arg0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_meshgann_ie *ie = arg0;
	struct mbuf *m;
	uint8_t *frm;

	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
	    ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t) +	/* action+category */
	    IEEE80211_MESHGANN_BASE_SZ
	);
	if (m != NULL) {
		/*
		 * mesh link metric
		 *   [1] category
		 *   [1] action
		 *   [tlv] mesh gate annoucement
		 */
		*frm++ = category;
		*frm++ = action;
		frm = ieee80211_add_meshgate(frm, ie);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, vap->iv_myaddr, broadcastaddr, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static void
mesh_peer_timeout_setup(struct ieee80211_node *ni)
{
	switch (ni->ni_mlstate) {
	case IEEE80211_NODE_MESH_HOLDING:
		ni->ni_mltval = ieee80211_mesh_holdingtimeout;
		break;
	case IEEE80211_NODE_MESH_CONFIRMRCV:
		ni->ni_mltval = ieee80211_mesh_confirmtimeout;
		break;
	case IEEE80211_NODE_MESH_IDLE:
		ni->ni_mltval = 0;
		break;
	default:
		ni->ni_mltval = ieee80211_mesh_retrytimeout;
		break;
	}
	if (ni->ni_mltval)
		callout_reset(&ni->ni_mltimer, ni->ni_mltval,
		    mesh_peer_timeout_cb, ni);
}

/*
 * Same as above but backoffs timer statisically 50%.
 */
static void
mesh_peer_timeout_backoff(struct ieee80211_node *ni)
{
	uint32_t r;
	
	r = arc4random();
	ni->ni_mltval += r % ni->ni_mltval;
	callout_reset(&ni->ni_mltimer, ni->ni_mltval, mesh_peer_timeout_cb,
	    ni);
}

static __inline void
mesh_peer_timeout_stop(struct ieee80211_node *ni)
{
	callout_drain(&ni->ni_mltimer);
}

static void
mesh_peer_backoff_cb(void *arg)
{
	struct ieee80211_node *ni = (struct ieee80211_node *)arg;

	/* After backoff timeout, try to peer automatically again. */
	ni->ni_mlhcnt = 0;
}

/*
 * Mesh Peer Link Management FSM timeout handling.
 */
static void
mesh_peer_timeout_cb(void *arg)
{
	struct ieee80211_node *ni = (struct ieee80211_node *)arg;
	uint16_t args[3];

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_MESH,
	    ni, "mesh link timeout, state %d, retry counter %d",
	    ni->ni_mlstate, ni->ni_mlrcnt);
	
	switch (ni->ni_mlstate) {
	case IEEE80211_NODE_MESH_IDLE:
	case IEEE80211_NODE_MESH_ESTABLISHED:
		break;
	case IEEE80211_NODE_MESH_OPENSNT:
	case IEEE80211_NODE_MESH_OPENRCV:
		if (ni->ni_mlrcnt == ieee80211_mesh_maxretries) {
			args[0] = ni->ni_mlpid;
			args[2] = IEEE80211_REASON_MESH_MAX_RETRIES;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_CLOSE, args);
			ni->ni_mlrcnt = 0;
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
		} else {
			args[0] = ni->ni_mlpid;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_SELF_PROT,
			    IEEE80211_ACTION_MESHPEERING_OPEN, args);
			ni->ni_mlrcnt++;
			mesh_peer_timeout_backoff(ni);
		}
		break;
	case IEEE80211_NODE_MESH_CONFIRMRCV:
		args[0] = ni->ni_mlpid;
		args[2] = IEEE80211_REASON_MESH_CONFIRM_TIMEOUT;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_SELF_PROT,
		    IEEE80211_ACTION_MESHPEERING_CLOSE, args);
		mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
		mesh_peer_timeout_setup(ni);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		ni->ni_mlhcnt++;
		if (ni->ni_mlhcnt >= ieee80211_mesh_maxholding)
			callout_reset(&ni->ni_mlhtimer,
			    ieee80211_mesh_backofftimeout,
			    mesh_peer_backoff_cb, ni);
		mesh_linkchange(ni, IEEE80211_NODE_MESH_IDLE);
		break;
	}
}

static int
mesh_verify_meshid(struct ieee80211vap *vap, const uint8_t *ie)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	if (ie == NULL || ie[1] != ms->ms_idlen)
		return 1;
	return memcmp(ms->ms_id, ie + 2, ms->ms_idlen);
}

/*
 * Check if we are using the same algorithms for this mesh.
 */
static int
mesh_verify_meshconf(struct ieee80211vap *vap, const uint8_t *ie)
{
	const struct ieee80211_meshconf_ie *meshconf =
	    (const struct ieee80211_meshconf_ie *) ie;
	const struct ieee80211_mesh_state *ms = vap->iv_mesh;

	if (meshconf == NULL)
		return 1;
	if (meshconf->conf_pselid != ms->ms_ppath->mpp_ie) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "unknown path selection algorithm: 0x%x\n",
		    meshconf->conf_pselid);
		return 1;
	}
	if (meshconf->conf_pmetid != ms->ms_pmetric->mpm_ie) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "unknown path metric algorithm: 0x%x\n",
		    meshconf->conf_pmetid);
		return 1;
	}
	if (meshconf->conf_ccid != 0) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "unknown congestion control algorithm: 0x%x\n",
		    meshconf->conf_ccid);
		return 1;
	}
	if (meshconf->conf_syncid != IEEE80211_MESHCONF_SYNC_NEIGHOFF) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "unknown sync algorithm: 0x%x\n",
		    meshconf->conf_syncid);
		return 1;
	}
	if (meshconf->conf_authid != 0) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "unknown auth auth algorithm: 0x%x\n",
		    meshconf->conf_pselid);
		return 1;
	}
	/* Not accepting peers */
	if (!(meshconf->conf_cap & IEEE80211_MESHCONF_CAP_AP)) {
		IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
		    "not accepting peers: 0x%x\n", meshconf->conf_cap);
		return 1;
	}
	return 0;
}

static int
mesh_verify_meshpeer(struct ieee80211vap *vap, uint8_t subtype,
    const uint8_t *ie)
{
	const struct ieee80211_meshpeer_ie *meshpeer =
	    (const struct ieee80211_meshpeer_ie *) ie;

	if (meshpeer == NULL ||
	    meshpeer->peer_len < IEEE80211_MPM_BASE_SZ ||
	    meshpeer->peer_len > IEEE80211_MPM_MAX_SZ)
		return 1;
	if (meshpeer->peer_proto != IEEE80211_MPPID_MPM) {
		IEEE80211_DPRINTF(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    "Only MPM protocol is supported (proto: 0x%02X)",
		    meshpeer->peer_proto);
		return 1;
	}
	switch (subtype) {
	case IEEE80211_ACTION_MESHPEERING_OPEN:
		if (meshpeer->peer_len != IEEE80211_MPM_BASE_SZ)
			return 1;
		break;
	case IEEE80211_ACTION_MESHPEERING_CONFIRM:
		if (meshpeer->peer_len != IEEE80211_MPM_BASE_SZ + 2)
			return 1;
		break;
	case IEEE80211_ACTION_MESHPEERING_CLOSE:
		if (meshpeer->peer_len < IEEE80211_MPM_BASE_SZ + 2)
			return 1;
		if (meshpeer->peer_len == (IEEE80211_MPM_BASE_SZ + 2) &&
		    meshpeer->peer_linkid != 0)
			return 1;
		if (meshpeer->peer_rcode == 0)
			return 1;
		break;
	}
	return 0;
}

/*
 * Add a Mesh ID IE to a frame.
 */
uint8_t *
ieee80211_add_meshid(uint8_t *frm, struct ieee80211vap *vap)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a mbss vap"));

	*frm++ = IEEE80211_ELEMID_MESHID;
	*frm++ = ms->ms_idlen;
	memcpy(frm, ms->ms_id, ms->ms_idlen);
	return frm + ms->ms_idlen;
}

/*
 * Add a Mesh Configuration IE to a frame.
 * For now just use HWMP routing, Airtime link metric, Null Congestion
 * Signaling, Null Sync Protocol and Null Authentication.
 */
uint8_t *
ieee80211_add_meshconf(uint8_t *frm, struct ieee80211vap *vap)
{
	const struct ieee80211_mesh_state *ms = vap->iv_mesh;
	uint16_t caps;

	KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a MBSS vap"));

	*frm++ = IEEE80211_ELEMID_MESHCONF;
	*frm++ = IEEE80211_MESH_CONF_SZ;
	*frm++ = ms->ms_ppath->mpp_ie;		/* path selection */
	*frm++ = ms->ms_pmetric->mpm_ie;	/* link metric */
	*frm++ = IEEE80211_MESHCONF_CC_DISABLED;
	*frm++ = IEEE80211_MESHCONF_SYNC_NEIGHOFF;
	*frm++ = IEEE80211_MESHCONF_AUTH_DISABLED;
	/* NB: set the number of neighbors before the rest */
	*frm = (ms->ms_neighbors > IEEE80211_MESH_MAX_NEIGHBORS ?
	    IEEE80211_MESH_MAX_NEIGHBORS : ms->ms_neighbors) << 1;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_GATE)
		*frm |= IEEE80211_MESHCONF_FORM_GATE;
	frm += 1;
	caps = 0;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_AP)
		caps |= IEEE80211_MESHCONF_CAP_AP;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_FWD)
		caps |= IEEE80211_MESHCONF_CAP_FWRD;
	*frm++ = caps;
	return frm;
}

/*
 * Add a Mesh Peer Management IE to a frame.
 */
uint8_t *
ieee80211_add_meshpeer(uint8_t *frm, uint8_t subtype, uint16_t localid,
    uint16_t peerid, uint16_t reason)
{

	KASSERT(localid != 0, ("localid == 0"));

	*frm++ = IEEE80211_ELEMID_MESHPEER;
	switch (subtype) {
	case IEEE80211_ACTION_MESHPEERING_OPEN:
		*frm++ = IEEE80211_MPM_BASE_SZ;		/* length */
		ADDSHORT(frm, IEEE80211_MPPID_MPM);	/* proto */
		ADDSHORT(frm, localid);			/* local ID */
		break;
	case IEEE80211_ACTION_MESHPEERING_CONFIRM:
		KASSERT(peerid != 0, ("sending peer confirm without peer id"));
		*frm++ = IEEE80211_MPM_BASE_SZ + 2;	/* length */
		ADDSHORT(frm, IEEE80211_MPPID_MPM);	/* proto */
		ADDSHORT(frm, localid);			/* local ID */
		ADDSHORT(frm, peerid);			/* peer ID */
		break;
	case IEEE80211_ACTION_MESHPEERING_CLOSE:
		if (peerid)
			*frm++ = IEEE80211_MPM_MAX_SZ;	/* length */
		else
			*frm++ = IEEE80211_MPM_BASE_SZ + 2; /* length */
		ADDSHORT(frm, IEEE80211_MPPID_MPM);	/* proto */
		ADDSHORT(frm, localid);	/* local ID */
		if (peerid)
			ADDSHORT(frm, peerid);	/* peer ID */
		ADDSHORT(frm, reason);
		break;
	}
	return frm;
}

/*
 * Compute an Airtime Link Metric for the link with this node.
 *
 * Based on Draft 3.0 spec (11B.10, p.149).
 */
/*
 * Max 802.11s overhead.
 */
#define IEEE80211_MESH_MAXOVERHEAD \
	(sizeof(struct ieee80211_qosframe_addr4) \
	 + sizeof(struct ieee80211_meshcntl_ae10) \
	+ sizeof(struct llc) \
	+ IEEE80211_ADDR_LEN \
	+ IEEE80211_WEP_IVLEN \
	+ IEEE80211_WEP_KIDLEN \
	+ IEEE80211_WEP_CRCLEN \
	+ IEEE80211_WEP_MICLEN \
	+ IEEE80211_CRC_LEN)
uint32_t
mesh_airtime_calc(struct ieee80211_node *ni)
{
#define M_BITS 8
#define S_FACTOR (2 * M_BITS)
	struct ieee80211com *ic = ni->ni_ic;
	struct ifnet *ifp = ni->ni_vap->iv_ifp;
	const static int nbits = 8192 << M_BITS;
	uint32_t overhead, rate, errrate;
	uint64_t res;

	/* Time to transmit a frame */
	rate = ni->ni_txrate;
	overhead = ieee80211_compute_duration(ic->ic_rt,
	    ifp->if_mtu + IEEE80211_MESH_MAXOVERHEAD, rate, 0) << M_BITS;
	/* Error rate in percentage */
	/* XXX assuming small failures are ok */
	errrate = (((ifp->if_get_counter(ifp, IFCOUNTER_OERRORS) +
	    ifp->if_get_counter(ifp, IFCOUNTER_IERRORS)) / 100) << M_BITS)
	    / 100;
	res = (overhead + (nbits / rate)) *
	    ((1 << S_FACTOR) / ((1 << M_BITS) - errrate));

	return (uint32_t)(res >> S_FACTOR);
#undef M_BITS
#undef S_FACTOR
}

/*
 * Add a Mesh Link Metric report IE to a frame.
 */
uint8_t *
ieee80211_add_meshlmetric(uint8_t *frm, uint8_t flags, uint32_t metric)
{
	*frm++ = IEEE80211_ELEMID_MESHLINK;
	*frm++ = 5;
	*frm++ = flags;
	ADDWORD(frm, metric);
	return frm;
}

/*
 * Add a Mesh Gate Announcement IE to a frame.
 */
uint8_t *
ieee80211_add_meshgate(uint8_t *frm, struct ieee80211_meshgann_ie *ie)
{
	*frm++ = IEEE80211_ELEMID_MESHGANN; /* ie */
	*frm++ = IEEE80211_MESHGANN_BASE_SZ; /* len */
	*frm++ = ie->gann_flags;
	*frm++ = ie->gann_hopcount;
	*frm++ = ie->gann_ttl;
	IEEE80211_ADDR_COPY(frm, ie->gann_addr);
	frm += 6;
	ADDWORD(frm, ie->gann_seq);
	ADDSHORT(frm, ie->gann_interval);
	return frm;
}
#undef ADDSHORT
#undef ADDWORD

/*
 * Initialize any mesh-specific node state.
 */
void
ieee80211_mesh_node_init(struct ieee80211vap *vap, struct ieee80211_node *ni)
{
	ni->ni_flags |= IEEE80211_NODE_QOS;
	callout_init(&ni->ni_mltimer, 1);
	callout_init(&ni->ni_mlhtimer, 1);
}

/*
 * Cleanup any mesh-specific node state.
 */
void
ieee80211_mesh_node_cleanup(struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_mesh_state *ms = vap->iv_mesh;

	callout_drain(&ni->ni_mltimer);
	callout_drain(&ni->ni_mlhtimer);
	/* NB: short-circuit callbacks after mesh_vdetach */
	if (vap->iv_mesh != NULL)
		ms->ms_ppath->mpp_peerdown(ni);
}

void
ieee80211_parse_meshid(struct ieee80211_node *ni, const uint8_t *ie)
{
	ni->ni_meshidlen = ie[1];
	memcpy(ni->ni_meshid, ie + 2, ie[1]);
}

/*
 * Setup mesh-specific node state on neighbor discovery.
 */
void
ieee80211_mesh_init_neighbor(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const struct ieee80211_scanparams *sp)
{
	ieee80211_parse_meshid(ni, sp->meshid);
}

void
ieee80211_mesh_update_beacon(struct ieee80211vap *vap,
	struct ieee80211_beacon_offsets *bo)
{
	KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a MBSS vap"));

	if (isset(bo->bo_flags, IEEE80211_BEACON_MESHCONF)) {
		(void)ieee80211_add_meshconf(bo->bo_meshconf, vap);
		clrbit(bo->bo_flags, IEEE80211_BEACON_MESHCONF);
	}
}

static int
mesh_ioctl_get80211(struct ieee80211vap *vap, struct ieee80211req *ireq)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	uint8_t tmpmeshid[IEEE80211_NWID_LEN];
	struct ieee80211_mesh_route *rt;
	struct ieee80211req_mesh_route *imr;
	size_t len, off;
	uint8_t *p;
	int error;

	if (vap->iv_opmode != IEEE80211_M_MBSS)
		return ENOSYS;

	error = 0;
	switch (ireq->i_type) {
	case IEEE80211_IOC_MESH_ID:
		ireq->i_len = ms->ms_idlen;
		memcpy(tmpmeshid, ms->ms_id, ireq->i_len);
		error = copyout(tmpmeshid, ireq->i_data, ireq->i_len);
		break;
	case IEEE80211_IOC_MESH_AP:
		ireq->i_val = (ms->ms_flags & IEEE80211_MESHFLAGS_AP) != 0;
		break;
	case IEEE80211_IOC_MESH_FWRD:
		ireq->i_val = (ms->ms_flags & IEEE80211_MESHFLAGS_FWD) != 0;
		break;
	case IEEE80211_IOC_MESH_GATE:
		ireq->i_val = (ms->ms_flags & IEEE80211_MESHFLAGS_GATE) != 0;
		break;
	case IEEE80211_IOC_MESH_TTL:
		ireq->i_val = ms->ms_ttl;
		break;
	case IEEE80211_IOC_MESH_RTCMD:
		switch (ireq->i_val) {
		case IEEE80211_MESH_RTCMD_LIST:
			len = 0;
			MESH_RT_LOCK(ms);
			TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
				len += sizeof(*imr);
			}
			MESH_RT_UNLOCK(ms);
			if (len > ireq->i_len || ireq->i_len < sizeof(*imr)) {
				ireq->i_len = len;
				return ENOMEM;
			}
			ireq->i_len = len;
			/* XXX M_WAIT? */
			p = IEEE80211_MALLOC(len, M_TEMP,
			    IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
			if (p == NULL)
				return ENOMEM;
			off = 0;
			MESH_RT_LOCK(ms);
			TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
				if (off >= len)
					break;
				imr = (struct ieee80211req_mesh_route *)
				    (p + off);
				IEEE80211_ADDR_COPY(imr->imr_dest,
				    rt->rt_dest);
				IEEE80211_ADDR_COPY(imr->imr_nexthop,
				    rt->rt_nexthop);
				imr->imr_metric = rt->rt_metric;
				imr->imr_nhops = rt->rt_nhops;
				imr->imr_lifetime =
				    ieee80211_mesh_rt_update(rt, 0);
				imr->imr_lastmseq = rt->rt_lastmseq;
				imr->imr_flags = rt->rt_flags; /* last */
				off += sizeof(*imr);
			}
			MESH_RT_UNLOCK(ms);
			error = copyout(p, (uint8_t *)ireq->i_data,
			    ireq->i_len);
			IEEE80211_FREE(p, M_TEMP);
			break;
		case IEEE80211_MESH_RTCMD_FLUSH:
		case IEEE80211_MESH_RTCMD_ADD:
		case IEEE80211_MESH_RTCMD_DELETE:
			return EINVAL;
		default:
			return ENOSYS;
		}
		break;
	case IEEE80211_IOC_MESH_PR_METRIC:
		len = strlen(ms->ms_pmetric->mpm_descr);
		if (ireq->i_len < len)
			return EINVAL;
		ireq->i_len = len;
		error = copyout(ms->ms_pmetric->mpm_descr,
		    (uint8_t *)ireq->i_data, len);
		break;
	case IEEE80211_IOC_MESH_PR_PATH:
		len = strlen(ms->ms_ppath->mpp_descr);
		if (ireq->i_len < len)
			return EINVAL;
		ireq->i_len = len;
		error = copyout(ms->ms_ppath->mpp_descr,
		    (uint8_t *)ireq->i_data, len);
		break;
	default:
		return ENOSYS;
	}

	return error;
}
IEEE80211_IOCTL_GET(mesh, mesh_ioctl_get80211);

static int
mesh_ioctl_set80211(struct ieee80211vap *vap, struct ieee80211req *ireq)
{
	struct ieee80211_mesh_state *ms = vap->iv_mesh;
	uint8_t tmpmeshid[IEEE80211_NWID_LEN];
	uint8_t tmpaddr[IEEE80211_ADDR_LEN];
	char tmpproto[IEEE80211_MESH_PROTO_DSZ];
	int error;

	if (vap->iv_opmode != IEEE80211_M_MBSS)
		return ENOSYS;

	error = 0;
	switch (ireq->i_type) {
	case IEEE80211_IOC_MESH_ID:
		if (ireq->i_val != 0 || ireq->i_len > IEEE80211_MESHID_LEN)
			return EINVAL;
		error = copyin(ireq->i_data, tmpmeshid, ireq->i_len);
		if (error != 0)
			break;
		memset(ms->ms_id, 0, IEEE80211_NWID_LEN);
		ms->ms_idlen = ireq->i_len;
		memcpy(ms->ms_id, tmpmeshid, ireq->i_len);
		error = ENETRESET;
		break;
	case IEEE80211_IOC_MESH_AP:
		if (ireq->i_val)
			ms->ms_flags |= IEEE80211_MESHFLAGS_AP;
		else
			ms->ms_flags &= ~IEEE80211_MESHFLAGS_AP;
		error = ENETRESET;
		break;
	case IEEE80211_IOC_MESH_FWRD:
		if (ireq->i_val)
			ms->ms_flags |= IEEE80211_MESHFLAGS_FWD;
		else
			ms->ms_flags &= ~IEEE80211_MESHFLAGS_FWD;
		mesh_gatemode_setup(vap);
		break;
	case IEEE80211_IOC_MESH_GATE:
		if (ireq->i_val)
			ms->ms_flags |= IEEE80211_MESHFLAGS_GATE;
		else
			ms->ms_flags &= ~IEEE80211_MESHFLAGS_GATE;
		break;
	case IEEE80211_IOC_MESH_TTL:
		ms->ms_ttl = (uint8_t) ireq->i_val;
		break;
	case IEEE80211_IOC_MESH_RTCMD:
		switch (ireq->i_val) {
		case IEEE80211_MESH_RTCMD_LIST:
			return EINVAL;
		case IEEE80211_MESH_RTCMD_FLUSH:
			ieee80211_mesh_rt_flush(vap);
			break;
		case IEEE80211_MESH_RTCMD_ADD:
			if (IEEE80211_ADDR_EQ(vap->iv_myaddr, ireq->i_data) ||
			    IEEE80211_ADDR_EQ(broadcastaddr, ireq->i_data))
				return EINVAL;
			error = copyin(ireq->i_data, &tmpaddr,
			    IEEE80211_ADDR_LEN);
			if (error == 0)
				ieee80211_mesh_discover(vap, tmpaddr, NULL);
			break;
		case IEEE80211_MESH_RTCMD_DELETE:
			ieee80211_mesh_rt_del(vap, ireq->i_data);
			break;
		default:
			return ENOSYS;
		}
		break;
	case IEEE80211_IOC_MESH_PR_METRIC:
		error = copyin(ireq->i_data, tmpproto, sizeof(tmpproto));
		if (error == 0) {
			error = mesh_select_proto_metric(vap, tmpproto);
			if (error == 0)
				error = ENETRESET;
		}
		break;
	case IEEE80211_IOC_MESH_PR_PATH:
		error = copyin(ireq->i_data, tmpproto, sizeof(tmpproto));
		if (error == 0) {
			error = mesh_select_proto_path(vap, tmpproto);
			if (error == 0)
				error = ENETRESET;
		}
		break;
	default:
		return ENOSYS;
	}
	return error;
}
IEEE80211_IOCTL_SET(mesh, mesh_ioctl_set80211);