summaryrefslogtreecommitdiffstats
path: root/freebsd/sys/net80211/ieee80211_mesh.c
blob: cd2ddb949c771ecbe81100330a26374cd5b99b27 (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
#include <machine/rtems-bsd-kernel-space.h>

/*- 
 * 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 <rtems/bsd/local/opt_inet.h>
#include <rtems/bsd/local/opt_wlan.h>

#include <rtems/bsd/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 <rtems/bsd/sys/errno.h>
#include <sys/proc.h>
#include <sys/sysctl.h>

#include <net/if.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>
#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_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 struct ieee80211_node *
		mesh_find_txnode(struct ieee80211vap *,
		    const uint8_t [IEEE80211_ADDR_LEN]);
static void	mesh_forward(struct ieee80211vap *, struct mbuf *,
		    const struct ieee80211_meshcntl *);
static int	mesh_input(struct ieee80211_node *, struct mbuf *, int, int);
static void	mesh_recv_mgmt(struct ieee80211_node *, struct mbuf *, int,
		    int, 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.
 */
SYSCTL_NODE(_net_wlan, OID_AUTO, mesh, CTLFLAG_RD, 0,
    "IEEE 802.11s parameters");
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_maxretries = 2;
SYSCTL_INT(_net_wlan_mesh, OID_AUTO, maxretries, CTLTYPE_INT | CTLFLAG_RW,
    &ieee80211_mesh_maxretries, 0,
    "Maximum retries 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_req;
static	ieee80211_recv_action_func mesh_recv_action_meshlmetric_rep;

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_meshlink_request;
static	ieee80211_send_action_func mesh_send_action_meshlink_reply;

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];

#define	MESH_RT_LOCK(ms)	mtx_lock(&(ms)->ms_rt_lock)
#define	MESH_RT_LOCK_ASSERT(ms)	mtx_assert(&(ms)->ms_rt_lock, MA_OWNED)
#define	MESH_RT_UNLOCK(ms)	mtx_unlock(&(ms)->ms_rt_lock)

MALLOC_DEFINE(M_80211_MESH_RT, "80211mesh", "802.11s routing 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 ieee80211_mesh_state *ms,
    const uint8_t dest[IEEE80211_ADDR_LEN])
{
	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 = malloc(ALIGN(sizeof(struct ieee80211_mesh_route)) +
	    ms->ms_ppath->mpp_privlen, M_80211_MESH_RT, M_NOWAIT | M_ZERO);
	if (rt != NULL) {
		IEEE80211_ADDR_COPY(rt->rt_dest, dest);
		rt->rt_priv = (void *)ALIGN(&rt[1]);
		rt->rt_crtime = ticks;
		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(ms, dest);
	MESH_RT_UNLOCK(ms);
	return rt;
}

/*
 * 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(ms, 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_nexthop, vap->iv_myaddr);
			rt->rt_flags |= IEEE80211_MESHRT_FLAGS_VALID
				     |  IEEE80211_MESHRT_FLAGS_PROXY;
		}
	/* XXX assert PROXY? */
	} else if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0) {
		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);
	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)) {
			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) {
		if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0 &&
		    ticks - rt->rt_crtime >= ms->ms_ppath->mpp_inact)
			mesh_rt_del(ms, rt);
	}
	MESH_RT_UNLOCK(ms);
}

#define	N(a)	(sizeof(a) / sizeof(a[0]))
int
ieee80211_mesh_register_proto_path(const struct ieee80211_mesh_proto_path *mpp)
{
	int i, firstempty = -1;

	for (i = 0; i < N(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 < N(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 < N(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 < N(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;
}
#undef	N

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_retrytimeout = msecs_to_ticks(40);
	ieee80211_mesh_holdingtimeout = msecs_to_ticks(40);
	ieee80211_mesh_confirmtimeout = msecs_to_ticks(40);

	/*
	 * Register action frame handlers.
	 */
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESHPEERING,
	    IEEE80211_ACTION_MESHPEERING_OPEN,
	    mesh_recv_action_meshpeering_open);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESHPEERING,
	    IEEE80211_ACTION_MESHPEERING_CONFIRM,
	    mesh_recv_action_meshpeering_confirm);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESHPEERING,
	    IEEE80211_ACTION_MESHPEERING_CLOSE,
	    mesh_recv_action_meshpeering_close);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESHLMETRIC,
	    IEEE80211_ACTION_MESHLMETRIC_REQ, mesh_recv_action_meshlmetric_req);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESHLMETRIC,
	    IEEE80211_ACTION_MESHLMETRIC_REP, mesh_recv_action_meshlmetric_rep);

	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESHPEERING, 
	    IEEE80211_ACTION_MESHPEERING_OPEN,
	    mesh_send_action_meshpeering_open);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESHPEERING, 
	    IEEE80211_ACTION_MESHPEERING_CONFIRM,
	    mesh_send_action_meshpeering_confirm);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESHPEERING, 
	    IEEE80211_ACTION_MESHPEERING_CLOSE,
	    mesh_send_action_meshpeering_close);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESHLMETRIC, 
	    IEEE80211_ACTION_MESHLMETRIC_REQ,
	    mesh_send_action_meshlink_request);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESHLMETRIC, 
	    IEEE80211_ACTION_MESHLMETRIC_REP,
	    mesh_send_action_meshlink_reply);

	/*
	 * 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_MESHPEERING,
		    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);
	mtx_destroy(&ms->ms_rt_lock);
	ms->ms_ppath->mpp_vdetach(vap);
	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;
	ms = malloc(sizeof(struct ieee80211_mesh_state), M_80211_VAP,
	    M_NOWAIT | 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_routes);
	mtx_init(&ms->ms_rt_lock, "MBSS", "802.11s routing table", MTX_DEF);
	callout_init(&ms->ms_cleantimer, CALLOUT_MPSAFE);
	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);
	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(vap->iv_bss,
			    ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
				ieee80211_htchanflags(vap->iv_bss->ni_chan)));
			/* XXX bypass debug msgs */
			break;
		case IEEE80211_S_SCAN:
		case IEEE80211_S_RUN:
#ifdef IEEE80211_DEBUG
			if (ieee80211_msg_debug(vap)) {
				struct ieee80211_node *ni = vap->iv_bss;
				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(vap->iv_bss);
		callout_reset(&ms->ms_cleantimer, ms->ms_ppath->mpp_inact,
                    mesh_rt_cleanup_cb, 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);
}


/*
 * 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.
 */
static struct ieee80211_node *
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 ||
	    (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY)) {
		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
		    "%s: !valid or proxy, flags 0x%x", __func__, rt->rt_flags);
		/* XXX stat */
		return NULL;
	}
	return ieee80211_find_txnode(vap, rt->rt_nexthop);
}

/*
 * 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;
	struct ifnet *parent = ic->ic_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;

	if (mc->mc_ttl == 0) {
		IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
		    "%s", "frame not fwd'd, ttl 0");
		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_DONTWAIT);
	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++;
		ifp->if_oerrors++;
		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++;
		ifp->if_oerrors++;
		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 = mesh_find_txnode(vap, whcopy->i_addr3);
		if (ni == NULL) {
			IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
			    "%s", "frame not fwd'd, no path");
			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? */
	mcopy->m_pkthdr.rcvif = (void *) ni;
	err = parent->if_transmit(parent, mcopy);
	if (err != 0) {
		/* NB: IFQ_HANDOFF reclaims mbuf */
		ieee80211_free_node(ni);
	} else {
		ifp->if_opackets++;
	}
}

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)
	uint8_t b[sizeof(struct ieee80211_qosframe_addr4) +
		  sizeof(struct ieee80211_meshcntl_ae11)];
	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 & 3;
	if (WHDIR(wh) == IEEE80211_FC1_DIR_FROMDS) {
		IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr1);
		if (ae == 0) {
			IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr3);
		} else if (ae == 1) {
			IEEE80211_ADDR_COPY(eh->ether_shost, 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 == 0) {
			IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr3);
			IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr4);
		} else if (ae == 2) {
			IEEE80211_ADDR_COPY(eh->ether_dhost, mc->mc_addr4);
			IEEE80211_ADDR_COPY(eh->ether_shost, mc->mc_addr5);
		} 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;
		}
	}
#ifdef ALIGNED_POINTER
	if (!ALIGNED_POINTER(mtod(m, caddr_t) + sizeof(*eh), uint32_t)) {
		m = ieee80211_realign(vap, m, sizeof(*eh));
		if (m == NULL)
			return NULL;
	}
#endif /* ALIGNED_POINTER */
	if (llc != NULL) {
		eh = mtod(m, struct ether_header *);
		eh->ether_type = htons(m->m_pkthdr.len - sizeof(*eh));
	}
	return m;
#undef WDIR
}

/*
 * 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 == 0 || ae == 2, ("bad AE %d", ae));
	if (ae == 2) {				/* 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_addr4);
		/* 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);
}

static int
mesh_input(struct ieee80211_node *ni, struct mbuf *m, int rssi, int nf)
{
#define	SEQ_LEQ(a,b)	((int)((a)-(b)) <= 0)
#define	HAS_SEQ(type)	((type & 0x4) == 0)
	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;
	uint8_t dir, type, subtype, qos;
	uint32_t seq;
	uint8_t *addr;
	ieee80211_seq rxseq;

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

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

	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++;
			rxseq = le16toh(*(uint16_t *)wh->i_seq);
			if ((ni->ni_flags & IEEE80211_NODE_HT) == 0 &&
			    (wh->i_fc[1] & IEEE80211_FC1_RETRY) &&
			    SEQ_LEQ(rxseq, ni->ni_rxseqs[tid])) {
				/* duplicate, discard */
				IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
				    wh->i_addr1, "duplicate",
				    "seqno <%u,%u> fragno <%u,%u> tid %u",
				    rxseq >> IEEE80211_SEQ_SEQ_SHIFT,
				    ni->ni_rxseqs[tid] >>
				    IEEE80211_SEQ_SEQ_SHIFT,
				    rxseq & IEEE80211_SEQ_FRAG_MASK,
				    ni->ni_rxseqs[tid] &
				    IEEE80211_SEQ_FRAG_MASK,
				    tid);
				vap->iv_stats.is_rx_dup++;
				IEEE80211_NODE_STAT(ni, rx_dup);
				goto out;
			}
			ni->ni_rxseqs[tid] = rxseq;
		}
	}
#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->i_addr2)) {
		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;
		}
		/* pull up enough to get to the mesh control */
		hdrspace = ieee80211_hdrspace(ic, wh);
		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);
		meshdrlen = sizeof(struct ieee80211_meshcntl) +
		    (mc->mc_flags & 3) * IEEE80211_ADDR_LEN;
		hdrspace += meshdrlen;
		seq = LE_READ_4(mc->mc_seq);
		if (IEEE80211_IS_MULTICAST(wh->i_addr1))
			addr = wh->i_addr3;
		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;
		}

		/*
		 * Potentially forward packet.  See table s36 (p140)
		 * for the rules.  XXX tap fwd'd packets not for us?
		 */
		if (dir == IEEE80211_FC1_DIR_FROMDS ||
		    !mesh_isucastforme(vap, wh, mc)) {
			mesh_forward(vap, m, mc);
			if (dir == IEEE80211_FC1_DIR_DSTODS)
				goto out;
			/* NB: fall thru to deliver mcast frames locally */
		}

		/*
		 * Save QoS bits for use below--before we strip the header.
		 */
		if (subtype == IEEE80211_FC0_SUBTYPE_QOS) {
			qos = (dir == IEEE80211_FC1_DIR_DSTODS) ?
			    ((struct ieee80211_qosframe_addr4 *)wh)->i_qos[0] :
			    ((struct ieee80211_qosframe *)wh)->i_qos[0];
		} else
			qos = 0;
		/*
		 * Next up, any fragmentation.
		 */
		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 = NULL;		/* no longer valid, catch any uses */

		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 & 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 >>
			    IEEE80211_FC0_SUBTYPE_SHIFT],
			    ether_sprintf(wh->i_addr2), rssi);
		}
#endif
		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
			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, 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:
	ifp->if_ierrors++;
out:
	if (m != NULL) {
		if (need_tap && ieee80211_radiotap_active_vap(vap))
			ieee80211_radiotap_rx(vap, m);
		m_freem(m);
	}
	return type;
}

static void
mesh_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m0, int subtype,
    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_frame *wh;
	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;
		/*
		 * We process beacon/probe response
		 * frames to discover neighbors.
		 */
		if (ieee80211_parse_beacon(ni, m0, &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, &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->i_addr2)) {
			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.
		 * XXX backoff on repeated failure
		 */
		if (ni != vap->iv_bss &&
		    (ms->ms_flags & IEEE80211_MESHFLAGS_AP) &&
		    ni->ni_mlstate == IEEE80211_NODE_MESH_IDLE) {
			uint16_t args[1];

			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_MESHPEERING,
			    IEEE80211_ACTION_MESHPEERING_OPEN, args);
			ni->ni_mlrcnt = 0;
			mesh_peer_timeout_setup(ni);
		}
		break;
	}
	case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
	{
		uint8_t *ssid, *meshid, *rates, *xrates;
		uint8_t *sfrm;

		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;
		sfrm = frm;
		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:
		if (vap->iv_state != IEEE80211_S_RUN) {
			vap->iv_stats.is_rx_mgtdiscard++;
			break;
		}
		/*
		 * We received an action for an unknown neighbor.
		 * XXX: wait for it to beacon or create ieee80211_node?
		 */
		if (ni == vap->iv_bss) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_MESH,
			    wh, NULL, "%s", "unknown node");
			vap->iv_stats.is_rx_mgtdiscard++;
			break;
		}
		/*
		 * Discard if not for us.
		 */
		if (!IEEE80211_ADDR_EQ(vap->iv_myaddr, wh->i_addr1) &&
		    !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
			IEEE80211_DISCARD(vap, IEEE80211_MSG_MESH,
			    wh, NULL, "%s", "not for me");
			vap->iv_stats.is_rx_mgtdiscard++;
			break;
		}
		/* XXX parse_action is a bit useless now */
		if (ieee80211_parse_action(ni, m0) == 0)
			ic->ic_recv_action(ni, wh, frm, efrm);
		break;
	case IEEE80211_FC0_SUBTYPE_AUTH:
	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
	case IEEE80211_FC0_SUBTYPE_DEAUTH:
	case IEEE80211_FC0_SUBTYPE_DISASSOC:
		IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
		    wh, NULL, "%s", "not handled");
		vap->iv_stats.is_rx_mgtdiscard++;
		return;
	default:
		IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
		    wh, "mgt", "subtype 0x%x not handled", subtype);
		vap->iv_stats.is_rx_badsubtype++;
		break;
	}
}

/*
 * Parse meshpeering action ie's for open+confirm frames; the
 * important bits are returned in the supplied structure.
 */
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;
	const uint8_t *meshid, *meshconf, *meshpeer;

	meshid = meshconf = meshpeer = 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:
			meshpeer = frm;
			mpie = (const struct ieee80211_meshpeer_ie *) frm;
			memset(mp, 0, sizeof(*mp));
			mp->peer_llinkid = LE_READ_2(&mpie->peer_llinkid);
			/* NB: peer link ID is optional on these frames */
			if (subtype == IEEE80211_MESH_PEER_LINK_CLOSE &&
			    mpie->peer_len == 8) {
				mp->peer_linkid = 0;
				mp->peer_rcode = LE_READ_2(&mpie->peer_linkid);
			} else {
				mp->peer_linkid = LE_READ_2(&mpie->peer_linkid);
				mp->peer_rcode = LE_READ_2(&mpie->peer_rcode);
			}
			break;
		}
		frm += frm[1] + 2;
	}

	/*
	 * Verify the contents of the frame. Action frames with
	 * close subtype don't have a Mesh Configuration IE.
	 * If if fails validation, close the peer link.
	 */
	KASSERT(meshpeer != NULL &&
	    subtype != IEEE80211_ACTION_MESHPEERING_CLOSE,
	    ("parsing close action"));

	if (mesh_verify_meshid(vap, meshid) ||
	    mesh_verify_meshpeer(vap, subtype, meshpeer) ||
	    mesh_verify_meshconf(vap, meshconf)) {
		uint16_t args[3];

		IEEE80211_DISCARD(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
		    wh, NULL, "%s", "not for our mesh");
		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;
			args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_MESHPEERING,
			    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_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:
		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_MESHPEERING,
		    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_MESHPEERING,
		    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_MESHPEERING,
			    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_MESHPEERING,
		    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_MESHPEERING,
		    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_MESHPEERING,
			    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_MESHPEERING,
		    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_MESHPEERING,
			    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_MESHPEERING,
		    IEEE80211_ACTION_MESHPEERING_CONFIRM,
		    args);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		args[0] = ni->ni_mlpid;
		args[1] = meshpeer->peer_llinkid;
		args[2] = IEEE80211_REASON_MESH_MAX_RETRIES;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_MESHPEERING,
		    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);
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		args[0] = ni->ni_mlpid;
		args[1] = meshpeer->peer_llinkid;
		args[2] = IEEE80211_REASON_MESH_MAX_RETRIES;
		ieee80211_send_action(ni,
		    IEEE80211_ACTION_CAT_MESHPEERING,
		    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_MESHPEERING,
			    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)
{
	uint16_t args[3];

	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_MESHPEERING,
		    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_setup(ni);
		break;
	}
	return 0;
}

/*
 * Link Metric handling.
 */
static int
mesh_recv_action_meshlmetric_req(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	uint32_t metric;

	metric = mesh_airtime_calc(ni);
	ieee80211_send_action(ni,
	    IEEE80211_ACTION_CAT_MESHLMETRIC,
	    IEEE80211_ACTION_MESHLMETRIC_REP,
	    &metric);
	return 0;
}

static int
mesh_recv_action_meshlmetric_rep(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	return 0;
}

static int
mesh_send_action(struct ieee80211_node *ni, struct mbuf *m)
{
	struct ieee80211_bpf_params params;

	memset(&params, 0, sizeof(params));
	params.ibp_pri = WME_AC_VO;
	params.ibp_rate0 = ni->ni_txparms->mgmtrate;
	/* XXX ucast/mcast */
	params.ibp_try0 = ni->ni_txparms->maxretry;
	params.ibp_power = ni->ni_txpower;
	return ieee80211_mgmt_output(ni, m, IEEE80211_FC0_SUBTYPE_ACTION,
	     &params);
}

#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_MESH_PEER_LINK_OPEN,
		    args[0], 0, 0);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, 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_MESH_PEER_LINK_CONFIRM,
		    args[0], args[1], 0);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, 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",
	    args[0], args[1], 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
		 *   [2] reason code
		 *   [tlv] mesh id
		 *   [tlv] mesh peer link mgmt
		 */
		*frm++ = category;
		*frm++ = action;
		ADDSHORT(frm, args[2]);		/* reason code */
		frm = ieee80211_add_meshid(frm, vap);
		frm = ieee80211_add_meshpeer(frm,
		    IEEE80211_MESH_PEER_LINK_CLOSE,
		    args[0], args[1], args[2]);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

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

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "%s", "send LINK METRIC REQUEST action");

	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 */
	);
	if (m != NULL) {
		/*
		 * mesh link metric request
		 *   [1] category
		 *   [1] action
		 */
		*frm++ = category;
		*frm++ = action;
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

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

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
	    "send LINK METRIC REPLY action: metric 0x%x", *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 reply
		 *   [1] category
		 *   [1] action
		 *   [tlv] mesh link metric
		 */
		*frm++ = category;
		*frm++ = action;
		frm = ieee80211_add_meshlmetric(frm, *metric);
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return mesh_send_action(ni, 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);
}

/*
 * 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_MESHPEERING,
			    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_MESHPEERING,
			    IEEE80211_ACTION_MESHPEERING_OPEN, args);
			ni->ni_mlrcnt++;
			mesh_peer_timeout_backoff(ni);
		}
		break;
	case IEEE80211_NODE_MESH_CONFIRMRCV:
		if (ni->ni_mlrcnt == ieee80211_mesh_maxretries) {
			args[0] = ni->ni_mlpid;
			args[2] = IEEE80211_REASON_MESH_CONFIRM_TIMEOUT;
			ieee80211_send_action(ni,
			    IEEE80211_ACTION_CAT_MESHPEERING,
			    IEEE80211_ACTION_MESHPEERING_CLOSE, args);
			ni->ni_mlrcnt = 0;
			mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
			mesh_peer_timeout_setup(ni);
		} else {
			ni->ni_mlrcnt++;
			mesh_peer_timeout_setup(ni);
		}
		break;
	case IEEE80211_NODE_MESH_HOLDING:
		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 < 6 ||
	    meshpeer->peer_len > 10)
		return 1;
	switch (subtype) {
	case IEEE80211_MESH_PEER_LINK_OPEN:
		if (meshpeer->peer_len != 6)
			return 1;
		break;
	case IEEE80211_MESH_PEER_LINK_CONFIRM:
		if (meshpeer->peer_len != 8)
			return 1;
		break;
	case IEEE80211_MESH_PEER_LINK_CLOSE:
		if (meshpeer->peer_len < 8)
			return 1;
		if (meshpeer->peer_len == 8 && 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;

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

	*frm++ = IEEE80211_ELEMID_MESHCONF;
	*frm++ = sizeof(struct ieee80211_meshconf_ie) - 2;
	*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 > 15 ? 15 : ms->ms_neighbors) << 1;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_PORTAL)
		*frm |= IEEE80211_MESHCONF_FORM_MP;
	frm += 1;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_AP)
		*frm |= IEEE80211_MESHCONF_CAP_AP;
	if (ms->ms_flags & IEEE80211_MESHFLAGS_FWD)
		*frm |= IEEE80211_MESHCONF_CAP_FWRD;
	frm += 1;
	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)
{
	/* XXX change for AH */
	static const uint8_t meshpeerproto[4] = IEEE80211_MESH_PEER_PROTO;

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

	*frm++ = IEEE80211_ELEMID_MESHPEER;
	switch (subtype) {
	case IEEE80211_MESH_PEER_LINK_OPEN:
		*frm++ = 6;		/* length */
		memcpy(frm, meshpeerproto, 4);
		frm += 4;
		ADDSHORT(frm, localid);	/* local ID */
		break;
	case IEEE80211_MESH_PEER_LINK_CONFIRM:
		KASSERT(peerid != 0, ("sending peer confirm without peer id"));
		*frm++ = 8;		/* length */
		memcpy(frm, meshpeerproto, 4);
		frm += 4;
		ADDSHORT(frm, localid);	/* local ID */
		ADDSHORT(frm, peerid);	/* peer ID */
		break;
	case IEEE80211_MESH_PEER_LINK_CLOSE:
		if (peerid)
			*frm++ = 10;	/* length */
		else
			*frm++ = 8;	/* length */
		memcpy(frm, meshpeerproto, 4);
		frm += 4;
		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_ae11) \
	+ 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_oerrors +
	    ifp->if_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, uint32_t metric)
{
	*frm++ = IEEE80211_ELEMID_MESHLINK;
	*frm++ = 4;
	ADDWORD(frm, metric);
	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, CALLOUT_MPSAFE);
}

/*
 * 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);
	/* 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_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 = malloc(len, M_TEMP, M_NOWAIT | 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);
				imr->imr_flags = rt->rt_flags;
				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 = rt->rt_lifetime;
				imr->imr_lastmseq = rt->rt_lastmseq;
				off += sizeof(*imr);
			}
			MESH_RT_UNLOCK(ms);
			error = copyout(p, (uint8_t *)ireq->i_data,
			    ireq->i_len);
			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;
		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);