DragonFlyBSD Kernel Audit
sys/netproto/802_11/wlan/ieee80211_ht.c
← back
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
/*-
 * Copyright (c) 2007-2008 Sam Leffler, Errno Consulting
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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.11n protocol support.
 */

#include "opt_inet.h"
#include "opt_wlan.h"

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

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

#include <netproto/802_11/ieee80211_var.h>
#include <netproto/802_11/ieee80211_action.h>
#include <netproto/802_11/ieee80211_input.h>

/* define here, used throughout file */
#define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
#define	SM(_v, _f)	(((_v) << _f##_S) & _f)

const struct ieee80211_mcs_rates ieee80211_htrates[IEEE80211_HTRATE_MAXSIZE] = {
	{  13,  14,   27,   30 },	/* MCS 0 */
	{  26,  29,   54,   60 },	/* MCS 1 */
	{  39,  43,   81,   90 },	/* MCS 2 */
	{  52,  58,  108,  120 },	/* MCS 3 */
	{  78,  87,  162,  180 },	/* MCS 4 */
	{ 104, 116,  216,  240 },	/* MCS 5 */
	{ 117, 130,  243,  270 },	/* MCS 6 */
	{ 130, 144,  270,  300 },	/* MCS 7 */
	{  26,  29,   54,   60 },	/* MCS 8 */
	{  52,  58,  108,  120 },	/* MCS 9 */
	{  78,  87,  162,  180 },	/* MCS 10 */
	{ 104, 116,  216,  240 },	/* MCS 11 */
	{ 156, 173,  324,  360 },	/* MCS 12 */
	{ 208, 231,  432,  480 },	/* MCS 13 */
	{ 234, 260,  486,  540 },	/* MCS 14 */
	{ 260, 289,  540,  600 },	/* MCS 15 */
	{  39,  43,   81,   90 },	/* MCS 16 */
	{  78,  87,  162,  180 },	/* MCS 17 */
	{ 117, 130,  243,  270 },	/* MCS 18 */
	{ 156, 173,  324,  360 },	/* MCS 19 */
	{ 234, 260,  486,  540 },	/* MCS 20 */
	{ 312, 347,  648,  720 },	/* MCS 21 */
	{ 351, 390,  729,  810 },	/* MCS 22 */
	{ 390, 433,  810,  900 },	/* MCS 23 */
	{  52,  58,  108,  120 },	/* MCS 24 */
	{ 104, 116,  216,  240 },	/* MCS 25 */
	{ 156, 173,  324,  360 },	/* MCS 26 */
	{ 208, 231,  432,  480 },	/* MCS 27 */
	{ 312, 347,  648,  720 },	/* MCS 28 */
	{ 416, 462,  864,  960 },	/* MCS 29 */
	{ 468, 520,  972, 1080 },	/* MCS 30 */
	{ 520, 578, 1080, 1200 },	/* MCS 31 */
	{   0,   0,   12,   13 },	/* MCS 32 */
	{  78,  87,  162,  180 },	/* MCS 33 */
	{ 104, 116,  216,  240 },	/* MCS 34 */
	{ 130, 144,  270,  300 },	/* MCS 35 */
	{ 117, 130,  243,  270 },	/* MCS 36 */
	{ 156, 173,  324,  360 },	/* MCS 37 */
	{ 195, 217,  405,  450 },	/* MCS 38 */
	{ 104, 116,  216,  240 },	/* MCS 39 */
	{ 130, 144,  270,  300 },	/* MCS 40 */
	{ 130, 144,  270,  300 },	/* MCS 41 */
	{ 156, 173,  324,  360 },	/* MCS 42 */
	{ 182, 202,  378,  420 },	/* MCS 43 */
	{ 182, 202,  378,  420 },	/* MCS 44 */
	{ 208, 231,  432,  480 },	/* MCS 45 */
	{ 156, 173,  324,  360 },	/* MCS 46 */
	{ 195, 217,  405,  450 },	/* MCS 47 */
	{ 195, 217,  405,  450 },	/* MCS 48 */
	{ 234, 260,  486,  540 },	/* MCS 49 */
	{ 273, 303,  567,  630 },	/* MCS 50 */
	{ 273, 303,  567,  630 },	/* MCS 51 */
	{ 312, 347,  648,  720 },	/* MCS 52 */
	{ 130, 144,  270,  300 },	/* MCS 53 */
	{ 156, 173,  324,  360 },	/* MCS 54 */
	{ 182, 202,  378,  420 },	/* MCS 55 */
	{ 156, 173,  324,  360 },	/* MCS 56 */
	{ 182, 202,  378,  420 },	/* MCS 57 */
	{ 208, 231,  432,  480 },	/* MCS 58 */
	{ 234, 260,  486,  540 },	/* MCS 59 */
	{ 208, 231,  432,  480 },	/* MCS 60 */
	{ 234, 260,  486,  540 },	/* MCS 61 */
	{ 260, 289,  540,  600 },	/* MCS 62 */
	{ 260, 289,  540,  600 },	/* MCS 63 */
	{ 286, 318,  594,  660 },	/* MCS 64 */
	{ 195, 217,  405,  450 },	/* MCS 65 */
	{ 234, 260,  486,  540 },	/* MCS 66 */
	{ 273, 303,  567,  630 },	/* MCS 67 */
	{ 234, 260,  486,  540 },	/* MCS 68 */
	{ 273, 303,  567,  630 },	/* MCS 69 */
	{ 312, 347,  648,  720 },	/* MCS 70 */
	{ 351, 390,  729,  810 },	/* MCS 71 */
	{ 312, 347,  648,  720 },	/* MCS 72 */
	{ 351, 390,  729,  810 },	/* MCS 73 */
	{ 390, 433,  810,  900 },	/* MCS 74 */
	{ 390, 433,  810,  900 },	/* MCS 75 */
	{ 429, 477,  891,  990 },	/* MCS 76 */
};

static	int ieee80211_ampdu_age = -1;	/* threshold for ampdu reorder q (ms) */
SYSCTL_PROC(_net_wlan, OID_AUTO, ampdu_age, CTLTYPE_INT | CTLFLAG_RW,
	&ieee80211_ampdu_age, 0, ieee80211_sysctl_msecs_ticks, "I",
	"AMPDU max reorder age (ms)");

static	int ieee80211_recv_bar_ena = 1;
SYSCTL_INT(_net_wlan, OID_AUTO, recv_bar, CTLFLAG_RW, &ieee80211_recv_bar_ena,
	    0, "BAR frame processing (ena/dis)");

static	int ieee80211_addba_timeout = -1;/* timeout for ADDBA response */
SYSCTL_PROC(_net_wlan, OID_AUTO, addba_timeout, CTLTYPE_INT | CTLFLAG_RW,
	&ieee80211_addba_timeout, 0, ieee80211_sysctl_msecs_ticks, "I",
	"ADDBA request timeout (ms)");
static	int ieee80211_addba_backoff = -1;/* backoff after max ADDBA requests */
SYSCTL_PROC(_net_wlan, OID_AUTO, addba_backoff, CTLTYPE_INT | CTLFLAG_RW,
	&ieee80211_addba_backoff, 0, ieee80211_sysctl_msecs_ticks, "I",
	"ADDBA request backoff (ms)");
static	int ieee80211_addba_maxtries = 3;/* max ADDBA requests before backoff */
SYSCTL_INT(_net_wlan, OID_AUTO, addba_maxtries, CTLFLAG_RW,
	&ieee80211_addba_maxtries, 0, "max ADDBA requests sent before backoff");

static	int ieee80211_bar_timeout = -1;	/* timeout waiting for BAR response */
static	int ieee80211_bar_maxtries = 50;/* max BAR requests before DELBA */

static	ieee80211_recv_action_func ht_recv_action_ba_addba_request;
static	ieee80211_recv_action_func ht_recv_action_ba_addba_response;
static	ieee80211_recv_action_func ht_recv_action_ba_delba;
static	ieee80211_recv_action_func ht_recv_action_ht_mimopwrsave;
static	ieee80211_recv_action_func ht_recv_action_ht_txchwidth;

static	ieee80211_send_action_func ht_send_action_ba_addba;
static	ieee80211_send_action_func ht_send_action_ba_delba;
static	ieee80211_send_action_func ht_send_action_ht_txchwidth;

static void
ieee80211_ht_init(void)
{
	/*
	 * Setup HT parameters that depends on the clock frequency.
	 */
	ieee80211_ampdu_age = msecs_to_ticks(500);
	ieee80211_addba_timeout = msecs_to_ticks(250);
	ieee80211_addba_backoff = msecs_to_ticks(10*1000);
	ieee80211_bar_timeout = msecs_to_ticks(250);
	/*
	 * Register action frame handlers.
	 */
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_ADDBA_REQUEST, ht_recv_action_ba_addba_request);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_ADDBA_RESPONSE, ht_recv_action_ba_addba_response);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_DELBA, ht_recv_action_ba_delba);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_HT, 
	    IEEE80211_ACTION_HT_MIMOPWRSAVE, ht_recv_action_ht_mimopwrsave);
	ieee80211_recv_action_register(IEEE80211_ACTION_CAT_HT, 
	    IEEE80211_ACTION_HT_TXCHWIDTH, ht_recv_action_ht_txchwidth);

	ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_ADDBA_REQUEST, ht_send_action_ba_addba);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_ADDBA_RESPONSE, ht_send_action_ba_addba);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
	    IEEE80211_ACTION_BA_DELBA, ht_send_action_ba_delba);
	ieee80211_send_action_register(IEEE80211_ACTION_CAT_HT, 
	    IEEE80211_ACTION_HT_TXCHWIDTH, ht_send_action_ht_txchwidth);
}
SYSINIT(wlan_ht, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_ht_init, NULL);

static int ieee80211_ampdu_enable(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap);
static int ieee80211_addba_request(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap,
	int dialogtoken, int baparamset, int batimeout);
static int ieee80211_addba_response(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap,
	int code, int baparamset, int batimeout);
static void ieee80211_addba_stop(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap);
static void null_addba_response_timeout(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap);

static void ieee80211_bar_response(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap, int status);
static void ampdu_tx_stop(struct ieee80211_tx_ampdu *tap);
static void bar_stop_timer(struct ieee80211_tx_ampdu *tap);
static int ampdu_rx_start(struct ieee80211_node *, struct ieee80211_rx_ampdu *,
	int baparamset, int batimeout, int baseqctl);
static void ampdu_rx_stop(struct ieee80211_node *, struct ieee80211_rx_ampdu *);

void
ieee80211_ht_attach(struct ieee80211com *ic)
{
	/* setup default aggregation policy */
	ic->ic_recv_action = ieee80211_recv_action;
	ic->ic_send_action = ieee80211_send_action;
	ic->ic_ampdu_enable = ieee80211_ampdu_enable;
	ic->ic_addba_request = ieee80211_addba_request;
	ic->ic_addba_response = ieee80211_addba_response;
	ic->ic_addba_response_timeout = null_addba_response_timeout;
	ic->ic_addba_stop = ieee80211_addba_stop;
	ic->ic_bar_response = ieee80211_bar_response;
	ic->ic_ampdu_rx_start = ampdu_rx_start;
	ic->ic_ampdu_rx_stop = ampdu_rx_stop;

	ic->ic_htprotmode = IEEE80211_PROT_RTSCTS;
	ic->ic_curhtprotmode = IEEE80211_HTINFO_OPMODE_PURE;
}

void
ieee80211_ht_detach(struct ieee80211com *ic)
{
}

void
ieee80211_ht_vattach(struct ieee80211vap *vap)
{

	/* driver can override defaults */
	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_8K;
	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_NA;
	vap->iv_ampdu_limit = vap->iv_ampdu_rxmax;
	vap->iv_amsdu_limit = vap->iv_htcaps & IEEE80211_HTCAP_MAXAMSDU;
	/* tx aggregation traffic thresholds */
	vap->iv_ampdu_mintraffic[WME_AC_BK] = 128;
	vap->iv_ampdu_mintraffic[WME_AC_BE] = 64;
	vap->iv_ampdu_mintraffic[WME_AC_VO] = 32;
	vap->iv_ampdu_mintraffic[WME_AC_VI] = 32;

	if (vap->iv_htcaps & IEEE80211_HTC_HT) {
		/*
		 * Device is HT capable; enable all HT-related
		 * facilities by default.
		 * XXX these choices may be too aggressive.
		 */
		vap->iv_flags_ht |= IEEE80211_FHT_HT
				 |  IEEE80211_FHT_HTCOMPAT
				 ;
		if (vap->iv_htcaps & IEEE80211_HTCAP_SHORTGI20)
			vap->iv_flags_ht |= IEEE80211_FHT_SHORTGI20;
		/* XXX infer from channel list? */
		if (vap->iv_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
			vap->iv_flags_ht |= IEEE80211_FHT_USEHT40;
			if (vap->iv_htcaps & IEEE80211_HTCAP_SHORTGI40)
				vap->iv_flags_ht |= IEEE80211_FHT_SHORTGI40;
		}
		/* enable RIFS if capable */
		if (vap->iv_htcaps & IEEE80211_HTC_RIFS)
			vap->iv_flags_ht |= IEEE80211_FHT_RIFS;

		/* NB: A-MPDU and A-MSDU rx are mandated, these are tx only */
		vap->iv_flags_ht |= IEEE80211_FHT_AMPDU_RX;
		if (vap->iv_htcaps & IEEE80211_HTC_AMPDU)
			vap->iv_flags_ht |= IEEE80211_FHT_AMPDU_TX;
		vap->iv_flags_ht |= IEEE80211_FHT_AMSDU_RX;
		if (vap->iv_htcaps & IEEE80211_HTC_AMSDU)
			vap->iv_flags_ht |= IEEE80211_FHT_AMSDU_TX;

		if (vap->iv_htcaps & IEEE80211_HTCAP_TXSTBC)
			vap->iv_flags_ht |= IEEE80211_FHT_STBC_TX;
		if (vap->iv_htcaps & IEEE80211_HTCAP_RXSTBC)
			vap->iv_flags_ht |= IEEE80211_FHT_STBC_RX;
	}
	/* NB: disable default legacy WDS, too many issues right now */
	if (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY)
		vap->iv_flags_ht &= ~IEEE80211_FHT_HT;
}

void
ieee80211_ht_vdetach(struct ieee80211vap *vap)
{
}

static int
ht_getrate(struct ieee80211com *ic, int index, enum ieee80211_phymode mode,
    int ratetype)
{
	int mword, rate;

	mword = ieee80211_rate2media(ic, index | IEEE80211_RATE_MCS, mode);
	if (IFM_SUBTYPE(mword) != IFM_IEEE80211_MCS)
		return (0);
	switch (ratetype) {
	case 0:
		rate = ieee80211_htrates[index].ht20_rate_800ns;
		break;
	case 1:
		rate = ieee80211_htrates[index].ht20_rate_400ns;
		break;
	case 2:
		rate = ieee80211_htrates[index].ht40_rate_800ns;
		break;
	default:
		rate = ieee80211_htrates[index].ht40_rate_400ns;
		break;
	}
	return (rate);
}

static struct printranges {
	int	minmcs;
	int	maxmcs;
	int	txstream;
	int	ratetype;
	int	htcapflags;
} ranges[] = {
	{  0,  7, 1, 0, 0 },
	{  8, 15, 2, 0, 0 },
	{ 16, 23, 3, 0, 0 },
	{ 24, 31, 4, 0, 0 },
	{ 32,  0, 1, 2, IEEE80211_HTC_TXMCS32 },
	{ 33, 38, 2, 0, IEEE80211_HTC_TXUNEQUAL },
	{ 39, 52, 3, 0, IEEE80211_HTC_TXUNEQUAL },
	{ 53, 76, 4, 0, IEEE80211_HTC_TXUNEQUAL },
	{  0,  0, 0, 0, 0 },
};

static void
ht_rateprint(struct ieee80211com *ic, enum ieee80211_phymode mode, int ratetype)
{
	int minrate, maxrate;
	struct printranges *range;

	for (range = ranges; range->txstream != 0; range++) {
		if (ic->ic_txstream < range->txstream)
			continue;
		if (range->htcapflags &&
		    (ic->ic_htcaps & range->htcapflags) == 0)
			continue;
		if (ratetype < range->ratetype)
			continue;
		minrate = ht_getrate(ic, range->minmcs, mode, ratetype);
		maxrate = ht_getrate(ic, range->maxmcs, mode, ratetype);
		if (range->maxmcs) {
			ic_printf(ic, "MCS %d-%d: %d%sMbps - %d%sMbps\n",
			    range->minmcs, range->maxmcs,
			    minrate/2, ((minrate & 0x1) != 0 ? ".5" : ""),
			    maxrate/2, ((maxrate & 0x1) != 0 ? ".5" : ""));
		} else {
			ic_printf(ic, "MCS %d: %d%sMbps\n", range->minmcs,
			    minrate/2, ((minrate & 0x1) != 0 ? ".5" : ""));
		}
	}
}

static void
ht_announce(struct ieee80211com *ic, enum ieee80211_phymode mode)
{
	const char *modestr = ieee80211_phymode_name[mode];

	ic_printf(ic, "%s MCS 20MHz\n", modestr);
	ht_rateprint(ic, mode, 0);
	if (ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI20) {
		ic_printf(ic, "%s MCS 20MHz SGI\n", modestr);
		ht_rateprint(ic, mode, 1);
	}
	if (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
		ic_printf(ic, "%s MCS 40MHz:\n", modestr);
		ht_rateprint(ic, mode, 2);
	}
	if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
	    (ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI40)) {
		ic_printf(ic, "%s MCS 40MHz SGI:\n", modestr);
		ht_rateprint(ic, mode, 3);
	}
}

void
ieee80211_ht_announce(struct ieee80211com *ic)
{

	if (isset(ic->ic_modecaps, IEEE80211_MODE_11NA) ||
	    isset(ic->ic_modecaps, IEEE80211_MODE_11NG))
		ic_printf(ic, "%dT%dR\n", ic->ic_txstream, ic->ic_rxstream);
	if (isset(ic->ic_modecaps, IEEE80211_MODE_11NA))
		ht_announce(ic, IEEE80211_MODE_11NA);
	if (isset(ic->ic_modecaps, IEEE80211_MODE_11NG))
		ht_announce(ic, IEEE80211_MODE_11NG);
}

static struct ieee80211_htrateset htrateset;

const struct ieee80211_htrateset *
ieee80211_get_suphtrates(struct ieee80211com *ic,
    const struct ieee80211_channel *c)
{
#define	ADDRATE(x)	do {						\
	htrateset.rs_rates[htrateset.rs_nrates] = x;			\
	htrateset.rs_nrates++;						\
} while (0)
	int i;

	memset(&htrateset, 0, sizeof(struct ieee80211_htrateset));
	for (i = 0; i < ic->ic_txstream * 8; i++)
		ADDRATE(i);
	if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
	    (ic->ic_htcaps & IEEE80211_HTC_TXMCS32))
		ADDRATE(32);
	if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL) {
		if (ic->ic_txstream >= 2) {
			 for (i = 33; i <= 38; i++)
				ADDRATE(i);
		}
		if (ic->ic_txstream >= 3) {
			for (i = 39; i <= 52; i++)
				ADDRATE(i);
		}
		if (ic->ic_txstream == 4) {
			for (i = 53; i <= 76; i++)
				ADDRATE(i);
		}
	}
	return &htrateset;
#undef	ADDRATE
}

/*
 * Receive processing.
 */

/*
 * Decap the encapsulated A-MSDU frames and dispatch all but
 * the last for delivery.  The last frame is returned for 
 * delivery via the normal path.
 */
struct mbuf *
ieee80211_decap_amsdu(struct ieee80211_node *ni, struct mbuf *m)
{
	struct ieee80211vap *vap = ni->ni_vap;
	int framelen;
	struct mbuf *n;

	/* discard 802.3 header inserted by ieee80211_decap */
	m_adj(m, sizeof(struct ether_header));

	vap->iv_stats.is_amsdu_decap++;

	for (;;) {
		/*
		 * Decap the first frame, bust it apart from the
		 * remainder and deliver.  We leave the last frame
		 * delivery to the caller (for consistency with other
		 * code paths, could also do it here).
		 */
		m = ieee80211_decap1(m, &framelen);
		if (m == NULL) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
			    ni->ni_macaddr, "a-msdu", "%s", "decap failed");
			vap->iv_stats.is_amsdu_tooshort++;
			return NULL;
		}
		if (m->m_pkthdr.len == framelen)
			break;
		n = m_split(m, framelen, M_NOWAIT);
		if (n == NULL) {
			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
			    ni->ni_macaddr, "a-msdu",
			    "%s", "unable to split encapsulated frames");
			vap->iv_stats.is_amsdu_split++;
			m_freem(m);			/* NB: must reclaim */
			return NULL;
		}
		vap->iv_deliver_data(vap, ni, m);

		/*
		 * Remove frame contents; each intermediate frame
		 * is required to be aligned to a 4-byte boundary.
		 */
		m = n;
		m_adj(m, roundup2(framelen, 4) - framelen);	/* padding */
	}
	return m;				/* last delivered by caller */
}

/*
 * Purge all frames in the A-MPDU re-order queue.
 */
static void
ampdu_rx_purge(struct ieee80211_rx_ampdu *rap)
{
	struct mbuf *m;
	int i;

	for (i = 0; i < rap->rxa_wnd; i++) {
		m = rap->rxa_m[i];
		if (m != NULL) {
			rap->rxa_m[i] = NULL;
			rap->rxa_qbytes -= m->m_pkthdr.len;
			m_freem(m);
			if (--rap->rxa_qframes == 0)
				break;
		}
	}
	KASSERT(rap->rxa_qbytes == 0 && rap->rxa_qframes == 0,
	    ("lost %u data, %u frames on ampdu rx q",
	    rap->rxa_qbytes, rap->rxa_qframes));
}

/*
 * Start A-MPDU rx/re-order processing for the specified TID.
 */
static int
ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
	int baparamset, int batimeout, int baseqctl)
{
	int bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);

	if (rap->rxa_flags & IEEE80211_AGGR_RUNNING) {
		/*
		 * AMPDU previously setup and not terminated with a DELBA,
		 * flush the reorder q's in case anything remains.
		 */
		ampdu_rx_purge(rap);
	}
	memset(rap, 0, sizeof(*rap));
	rap->rxa_wnd = (bufsiz == 0) ?
	    IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
	rap->rxa_start = MS(baseqctl, IEEE80211_BASEQ_START);
	rap->rxa_flags |=  IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_XCHGPEND;

	return 0;
}

/*
 * Public function; manually setup the RX ampdu state.
 */
int
ieee80211_ampdu_rx_start_ext(struct ieee80211_node *ni, int tid, int seq, int baw)
{
	struct ieee80211_rx_ampdu *rap;

	/* XXX TODO: sanity check tid, seq, baw */

	rap = &ni->ni_rx_ampdu[tid];

	if (rap->rxa_flags & IEEE80211_AGGR_RUNNING) {
		/*
		 * AMPDU previously setup and not terminated with a DELBA,
		 * flush the reorder q's in case anything remains.
		 */
		ampdu_rx_purge(rap);
	}

	memset(rap, 0, sizeof(*rap));
	rap->rxa_wnd = (baw== 0) ?
	    IEEE80211_AGGR_BAWMAX : min(baw, IEEE80211_AGGR_BAWMAX);
	rap->rxa_start = seq;
	rap->rxa_flags |=  IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_XCHGPEND;

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N, ni,
	    "%s: tid=%d, start=%d, wnd=%d, flags=0x%08x\n",
	    __func__,
	    tid,
	    seq,
	    rap->rxa_wnd,
	    rap->rxa_flags);

	return 0;
}

/*
 * Stop A-MPDU rx processing for the specified TID.
 */
static void
ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
{

	ampdu_rx_purge(rap);
	rap->rxa_flags &= ~(IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_XCHGPEND);
}

/*
 * Dispatch a frame from the A-MPDU reorder queue.  The
 * frame is fed back into ieee80211_input marked with an
 * M_AMPDU_MPDU flag so it doesn't come back to us (it also
 * permits ieee80211_input to optimize re-processing).
 */
static __inline void
ampdu_dispatch(struct ieee80211_node *ni, struct mbuf *m)
{
	m->m_flags |= M_AMPDU_MPDU;	/* bypass normal processing */
	/* NB: rssi and noise are ignored w/ M_AMPDU_MPDU set */
	(void) ieee80211_input(ni, m, 0, 0);
}

/*
 * Dispatch as many frames as possible from the re-order queue.
 * Frames will always be "at the front"; we process all frames
 * up to the first empty slot in the window.  On completion we
 * cleanup state if there are still pending frames in the current
 * BA window.  We assume the frame at slot 0 is already handled
 * by the caller; we always start at slot 1.
 */
static void
ampdu_rx_dispatch(struct ieee80211_rx_ampdu *rap, struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct mbuf *m;
	int i;

	/* flush run of frames */
	for (i = 1; i < rap->rxa_wnd; i++) {
		m = rap->rxa_m[i];
		if (m == NULL)
			break;
		rap->rxa_m[i] = NULL;
		rap->rxa_qbytes -= m->m_pkthdr.len;
		rap->rxa_qframes--;

		ampdu_dispatch(ni, m);
	}
	/*
	 * If frames remain, copy the mbuf pointers down so
	 * they correspond to the offsets in the new window.
	 */
	if (rap->rxa_qframes != 0) {
		int n = rap->rxa_qframes, j;
		for (j = i+1; j < rap->rxa_wnd; j++) {
			if (rap->rxa_m[j] != NULL) {
				rap->rxa_m[j-i] = rap->rxa_m[j];
				rap->rxa_m[j] = NULL;
				if (--n == 0)
					break;
			}
		}
		KASSERT(n == 0, ("lost %d frames", n));
		vap->iv_stats.is_ampdu_rx_copy += rap->rxa_qframes;
	}
	/*
	 * Adjust the start of the BA window to
	 * reflect the frames just dispatched.
	 */
	rap->rxa_start = IEEE80211_SEQ_ADD(rap->rxa_start, i);
	vap->iv_stats.is_ampdu_rx_oor += i;
}

/*
 * Dispatch all frames in the A-MPDU re-order queue.
 */
static void
ampdu_rx_flush(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct mbuf *m;
	int i;

	for (i = 0; i < rap->rxa_wnd; i++) {
		m = rap->rxa_m[i];
		if (m == NULL)
			continue;
		rap->rxa_m[i] = NULL;
		rap->rxa_qbytes -= m->m_pkthdr.len;
		rap->rxa_qframes--;
		vap->iv_stats.is_ampdu_rx_oor++;

		ampdu_dispatch(ni, m);
		if (rap->rxa_qframes == 0)
			break;
	}
}

/*
 * Dispatch all frames in the A-MPDU re-order queue
 * preceding the specified sequence number.  This logic
 * handles window moves due to a received MSDU or BAR.
 */
static void
ampdu_rx_flush_upto(struct ieee80211_node *ni,
	struct ieee80211_rx_ampdu *rap, ieee80211_seq winstart)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct mbuf *m;
	ieee80211_seq seqno;
	int i;

	/*
	 * Flush any complete MSDU's with a sequence number lower
	 * than winstart.  Gaps may exist.  Note that we may actually
	 * dispatch frames past winstart if a run continues; this is
	 * an optimization that avoids having to do a separate pass
	 * to dispatch frames after moving the BA window start.
	 */
	seqno = rap->rxa_start;
	for (i = 0; i < rap->rxa_wnd; i++) {
		m = rap->rxa_m[i];
		if (m != NULL) {
			rap->rxa_m[i] = NULL;
			rap->rxa_qbytes -= m->m_pkthdr.len;
			rap->rxa_qframes--;
			vap->iv_stats.is_ampdu_rx_oor++;

			ampdu_dispatch(ni, m);
		} else {
			if (!IEEE80211_SEQ_BA_BEFORE(seqno, winstart))
				break;
		}
		seqno = IEEE80211_SEQ_INC(seqno);
	}
	/*
	 * If frames remain, copy the mbuf pointers down so
	 * they correspond to the offsets in the new window.
	 */
	if (rap->rxa_qframes != 0) {
		int n = rap->rxa_qframes, j;

		/* NB: this loop assumes i > 0 and/or rxa_m[0] is NULL */
		KASSERT(rap->rxa_m[0] == NULL,
		    ("%s: BA window slot 0 occupied", __func__));
		for (j = i+1; j < rap->rxa_wnd; j++) {
			if (rap->rxa_m[j] != NULL) {
				rap->rxa_m[j-i] = rap->rxa_m[j];
				rap->rxa_m[j] = NULL;
				if (--n == 0)
					break;
			}
		}
		KASSERT(n == 0, ("%s: lost %d frames, qframes %d off %d "
		    "BA win <%d:%d> winstart %d",
		    __func__, n, rap->rxa_qframes, i, rap->rxa_start,
		    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
		    winstart));
		vap->iv_stats.is_ampdu_rx_copy += rap->rxa_qframes;
	}
	/*
	 * Move the start of the BA window; we use the
	 * sequence number of the last MSDU that was
	 * passed up the stack+1 or winstart if stopped on
	 * a gap in the reorder buffer.
	 */
	rap->rxa_start = seqno;
}

/*
 * Process a received QoS data frame for an HT station.  Handle
 * A-MPDU reordering: if this frame is received out of order
 * and falls within the BA window hold onto it.  Otherwise if
 * this frame completes a run, flush any pending frames.  We
 * return 1 if the frame is consumed.  A 0 is returned if
 * the frame should be processed normally by the caller.
 */
int
ieee80211_ampdu_reorder(struct ieee80211_node *ni, struct mbuf *m)
{
#define	IEEE80211_FC0_QOSDATA \
	(IEEE80211_FC0_TYPE_DATA|IEEE80211_FC0_SUBTYPE_QOS|IEEE80211_FC0_VERSION_0)
#define	PROCESS		0	/* caller should process frame */
#define	CONSUMED	1	/* frame consumed, caller does nothing */
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_qosframe *wh;
	struct ieee80211_rx_ampdu *rap;
	ieee80211_seq rxseq;
	uint8_t tid;
	int off;

	KASSERT((m->m_flags & (M_AMPDU | M_AMPDU_MPDU)) == M_AMPDU,
	    ("!a-mpdu or already re-ordered, flags 0x%x", m->m_flags));
	KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT sta"));

	/* NB: m_len known to be sufficient */
	wh = mtod(m, struct ieee80211_qosframe *);
	if (wh->i_fc[0] != IEEE80211_FC0_QOSDATA) {
		/*
		 * Not QoS data, shouldn't get here but just
		 * return it to the caller for processing.
		 */
		return PROCESS;
	}
	if (IEEE80211_IS_DSTODS(wh))
		tid = ((struct ieee80211_qosframe_addr4 *)wh)->i_qos[0];
	else
		tid = wh->i_qos[0];
	tid &= IEEE80211_QOS_TID;
	rap = &ni->ni_rx_ampdu[tid];
	if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
		/*
		 * No ADDBA request yet, don't touch.
		 */
		return PROCESS;
	}
	rxseq = le16toh(*(uint16_t *)wh->i_seq);
	if ((rxseq & IEEE80211_SEQ_FRAG_MASK) != 0) {
		/*
		 * Fragments are not allowed; toss.
		 */
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
		    "A-MPDU", "fragment, rxseq 0x%x tid %u%s", rxseq, tid,
		    wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
		vap->iv_stats.is_ampdu_rx_drop++;
		IEEE80211_NODE_STAT(ni, rx_drop);
		m_freem(m);
		return CONSUMED;
	}
	rxseq >>= IEEE80211_SEQ_SEQ_SHIFT;
	rap->rxa_nframes++;
again:
	if (rxseq == rap->rxa_start) {
		/*
		 * First frame in window.
		 */
		if (rap->rxa_qframes != 0) {
			/*
			 * Dispatch as many packets as we can.
			 */
			KASSERT(rap->rxa_m[0] == NULL, ("unexpected dup"));
			ampdu_dispatch(ni, m);
			ampdu_rx_dispatch(rap, ni);
			return CONSUMED;
		} else {
			/*
			 * In order; advance window and notify
			 * caller to dispatch directly.
			 */
			rap->rxa_start = IEEE80211_SEQ_INC(rxseq);
			return PROCESS;
		}
	}
	/*
	 * Frame is out of order; store if in the BA window.
	 */
	/* calculate offset in BA window */
	off = IEEE80211_SEQ_SUB(rxseq, rap->rxa_start);
	if (off < rap->rxa_wnd) {
		/*
		 * Common case (hopefully): in the BA window.
		 * Sec 9.10.7.6.2 a) (p.137)
		 */

		/* 
		 * Check for frames sitting too long in the reorder queue.
		 * This should only ever happen if frames are not delivered
		 * without the sender otherwise notifying us (e.g. with a
		 * BAR to move the window).  Typically this happens because
		 * of vendor bugs that cause the sequence number to jump.
		 * When this happens we get a gap in the reorder queue that
		 * leaves frame sitting on the queue until they get pushed
		 * out due to window moves.  When the vendor does not send
		 * BAR this move only happens due to explicit packet sends
		 *
		 * NB: we only track the time of the oldest frame in the
		 * reorder q; this means that if we flush we might push
		 * frames that still "new"; if this happens then subsequent
		 * frames will result in BA window moves which cost something
		 * but is still better than a big throughput dip.
		 */
		if (rap->rxa_qframes != 0) {
			/* XXX honor batimeout? */
			if (ticks - rap->rxa_age > ieee80211_ampdu_age) {
				/*
				 * Too long since we received the first
				 * frame; flush the reorder buffer.
				 */
				if (rap->rxa_qframes != 0) {
					vap->iv_stats.is_ampdu_rx_age +=
					    rap->rxa_qframes;
					ampdu_rx_flush(ni, rap);
				}
				rap->rxa_start = IEEE80211_SEQ_INC(rxseq);
				return PROCESS;
			}
		} else {
			/*
			 * First frame, start aging timer.
			 */
			rap->rxa_age = ticks;
		}

		/* save packet */
		if (rap->rxa_m[off] == NULL) {
			rap->rxa_m[off] = m;
			rap->rxa_qframes++;
			rap->rxa_qbytes += m->m_pkthdr.len;
			vap->iv_stats.is_ampdu_rx_reorder++;
		} else {
			IEEE80211_DISCARD_MAC(vap,
			    IEEE80211_MSG_INPUT | IEEE80211_MSG_11N,
			    ni->ni_macaddr, "a-mpdu duplicate",
			    "seqno %u tid %u BA win <%u:%u>",
			    rxseq, tid, rap->rxa_start,
			    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1));
			vap->iv_stats.is_rx_dup++;
			IEEE80211_NODE_STAT(ni, rx_dup);
			m_freem(m);
		}
		return CONSUMED;
	}
	if (off < IEEE80211_SEQ_BA_RANGE) {
		/*
		 * Outside the BA window, but within range;
		 * flush the reorder q and move the window.
		 * Sec 9.10.7.6.2 b) (p.138)
		 */
		IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
		    "move BA win <%u:%u> (%u frames) rxseq %u tid %u",
		    rap->rxa_start,
		    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
		    rap->rxa_qframes, rxseq, tid);
		vap->iv_stats.is_ampdu_rx_move++;

		/*
		 * The spec says to flush frames up to but not including:
		 * 	WinStart_B = rxseq - rap->rxa_wnd + 1
		 * Then insert the frame or notify the caller to process
		 * it immediately.  We can safely do this by just starting
		 * over again because we know the frame will now be within
		 * the BA window.
		 */
		/* NB: rxa_wnd known to be >0 */
		ampdu_rx_flush_upto(ni, rap,
		    IEEE80211_SEQ_SUB(rxseq, rap->rxa_wnd-1));
		goto again;
	} else {
		/*
		 * Outside the BA window and out of range; toss.
		 * Sec 9.10.7.6.2 c) (p.138)
		 */
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
		    "MPDU", "BA win <%u:%u> (%u frames) rxseq %u tid %u%s",
		    rap->rxa_start,
		    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
		    rap->rxa_qframes, rxseq, tid,
		    wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
		vap->iv_stats.is_ampdu_rx_drop++;
		IEEE80211_NODE_STAT(ni, rx_drop);
		m_freem(m);
		return CONSUMED;
	}
#undef CONSUMED
#undef PROCESS
#undef IEEE80211_FC0_QOSDATA
}

/*
 * Process a BAR ctl frame.  Dispatch all frames up to
 * the sequence number of the frame.  If this frame is
 * out of range it's discarded.
 */
void
ieee80211_recv_bar(struct ieee80211_node *ni, struct mbuf *m0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_frame_bar *wh;
	struct ieee80211_rx_ampdu *rap;
	ieee80211_seq rxseq;
	int tid, off;

	if (!ieee80211_recv_bar_ena) {
#if 0
		IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_11N,
		    ni->ni_macaddr, "BAR", "%s", "processing disabled");
#endif
		vap->iv_stats.is_ampdu_bar_bad++;
		return;
	}
	wh = mtod(m0, struct ieee80211_frame_bar *);
	/* XXX check basic BAR */
	tid = MS(le16toh(wh->i_ctl), IEEE80211_BAR_TID);
	rap = &ni->ni_rx_ampdu[tid];
	if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
		/*
		 * No ADDBA request yet, don't touch.
		 */
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_INPUT | IEEE80211_MSG_11N,
		    ni->ni_macaddr, "BAR", "no BA stream, tid %u", tid);
		vap->iv_stats.is_ampdu_bar_bad++;
		return;
	}
	vap->iv_stats.is_ampdu_bar_rx++;
	rxseq = le16toh(wh->i_seq) >> IEEE80211_SEQ_SEQ_SHIFT;
	if (rxseq == rap->rxa_start)
		return;
	/* calculate offset in BA window */
	off = IEEE80211_SEQ_SUB(rxseq, rap->rxa_start);
	if (off < IEEE80211_SEQ_BA_RANGE) {
		/*
		 * Flush the reorder q up to rxseq and move the window.
		 * Sec 9.10.7.6.3 a) (p.138)
		 */
		IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
		    "BAR moves BA win <%u:%u> (%u frames) rxseq %u tid %u",
		    rap->rxa_start,
		    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
		    rap->rxa_qframes, rxseq, tid);
		vap->iv_stats.is_ampdu_bar_move++;

		ampdu_rx_flush_upto(ni, rap, rxseq);
		if (off >= rap->rxa_wnd) {
			/*
			 * BAR specifies a window start to the right of BA
			 * window; we must move it explicitly since
			 * ampdu_rx_flush_upto will not.
			 */
			rap->rxa_start = rxseq;
		}
	} else {
		/*
		 * Out of range; toss.
		 * Sec 9.10.7.6.3 b) (p.138)
		 */
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
		    "BAR", "BA win <%u:%u> (%u frames) rxseq %u tid %u%s",
		    rap->rxa_start,
		    IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
		    rap->rxa_qframes, rxseq, tid,
		    wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
		vap->iv_stats.is_ampdu_bar_oow++;
		IEEE80211_NODE_STAT(ni, rx_drop);
	}
}

/*
 * Setup HT-specific state in a node.  Called only
 * when HT use is negotiated so we don't do extra
 * work for temporary and/or legacy sta's.
 */
void
ieee80211_ht_node_init(struct ieee80211_node *ni)
{
	struct ieee80211_tx_ampdu *tap;
	int tid;

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
	    ni,
	    "%s: called (%p)",
	    __func__,
	    ni);

	if (ni->ni_flags & IEEE80211_NODE_HT) {
		/*
		 * Clean AMPDU state on re-associate.  This handles the case
		 * where a station leaves w/o notifying us and then returns
		 * before node is reaped for inactivity.
		 */
		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
		    ni,
		    "%s: calling cleanup (%p)",
		    __func__, ni);
		ieee80211_ht_node_cleanup(ni);
	}
	for (tid = 0; tid < WME_NUM_TID; tid++) {
		tap = &ni->ni_tx_ampdu[tid];
		tap->txa_tid = tid;
		tap->txa_ni = ni;
		ieee80211_txampdu_init_pps(tap);
		/* NB: further initialization deferred */
	}
	ni->ni_flags |= IEEE80211_NODE_HT | IEEE80211_NODE_AMPDU;
}

/*
 * Cleanup HT-specific state in a node.  Called only
 * when HT use has been marked.
 */
void
ieee80211_ht_node_cleanup(struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;
	int i;

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
	    ni,
	    "%s: called (%p)",
	    __func__, ni);

	KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT node"));

	/* XXX optimize this */
	for (i = 0; i < WME_NUM_TID; i++) {
		struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[i];
		if (tap->txa_flags & IEEE80211_AGGR_SETUP)
			ampdu_tx_stop(tap);
	}
	for (i = 0; i < WME_NUM_TID; i++)
		ic->ic_ampdu_rx_stop(ni, &ni->ni_rx_ampdu[i]);

	ni->ni_htcap = 0;
	ni->ni_flags &= ~IEEE80211_NODE_HT_ALL;
}

/*
 * Age out HT resources for a station.
 */
void
ieee80211_ht_node_age(struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	uint8_t tid;

	KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT sta"));

	for (tid = 0; tid < WME_NUM_TID; tid++) {
		struct ieee80211_rx_ampdu *rap;

		rap = &ni->ni_rx_ampdu[tid];
		if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0)
			continue;
		if (rap->rxa_qframes == 0)
			continue;
		/* 
		 * Check for frames sitting too long in the reorder queue.
		 * See above for more details on what's happening here.
		 */
		/* XXX honor batimeout? */
		if (ticks - rap->rxa_age > ieee80211_ampdu_age) {
			/*
			 * Too long since we received the first
			 * frame; flush the reorder buffer.
			 */
			vap->iv_stats.is_ampdu_rx_age += rap->rxa_qframes;
			ampdu_rx_flush(ni, rap);
		}
	}
}

static struct ieee80211_channel *
findhtchan(struct ieee80211com *ic, struct ieee80211_channel *c, int htflags)
{
	return ieee80211_find_channel(ic, c->ic_freq,
	    (c->ic_flags &~ IEEE80211_CHAN_HT) | htflags);
}

/*
 * Adjust a channel to be HT/non-HT according to the vap's configuration.
 */
struct ieee80211_channel *
ieee80211_ht_adjust_channel(struct ieee80211com *ic,
	struct ieee80211_channel *chan, int flags)
{
	struct ieee80211_channel *c;

	if (flags & IEEE80211_FHT_HT) {
		/* promote to HT if possible */
		if (flags & IEEE80211_FHT_USEHT40) {
			if (!IEEE80211_IS_CHAN_HT40(chan)) {
				/* NB: arbitrarily pick ht40+ over ht40- */
				c = findhtchan(ic, chan, IEEE80211_CHAN_HT40U);
				if (c == NULL)
					c = findhtchan(ic, chan,
						IEEE80211_CHAN_HT40D);
				if (c == NULL)
					c = findhtchan(ic, chan,
						IEEE80211_CHAN_HT20);
				if (c != NULL)
					chan = c;
			}
		} else if (!IEEE80211_IS_CHAN_HT20(chan)) {
			c = findhtchan(ic, chan, IEEE80211_CHAN_HT20);
			if (c != NULL)
				chan = c;
		}
	} else if (IEEE80211_IS_CHAN_HT(chan)) {
		/* demote to legacy, HT use is disabled */
		c = ieee80211_find_channel(ic, chan->ic_freq,
		    chan->ic_flags &~ IEEE80211_CHAN_HT);
		if (c != NULL)
			chan = c;
	}
	return chan;
}

/*
 * Setup HT-specific state for a legacy WDS peer.
 */
void
ieee80211_ht_wds_init(struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_tx_ampdu *tap;
	int tid;

	KASSERT(vap->iv_flags_ht & IEEE80211_FHT_HT, ("no HT requested"));

	/* XXX check scan cache in case peer has an ap and we have info */
	/*
	 * If setup with a legacy channel; locate an HT channel.
	 * Otherwise if the inherited channel (from a companion
	 * AP) is suitable use it so we use the same location
	 * for the extension channel).
	 */
	ni->ni_chan = ieee80211_ht_adjust_channel(ni->ni_ic,
	    ni->ni_chan, ieee80211_htchanflags(ni->ni_chan));

	ni->ni_htcap = 0;
	if (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20)
		ni->ni_htcap |= IEEE80211_HTCAP_SHORTGI20;
	if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
		ni->ni_htcap |= IEEE80211_HTCAP_CHWIDTH40;
		ni->ni_chw = 40;
		if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
			ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_ABOVE;
		else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
			ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_BELOW;
		if (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40)
			ni->ni_htcap |= IEEE80211_HTCAP_SHORTGI40;
	} else {
		ni->ni_chw = 20;
		ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_NONE;
	}
	ni->ni_htctlchan = ni->ni_chan->ic_ieee;
	if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
		ni->ni_flags |= IEEE80211_NODE_RIFS;
	/* XXX does it make sense to enable SMPS? */

	ni->ni_htopmode = 0;		/* XXX need protection state */
	ni->ni_htstbc = 0;		/* XXX need info */

	for (tid = 0; tid < WME_NUM_TID; tid++) {
		tap = &ni->ni_tx_ampdu[tid];
		tap->txa_tid = tid;
		ieee80211_txampdu_init_pps(tap);
	}
	/* NB: AMPDU tx/rx governed by IEEE80211_FHT_AMPDU_{TX,RX} */
	ni->ni_flags |= IEEE80211_NODE_HT | IEEE80211_NODE_AMPDU;
}

/*
 * Notify hostap vaps of a change in the HTINFO ie.
 */
static void
htinfo_notify(struct ieee80211com *ic)
{
	struct ieee80211vap *vap;
	int first = 1;

	IEEE80211_LOCK_ASSERT(ic);

	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
		if (vap->iv_opmode != IEEE80211_M_HOSTAP)
			continue;
		if (vap->iv_state != IEEE80211_S_RUN ||
		    !IEEE80211_IS_CHAN_HT(vap->iv_bss->ni_chan))
			continue;
		if (first) {
			IEEE80211_NOTE(vap,
			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N,
			    vap->iv_bss,
			    "HT bss occupancy change: %d sta, %d ht, "
			    "%d ht40%s, HT protmode now 0x%x"
			    , ic->ic_sta_assoc
			    , ic->ic_ht_sta_assoc
			    , ic->ic_ht40_sta_assoc
			    , (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) ?
				 ", non-HT sta present" : ""
			    , ic->ic_curhtprotmode);
			first = 0;
		}
		ieee80211_beacon_notify(vap, IEEE80211_BEACON_HTINFO);
	}
}

/*
 * Calculate HT protection mode from current
 * state and handle updates.
 */
static void
htinfo_update(struct ieee80211com *ic)
{
	uint8_t protmode;

	if (ic->ic_sta_assoc != ic->ic_ht_sta_assoc) {
		protmode = IEEE80211_HTINFO_OPMODE_MIXED
			 | IEEE80211_HTINFO_NONHT_PRESENT;
	} else if (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) {
		protmode = IEEE80211_HTINFO_OPMODE_PROTOPT
			 | IEEE80211_HTINFO_NONHT_PRESENT;
	} else if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
	    IEEE80211_IS_CHAN_HT40(ic->ic_bsschan) && 
	    ic->ic_sta_assoc != ic->ic_ht40_sta_assoc) {
		protmode = IEEE80211_HTINFO_OPMODE_HT20PR;
	} else {
		protmode = IEEE80211_HTINFO_OPMODE_PURE;
	}
	if (protmode != ic->ic_curhtprotmode) {
		ic->ic_curhtprotmode = protmode;
		htinfo_notify(ic);
	}
}

/*
 * Handle an HT station joining a BSS.
 */
void
ieee80211_ht_node_join(struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;

	IEEE80211_LOCK_ASSERT(ic);

	if (ni->ni_flags & IEEE80211_NODE_HT) {
		ic->ic_ht_sta_assoc++;
		if (ni->ni_chw == 40)
			ic->ic_ht40_sta_assoc++;
	}
	htinfo_update(ic);
}

/*
 * Handle an HT station leaving a BSS.
 */
void
ieee80211_ht_node_leave(struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;

	IEEE80211_LOCK_ASSERT(ic);

	if (ni->ni_flags & IEEE80211_NODE_HT) {
		ic->ic_ht_sta_assoc--;
		if (ni->ni_chw == 40)
			ic->ic_ht40_sta_assoc--;
	}
	htinfo_update(ic);
}

/*
 * Public version of htinfo_update; used for processing
 * beacon frames from overlapping bss.
 *
 * Caller can specify either IEEE80211_HTINFO_OPMODE_MIXED
 * (on receipt of a beacon that advertises MIXED) or
 * IEEE80211_HTINFO_OPMODE_PROTOPT (on receipt of a beacon
 * from an overlapping legacy bss).  We treat MIXED with
 * a higher precedence than PROTOPT (i.e. we will not change
 * change PROTOPT -> MIXED; only MIXED -> PROTOPT).  This
 * corresponds to how we handle things in htinfo_update.
 */
void
ieee80211_htprot_update(struct ieee80211com *ic, int protmode)
{
#define	OPMODE(x)	SM(x, IEEE80211_HTINFO_OPMODE)
	IEEE80211_LOCK(ic);

	/* track non-HT station presence */
	KASSERT(protmode & IEEE80211_HTINFO_NONHT_PRESENT,
	    ("protmode 0x%x", protmode));
	ic->ic_flags_ht |= IEEE80211_FHT_NONHT_PR;
	ic->ic_lastnonht = ticks;

	if (protmode != ic->ic_curhtprotmode &&
	    (OPMODE(ic->ic_curhtprotmode) != IEEE80211_HTINFO_OPMODE_MIXED ||
	     OPMODE(protmode) == IEEE80211_HTINFO_OPMODE_PROTOPT)) {
		/* push beacon update */
		ic->ic_curhtprotmode = protmode;
		htinfo_notify(ic);
	}
	IEEE80211_UNLOCK(ic);
#undef OPMODE
}

/*
 * Time out presence of an overlapping bss with non-HT
 * stations.  When operating in hostap mode we listen for
 * beacons from other stations and if we identify a non-HT
 * station is present we update the opmode field of the
 * HTINFO ie.  To identify when all non-HT stations are
 * gone we time out this condition.
 */
void
ieee80211_ht_timeout(struct ieee80211com *ic)
{
	IEEE80211_LOCK_ASSERT(ic);

	if ((ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) &&
	    ieee80211_time_after(ticks, ic->ic_lastnonht + IEEE80211_NONHT_PRESENT_AGE)) {
#if 0
		IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
		    "%s", "time out non-HT STA present on channel");
#endif
		ic->ic_flags_ht &= ~IEEE80211_FHT_NONHT_PR;
		htinfo_update(ic);
	}
}

/*
 * Process an 802.11n HT capabilities ie.
 */
void
ieee80211_parse_htcap(struct ieee80211_node *ni, const uint8_t *ie)
{
	if (ie[0] == IEEE80211_ELEMID_VENDOR) {
		/*
		 * Station used Vendor OUI ie to associate;
		 * mark the node so when we respond we'll use
		 * the Vendor OUI's and not the standard ie's.
		 */
		ni->ni_flags |= IEEE80211_NODE_HTCOMPAT;
		ie += 4;
	} else
		ni->ni_flags &= ~IEEE80211_NODE_HTCOMPAT;

	ni->ni_htcap = le16dec(ie +
		__offsetof(struct ieee80211_ie_htcap, hc_cap));
	ni->ni_htparam = ie[__offsetof(struct ieee80211_ie_htcap, hc_param)];
}

static void
htinfo_parse(struct ieee80211_node *ni,
	const struct ieee80211_ie_htinfo *htinfo)
{
	uint16_t w;

	ni->ni_htctlchan = htinfo->hi_ctrlchannel;
	ni->ni_ht2ndchan = SM(htinfo->hi_byte1, IEEE80211_HTINFO_2NDCHAN);
	w = le16dec(&htinfo->hi_byte2);
	ni->ni_htopmode = SM(w, IEEE80211_HTINFO_OPMODE);
	w = le16dec(&htinfo->hi_byte45);
	ni->ni_htstbc = SM(w, IEEE80211_HTINFO_BASIC_STBCMCS);
}

/*
 * Parse an 802.11n HT info ie and save useful information
 * to the node state.  Note this does not effect any state
 * changes such as for channel width change.
 */
void
ieee80211_parse_htinfo(struct ieee80211_node *ni, const uint8_t *ie)
{
	if (ie[0] == IEEE80211_ELEMID_VENDOR)
		ie += 4;
	htinfo_parse(ni, (const struct ieee80211_ie_htinfo *) ie);
}

/*
 * Handle 11n channel switch.  Use the received HT ie's to
 * identify the right channel to use.  If we cannot locate it
 * in the channel table then fallback to legacy operation.
 * Note that we use this information to identify the node's
 * channel only; the caller is responsible for insuring any
 * required channel change is done (e.g. in sta mode when
 * parsing the contents of a beacon frame).
 */
static int
htinfo_update_chw(struct ieee80211_node *ni, int htflags)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_channel *c;
	int chanflags;
	int ret = 0;

	chanflags = (ni->ni_chan->ic_flags &~ IEEE80211_CHAN_HT) | htflags;
	if (chanflags != ni->ni_chan->ic_flags) {
		/* XXX not right for ht40- */
		c = ieee80211_find_channel(ic, ni->ni_chan->ic_freq, chanflags);
		if (c == NULL && (htflags & IEEE80211_CHAN_HT40)) {
			/*
			 * No HT40 channel entry in our table; fall back
			 * to HT20 operation.  This should not happen.
			 */
			c = findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT20);
#if 0
			IEEE80211_NOTE(ni->ni_vap,
			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
			    "no HT40 channel (freq %u), falling back to HT20",
			    ni->ni_chan->ic_freq);
#endif
			/* XXX stat */
		}
		if (c != NULL && c != ni->ni_chan) {
			IEEE80211_NOTE(ni->ni_vap,
			    IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
			    "switch station to HT%d channel %u/0x%x",
			    IEEE80211_IS_CHAN_HT40(c) ? 40 : 20,
			    c->ic_freq, c->ic_flags);
			ni->ni_chan = c;
			ret = 1;
		}
		/* NB: caller responsible for forcing any channel change */
	}
	/* update node's tx channel width */
	ni->ni_chw = IEEE80211_IS_CHAN_HT40(ni->ni_chan)? 40 : 20;
	return (ret);
}

/*
 * Update 11n MIMO PS state according to received htcap.
 */
static __inline int
htcap_update_mimo_ps(struct ieee80211_node *ni)
{
	uint16_t oflags = ni->ni_flags;

	switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
	case IEEE80211_HTCAP_SMPS_DYNAMIC:
		ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
		ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
		break;
	case IEEE80211_HTCAP_SMPS_ENA:
		ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
		ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
		break;
	case IEEE80211_HTCAP_SMPS_OFF:
	default:		/* disable on rx of reserved value */
		ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
		ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
		break;
	}
	return (oflags ^ ni->ni_flags);
}

/*
 * Update short GI state according to received htcap
 * and local settings.
 */
static __inline void
htcap_update_shortgi(struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;

	ni->ni_flags &= ~(IEEE80211_NODE_SGI20|IEEE80211_NODE_SGI40);
	if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20))
		ni->ni_flags |= IEEE80211_NODE_SGI20;
	if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40))
		ni->ni_flags |= IEEE80211_NODE_SGI40;
}

/*
 * Parse and update HT-related state extracted from
 * the HT cap and info ie's.
 */
int
ieee80211_ht_updateparams(struct ieee80211_node *ni,
	const uint8_t *htcapie, const uint8_t *htinfoie)
{
	struct ieee80211vap *vap = ni->ni_vap;
	const struct ieee80211_ie_htinfo *htinfo;
	int htflags;
	int ret = 0;

	ieee80211_parse_htcap(ni, htcapie);
	if (vap->iv_htcaps & IEEE80211_HTCAP_SMPS)
		htcap_update_mimo_ps(ni);
	htcap_update_shortgi(ni);

	if (htinfoie[0] == IEEE80211_ELEMID_VENDOR)
		htinfoie += 4;
	htinfo = (const struct ieee80211_ie_htinfo *) htinfoie;
	htinfo_parse(ni, htinfo);

	htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
	    IEEE80211_CHAN_HT20 : 0;
	/* NB: honor operating mode constraint */
	if ((htinfo->hi_byte1 & IEEE80211_HTINFO_TXWIDTH_2040) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
		if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_ABOVE)
			htflags = IEEE80211_CHAN_HT40U;
		else if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_BELOW)
			htflags = IEEE80211_CHAN_HT40D;
	}
	if (htinfo_update_chw(ni, htflags))
		ret = 1;

	if ((htinfo->hi_byte1 & IEEE80211_HTINFO_RIFSMODE_PERM) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_RIFS))
		ni->ni_flags |= IEEE80211_NODE_RIFS;
	else
		ni->ni_flags &= ~IEEE80211_NODE_RIFS;

	return (ret);
}

/*
 * Parse and update HT-related state extracted from the HT cap ie
 * for a station joining an HT BSS.
 */
void
ieee80211_ht_updatehtcap(struct ieee80211_node *ni, const uint8_t *htcapie)
{
	struct ieee80211vap *vap = ni->ni_vap;
	int htflags;

	ieee80211_parse_htcap(ni, htcapie);
	if (vap->iv_htcaps & IEEE80211_HTCAP_SMPS)
		htcap_update_mimo_ps(ni);
	htcap_update_shortgi(ni);

	/* NB: honor operating mode constraint */
	/* XXX 40 MHz intolerant */
	htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
	    IEEE80211_CHAN_HT20 : 0;
	if ((ni->ni_htcap & IEEE80211_HTCAP_CHWIDTH40) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
		if (IEEE80211_IS_CHAN_HT40U(vap->iv_bss->ni_chan))
			htflags = IEEE80211_CHAN_HT40U;
		else if (IEEE80211_IS_CHAN_HT40D(vap->iv_bss->ni_chan))
			htflags = IEEE80211_CHAN_HT40D;
	}
	(void) htinfo_update_chw(ni, htflags);
}

/*
 * Install received HT rate set by parsing the HT cap ie.
 */
int
ieee80211_setup_htrates(struct ieee80211_node *ni, const uint8_t *ie, int flags)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211vap *vap = ni->ni_vap;
	const struct ieee80211_ie_htcap *htcap;
	struct ieee80211_htrateset *rs;
	int i, maxequalmcs, maxunequalmcs;

	maxequalmcs = ic->ic_txstream * 8 - 1;
	if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL) {
		if (ic->ic_txstream >= 2)
			maxunequalmcs = 38;
		if (ic->ic_txstream >= 3)
			maxunequalmcs = 52;
		if (ic->ic_txstream >= 4)
			maxunequalmcs = 76;
	} else
		maxunequalmcs = 0;

	rs = &ni->ni_htrates;
	memset(rs, 0, sizeof(*rs));
	if (ie != NULL) {
		if (ie[0] == IEEE80211_ELEMID_VENDOR)
			ie += 4;
		htcap = (const struct ieee80211_ie_htcap *) ie;
		for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
			if (isclr(htcap->hc_mcsset, i))
				continue;
			if (rs->rs_nrates == IEEE80211_HTRATE_MAXSIZE) {
				IEEE80211_NOTE(vap,
				    IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
				    "WARNING, HT rate set too large; only "
				    "using %u rates", IEEE80211_HTRATE_MAXSIZE);
				vap->iv_stats.is_rx_rstoobig++;
				break;
			}
			if (i <= 31 && i > maxequalmcs)
				continue;
			if (i == 32 &&
			    (ic->ic_htcaps & IEEE80211_HTC_TXMCS32) == 0)
				continue;
			if (i > 32 && i > maxunequalmcs)
				continue;
			rs->rs_rates[rs->rs_nrates++] = i;
		}
	}
	return ieee80211_fix_rate(ni, (struct ieee80211_rateset *) rs, flags);
}

/*
 * Mark rates in a node's HT rate set as basic according
 * to the information in the supplied HT info ie.
 */
void
ieee80211_setup_basic_htrates(struct ieee80211_node *ni, const uint8_t *ie)
{
	const struct ieee80211_ie_htinfo *htinfo;
	struct ieee80211_htrateset *rs;
	int i, j;

	if (ie[0] == IEEE80211_ELEMID_VENDOR)
		ie += 4;
	htinfo = (const struct ieee80211_ie_htinfo *) ie;
	rs = &ni->ni_htrates;
	if (rs->rs_nrates == 0) {
		IEEE80211_NOTE(ni->ni_vap,
		    IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
		    "%s", "WARNING, empty HT rate set");
		return;
	}
	for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
		if (isclr(htinfo->hi_basicmcsset, i))
			continue;
		for (j = 0; j < rs->rs_nrates; j++)
			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == i)
				rs->rs_rates[j] |= IEEE80211_RATE_BASIC;
	}
}

static void
ampdu_tx_setup(struct ieee80211_tx_ampdu *tap)
{
#if defined(__DragonFly__)
	callout_init_mp(&tap->txa_timer);
#else
	callout_init(&tap->txa_timer, 1);
#endif
	tap->txa_flags |= IEEE80211_AGGR_SETUP;
	tap->txa_lastsample = ticks;
}

static void
ampdu_tx_stop(struct ieee80211_tx_ampdu *tap)
{
	struct ieee80211_node *ni = tap->txa_ni;
	struct ieee80211com *ic = ni->ni_ic;

	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: called",
	    __func__);

	KASSERT(tap->txa_flags & IEEE80211_AGGR_SETUP,
	    ("txa_flags 0x%x tid %d ac %d", tap->txa_flags, tap->txa_tid,
	    TID_TO_WME_AC(tap->txa_tid)));

	/*
	 * Stop BA stream if setup so driver has a chance
	 * to reclaim any resources it might have allocated.
	 */
	ic->ic_addba_stop(ni, tap);
	/*
	 * Stop any pending BAR transmit.
	 */
	bar_stop_timer(tap);

	/*
	 * Reset packet estimate.
	 */
	ieee80211_txampdu_init_pps(tap);

	/* NB: clearing NAK means we may re-send ADDBA */ 
	tap->txa_flags &= ~(IEEE80211_AGGR_SETUP | IEEE80211_AGGR_NAK);
}

/*
 * ADDBA response timeout.
 *
 * If software aggregation and per-TID queue management was done here,
 * that queue would be unpaused after the ADDBA timeout occurs.
 */
static void
addba_timeout(void *arg)
{
	struct ieee80211_tx_ampdu *tap = arg;
	struct ieee80211_node *ni = tap->txa_ni;
	struct ieee80211com *ic = ni->ni_ic;

	/* XXX ? */
	tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
	tap->txa_attempts++;
	ic->ic_addba_response_timeout(ni, tap);
}

static void
addba_start_timeout(struct ieee80211_tx_ampdu *tap)
{
	/* XXX use CALLOUT_PENDING instead? */
	callout_reset(&tap->txa_timer, ieee80211_addba_timeout,
	    addba_timeout, tap);
	tap->txa_flags |= IEEE80211_AGGR_XCHGPEND;
	tap->txa_nextrequest = ticks + ieee80211_addba_timeout;
}

static void
addba_stop_timeout(struct ieee80211_tx_ampdu *tap)
{
	/* XXX use CALLOUT_PENDING instead? */
	if (tap->txa_flags & IEEE80211_AGGR_XCHGPEND) {
		callout_stop(&tap->txa_timer);
		tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
	}
}

static void
null_addba_response_timeout(struct ieee80211_node *ni,
    struct ieee80211_tx_ampdu *tap)
{
}

/*
 * Default method for requesting A-MPDU tx aggregation.
 * We setup the specified state block and start a timer
 * to wait for an ADDBA response frame.
 */
static int
ieee80211_addba_request(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap,
	int dialogtoken, int baparamset, int batimeout)
{
	int bufsiz;

	/* XXX locking */
	tap->txa_token = dialogtoken;
	tap->txa_flags |= IEEE80211_AGGR_IMMEDIATE;
	bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
	tap->txa_wnd = (bufsiz == 0) ?
	    IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
	addba_start_timeout(tap);
	return 1;
}

/*
 * Called by drivers that wish to request an ADDBA session be
 * setup.  This brings it up and starts the request timer.
 */
int
ieee80211_ampdu_tx_request_ext(struct ieee80211_node *ni, int tid)
{
	struct ieee80211_tx_ampdu *tap;

	if (tid < 0 || tid > 15)
		return (0);
	tap = &ni->ni_tx_ampdu[tid];

	/* XXX locking */
	if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
		/* do deferred setup of state */
		ampdu_tx_setup(tap);
	}
	/* XXX hack for not doing proper locking */
	tap->txa_flags &= ~IEEE80211_AGGR_NAK;
	addba_start_timeout(tap);
	return (1);
}

/*
 * Called by drivers that have marked a session as active.
 */
int
ieee80211_ampdu_tx_request_active_ext(struct ieee80211_node *ni, int tid,
    int status)
{
	struct ieee80211_tx_ampdu *tap;

	if (tid < 0 || tid > 15)
		return (0);
	tap = &ni->ni_tx_ampdu[tid];

	/* XXX locking */
	addba_stop_timeout(tap);
	if (status == 1) {
		tap->txa_flags |= IEEE80211_AGGR_RUNNING;
		tap->txa_attempts = 0;
	} else {
		/* mark tid so we don't try again */
		tap->txa_flags |= IEEE80211_AGGR_NAK;
	}
	return (1);
}

/*
 * Default method for processing an A-MPDU tx aggregation
 * response.  We shutdown any pending timer and update the
 * state block according to the reply.
 */
static int
ieee80211_addba_response(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap,
	int status, int baparamset, int batimeout)
{
	int bufsiz, tid;

	/* XXX locking */
	addba_stop_timeout(tap);
	if (status == IEEE80211_STATUS_SUCCESS) {
		bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
		/* XXX override our request? */
		tap->txa_wnd = (bufsiz == 0) ?
		    IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
		/* XXX AC/TID */
		tid = MS(baparamset, IEEE80211_BAPS_TID);
		tap->txa_flags |= IEEE80211_AGGR_RUNNING;
		tap->txa_attempts = 0;
	} else {
		/* mark tid so we don't try again */
		tap->txa_flags |= IEEE80211_AGGR_NAK;
	}
	return 1;
}

/*
 * Default method for stopping A-MPDU tx aggregation.
 * Any timer is cleared and we drain any pending frames.
 */
static void
ieee80211_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
{
	/* XXX locking */
	addba_stop_timeout(tap);
	if (tap->txa_flags & IEEE80211_AGGR_RUNNING) {
		/* XXX clear aggregation queue */
		tap->txa_flags &= ~IEEE80211_AGGR_RUNNING;
	}
	tap->txa_attempts = 0;
}

/*
 * Process a received action frame using the default aggregation
 * policy.  We intercept ADDBA-related frames and use them to
 * update our aggregation state.  All other frames are passed up
 * for processing by ieee80211_recv_action.
 */
static int
ht_recv_action_ba_addba_request(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_rx_ampdu *rap;
	uint8_t dialogtoken;
	uint16_t baparamset, batimeout, baseqctl;
	uint16_t args[5];
	int tid;

	dialogtoken = frm[2];
	baparamset = le16dec(frm+3);
	batimeout = le16dec(frm+5);
	baseqctl = le16dec(frm+7);

	tid = MS(baparamset, IEEE80211_BAPS_TID);

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "recv ADDBA request: dialogtoken %u baparamset 0x%x "
	    "(tid %d bufsiz %d) batimeout %d baseqctl %d:%d",
	    dialogtoken, baparamset,
	    tid, MS(baparamset, IEEE80211_BAPS_BUFSIZ),
	    batimeout,
	    MS(baseqctl, IEEE80211_BASEQ_START),
	    MS(baseqctl, IEEE80211_BASEQ_FRAG));

	rap = &ni->ni_rx_ampdu[tid];

	/* Send ADDBA response */
	args[0] = dialogtoken;
	/*
	 * NB: We ack only if the sta associated with HT and
	 * the ap is configured to do AMPDU rx (the latter
	 * violates the 11n spec and is mostly for testing).
	 */
	if ((ni->ni_flags & IEEE80211_NODE_AMPDU_RX) &&
	    (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_RX)) {
		/* XXX handle ampdu_rx_start failure */
		ic->ic_ampdu_rx_start(ni, rap,
		    baparamset, batimeout, baseqctl);

		args[1] = IEEE80211_STATUS_SUCCESS;
	} else {
		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni, "reject ADDBA request: %s",
		    ni->ni_flags & IEEE80211_NODE_AMPDU_RX ?
		       "administratively disabled" :
		       "not negotiated for station");
		vap->iv_stats.is_addba_reject++;
		args[1] = IEEE80211_STATUS_UNSPECIFIED;
	}
	/* XXX honor rap flags? */
	args[2] = IEEE80211_BAPS_POLICY_IMMEDIATE
		| SM(tid, IEEE80211_BAPS_TID)
		| SM(rap->rxa_wnd, IEEE80211_BAPS_BUFSIZ)
		;
	args[3] = 0;
	args[4] = 0;
	ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
		IEEE80211_ACTION_BA_ADDBA_RESPONSE, args);
	return 0;
}

static int
ht_recv_action_ba_addba_response(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211_tx_ampdu *tap;
	uint8_t dialogtoken, policy;
	uint16_t baparamset, batimeout, code;
	int tid, bufsiz;

	dialogtoken = frm[2];
	code = le16dec(frm+3);
	baparamset = le16dec(frm+5);
	tid = MS(baparamset, IEEE80211_BAPS_TID);
	bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
	policy = MS(baparamset, IEEE80211_BAPS_POLICY);
	batimeout = le16dec(frm+7);

	tap = &ni->ni_tx_ampdu[tid];
	if ((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni->ni_macaddr, "ADDBA response",
		    "no pending ADDBA, tid %d dialogtoken %u "
		    "code %d", tid, dialogtoken, code);
		vap->iv_stats.is_addba_norequest++;
		return 0;
	}
	if (dialogtoken != tap->txa_token) {
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni->ni_macaddr, "ADDBA response",
		    "dialogtoken mismatch: waiting for %d, "
		    "received %d, tid %d code %d",
		    tap->txa_token, dialogtoken, tid, code);
		vap->iv_stats.is_addba_badtoken++;
		return 0;
	}
	/* NB: assumes IEEE80211_AGGR_IMMEDIATE is 1 */
	if (policy != (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE)) {
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni->ni_macaddr, "ADDBA response",
		    "policy mismatch: expecting %d, "
		    "received %d, tid %d code %d",
		    tap->txa_flags & IEEE80211_AGGR_IMMEDIATE,
		    policy, tid, code);
		vap->iv_stats.is_addba_badpolicy++;
		return 0;
	}
#if 0
	/* XXX we take MIN in ieee80211_addba_response */
	if (bufsiz > IEEE80211_AGGR_BAWMAX) {
		IEEE80211_DISCARD_MAC(vap,
		    IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni->ni_macaddr, "ADDBA response",
		    "BA window too large: max %d, "
		    "received %d, tid %d code %d",
		    bufsiz, IEEE80211_AGGR_BAWMAX, tid, code);
		vap->iv_stats.is_addba_badbawinsize++;
		return 0;
	}
#endif
	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "recv ADDBA response: dialogtoken %u code %d "
	    "baparamset 0x%x (tid %d bufsiz %d) batimeout %d",
	    dialogtoken, code, baparamset, tid, bufsiz,
	    batimeout);
	ic->ic_addba_response(ni, tap, code, baparamset, batimeout);
	return 0;
}

static int
ht_recv_action_ba_delba(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_rx_ampdu *rap;
	struct ieee80211_tx_ampdu *tap;
	uint16_t baparamset, code;
	int tid;

	baparamset = le16dec(frm+2);
	code = le16dec(frm+4);

	tid = MS(baparamset, IEEE80211_DELBAPS_TID);

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "recv DELBA: baparamset 0x%x (tid %d initiator %d) "
	    "code %d", baparamset, tid,
	    MS(baparamset, IEEE80211_DELBAPS_INIT), code);

	if ((baparamset & IEEE80211_DELBAPS_INIT) == 0) {
		tap = &ni->ni_tx_ampdu[tid];
		ic->ic_addba_stop(ni, tap);
	} else {
		rap = &ni->ni_rx_ampdu[tid];
		ic->ic_ampdu_rx_stop(ni, rap);
	}
	return 0;
}

static int
ht_recv_action_ht_txchwidth(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	int chw;

	chw = (frm[2] == IEEE80211_A_HT_TXCHWIDTH_2040) ? 40 : 20;

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "%s: HT txchwidth, width %d%s",
	    __func__, chw, ni->ni_chw != chw ? "*" : "");
	if (chw != ni->ni_chw) {
		ni->ni_chw = chw;
		/* XXX notify on change */
	}
	return 0;
}

static int
ht_recv_action_ht_mimopwrsave(struct ieee80211_node *ni,
	const struct ieee80211_frame *wh,
	const uint8_t *frm, const uint8_t *efrm)
{
	const struct ieee80211_action_ht_mimopowersave *mps =
	    (const struct ieee80211_action_ht_mimopowersave *) frm;

	/* XXX check iv_htcaps */
	if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_ENA)
		ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
	else
		ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
	if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_MODE)
		ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
	else
		ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
	/* XXX notify on change */
	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "%s: HT MIMO PS (%s%s)", __func__,
	    (ni->ni_flags & IEEE80211_NODE_MIMO_PS) ?  "on" : "off",
	    (ni->ni_flags & IEEE80211_NODE_MIMO_RTS) ?  "+rts" : ""
	);
	return 0;
}

/*
 * Transmit processing.
 */

/*
 * Check if A-MPDU should be requested/enabled for a stream.
 * We require a traffic rate above a per-AC threshold and we
 * also handle backoff from previous failed attempts.
 *
 * Drivers may override this method to bring in information
 * such as link state conditions in making the decision.
 */
static int
ieee80211_ampdu_enable(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap)
{
	struct ieee80211vap *vap = ni->ni_vap;

	if (tap->txa_avgpps <
	    vap->iv_ampdu_mintraffic[TID_TO_WME_AC(tap->txa_tid)])
		return 0;
	/* XXX check rssi? */
	if (tap->txa_attempts >= ieee80211_addba_maxtries &&
	    ieee80211_time_after(ticks, tap->txa_nextrequest)) {
		/*
		 * Don't retry too often; txa_nextrequest is set
		 * to the minimum interval we'll retry after
		 * ieee80211_addba_maxtries failed attempts are made.
		 */
		return 0;
	}
	IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
	    "enable AMPDU on tid %d (%s), avgpps %d pkts %d attempt %d",
	    tap->txa_tid, ieee80211_wme_acnames[TID_TO_WME_AC(tap->txa_tid)],
	    tap->txa_avgpps, tap->txa_pkts, tap->txa_attempts);
	return 1;
}

/*
 * Request A-MPDU tx aggregation.  Setup local state and
 * issue an ADDBA request.  BA use will only happen after
 * the other end replies with ADDBA response.
 */
int
ieee80211_ampdu_request(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap)
{
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t args[5];
	int tid, dialogtoken;
	static int tokens = 0;	/* XXX */

	/* XXX locking */
	if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
		/* do deferred setup of state */
		ampdu_tx_setup(tap);
	}
	/* XXX hack for not doing proper locking */
	tap->txa_flags &= ~IEEE80211_AGGR_NAK;

	dialogtoken = (tokens+1) % 63;		/* XXX */
	tid = tap->txa_tid;
	tap->txa_start = ni->ni_txseqs[tid];

	args[0] = dialogtoken;
	args[1] = 0;	/* NB: status code not used */
	args[2]	= IEEE80211_BAPS_POLICY_IMMEDIATE
		| SM(tid, IEEE80211_BAPS_TID)
		| SM(IEEE80211_AGGR_BAWMAX, IEEE80211_BAPS_BUFSIZ)
		;
	args[3] = 0;	/* batimeout */
	/* NB: do first so there's no race against reply */
	if (!ic->ic_addba_request(ni, tap, dialogtoken, args[2], args[3])) {
		/* unable to setup state, don't make request */
		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
		    ni, "%s: could not setup BA stream for TID %d AC %d",
		    __func__, tap->txa_tid, TID_TO_WME_AC(tap->txa_tid));
		/* defer next try so we don't slam the driver with requests */
		tap->txa_attempts = ieee80211_addba_maxtries;
		/* NB: check in case driver wants to override */
		if (tap->txa_nextrequest <= ticks)
			tap->txa_nextrequest = ticks + ieee80211_addba_backoff;
		return 0;
	}
	tokens = dialogtoken;			/* allocate token */
	/* NB: after calling ic_addba_request so driver can set txa_start */
	args[4] = SM(tap->txa_start, IEEE80211_BASEQ_START)
		| SM(0, IEEE80211_BASEQ_FRAG)
		;
	return ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
		IEEE80211_ACTION_BA_ADDBA_REQUEST, args);
}

/*
 * Terminate an AMPDU tx stream.  State is reclaimed
 * and the peer notified with a DelBA Action frame.
 */
void
ieee80211_ampdu_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
	int reason)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211vap *vap = ni->ni_vap;
	uint16_t args[4];

	/* XXX locking */
	tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
	if (IEEE80211_AMPDU_RUNNING(tap)) {
		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni, "%s: stop BA stream for TID %d (reason: %d (%s))",
		    __func__, tap->txa_tid, reason,
		    ieee80211_reason_to_string(reason));
		vap->iv_stats.is_ampdu_stop++;

		ic->ic_addba_stop(ni, tap);
		args[0] = tap->txa_tid;
		args[1] = IEEE80211_DELBAPS_INIT;
		args[2] = reason;			/* XXX reason code */
		ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
			IEEE80211_ACTION_BA_DELBA, args);
	} else {
		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
		    ni, "%s: BA stream for TID %d not running "
		    "(reason: %d (%s))", __func__, tap->txa_tid, reason,
		    ieee80211_reason_to_string(reason));
		vap->iv_stats.is_ampdu_stop_failed++;
	}
}

/* XXX */
static void bar_start_timer(struct ieee80211_tx_ampdu *tap);

static void
bar_timeout(void *arg)
{
	struct ieee80211_tx_ampdu *tap = arg;
	struct ieee80211_node *ni = tap->txa_ni;

	KASSERT((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0,
	    ("bar/addba collision, flags 0x%x", tap->txa_flags));

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
	    ni, "%s: tid %u flags 0x%x attempts %d", __func__,
	    tap->txa_tid, tap->txa_flags, tap->txa_attempts);

	/* guard against race with bar_tx_complete */
	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
		return;
	/* XXX ? */
	if (tap->txa_attempts >= ieee80211_bar_maxtries) {
		struct ieee80211com *ic = ni->ni_ic;

		ni->ni_vap->iv_stats.is_ampdu_bar_tx_fail++;
		/*
		 * If (at least) the last BAR TX timeout was due to
		 * an ieee80211_send_bar() failures, then we need
		 * to make sure we notify the driver that a BAR
		 * TX did occur and fail.  This gives the driver
		 * a chance to undo any queue pause that may
		 * have occurred.
		 */
		ic->ic_bar_response(ni, tap, 1);
		ieee80211_ampdu_stop(ni, tap, IEEE80211_REASON_TIMEOUT);
	} else {
		ni->ni_vap->iv_stats.is_ampdu_bar_tx_retry++;
		if (ieee80211_send_bar(ni, tap, tap->txa_seqpending) != 0) {
			IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
			    ni, "%s: failed to TX, starting timer\n",
			    __func__);
			/*
			 * If ieee80211_send_bar() fails here, the
			 * timer may have stopped and/or the pending
			 * flag may be clear.  Because of this,
			 * fake the BARPEND and reset the timer.
			 * A retransmission attempt will then occur
			 * during the next timeout.
			 */
			/* XXX locking */
			tap->txa_flags |= IEEE80211_AGGR_BARPEND;
			bar_start_timer(tap);
		}
	}
}

static void
bar_start_timer(struct ieee80211_tx_ampdu *tap)
{
	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: called",
	    __func__);
	callout_reset(&tap->txa_timer, ieee80211_bar_timeout, bar_timeout, tap);
}

static void
bar_stop_timer(struct ieee80211_tx_ampdu *tap)
{
	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: called",
	    __func__);
	callout_stop(&tap->txa_timer);
}

static void
bar_tx_complete(struct ieee80211_node *ni, void *arg, int status)
{
	struct ieee80211_tx_ampdu *tap = arg;

	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
	    ni, "%s: tid %u flags 0x%x pending %d status %d",
	    __func__, tap->txa_tid, tap->txa_flags,
	    callout_pending(&tap->txa_timer), status);

	ni->ni_vap->iv_stats.is_ampdu_bar_tx++;
	/* XXX locking */
	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) &&
	    callout_pending(&tap->txa_timer)) {
		struct ieee80211com *ic = ni->ni_ic;

		if (status == 0)		/* ACK'd */
			bar_stop_timer(tap);
		ic->ic_bar_response(ni, tap, status);
		/* NB: just let timer expire so we pace requests */
	}
}

static void
ieee80211_bar_response(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap, int status)
{

	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: called",
	    __func__);
	if (status == 0) {		/* got ACK */
		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
		    ni, "BAR moves BA win <%u:%u> (%u frames) txseq %u tid %u",
		    tap->txa_start,
		    IEEE80211_SEQ_ADD(tap->txa_start, tap->txa_wnd-1),
		    tap->txa_qframes, tap->txa_seqpending,
		    tap->txa_tid);

		/* NB: timer already stopped in bar_tx_complete */
		tap->txa_start = tap->txa_seqpending;
		tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
	}
}

/*
 * Transmit a BAR frame to the specified node.  The
 * BAR contents are drawn from the supplied aggregation
 * state associated with the node.
 *
 * NB: we only handle immediate ACK w/ compressed bitmap.
 */
int
ieee80211_send_bar(struct ieee80211_node *ni,
	struct ieee80211_tx_ampdu *tap, ieee80211_seq seq)
{
#define	senderr(_x, _v)	do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211_frame_bar *bar;
	struct mbuf *m;
	uint16_t barctl, barseqctl;
	uint8_t *frm;
	int tid, ret;


	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: called",
	    __func__);

	if ((tap->txa_flags & IEEE80211_AGGR_RUNNING) == 0) {
		/* no ADDBA response, should not happen */
		/* XXX stat+msg */
		return EINVAL;
	}
	/* XXX locking */
	bar_stop_timer(tap);

	ieee80211_ref_node(ni);

	m = ieee80211_getmgtframe(&frm, ic->ic_headroom, sizeof(*bar));
	if (m == NULL)
		senderr(ENOMEM, is_tx_nobuf);

	if (!ieee80211_add_callback(m, bar_tx_complete, tap)) {
		m_freem(m);
		senderr(ENOMEM, is_tx_nobuf);	/* XXX */
		/* NOTREACHED */
	}

	bar = mtod(m, struct ieee80211_frame_bar *);
	bar->i_fc[0] = IEEE80211_FC0_VERSION_0 |
		IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR;
	bar->i_fc[1] = 0;
	IEEE80211_ADDR_COPY(bar->i_ra, ni->ni_macaddr);
	IEEE80211_ADDR_COPY(bar->i_ta, vap->iv_myaddr);

	tid = tap->txa_tid;
	barctl 	= (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE ?
			0 : IEEE80211_BAR_NOACK)
		| IEEE80211_BAR_COMP
		| SM(tid, IEEE80211_BAR_TID)
		;
	barseqctl = SM(seq, IEEE80211_BAR_SEQ_START);
	/* NB: known to have proper alignment */
	bar->i_ctl = htole16(barctl);
	bar->i_seq = htole16(barseqctl);
	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_bar);

	M_WME_SETAC(m, WME_AC_VO);

	IEEE80211_NODE_STAT(ni, tx_mgmt);	/* XXX tx_ctl? */

	/* XXX locking */
	/* init/bump attempts counter */
	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
		tap->txa_attempts = 1;
	else
		tap->txa_attempts++;
	tap->txa_seqpending = seq;
	tap->txa_flags |= IEEE80211_AGGR_BARPEND;

	IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
	    ni, "send BAR: tid %u ctl 0x%x start %u (attempt %d)",
	    tid, barctl, seq, tap->txa_attempts);

	/*
	 * ic_raw_xmit will free the node reference
	 * regardless of queue/TX success or failure.
	 */
	IEEE80211_TX_LOCK(ic);
	ret = ieee80211_raw_output(vap, ni, m, NULL);
	IEEE80211_TX_UNLOCK(ic);
	if (ret != 0) {
		IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
		    ni, "send BAR: failed: (ret = %d)\n",
		    ret);
		/* xmit failed, clear state flag */
		tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
		vap->iv_stats.is_ampdu_bar_tx_fail++;
		return ret;
	}
	/* XXX hack against tx complete happening before timer is started */
	if (tap->txa_flags & IEEE80211_AGGR_BARPEND)
		bar_start_timer(tap);
	return 0;
bad:
	IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
	    tap->txa_ni,
	    "%s: bad! ret=%d",
	    __func__, ret);
	vap->iv_stats.is_ampdu_bar_tx_fail++;
	ieee80211_free_node(ni);
	return ret;
#undef senderr
}

static int
ht_action_output(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;
	/* NB: we know all frames are unicast */
	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)

/*
 * Send an action management frame.  The arguments are stuff
 * into a frame without inspection; the caller is assumed to
 * prepare them carefully (e.g. based on the aggregation state).
 */
static int
ht_send_action_ba_addba(struct ieee80211_node *ni,
	int category, int action, void *arg0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;
	uint16_t *args = arg0;
	struct mbuf *m;
	uint8_t *frm;

	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "send ADDBA %s: dialogtoken %d status %d "
	    "baparamset 0x%x (tid %d) batimeout 0x%x baseqctl 0x%x",
	    (action == IEEE80211_ACTION_BA_ADDBA_REQUEST) ?
		"request" : "response",
	    args[0], args[1], args[2], MS(args[2], IEEE80211_BAPS_TID),
	    args[3], args[4]);

	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 */
	    /* XXX may action payload */
	    + sizeof(struct ieee80211_action_ba_addbaresponse)
	);
	if (m != NULL) {
		*frm++ = category;
		*frm++ = action;
		*frm++ = args[0];		/* dialog token */
		if (action == IEEE80211_ACTION_BA_ADDBA_RESPONSE)
			ADDSHORT(frm, args[1]);	/* status code */
		ADDSHORT(frm, args[2]);		/* baparamset */
		ADDSHORT(frm, args[3]);		/* batimeout */
		if (action == IEEE80211_ACTION_BA_ADDBA_REQUEST)
			ADDSHORT(frm, args[4]);	/* baseqctl */
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return ht_action_output(ni, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

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

	baparamset = SM(args[0], IEEE80211_DELBAPS_TID)
		   | args[1]
		   ;
	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
	    "send DELBA action: tid %d, initiator %d reason %d (%s)",
	    args[0], args[1], args[2], ieee80211_reason_to_string(args[2]));

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

	m = ieee80211_getmgtframe(&frm,
	    ic->ic_headroom + sizeof(struct ieee80211_frame),
	    sizeof(uint16_t)	/* action+category */
	    /* XXX may action payload */
	    + sizeof(struct ieee80211_action_ba_addbaresponse)
	);
	if (m != NULL) {
		*frm++ = category;
		*frm++ = action;
		ADDSHORT(frm, baparamset);
		ADDSHORT(frm, args[2]);		/* reason code */
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return ht_action_output(ni, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}

static int
ht_send_action_ht_txchwidth(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_11N, ni,
	    "send HT txchwidth: width %d",
	    IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 40 : 20);

	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 */
	    /* XXX may action payload */
	    + sizeof(struct ieee80211_action_ba_addbaresponse)
	);
	if (m != NULL) {
		*frm++ = category;
		*frm++ = action;
		*frm++ = IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 
			IEEE80211_A_HT_TXCHWIDTH_2040 :
			IEEE80211_A_HT_TXCHWIDTH_20;
		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
		return ht_action_output(ni, m);
	} else {
		vap->iv_stats.is_tx_nobuf++;
		ieee80211_free_node(ni);
		return ENOMEM;
	}
}
#undef ADDSHORT

/*
 * Construct the MCS bit mask for inclusion in an HT capabilities
 * information element.
 */
static void
ieee80211_set_mcsset(struct ieee80211com *ic, uint8_t *frm)
{
	int i;
	uint8_t txparams;

	KASSERT((ic->ic_rxstream > 0 && ic->ic_rxstream <= 4),
	    ("ic_rxstream %d out of range", ic->ic_rxstream));
	KASSERT((ic->ic_txstream > 0 && ic->ic_txstream <= 4),
	    ("ic_txstream %d out of range", ic->ic_txstream));

	for (i = 0; i < ic->ic_rxstream * 8; i++)
		setbit(frm, i);
	if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
	    (ic->ic_htcaps & IEEE80211_HTC_RXMCS32))
		setbit(frm, 32);
	if (ic->ic_htcaps & IEEE80211_HTC_RXUNEQUAL) {
		if (ic->ic_rxstream >= 2) {
			for (i = 33; i <= 38; i++)
				setbit(frm, i);
		}
		if (ic->ic_rxstream >= 3) {
			for (i = 39; i <= 52; i++)
				setbit(frm, i);
		}
		if (ic->ic_txstream >= 4) {
			for (i = 53; i <= 76; i++)
				setbit(frm, i);
		}
	}

	if (ic->ic_rxstream != ic->ic_txstream) {
		txparams = 0x1;			/* TX MCS set defined */
		txparams |= 0x2;		/* TX RX MCS not equal */
		txparams |= (ic->ic_txstream - 1) << 2;	/* num TX streams */
		if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL)
			txparams |= 0x16;	/* TX unequal modulation sup */
	} else
		txparams = 0;
	frm[12] = txparams;
}

/*
 * Add body of an HTCAP information element.
 */
static uint8_t *
ieee80211_add_htcap_body(uint8_t *frm, struct ieee80211_node *ni)
{
#define	ADDSHORT(frm, v) do {			\
	frm[0] = (v) & 0xff;			\
	frm[1] = (v) >> 8;			\
	frm += 2;				\
} while (0)
	struct ieee80211com *ic = ni->ni_ic;
	struct ieee80211vap *vap = ni->ni_vap;
	uint16_t caps, extcaps;
	int rxmax, density;

	/* HT capabilities */
	caps = vap->iv_htcaps & 0xffff;
	/*
	 * Note channel width depends on whether we are operating as
	 * a sta or not.  When operating as a sta we are generating
	 * a request based on our desired configuration.  Otherwise
	 * we are operational and the channel attributes identify
	 * how we've been setup (which might be different if a fixed
	 * channel is specified).
	 */
	if (vap->iv_opmode == IEEE80211_M_STA) {
		/* override 20/40 use based on config */
		if (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)
			caps |= IEEE80211_HTCAP_CHWIDTH40;
		else
			caps &= ~IEEE80211_HTCAP_CHWIDTH40;

		/* Start by using the advertised settings */
		rxmax = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU);
		density = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY);

		IEEE80211_DPRINTF(vap, IEEE80211_MSG_11N,
		    "%s: advertised rxmax=%d, density=%d, vap rxmax=%d, density=%d\n",
		    __func__,
		    rxmax,
		    density,
		    vap->iv_ampdu_rxmax,
		    vap->iv_ampdu_density);

		/* Cap at VAP rxmax */
		if (rxmax > vap->iv_ampdu_rxmax)
			rxmax = vap->iv_ampdu_rxmax;

		/*
		 * If the VAP ampdu density value greater, use that.
		 *
		 * (Larger density value == larger minimum gap between A-MPDU
		 * subframes.)
		 */
		if (vap->iv_ampdu_density > density)
			density = vap->iv_ampdu_density;

		/*
		 * NB: Hardware might support HT40 on some but not all
		 * channels. We can't determine this earlier because only
		 * after association the channel is upgraded to HT based
		 * on the negotiated capabilities.
		 */
		if (ni->ni_chan != IEEE80211_CHAN_ANYC &&
		    findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT40U) == NULL &&
		    findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT40D) == NULL)
			caps &= ~IEEE80211_HTCAP_CHWIDTH40;
	} else {
		/* override 20/40 use based on current channel */
		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
			caps |= IEEE80211_HTCAP_CHWIDTH40;
		else
			caps &= ~IEEE80211_HTCAP_CHWIDTH40;

		/* XXX TODO should it start by using advertised settings? */
		rxmax = vap->iv_ampdu_rxmax;
		density = vap->iv_ampdu_density;
	}

	/* adjust short GI based on channel and config */
	if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
		caps &= ~IEEE80211_HTCAP_SHORTGI20;
	if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0 ||
	    (caps & IEEE80211_HTCAP_CHWIDTH40) == 0)
		caps &= ~IEEE80211_HTCAP_SHORTGI40;

	/* adjust STBC based on receive capabilities */
	if ((vap->iv_flags_ht & IEEE80211_FHT_STBC_RX) == 0)
		caps &= ~IEEE80211_HTCAP_RXSTBC;

	/* XXX TODO: adjust LDPC based on receive capabilities */

	ADDSHORT(frm, caps);

	/* HT parameters */
	*frm = SM(rxmax, IEEE80211_HTCAP_MAXRXAMPDU)
	     | SM(density, IEEE80211_HTCAP_MPDUDENSITY)
	     ;
	frm++;

	/* pre-zero remainder of ie */
	memset(frm, 0, sizeof(struct ieee80211_ie_htcap) - 
		__offsetof(struct ieee80211_ie_htcap, hc_mcsset));

	/* supported MCS set */
	/*
	 * XXX: For sta mode the rate set should be restricted based
	 * on the AP's capabilities, but ni_htrates isn't setup when
	 * we're called to form an AssocReq frame so for now we're
	 * restricted to the device capabilities.
	 */
	ieee80211_set_mcsset(ni->ni_ic, frm);

	frm += __offsetof(struct ieee80211_ie_htcap, hc_extcap) -
		__offsetof(struct ieee80211_ie_htcap, hc_mcsset);

	/* HT extended capabilities */
	extcaps = vap->iv_htextcaps & 0xffff;

	ADDSHORT(frm, extcaps);

	frm += sizeof(struct ieee80211_ie_htcap) -
		__offsetof(struct ieee80211_ie_htcap, hc_txbf);

	return frm;
#undef ADDSHORT
}

/*
 * Add 802.11n HT capabilities information element
 */
uint8_t *
ieee80211_add_htcap(uint8_t *frm, struct ieee80211_node *ni)
{
	frm[0] = IEEE80211_ELEMID_HTCAP;
	frm[1] = sizeof(struct ieee80211_ie_htcap) - 2;
	return ieee80211_add_htcap_body(frm + 2, ni);
}

/*
 * Add Broadcom OUI wrapped standard HTCAP ie; this is
 * used for compatibility w/ pre-draft implementations.
 */
uint8_t *
ieee80211_add_htcap_vendor(uint8_t *frm, struct ieee80211_node *ni)
{
	frm[0] = IEEE80211_ELEMID_VENDOR;
	frm[1] = 4 + sizeof(struct ieee80211_ie_htcap) - 2;
	frm[2] = (BCM_OUI >> 0) & 0xff;
	frm[3] = (BCM_OUI >> 8) & 0xff;
	frm[4] = (BCM_OUI >> 16) & 0xff;
	frm[5] = BCM_OUI_HTCAP;
	return ieee80211_add_htcap_body(frm + 6, ni);
}

/*
 * Construct the MCS bit mask of basic rates
 * for inclusion in an HT information element.
 */
static void
ieee80211_set_basic_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
{
	int i;

	for (i = 0; i < rs->rs_nrates; i++) {
		int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
		if ((rs->rs_rates[i] & IEEE80211_RATE_BASIC) &&
		    r < IEEE80211_HTRATE_MAXSIZE) {
			/* NB: this assumes a particular implementation */
			setbit(frm, r);
		}
	}
}

/*
 * Update the HTINFO ie for a beacon frame.
 */
void
ieee80211_ht_update_beacon(struct ieee80211vap *vap,
	struct ieee80211_beacon_offsets *bo)
{
#define	PROTMODE	(IEEE80211_HTINFO_OPMODE|IEEE80211_HTINFO_NONHT_PRESENT)
	struct ieee80211_node *ni;
	const struct ieee80211_channel *bsschan;
	struct ieee80211com *ic = vap->iv_ic;
	struct ieee80211_ie_htinfo *ht =
	   (struct ieee80211_ie_htinfo *) bo->bo_htinfo;

	ni = ieee80211_ref_node(vap->iv_bss);
	bsschan = ni->ni_chan;

	/* XXX only update on channel change */
	ht->hi_ctrlchannel = ieee80211_chan2ieee(ic, bsschan);
	if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
		ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PERM;
	else
		ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PROH;
	if (IEEE80211_IS_CHAN_HT40U(bsschan))
		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
	else if (IEEE80211_IS_CHAN_HT40D(bsschan))
		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_BELOW;
	else
		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_NONE;
	if (IEEE80211_IS_CHAN_HT40(bsschan))
		ht->hi_byte1 |= IEEE80211_HTINFO_TXWIDTH_2040;

	/* protection mode */
	ht->hi_byte2 = (ht->hi_byte2 &~ PROTMODE) | ic->ic_curhtprotmode;

	ieee80211_free_node(ni);

	/* XXX propagate to vendor ie's */
#undef PROTMODE
}

/*
 * Add body of an HTINFO information element.
 *
 * NB: We don't use struct ieee80211_ie_htinfo because we can
 * be called to fillin both a standard ie and a compat ie that
 * has a vendor OUI at the front.
 */
static uint8_t *
ieee80211_add_htinfo_body(uint8_t *frm, struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ieee80211com *ic = ni->ni_ic;

	/* pre-zero remainder of ie */
	memset(frm, 0, sizeof(struct ieee80211_ie_htinfo) - 2);

	/* primary/control channel center */
	*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);

	if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
		frm[0] = IEEE80211_HTINFO_RIFSMODE_PERM;
	else
		frm[0] = IEEE80211_HTINFO_RIFSMODE_PROH;
	if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
		frm[0] |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
	else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
		frm[0] |= IEEE80211_HTINFO_2NDCHAN_BELOW;
	else
		frm[0] |= IEEE80211_HTINFO_2NDCHAN_NONE;
	if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
		frm[0] |= IEEE80211_HTINFO_TXWIDTH_2040;

	frm[1] = ic->ic_curhtprotmode;

	frm += 5;

	/* basic MCS set */
	ieee80211_set_basic_htrates(frm, &ni->ni_htrates);
	frm += sizeof(struct ieee80211_ie_htinfo) -
		__offsetof(struct ieee80211_ie_htinfo, hi_basicmcsset);
	return frm;
}

/*
 * Add 802.11n HT information information element.
 */
uint8_t *
ieee80211_add_htinfo(uint8_t *frm, struct ieee80211_node *ni)
{
	frm[0] = IEEE80211_ELEMID_HTINFO;
	frm[1] = sizeof(struct ieee80211_ie_htinfo) - 2;
	return ieee80211_add_htinfo_body(frm + 2, ni);
}

/*
 * Add Broadcom OUI wrapped standard HTINFO ie; this is
 * used for compatibility w/ pre-draft implementations.
 */
uint8_t *
ieee80211_add_htinfo_vendor(uint8_t *frm, struct ieee80211_node *ni)
{
	frm[0] = IEEE80211_ELEMID_VENDOR;
	frm[1] = 4 + sizeof(struct ieee80211_ie_htinfo) - 2;
	frm[2] = (BCM_OUI >> 0) & 0xff;
	frm[3] = (BCM_OUI >> 8) & 0xff;
	frm[4] = (BCM_OUI >> 16) & 0xff;
	frm[5] = BCM_OUI_HTINFO;
	return ieee80211_add_htinfo_body(frm + 6, ni);
}