]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net80211/ieee80211_ht.c
MFV r361938:
[FreeBSD/FreeBSD.git] / sys / net80211 / ieee80211_ht.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007-2008 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 #ifdef __FreeBSD__
30 __FBSDID("$FreeBSD$");
31 #endif
32
33 /*
34  * IEEE 802.11n protocol support.
35  */
36
37 #include "opt_inet.h"
38 #include "opt_wlan.h"
39
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/systm.h> 
44 #include <sys/endian.h>
45  
46 #include <sys/socket.h>
47
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_media.h>
51 #include <net/ethernet.h>
52
53 #include <net80211/ieee80211_var.h>
54 #include <net80211/ieee80211_action.h>
55 #include <net80211/ieee80211_input.h>
56
57 /* define here, used throughout file */
58 #define MS(_v, _f)      (((_v) & _f) >> _f##_S)
59 #define SM(_v, _f)      (((_v) << _f##_S) & _f)
60
61 const struct ieee80211_mcs_rates ieee80211_htrates[IEEE80211_HTRATE_MAXSIZE] = {
62         {  13,  14,   27,   30 },       /* MCS 0 */
63         {  26,  29,   54,   60 },       /* MCS 1 */
64         {  39,  43,   81,   90 },       /* MCS 2 */
65         {  52,  58,  108,  120 },       /* MCS 3 */
66         {  78,  87,  162,  180 },       /* MCS 4 */
67         { 104, 116,  216,  240 },       /* MCS 5 */
68         { 117, 130,  243,  270 },       /* MCS 6 */
69         { 130, 144,  270,  300 },       /* MCS 7 */
70         {  26,  29,   54,   60 },       /* MCS 8 */
71         {  52,  58,  108,  120 },       /* MCS 9 */
72         {  78,  87,  162,  180 },       /* MCS 10 */
73         { 104, 116,  216,  240 },       /* MCS 11 */
74         { 156, 173,  324,  360 },       /* MCS 12 */
75         { 208, 231,  432,  480 },       /* MCS 13 */
76         { 234, 260,  486,  540 },       /* MCS 14 */
77         { 260, 289,  540,  600 },       /* MCS 15 */
78         {  39,  43,   81,   90 },       /* MCS 16 */
79         {  78,  87,  162,  180 },       /* MCS 17 */
80         { 117, 130,  243,  270 },       /* MCS 18 */
81         { 156, 173,  324,  360 },       /* MCS 19 */
82         { 234, 260,  486,  540 },       /* MCS 20 */
83         { 312, 347,  648,  720 },       /* MCS 21 */
84         { 351, 390,  729,  810 },       /* MCS 22 */
85         { 390, 433,  810,  900 },       /* MCS 23 */
86         {  52,  58,  108,  120 },       /* MCS 24 */
87         { 104, 116,  216,  240 },       /* MCS 25 */
88         { 156, 173,  324,  360 },       /* MCS 26 */
89         { 208, 231,  432,  480 },       /* MCS 27 */
90         { 312, 347,  648,  720 },       /* MCS 28 */
91         { 416, 462,  864,  960 },       /* MCS 29 */
92         { 468, 520,  972, 1080 },       /* MCS 30 */
93         { 520, 578, 1080, 1200 },       /* MCS 31 */
94         {   0,   0,   12,   13 },       /* MCS 32 */
95         {  78,  87,  162,  180 },       /* MCS 33 */
96         { 104, 116,  216,  240 },       /* MCS 34 */
97         { 130, 144,  270,  300 },       /* MCS 35 */
98         { 117, 130,  243,  270 },       /* MCS 36 */
99         { 156, 173,  324,  360 },       /* MCS 37 */
100         { 195, 217,  405,  450 },       /* MCS 38 */
101         { 104, 116,  216,  240 },       /* MCS 39 */
102         { 130, 144,  270,  300 },       /* MCS 40 */
103         { 130, 144,  270,  300 },       /* MCS 41 */
104         { 156, 173,  324,  360 },       /* MCS 42 */
105         { 182, 202,  378,  420 },       /* MCS 43 */
106         { 182, 202,  378,  420 },       /* MCS 44 */
107         { 208, 231,  432,  480 },       /* MCS 45 */
108         { 156, 173,  324,  360 },       /* MCS 46 */
109         { 195, 217,  405,  450 },       /* MCS 47 */
110         { 195, 217,  405,  450 },       /* MCS 48 */
111         { 234, 260,  486,  540 },       /* MCS 49 */
112         { 273, 303,  567,  630 },       /* MCS 50 */
113         { 273, 303,  567,  630 },       /* MCS 51 */
114         { 312, 347,  648,  720 },       /* MCS 52 */
115         { 130, 144,  270,  300 },       /* MCS 53 */
116         { 156, 173,  324,  360 },       /* MCS 54 */
117         { 182, 202,  378,  420 },       /* MCS 55 */
118         { 156, 173,  324,  360 },       /* MCS 56 */
119         { 182, 202,  378,  420 },       /* MCS 57 */
120         { 208, 231,  432,  480 },       /* MCS 58 */
121         { 234, 260,  486,  540 },       /* MCS 59 */
122         { 208, 231,  432,  480 },       /* MCS 60 */
123         { 234, 260,  486,  540 },       /* MCS 61 */
124         { 260, 289,  540,  600 },       /* MCS 62 */
125         { 260, 289,  540,  600 },       /* MCS 63 */
126         { 286, 318,  594,  660 },       /* MCS 64 */
127         { 195, 217,  405,  450 },       /* MCS 65 */
128         { 234, 260,  486,  540 },       /* MCS 66 */
129         { 273, 303,  567,  630 },       /* MCS 67 */
130         { 234, 260,  486,  540 },       /* MCS 68 */
131         { 273, 303,  567,  630 },       /* MCS 69 */
132         { 312, 347,  648,  720 },       /* MCS 70 */
133         { 351, 390,  729,  810 },       /* MCS 71 */
134         { 312, 347,  648,  720 },       /* MCS 72 */
135         { 351, 390,  729,  810 },       /* MCS 73 */
136         { 390, 433,  810,  900 },       /* MCS 74 */
137         { 390, 433,  810,  900 },       /* MCS 75 */
138         { 429, 477,  891,  990 },       /* MCS 76 */
139 };
140
141 static  int ieee80211_ampdu_age = -1;   /* threshold for ampdu reorder q (ms) */
142 SYSCTL_PROC(_net_wlan, OID_AUTO, ampdu_age,
143     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
144     &ieee80211_ampdu_age, 0, ieee80211_sysctl_msecs_ticks, "I",
145     "AMPDU max reorder age (ms)");
146
147 static  int ieee80211_recv_bar_ena = 1;
148 SYSCTL_INT(_net_wlan, OID_AUTO, recv_bar, CTLFLAG_RW, &ieee80211_recv_bar_ena,
149             0, "BAR frame processing (ena/dis)");
150
151 static  int ieee80211_addba_timeout = -1;/* timeout for ADDBA response */
152 SYSCTL_PROC(_net_wlan, OID_AUTO, addba_timeout,
153     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
154     &ieee80211_addba_timeout, 0, ieee80211_sysctl_msecs_ticks, "I",
155     "ADDBA request timeout (ms)");
156 static  int ieee80211_addba_backoff = -1;/* backoff after max ADDBA requests */
157 SYSCTL_PROC(_net_wlan, OID_AUTO, addba_backoff,
158     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
159     &ieee80211_addba_backoff, 0, ieee80211_sysctl_msecs_ticks, "I",
160     "ADDBA request backoff (ms)");
161 static  int ieee80211_addba_maxtries = 3;/* max ADDBA requests before backoff */
162 SYSCTL_INT(_net_wlan, OID_AUTO, addba_maxtries, CTLFLAG_RW,
163         &ieee80211_addba_maxtries, 0, "max ADDBA requests sent before backoff");
164
165 static  int ieee80211_bar_timeout = -1; /* timeout waiting for BAR response */
166 static  int ieee80211_bar_maxtries = 50;/* max BAR requests before DELBA */
167
168 static  ieee80211_recv_action_func ht_recv_action_ba_addba_request;
169 static  ieee80211_recv_action_func ht_recv_action_ba_addba_response;
170 static  ieee80211_recv_action_func ht_recv_action_ba_delba;
171 static  ieee80211_recv_action_func ht_recv_action_ht_mimopwrsave;
172 static  ieee80211_recv_action_func ht_recv_action_ht_txchwidth;
173
174 static  ieee80211_send_action_func ht_send_action_ba_addba;
175 static  ieee80211_send_action_func ht_send_action_ba_delba;
176 static  ieee80211_send_action_func ht_send_action_ht_txchwidth;
177
178 static void
179 ieee80211_ht_init(void)
180 {
181         /*
182          * Setup HT parameters that depends on the clock frequency.
183          */
184         ieee80211_ampdu_age = msecs_to_ticks(500);
185         ieee80211_addba_timeout = msecs_to_ticks(250);
186         ieee80211_addba_backoff = msecs_to_ticks(10*1000);
187         ieee80211_bar_timeout = msecs_to_ticks(250);
188         /*
189          * Register action frame handlers.
190          */
191         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
192             IEEE80211_ACTION_BA_ADDBA_REQUEST, ht_recv_action_ba_addba_request);
193         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
194             IEEE80211_ACTION_BA_ADDBA_RESPONSE, ht_recv_action_ba_addba_response);
195         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_BA, 
196             IEEE80211_ACTION_BA_DELBA, ht_recv_action_ba_delba);
197         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_HT, 
198             IEEE80211_ACTION_HT_MIMOPWRSAVE, ht_recv_action_ht_mimopwrsave);
199         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_HT, 
200             IEEE80211_ACTION_HT_TXCHWIDTH, ht_recv_action_ht_txchwidth);
201
202         ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
203             IEEE80211_ACTION_BA_ADDBA_REQUEST, ht_send_action_ba_addba);
204         ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
205             IEEE80211_ACTION_BA_ADDBA_RESPONSE, ht_send_action_ba_addba);
206         ieee80211_send_action_register(IEEE80211_ACTION_CAT_BA, 
207             IEEE80211_ACTION_BA_DELBA, ht_send_action_ba_delba);
208         ieee80211_send_action_register(IEEE80211_ACTION_CAT_HT, 
209             IEEE80211_ACTION_HT_TXCHWIDTH, ht_send_action_ht_txchwidth);
210 }
211 SYSINIT(wlan_ht, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_ht_init, NULL);
212
213 static int ieee80211_ampdu_enable(struct ieee80211_node *ni,
214         struct ieee80211_tx_ampdu *tap);
215 static int ieee80211_addba_request(struct ieee80211_node *ni,
216         struct ieee80211_tx_ampdu *tap,
217         int dialogtoken, int baparamset, int batimeout);
218 static int ieee80211_addba_response(struct ieee80211_node *ni,
219         struct ieee80211_tx_ampdu *tap,
220         int code, int baparamset, int batimeout);
221 static void ieee80211_addba_stop(struct ieee80211_node *ni,
222         struct ieee80211_tx_ampdu *tap);
223 static void null_addba_response_timeout(struct ieee80211_node *ni,
224         struct ieee80211_tx_ampdu *tap);
225
226 static void ieee80211_bar_response(struct ieee80211_node *ni,
227         struct ieee80211_tx_ampdu *tap, int status);
228 static void ampdu_tx_stop(struct ieee80211_tx_ampdu *tap);
229 static void bar_stop_timer(struct ieee80211_tx_ampdu *tap);
230 static int ampdu_rx_start(struct ieee80211_node *, struct ieee80211_rx_ampdu *,
231         int baparamset, int batimeout, int baseqctl);
232 static void ampdu_rx_stop(struct ieee80211_node *, struct ieee80211_rx_ampdu *);
233
234 void
235 ieee80211_ht_attach(struct ieee80211com *ic)
236 {
237         /* setup default aggregation policy */
238         ic->ic_recv_action = ieee80211_recv_action;
239         ic->ic_send_action = ieee80211_send_action;
240         ic->ic_ampdu_enable = ieee80211_ampdu_enable;
241         ic->ic_addba_request = ieee80211_addba_request;
242         ic->ic_addba_response = ieee80211_addba_response;
243         ic->ic_addba_response_timeout = null_addba_response_timeout;
244         ic->ic_addba_stop = ieee80211_addba_stop;
245         ic->ic_bar_response = ieee80211_bar_response;
246         ic->ic_ampdu_rx_start = ampdu_rx_start;
247         ic->ic_ampdu_rx_stop = ampdu_rx_stop;
248
249         ic->ic_htprotmode = IEEE80211_PROT_RTSCTS;
250         ic->ic_curhtprotmode = IEEE80211_HTINFO_OPMODE_PURE;
251 }
252
253 void
254 ieee80211_ht_detach(struct ieee80211com *ic)
255 {
256 }
257
258 void
259 ieee80211_ht_vattach(struct ieee80211vap *vap)
260 {
261
262         /* driver can override defaults */
263         vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_8K;
264         vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_NA;
265         vap->iv_ampdu_limit = vap->iv_ampdu_rxmax;
266         vap->iv_amsdu_limit = vap->iv_htcaps & IEEE80211_HTCAP_MAXAMSDU;
267         /* tx aggregation traffic thresholds */
268         vap->iv_ampdu_mintraffic[WME_AC_BK] = 128;
269         vap->iv_ampdu_mintraffic[WME_AC_BE] = 64;
270         vap->iv_ampdu_mintraffic[WME_AC_VO] = 32;
271         vap->iv_ampdu_mintraffic[WME_AC_VI] = 32;
272
273         if (vap->iv_htcaps & IEEE80211_HTC_HT) {
274                 /*
275                  * Device is HT capable; enable all HT-related
276                  * facilities by default.
277                  * XXX these choices may be too aggressive.
278                  */
279                 vap->iv_flags_ht |= IEEE80211_FHT_HT
280                                  |  IEEE80211_FHT_HTCOMPAT
281                                  ;
282                 if (vap->iv_htcaps & IEEE80211_HTCAP_SHORTGI20)
283                         vap->iv_flags_ht |= IEEE80211_FHT_SHORTGI20;
284                 /* XXX infer from channel list? */
285                 if (vap->iv_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
286                         vap->iv_flags_ht |= IEEE80211_FHT_USEHT40;
287                         if (vap->iv_htcaps & IEEE80211_HTCAP_SHORTGI40)
288                                 vap->iv_flags_ht |= IEEE80211_FHT_SHORTGI40;
289                 }
290                 /* enable RIFS if capable */
291                 if (vap->iv_htcaps & IEEE80211_HTC_RIFS)
292                         vap->iv_flags_ht |= IEEE80211_FHT_RIFS;
293
294                 /* NB: A-MPDU and A-MSDU rx are mandated, these are tx only */
295                 vap->iv_flags_ht |= IEEE80211_FHT_AMPDU_RX;
296                 if (vap->iv_htcaps & IEEE80211_HTC_AMPDU)
297                         vap->iv_flags_ht |= IEEE80211_FHT_AMPDU_TX;
298                 vap->iv_flags_ht |= IEEE80211_FHT_AMSDU_RX;
299                 if (vap->iv_htcaps & IEEE80211_HTC_AMSDU)
300                         vap->iv_flags_ht |= IEEE80211_FHT_AMSDU_TX;
301
302                 if (vap->iv_htcaps & IEEE80211_HTCAP_TXSTBC)
303                         vap->iv_flags_ht |= IEEE80211_FHT_STBC_TX;
304                 if (vap->iv_htcaps & IEEE80211_HTCAP_RXSTBC)
305                         vap->iv_flags_ht |= IEEE80211_FHT_STBC_RX;
306
307                 if (vap->iv_htcaps & IEEE80211_HTCAP_LDPC)
308                         vap->iv_flags_ht |= IEEE80211_FHT_LDPC_RX;
309                 if (vap->iv_htcaps & IEEE80211_HTC_TXLDPC)
310                         vap->iv_flags_ht |= IEEE80211_FHT_LDPC_TX;
311         }
312         /* NB: disable default legacy WDS, too many issues right now */
313         if (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY)
314                 vap->iv_flags_ht &= ~IEEE80211_FHT_HT;
315 }
316
317 void
318 ieee80211_ht_vdetach(struct ieee80211vap *vap)
319 {
320 }
321
322 static int
323 ht_getrate(struct ieee80211com *ic, int index, enum ieee80211_phymode mode,
324     int ratetype)
325 {
326         int mword, rate;
327
328         mword = ieee80211_rate2media(ic, index | IEEE80211_RATE_MCS, mode);
329         if (IFM_SUBTYPE(mword) != IFM_IEEE80211_MCS)
330                 return (0);
331         switch (ratetype) {
332         case 0:
333                 rate = ieee80211_htrates[index].ht20_rate_800ns;
334                 break;
335         case 1:
336                 rate = ieee80211_htrates[index].ht20_rate_400ns;
337                 break;
338         case 2:
339                 rate = ieee80211_htrates[index].ht40_rate_800ns;
340                 break;
341         default:
342                 rate = ieee80211_htrates[index].ht40_rate_400ns;
343                 break;
344         }
345         return (rate);
346 }
347
348 static struct printranges {
349         int     minmcs;
350         int     maxmcs;
351         int     txstream;
352         int     ratetype;
353         int     htcapflags;
354 } ranges[] = {
355         {  0,  7, 1, 0, 0 },
356         {  8, 15, 2, 0, 0 },
357         { 16, 23, 3, 0, 0 },
358         { 24, 31, 4, 0, 0 },
359         { 32,  0, 1, 2, IEEE80211_HTC_TXMCS32 },
360         { 33, 38, 2, 0, IEEE80211_HTC_TXUNEQUAL },
361         { 39, 52, 3, 0, IEEE80211_HTC_TXUNEQUAL },
362         { 53, 76, 4, 0, IEEE80211_HTC_TXUNEQUAL },
363         {  0,  0, 0, 0, 0 },
364 };
365
366 static void
367 ht_rateprint(struct ieee80211com *ic, enum ieee80211_phymode mode, int ratetype)
368 {
369         int minrate, maxrate;
370         struct printranges *range;
371
372         for (range = ranges; range->txstream != 0; range++) {
373                 if (ic->ic_txstream < range->txstream)
374                         continue;
375                 if (range->htcapflags &&
376                     (ic->ic_htcaps & range->htcapflags) == 0)
377                         continue;
378                 if (ratetype < range->ratetype)
379                         continue;
380                 minrate = ht_getrate(ic, range->minmcs, mode, ratetype);
381                 maxrate = ht_getrate(ic, range->maxmcs, mode, ratetype);
382                 if (range->maxmcs) {
383                         ic_printf(ic, "MCS %d-%d: %d%sMbps - %d%sMbps\n",
384                             range->minmcs, range->maxmcs,
385                             minrate/2, ((minrate & 0x1) != 0 ? ".5" : ""),
386                             maxrate/2, ((maxrate & 0x1) != 0 ? ".5" : ""));
387                 } else {
388                         ic_printf(ic, "MCS %d: %d%sMbps\n", range->minmcs,
389                             minrate/2, ((minrate & 0x1) != 0 ? ".5" : ""));
390                 }
391         }
392 }
393
394 static void
395 ht_announce(struct ieee80211com *ic, enum ieee80211_phymode mode)
396 {
397         const char *modestr = ieee80211_phymode_name[mode];
398
399         ic_printf(ic, "%s MCS 20MHz\n", modestr);
400         ht_rateprint(ic, mode, 0);
401         if (ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI20) {
402                 ic_printf(ic, "%s MCS 20MHz SGI\n", modestr);
403                 ht_rateprint(ic, mode, 1);
404         }
405         if (ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
406                 ic_printf(ic, "%s MCS 40MHz:\n", modestr);
407                 ht_rateprint(ic, mode, 2);
408         }
409         if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
410             (ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI40)) {
411                 ic_printf(ic, "%s MCS 40MHz SGI:\n", modestr);
412                 ht_rateprint(ic, mode, 3);
413         }
414 }
415
416 void
417 ieee80211_ht_announce(struct ieee80211com *ic)
418 {
419
420         if (isset(ic->ic_modecaps, IEEE80211_MODE_11NA) ||
421             isset(ic->ic_modecaps, IEEE80211_MODE_11NG))
422                 ic_printf(ic, "%dT%dR\n", ic->ic_txstream, ic->ic_rxstream);
423         if (isset(ic->ic_modecaps, IEEE80211_MODE_11NA))
424                 ht_announce(ic, IEEE80211_MODE_11NA);
425         if (isset(ic->ic_modecaps, IEEE80211_MODE_11NG))
426                 ht_announce(ic, IEEE80211_MODE_11NG);
427 }
428
429 void
430 ieee80211_init_suphtrates(struct ieee80211com *ic)
431 {
432 #define ADDRATE(x)      do {                                            \
433         htrateset->rs_rates[htrateset->rs_nrates] = x;                  \
434         htrateset->rs_nrates++;                                         \
435 } while (0)
436         struct ieee80211_htrateset *htrateset = &ic->ic_sup_htrates;
437         int i;
438
439         memset(htrateset, 0, sizeof(struct ieee80211_htrateset));
440         for (i = 0; i < ic->ic_txstream * 8; i++)
441                 ADDRATE(i);
442         if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
443             (ic->ic_htcaps & IEEE80211_HTC_TXMCS32))
444                 ADDRATE(32);
445         if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL) {
446                 if (ic->ic_txstream >= 2) {
447                          for (i = 33; i <= 38; i++)
448                                 ADDRATE(i);
449                 }
450                 if (ic->ic_txstream >= 3) {
451                         for (i = 39; i <= 52; i++)
452                                 ADDRATE(i);
453                 }
454                 if (ic->ic_txstream == 4) {
455                         for (i = 53; i <= 76; i++)
456                                 ADDRATE(i);
457                 }
458         }
459 #undef  ADDRATE
460 }
461
462 /*
463  * Receive processing.
464  */
465
466 /*
467  * Decap the encapsulated A-MSDU frames and dispatch all but
468  * the last for delivery.  The last frame is returned for 
469  * delivery via the normal path.
470  */
471 struct mbuf *
472 ieee80211_decap_amsdu(struct ieee80211_node *ni, struct mbuf *m)
473 {
474         struct ieee80211vap *vap = ni->ni_vap;
475         int framelen;
476         struct mbuf *n;
477
478         /* discard 802.3 header inserted by ieee80211_decap */
479         m_adj(m, sizeof(struct ether_header));
480
481         vap->iv_stats.is_amsdu_decap++;
482
483         for (;;) {
484                 /*
485                  * Decap the first frame, bust it apart from the
486                  * remainder and deliver.  We leave the last frame
487                  * delivery to the caller (for consistency with other
488                  * code paths, could also do it here).
489                  */
490                 m = ieee80211_decap1(m, &framelen);
491                 if (m == NULL) {
492                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
493                             ni->ni_macaddr, "a-msdu", "%s", "decap failed");
494                         vap->iv_stats.is_amsdu_tooshort++;
495                         return NULL;
496                 }
497                 if (m->m_pkthdr.len == framelen)
498                         break;
499                 n = m_split(m, framelen, M_NOWAIT);
500                 if (n == NULL) {
501                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
502                             ni->ni_macaddr, "a-msdu",
503                             "%s", "unable to split encapsulated frames");
504                         vap->iv_stats.is_amsdu_split++;
505                         m_freem(m);                     /* NB: must reclaim */
506                         return NULL;
507                 }
508                 vap->iv_deliver_data(vap, ni, m);
509
510                 /*
511                  * Remove frame contents; each intermediate frame
512                  * is required to be aligned to a 4-byte boundary.
513                  */
514                 m = n;
515                 m_adj(m, roundup2(framelen, 4) - framelen);     /* padding */
516         }
517         return m;                               /* last delivered by caller */
518 }
519
520 /*
521  * Add the given frame to the current RX reorder slot.
522  *
523  * For future offloaded A-MSDU handling where multiple frames with
524  * the same sequence number show up here, this routine will append
525  * those frames as long as they're appropriately tagged.
526  */
527 static int
528 ampdu_rx_add_slot(struct ieee80211_rx_ampdu *rap, int off, int tid,
529     ieee80211_seq rxseq,
530     struct ieee80211_node *ni,
531     struct mbuf *m)
532 {
533         struct ieee80211vap *vap = ni->ni_vap;
534
535         if (rap->rxa_m[off] == NULL) {
536                 rap->rxa_m[off] = m;
537                 rap->rxa_qframes++;
538                 rap->rxa_qbytes += m->m_pkthdr.len;
539                 vap->iv_stats.is_ampdu_rx_reorder++;
540                 return (0);
541         } else {
542                 IEEE80211_DISCARD_MAC(vap,
543                     IEEE80211_MSG_INPUT | IEEE80211_MSG_11N,
544                     ni->ni_macaddr, "a-mpdu duplicate",
545                     "seqno %u tid %u BA win <%u:%u>",
546                     rxseq, tid, rap->rxa_start,
547                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1));
548                 vap->iv_stats.is_rx_dup++;
549                 IEEE80211_NODE_STAT(ni, rx_dup);
550                 m_freem(m);
551                 return (-1);
552         }
553 }
554
555 static void
556 ampdu_rx_purge_slot(struct ieee80211_rx_ampdu *rap, int i)
557 {
558         struct mbuf *m;
559
560         m = rap->rxa_m[i];
561         if (m == NULL)
562                 return;
563
564         rap->rxa_m[i] = NULL;
565         rap->rxa_qbytes -= m->m_pkthdr.len;
566         rap->rxa_qframes--;
567         m_freem(m);
568 }
569
570 /*
571  * Purge all frames in the A-MPDU re-order queue.
572  */
573 static void
574 ampdu_rx_purge(struct ieee80211_rx_ampdu *rap)
575 {
576         int i;
577
578         for (i = 0; i < rap->rxa_wnd; i++) {
579                 ampdu_rx_purge_slot(rap, i);
580                 if (rap->rxa_qframes == 0)
581                         break;
582         }
583         KASSERT(rap->rxa_qbytes == 0 && rap->rxa_qframes == 0,
584             ("lost %u data, %u frames on ampdu rx q",
585             rap->rxa_qbytes, rap->rxa_qframes));
586 }
587
588 /*
589  * Start A-MPDU rx/re-order processing for the specified TID.
590  */
591 static int
592 ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
593         int baparamset, int batimeout, int baseqctl)
594 {
595         struct ieee80211vap *vap = ni->ni_vap;
596         int bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
597
598         if (rap->rxa_flags & IEEE80211_AGGR_RUNNING) {
599                 /*
600                  * AMPDU previously setup and not terminated with a DELBA,
601                  * flush the reorder q's in case anything remains.
602                  */
603                 ampdu_rx_purge(rap);
604         }
605         memset(rap, 0, sizeof(*rap));
606         rap->rxa_wnd = (bufsiz == 0) ?
607             IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
608         rap->rxa_start = MS(baseqctl, IEEE80211_BASEQ_START);
609         rap->rxa_flags |=  IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_XCHGPEND;
610
611         /* XXX this should be a configuration flag */
612         if ((vap->iv_htcaps & IEEE80211_HTC_RX_AMSDU_AMPDU) &&
613             (MS(baparamset, IEEE80211_BAPS_AMSDU)))
614                 rap->rxa_flags |= IEEE80211_AGGR_AMSDU;
615         else
616                 rap->rxa_flags &= ~IEEE80211_AGGR_AMSDU;
617
618         return 0;
619 }
620
621 /*
622  * Public function; manually setup the RX ampdu state.
623  */
624 int
625 ieee80211_ampdu_rx_start_ext(struct ieee80211_node *ni, int tid, int seq, int baw)
626 {
627         struct ieee80211_rx_ampdu *rap;
628
629         /* XXX TODO: sanity check tid, seq, baw */
630
631         rap = &ni->ni_rx_ampdu[tid];
632
633         if (rap->rxa_flags & IEEE80211_AGGR_RUNNING) {
634                 /*
635                  * AMPDU previously setup and not terminated with a DELBA,
636                  * flush the reorder q's in case anything remains.
637                  */
638                 ampdu_rx_purge(rap);
639         }
640
641         memset(rap, 0, sizeof(*rap));
642         rap->rxa_wnd = (baw== 0) ?
643             IEEE80211_AGGR_BAWMAX : min(baw, IEEE80211_AGGR_BAWMAX);
644         if (seq == -1) {
645                 /* Wait for the first RX frame, use that as BAW */
646                 rap->rxa_start = 0;
647                 rap->rxa_flags |= IEEE80211_AGGR_WAITRX;
648         } else {
649                 rap->rxa_start = seq;
650         }
651         rap->rxa_flags |=  IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_XCHGPEND;
652
653         /* XXX TODO: no amsdu flag */
654
655         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N, ni,
656             "%s: tid=%d, start=%d, wnd=%d, flags=0x%08x",
657             __func__,
658             tid,
659             seq,
660             rap->rxa_wnd,
661             rap->rxa_flags);
662
663         return 0;
664 }
665
666 /*
667  * Public function; manually stop the RX AMPDU state.
668  */
669 void
670 ieee80211_ampdu_rx_stop_ext(struct ieee80211_node *ni, int tid)
671 {
672         struct ieee80211_rx_ampdu *rap;
673
674         /* XXX TODO: sanity check tid, seq, baw */
675         rap = &ni->ni_rx_ampdu[tid];
676         ampdu_rx_stop(ni, rap);
677 }
678
679 /*
680  * Stop A-MPDU rx processing for the specified TID.
681  */
682 static void
683 ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
684 {
685
686         ampdu_rx_purge(rap);
687         rap->rxa_flags &= ~(IEEE80211_AGGR_RUNNING
688             | IEEE80211_AGGR_XCHGPEND
689             | IEEE80211_AGGR_WAITRX);
690 }
691
692 /*
693  * Dispatch a frame from the A-MPDU reorder queue.  The
694  * frame is fed back into ieee80211_input marked with an
695  * M_AMPDU_MPDU flag so it doesn't come back to us (it also
696  * permits ieee80211_input to optimize re-processing).
697  */
698 static __inline void
699 ampdu_dispatch(struct ieee80211_node *ni, struct mbuf *m)
700 {
701         m->m_flags |= M_AMPDU_MPDU;     /* bypass normal processing */
702         /* NB: rssi and noise are ignored w/ M_AMPDU_MPDU set */
703         (void) ieee80211_input(ni, m, 0, 0);
704 }
705
706 static int
707 ampdu_dispatch_slot(struct ieee80211_rx_ampdu *rap, struct ieee80211_node *ni,
708     int i)
709 {
710         struct mbuf *m;
711
712         if (rap->rxa_m[i] == NULL)
713                 return (0);
714
715         m = rap->rxa_m[i];
716         rap->rxa_m[i] = NULL;
717         rap->rxa_qbytes -= m->m_pkthdr.len;
718         rap->rxa_qframes--;
719
720         ampdu_dispatch(ni, m);
721
722         return (1);
723 }
724
725 static void
726 ampdu_rx_moveup(struct ieee80211_rx_ampdu *rap, struct ieee80211_node *ni,
727     int i, int winstart)
728 {
729         struct ieee80211vap *vap = ni->ni_vap;
730
731         if (rap->rxa_qframes != 0) {
732                 int n = rap->rxa_qframes, j;
733
734                 if (winstart != -1) {
735                         /*
736                          * NB: in window-sliding mode, loop assumes i > 0
737                          * and/or rxa_m[0] is NULL
738                          */
739                         KASSERT(rap->rxa_m[0] == NULL,
740                             ("%s: BA window slot 0 occupied", __func__));
741                 }
742                 for (j = i+1; j < rap->rxa_wnd; j++) {
743                         if (rap->rxa_m[j] != NULL) {
744                                 rap->rxa_m[j-i] = rap->rxa_m[j];
745                                 rap->rxa_m[j] = NULL;
746                                 if (--n == 0)
747                                         break;
748                         }
749                 }
750                 KASSERT(n == 0, ("%s: lost %d frames, qframes %d off %d "
751                     "BA win <%d:%d> winstart %d",
752                     __func__, n, rap->rxa_qframes, i, rap->rxa_start,
753                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
754                     winstart));
755                 vap->iv_stats.is_ampdu_rx_copy += rap->rxa_qframes;
756         }
757 }
758
759 /*
760  * Dispatch as many frames as possible from the re-order queue.
761  * Frames will always be "at the front"; we process all frames
762  * up to the first empty slot in the window.  On completion we
763  * cleanup state if there are still pending frames in the current
764  * BA window.  We assume the frame at slot 0 is already handled
765  * by the caller; we always start at slot 1.
766  */
767 static void
768 ampdu_rx_dispatch(struct ieee80211_rx_ampdu *rap, struct ieee80211_node *ni)
769 {
770         struct ieee80211vap *vap = ni->ni_vap;
771         int i;
772
773         /* flush run of frames */
774         for (i = 1; i < rap->rxa_wnd; i++) {
775                 if (ampdu_dispatch_slot(rap, ni, i) == 0)
776                         break;
777         }
778
779         /*
780          * If frames remain, copy the mbuf pointers down so
781          * they correspond to the offsets in the new window.
782          */
783         ampdu_rx_moveup(rap, ni, i, -1);
784
785         /*
786          * Adjust the start of the BA window to
787          * reflect the frames just dispatched.
788          */
789         rap->rxa_start = IEEE80211_SEQ_ADD(rap->rxa_start, i);
790         vap->iv_stats.is_ampdu_rx_oor += i;
791 }
792
793 /*
794  * Dispatch all frames in the A-MPDU re-order queue.
795  */
796 static void
797 ampdu_rx_flush(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
798 {
799         struct ieee80211vap *vap = ni->ni_vap;
800         int i, r;
801
802         for (i = 0; i < rap->rxa_wnd; i++) {
803                 r = ampdu_dispatch_slot(rap, ni, i);
804                 if (r == 0)
805                         continue;
806                 vap->iv_stats.is_ampdu_rx_oor += r;
807
808                 if (rap->rxa_qframes == 0)
809                         break;
810         }
811 }
812
813 /*
814  * Dispatch all frames in the A-MPDU re-order queue
815  * preceding the specified sequence number.  This logic
816  * handles window moves due to a received MSDU or BAR.
817  */
818 static void
819 ampdu_rx_flush_upto(struct ieee80211_node *ni,
820         struct ieee80211_rx_ampdu *rap, ieee80211_seq winstart)
821 {
822         struct ieee80211vap *vap = ni->ni_vap;
823         ieee80211_seq seqno;
824         int i, r;
825
826         /*
827          * Flush any complete MSDU's with a sequence number lower
828          * than winstart.  Gaps may exist.  Note that we may actually
829          * dispatch frames past winstart if a run continues; this is
830          * an optimization that avoids having to do a separate pass
831          * to dispatch frames after moving the BA window start.
832          */
833         seqno = rap->rxa_start;
834         for (i = 0; i < rap->rxa_wnd; i++) {
835                 r = ampdu_dispatch_slot(rap, ni, i);
836                 if (r == 0) {
837                         if (!IEEE80211_SEQ_BA_BEFORE(seqno, winstart))
838                                 break;
839                 }
840                 vap->iv_stats.is_ampdu_rx_oor += r;
841                 seqno = IEEE80211_SEQ_INC(seqno);
842         }
843         /*
844          * If frames remain, copy the mbuf pointers down so
845          * they correspond to the offsets in the new window.
846          */
847         ampdu_rx_moveup(rap, ni, i, winstart);
848
849         /*
850          * Move the start of the BA window; we use the
851          * sequence number of the last MSDU that was
852          * passed up the stack+1 or winstart if stopped on
853          * a gap in the reorder buffer.
854          */
855         rap->rxa_start = seqno;
856 }
857
858 /*
859  * Process a received QoS data frame for an HT station.  Handle
860  * A-MPDU reordering: if this frame is received out of order
861  * and falls within the BA window hold onto it.  Otherwise if
862  * this frame completes a run, flush any pending frames.  We
863  * return 1 if the frame is consumed.  A 0 is returned if
864  * the frame should be processed normally by the caller.
865  */
866 int
867 ieee80211_ampdu_reorder(struct ieee80211_node *ni, struct mbuf *m,
868     const struct ieee80211_rx_stats *rxs)
869 {
870 #define PROCESS         0       /* caller should process frame */
871 #define CONSUMED        1       /* frame consumed, caller does nothing */
872         struct ieee80211vap *vap = ni->ni_vap;
873         struct ieee80211_qosframe *wh;
874         struct ieee80211_rx_ampdu *rap;
875         ieee80211_seq rxseq;
876         uint8_t tid;
877         int off;
878
879         KASSERT((m->m_flags & (M_AMPDU | M_AMPDU_MPDU)) == M_AMPDU,
880             ("!a-mpdu or already re-ordered, flags 0x%x", m->m_flags));
881         KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT sta"));
882
883         /* NB: m_len known to be sufficient */
884         wh = mtod(m, struct ieee80211_qosframe *);
885         if (wh->i_fc[0] != IEEE80211_FC0_QOSDATA) {
886                 /*
887                  * Not QoS data, shouldn't get here but just
888                  * return it to the caller for processing.
889                  */
890                 return PROCESS;
891         }
892
893         /*
894          * 802.11-2012 9.3.2.10 - Duplicate detection and recovery.
895          *
896          * Multicast QoS data frames are checked against a different
897          * counter, not the per-TID counter.
898          */
899         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
900                 return PROCESS;
901
902         tid = ieee80211_getqos(wh)[0];
903         tid &= IEEE80211_QOS_TID;
904         rap = &ni->ni_rx_ampdu[tid];
905         if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
906                 /*
907                  * No ADDBA request yet, don't touch.
908                  */
909                 return PROCESS;
910         }
911         rxseq = le16toh(*(uint16_t *)wh->i_seq);
912         if ((rxseq & IEEE80211_SEQ_FRAG_MASK) != 0) {
913                 /*
914                  * Fragments are not allowed; toss.
915                  */
916                 IEEE80211_DISCARD_MAC(vap,
917                     IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
918                     "A-MPDU", "fragment, rxseq 0x%x tid %u%s", rxseq, tid,
919                     wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
920                 vap->iv_stats.is_ampdu_rx_drop++;
921                 IEEE80211_NODE_STAT(ni, rx_drop);
922                 m_freem(m);
923                 return CONSUMED;
924         }
925         rxseq >>= IEEE80211_SEQ_SEQ_SHIFT;
926         rap->rxa_nframes++;
927
928         /*
929          * Handle waiting for the first frame to define the BAW.
930          * Some firmware doesn't provide the RX of the starting point
931          * of the BAW and we have to cope.
932          */
933         if (rap->rxa_flags & IEEE80211_AGGR_WAITRX) {
934                 rap->rxa_flags &= ~IEEE80211_AGGR_WAITRX;
935                 rap->rxa_start = rxseq;
936         }
937 again:
938         if (rxseq == rap->rxa_start) {
939                 /*
940                  * First frame in window.
941                  */
942                 if (rap->rxa_qframes != 0) {
943                         /*
944                          * Dispatch as many packets as we can.
945                          */
946                         KASSERT(rap->rxa_m[0] == NULL, ("unexpected dup"));
947                         ampdu_dispatch(ni, m);
948                         ampdu_rx_dispatch(rap, ni);
949                         return CONSUMED;
950                 } else {
951                         /*
952                          * In order; advance window and notify
953                          * caller to dispatch directly.
954                          */
955                         rap->rxa_start = IEEE80211_SEQ_INC(rxseq);
956                         return PROCESS;
957                 }
958         }
959         /*
960          * Frame is out of order; store if in the BA window.
961          */
962         /* calculate offset in BA window */
963         off = IEEE80211_SEQ_SUB(rxseq, rap->rxa_start);
964         if (off < rap->rxa_wnd) {
965                 /*
966                  * Common case (hopefully): in the BA window.
967                  * Sec 9.10.7.6.2 a) (p.137)
968                  */
969
970                 /* 
971                  * Check for frames sitting too long in the reorder queue.
972                  * This should only ever happen if frames are not delivered
973                  * without the sender otherwise notifying us (e.g. with a
974                  * BAR to move the window).  Typically this happens because
975                  * of vendor bugs that cause the sequence number to jump.
976                  * When this happens we get a gap in the reorder queue that
977                  * leaves frame sitting on the queue until they get pushed
978                  * out due to window moves.  When the vendor does not send
979                  * BAR this move only happens due to explicit packet sends
980                  *
981                  * NB: we only track the time of the oldest frame in the
982                  * reorder q; this means that if we flush we might push
983                  * frames that still "new"; if this happens then subsequent
984                  * frames will result in BA window moves which cost something
985                  * but is still better than a big throughput dip.
986                  */
987                 if (rap->rxa_qframes != 0) {
988                         /* XXX honor batimeout? */
989                         if (ticks - rap->rxa_age > ieee80211_ampdu_age) {
990                                 /*
991                                  * Too long since we received the first
992                                  * frame; flush the reorder buffer.
993                                  */
994                                 if (rap->rxa_qframes != 0) {
995                                         vap->iv_stats.is_ampdu_rx_age +=
996                                             rap->rxa_qframes;
997                                         ampdu_rx_flush(ni, rap);
998                                 }
999                                 rap->rxa_start = IEEE80211_SEQ_INC(rxseq);
1000                                 return PROCESS;
1001                         }
1002                 } else {
1003                         /*
1004                          * First frame, start aging timer.
1005                          */
1006                         rap->rxa_age = ticks;
1007                 }
1008
1009                 /* save packet - this consumes, no matter what */
1010                 ampdu_rx_add_slot(rap, off, tid, rxseq, ni, m);
1011
1012                 return CONSUMED;
1013         }
1014         if (off < IEEE80211_SEQ_BA_RANGE) {
1015                 /*
1016                  * Outside the BA window, but within range;
1017                  * flush the reorder q and move the window.
1018                  * Sec 9.10.7.6.2 b) (p.138)
1019                  */
1020                 IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1021                     "move BA win <%u:%u> (%u frames) rxseq %u tid %u",
1022                     rap->rxa_start,
1023                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
1024                     rap->rxa_qframes, rxseq, tid);
1025                 vap->iv_stats.is_ampdu_rx_move++;
1026
1027                 /*
1028                  * The spec says to flush frames up to but not including:
1029                  *      WinStart_B = rxseq - rap->rxa_wnd + 1
1030                  * Then insert the frame or notify the caller to process
1031                  * it immediately.  We can safely do this by just starting
1032                  * over again because we know the frame will now be within
1033                  * the BA window.
1034                  */
1035                 /* NB: rxa_wnd known to be >0 */
1036                 ampdu_rx_flush_upto(ni, rap,
1037                     IEEE80211_SEQ_SUB(rxseq, rap->rxa_wnd-1));
1038                 goto again;
1039         } else {
1040                 /*
1041                  * Outside the BA window and out of range; toss.
1042                  * Sec 9.10.7.6.2 c) (p.138)
1043                  */
1044                 IEEE80211_DISCARD_MAC(vap,
1045                     IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
1046                     "MPDU", "BA win <%u:%u> (%u frames) rxseq %u tid %u%s",
1047                     rap->rxa_start,
1048                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
1049                     rap->rxa_qframes, rxseq, tid,
1050                     wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
1051                 vap->iv_stats.is_ampdu_rx_drop++;
1052                 IEEE80211_NODE_STAT(ni, rx_drop);
1053                 m_freem(m);
1054                 return CONSUMED;
1055         }
1056 #undef CONSUMED
1057 #undef PROCESS
1058 }
1059
1060 /*
1061  * Process a BAR ctl frame.  Dispatch all frames up to
1062  * the sequence number of the frame.  If this frame is
1063  * out of range it's discarded.
1064  */
1065 void
1066 ieee80211_recv_bar(struct ieee80211_node *ni, struct mbuf *m0)
1067 {
1068         struct ieee80211vap *vap = ni->ni_vap;
1069         struct ieee80211_frame_bar *wh;
1070         struct ieee80211_rx_ampdu *rap;
1071         ieee80211_seq rxseq;
1072         int tid, off;
1073
1074         if (!ieee80211_recv_bar_ena) {
1075 #if 0
1076                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_11N,
1077                     ni->ni_macaddr, "BAR", "%s", "processing disabled");
1078 #endif
1079                 vap->iv_stats.is_ampdu_bar_bad++;
1080                 return;
1081         }
1082         wh = mtod(m0, struct ieee80211_frame_bar *);
1083         /* XXX check basic BAR */
1084         tid = MS(le16toh(wh->i_ctl), IEEE80211_BAR_TID);
1085         rap = &ni->ni_rx_ampdu[tid];
1086         if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
1087                 /*
1088                  * No ADDBA request yet, don't touch.
1089                  */
1090                 IEEE80211_DISCARD_MAC(vap,
1091                     IEEE80211_MSG_INPUT | IEEE80211_MSG_11N,
1092                     ni->ni_macaddr, "BAR", "no BA stream, tid %u", tid);
1093                 vap->iv_stats.is_ampdu_bar_bad++;
1094                 return;
1095         }
1096         vap->iv_stats.is_ampdu_bar_rx++;
1097         rxseq = le16toh(wh->i_seq) >> IEEE80211_SEQ_SEQ_SHIFT;
1098         if (rxseq == rap->rxa_start)
1099                 return;
1100         /* calculate offset in BA window */
1101         off = IEEE80211_SEQ_SUB(rxseq, rap->rxa_start);
1102         if (off < IEEE80211_SEQ_BA_RANGE) {
1103                 /*
1104                  * Flush the reorder q up to rxseq and move the window.
1105                  * Sec 9.10.7.6.3 a) (p.138)
1106                  */
1107                 IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1108                     "BAR moves BA win <%u:%u> (%u frames) rxseq %u tid %u",
1109                     rap->rxa_start,
1110                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
1111                     rap->rxa_qframes, rxseq, tid);
1112                 vap->iv_stats.is_ampdu_bar_move++;
1113
1114                 ampdu_rx_flush_upto(ni, rap, rxseq);
1115                 if (off >= rap->rxa_wnd) {
1116                         /*
1117                          * BAR specifies a window start to the right of BA
1118                          * window; we must move it explicitly since
1119                          * ampdu_rx_flush_upto will not.
1120                          */
1121                         rap->rxa_start = rxseq;
1122                 }
1123         } else {
1124                 /*
1125                  * Out of range; toss.
1126                  * Sec 9.10.7.6.3 b) (p.138)
1127                  */
1128                 IEEE80211_DISCARD_MAC(vap,
1129                     IEEE80211_MSG_INPUT | IEEE80211_MSG_11N, ni->ni_macaddr,
1130                     "BAR", "BA win <%u:%u> (%u frames) rxseq %u tid %u%s",
1131                     rap->rxa_start,
1132                     IEEE80211_SEQ_ADD(rap->rxa_start, rap->rxa_wnd-1),
1133                     rap->rxa_qframes, rxseq, tid,
1134                     wh->i_fc[1] & IEEE80211_FC1_RETRY ? " (retransmit)" : "");
1135                 vap->iv_stats.is_ampdu_bar_oow++;
1136                 IEEE80211_NODE_STAT(ni, rx_drop);
1137         }
1138 }
1139
1140 /*
1141  * Setup HT-specific state in a node.  Called only
1142  * when HT use is negotiated so we don't do extra
1143  * work for temporary and/or legacy sta's.
1144  */
1145 void
1146 ieee80211_ht_node_init(struct ieee80211_node *ni)
1147 {
1148         struct ieee80211_tx_ampdu *tap;
1149         int tid;
1150
1151         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1152             ni,
1153             "%s: called (%p)",
1154             __func__,
1155             ni);
1156
1157         if (ni->ni_flags & IEEE80211_NODE_HT) {
1158                 /*
1159                  * Clean AMPDU state on re-associate.  This handles the case
1160                  * where a station leaves w/o notifying us and then returns
1161                  * before node is reaped for inactivity.
1162                  */
1163                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1164                     ni,
1165                     "%s: calling cleanup (%p)",
1166                     __func__, ni);
1167                 ieee80211_ht_node_cleanup(ni);
1168         }
1169         for (tid = 0; tid < WME_NUM_TID; tid++) {
1170                 tap = &ni->ni_tx_ampdu[tid];
1171                 tap->txa_tid = tid;
1172                 tap->txa_ni = ni;
1173                 ieee80211_txampdu_init_pps(tap);
1174                 /* NB: further initialization deferred */
1175         }
1176         ni->ni_flags |= IEEE80211_NODE_HT | IEEE80211_NODE_AMPDU |
1177             IEEE80211_NODE_AMSDU;
1178 }
1179
1180 /*
1181  * Cleanup HT-specific state in a node.  Called only
1182  * when HT use has been marked.
1183  */
1184 void
1185 ieee80211_ht_node_cleanup(struct ieee80211_node *ni)
1186 {
1187         struct ieee80211com *ic = ni->ni_ic;
1188         int i;
1189
1190         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1191             ni,
1192             "%s: called (%p)",
1193             __func__, ni);
1194
1195         KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT node"));
1196
1197         /* XXX optimize this */
1198         for (i = 0; i < WME_NUM_TID; i++) {
1199                 struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[i];
1200                 if (tap->txa_flags & IEEE80211_AGGR_SETUP)
1201                         ampdu_tx_stop(tap);
1202         }
1203         for (i = 0; i < WME_NUM_TID; i++)
1204                 ic->ic_ampdu_rx_stop(ni, &ni->ni_rx_ampdu[i]);
1205
1206         ni->ni_htcap = 0;
1207         ni->ni_flags &= ~IEEE80211_NODE_HT_ALL;
1208 }
1209
1210 /*
1211  * Age out HT resources for a station.
1212  */
1213 void
1214 ieee80211_ht_node_age(struct ieee80211_node *ni)
1215 {
1216         struct ieee80211vap *vap = ni->ni_vap;
1217         uint8_t tid;
1218
1219         KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT sta"));
1220
1221         for (tid = 0; tid < WME_NUM_TID; tid++) {
1222                 struct ieee80211_rx_ampdu *rap;
1223
1224                 rap = &ni->ni_rx_ampdu[tid];
1225                 if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0)
1226                         continue;
1227                 if (rap->rxa_qframes == 0)
1228                         continue;
1229                 /* 
1230                  * Check for frames sitting too long in the reorder queue.
1231                  * See above for more details on what's happening here.
1232                  */
1233                 /* XXX honor batimeout? */
1234                 if (ticks - rap->rxa_age > ieee80211_ampdu_age) {
1235                         /*
1236                          * Too long since we received the first
1237                          * frame; flush the reorder buffer.
1238                          */
1239                         vap->iv_stats.is_ampdu_rx_age += rap->rxa_qframes;
1240                         ampdu_rx_flush(ni, rap);
1241                 }
1242         }
1243 }
1244
1245 static struct ieee80211_channel *
1246 findhtchan(struct ieee80211com *ic, struct ieee80211_channel *c, int htflags)
1247 {
1248         return ieee80211_find_channel(ic, c->ic_freq,
1249             (c->ic_flags &~ IEEE80211_CHAN_HT) | htflags);
1250 }
1251
1252 /*
1253  * Adjust a channel to be HT/non-HT according to the vap's configuration.
1254  */
1255 struct ieee80211_channel *
1256 ieee80211_ht_adjust_channel(struct ieee80211com *ic,
1257         struct ieee80211_channel *chan, int flags)
1258 {
1259         struct ieee80211_channel *c;
1260
1261         if (flags & IEEE80211_FHT_HT) {
1262                 /* promote to HT if possible */
1263                 if (flags & IEEE80211_FHT_USEHT40) {
1264                         if (!IEEE80211_IS_CHAN_HT40(chan)) {
1265                                 /* NB: arbitrarily pick ht40+ over ht40- */
1266                                 c = findhtchan(ic, chan, IEEE80211_CHAN_HT40U);
1267                                 if (c == NULL)
1268                                         c = findhtchan(ic, chan,
1269                                                 IEEE80211_CHAN_HT40D);
1270                                 if (c == NULL)
1271                                         c = findhtchan(ic, chan,
1272                                                 IEEE80211_CHAN_HT20);
1273                                 if (c != NULL)
1274                                         chan = c;
1275                         }
1276                 } else if (!IEEE80211_IS_CHAN_HT20(chan)) {
1277                         c = findhtchan(ic, chan, IEEE80211_CHAN_HT20);
1278                         if (c != NULL)
1279                                 chan = c;
1280                 }
1281         } else if (IEEE80211_IS_CHAN_HT(chan)) {
1282                 /* demote to legacy, HT use is disabled */
1283                 c = ieee80211_find_channel(ic, chan->ic_freq,
1284                     chan->ic_flags &~ IEEE80211_CHAN_HT);
1285                 if (c != NULL)
1286                         chan = c;
1287         }
1288         return chan;
1289 }
1290
1291 /*
1292  * Setup HT-specific state for a legacy WDS peer.
1293  */
1294 void
1295 ieee80211_ht_wds_init(struct ieee80211_node *ni)
1296 {
1297         struct ieee80211vap *vap = ni->ni_vap;
1298         struct ieee80211_tx_ampdu *tap;
1299         int tid;
1300
1301         KASSERT(vap->iv_flags_ht & IEEE80211_FHT_HT, ("no HT requested"));
1302
1303         /* XXX check scan cache in case peer has an ap and we have info */
1304         /*
1305          * If setup with a legacy channel; locate an HT channel.
1306          * Otherwise if the inherited channel (from a companion
1307          * AP) is suitable use it so we use the same location
1308          * for the extension channel).
1309          */
1310         ni->ni_chan = ieee80211_ht_adjust_channel(ni->ni_ic,
1311             ni->ni_chan, ieee80211_htchanflags(ni->ni_chan));
1312
1313         ni->ni_htcap = 0;
1314         if (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20)
1315                 ni->ni_htcap |= IEEE80211_HTCAP_SHORTGI20;
1316         if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
1317                 ni->ni_htcap |= IEEE80211_HTCAP_CHWIDTH40;
1318                 ni->ni_chw = 40;
1319                 if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
1320                         ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_ABOVE;
1321                 else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
1322                         ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_BELOW;
1323                 if (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40)
1324                         ni->ni_htcap |= IEEE80211_HTCAP_SHORTGI40;
1325         } else {
1326                 ni->ni_chw = 20;
1327                 ni->ni_ht2ndchan = IEEE80211_HTINFO_2NDCHAN_NONE;
1328         }
1329         ni->ni_htctlchan = ni->ni_chan->ic_ieee;
1330         if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
1331                 ni->ni_flags |= IEEE80211_NODE_RIFS;
1332         /* XXX does it make sense to enable SMPS? */
1333
1334         ni->ni_htopmode = 0;            /* XXX need protection state */
1335         ni->ni_htstbc = 0;              /* XXX need info */
1336
1337         for (tid = 0; tid < WME_NUM_TID; tid++) {
1338                 tap = &ni->ni_tx_ampdu[tid];
1339                 tap->txa_tid = tid;
1340                 ieee80211_txampdu_init_pps(tap);
1341         }
1342         /* NB: AMPDU tx/rx governed by IEEE80211_FHT_AMPDU_{TX,RX} */
1343         ni->ni_flags |= IEEE80211_NODE_HT | IEEE80211_NODE_AMPDU |
1344             IEEE80211_NODE_AMSDU;
1345 }
1346
1347 /*
1348  * Notify hostap vaps of a change in the HTINFO ie.
1349  */
1350 static void
1351 htinfo_notify(struct ieee80211com *ic)
1352 {
1353         struct ieee80211vap *vap;
1354         int first = 1;
1355
1356         IEEE80211_LOCK_ASSERT(ic);
1357
1358         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1359                 if (vap->iv_opmode != IEEE80211_M_HOSTAP)
1360                         continue;
1361                 if (vap->iv_state != IEEE80211_S_RUN ||
1362                     !IEEE80211_IS_CHAN_HT(vap->iv_bss->ni_chan))
1363                         continue;
1364                 if (first) {
1365                         IEEE80211_NOTE(vap,
1366                             IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N,
1367                             vap->iv_bss,
1368                             "HT bss occupancy change: %d sta, %d ht, "
1369                             "%d ht40%s, HT protmode now 0x%x"
1370                             , ic->ic_sta_assoc
1371                             , ic->ic_ht_sta_assoc
1372                             , ic->ic_ht40_sta_assoc
1373                             , (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) ?
1374                                  ", non-HT sta present" : ""
1375                             , ic->ic_curhtprotmode);
1376                         first = 0;
1377                 }
1378                 ieee80211_beacon_notify(vap, IEEE80211_BEACON_HTINFO);
1379         }
1380 }
1381
1382 /*
1383  * Calculate HT protection mode from current
1384  * state and handle updates.
1385  */
1386 static void
1387 htinfo_update(struct ieee80211com *ic)
1388 {
1389         uint8_t protmode;
1390
1391         if (ic->ic_sta_assoc != ic->ic_ht_sta_assoc) {
1392                 protmode = IEEE80211_HTINFO_OPMODE_MIXED
1393                          | IEEE80211_HTINFO_NONHT_PRESENT;
1394         } else if (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) {
1395                 protmode = IEEE80211_HTINFO_OPMODE_PROTOPT
1396                          | IEEE80211_HTINFO_NONHT_PRESENT;
1397         } else if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
1398             IEEE80211_IS_CHAN_HT40(ic->ic_bsschan) && 
1399             ic->ic_sta_assoc != ic->ic_ht40_sta_assoc) {
1400                 protmode = IEEE80211_HTINFO_OPMODE_HT20PR;
1401         } else {
1402                 protmode = IEEE80211_HTINFO_OPMODE_PURE;
1403         }
1404         if (protmode != ic->ic_curhtprotmode) {
1405                 ic->ic_curhtprotmode = protmode;
1406                 htinfo_notify(ic);
1407         }
1408 }
1409
1410 /*
1411  * Handle an HT station joining a BSS.
1412  */
1413 void
1414 ieee80211_ht_node_join(struct ieee80211_node *ni)
1415 {
1416         struct ieee80211com *ic = ni->ni_ic;
1417
1418         IEEE80211_LOCK_ASSERT(ic);
1419
1420         if (ni->ni_flags & IEEE80211_NODE_HT) {
1421                 ic->ic_ht_sta_assoc++;
1422                 if (ni->ni_chw == 40)
1423                         ic->ic_ht40_sta_assoc++;
1424         }
1425         htinfo_update(ic);
1426 }
1427
1428 /*
1429  * Handle an HT station leaving a BSS.
1430  */
1431 void
1432 ieee80211_ht_node_leave(struct ieee80211_node *ni)
1433 {
1434         struct ieee80211com *ic = ni->ni_ic;
1435
1436         IEEE80211_LOCK_ASSERT(ic);
1437
1438         if (ni->ni_flags & IEEE80211_NODE_HT) {
1439                 ic->ic_ht_sta_assoc--;
1440                 if (ni->ni_chw == 40)
1441                         ic->ic_ht40_sta_assoc--;
1442         }
1443         htinfo_update(ic);
1444 }
1445
1446 /*
1447  * Public version of htinfo_update; used for processing
1448  * beacon frames from overlapping bss.
1449  *
1450  * Caller can specify either IEEE80211_HTINFO_OPMODE_MIXED
1451  * (on receipt of a beacon that advertises MIXED) or
1452  * IEEE80211_HTINFO_OPMODE_PROTOPT (on receipt of a beacon
1453  * from an overlapping legacy bss).  We treat MIXED with
1454  * a higher precedence than PROTOPT (i.e. we will not change
1455  * change PROTOPT -> MIXED; only MIXED -> PROTOPT).  This
1456  * corresponds to how we handle things in htinfo_update.
1457  */
1458 void
1459 ieee80211_htprot_update(struct ieee80211com *ic, int protmode)
1460 {
1461 #define OPMODE(x)       SM(x, IEEE80211_HTINFO_OPMODE)
1462         IEEE80211_LOCK(ic);
1463
1464         /* track non-HT station presence */
1465         KASSERT(protmode & IEEE80211_HTINFO_NONHT_PRESENT,
1466             ("protmode 0x%x", protmode));
1467         ic->ic_flags_ht |= IEEE80211_FHT_NONHT_PR;
1468         ic->ic_lastnonht = ticks;
1469
1470         if (protmode != ic->ic_curhtprotmode &&
1471             (OPMODE(ic->ic_curhtprotmode) != IEEE80211_HTINFO_OPMODE_MIXED ||
1472              OPMODE(protmode) == IEEE80211_HTINFO_OPMODE_PROTOPT)) {
1473                 /* push beacon update */
1474                 ic->ic_curhtprotmode = protmode;
1475                 htinfo_notify(ic);
1476         }
1477         IEEE80211_UNLOCK(ic);
1478 #undef OPMODE
1479 }
1480
1481 /*
1482  * Time out presence of an overlapping bss with non-HT
1483  * stations.  When operating in hostap mode we listen for
1484  * beacons from other stations and if we identify a non-HT
1485  * station is present we update the opmode field of the
1486  * HTINFO ie.  To identify when all non-HT stations are
1487  * gone we time out this condition.
1488  */
1489 void
1490 ieee80211_ht_timeout(struct ieee80211com *ic)
1491 {
1492         IEEE80211_LOCK_ASSERT(ic);
1493
1494         if ((ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) &&
1495             ieee80211_time_after(ticks, ic->ic_lastnonht + IEEE80211_NONHT_PRESENT_AGE)) {
1496 #if 0
1497                 IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1498                     "%s", "time out non-HT STA present on channel");
1499 #endif
1500                 ic->ic_flags_ht &= ~IEEE80211_FHT_NONHT_PR;
1501                 htinfo_update(ic);
1502         }
1503 }
1504
1505 /*
1506  * Process an 802.11n HT capabilities ie.
1507  */
1508 void
1509 ieee80211_parse_htcap(struct ieee80211_node *ni, const uint8_t *ie)
1510 {
1511         if (ie[0] == IEEE80211_ELEMID_VENDOR) {
1512                 /*
1513                  * Station used Vendor OUI ie to associate;
1514                  * mark the node so when we respond we'll use
1515                  * the Vendor OUI's and not the standard ie's.
1516                  */
1517                 ni->ni_flags |= IEEE80211_NODE_HTCOMPAT;
1518                 ie += 4;
1519         } else
1520                 ni->ni_flags &= ~IEEE80211_NODE_HTCOMPAT;
1521
1522         ni->ni_htcap = le16dec(ie +
1523                 __offsetof(struct ieee80211_ie_htcap, hc_cap));
1524         ni->ni_htparam = ie[__offsetof(struct ieee80211_ie_htcap, hc_param)];
1525 }
1526
1527 static void
1528 htinfo_parse(struct ieee80211_node *ni,
1529         const struct ieee80211_ie_htinfo *htinfo)
1530 {
1531         uint16_t w;
1532
1533         ni->ni_htctlchan = htinfo->hi_ctrlchannel;
1534         ni->ni_ht2ndchan = SM(htinfo->hi_byte1, IEEE80211_HTINFO_2NDCHAN);
1535         w = le16dec(&htinfo->hi_byte2);
1536         ni->ni_htopmode = SM(w, IEEE80211_HTINFO_OPMODE);
1537         w = le16dec(&htinfo->hi_byte45);
1538         ni->ni_htstbc = SM(w, IEEE80211_HTINFO_BASIC_STBCMCS);
1539 }
1540
1541 /*
1542  * Parse an 802.11n HT info ie and save useful information
1543  * to the node state.  Note this does not effect any state
1544  * changes such as for channel width change.
1545  */
1546 void
1547 ieee80211_parse_htinfo(struct ieee80211_node *ni, const uint8_t *ie)
1548 {
1549         if (ie[0] == IEEE80211_ELEMID_VENDOR)
1550                 ie += 4;
1551         htinfo_parse(ni, (const struct ieee80211_ie_htinfo *) ie);
1552 }
1553
1554 /*
1555  * Handle 11n/11ac channel switch.
1556  *
1557  * Use the received HT/VHT ie's to identify the right channel to use.
1558  * If we cannot locate it in the channel table then fallback to
1559  * legacy operation.
1560  *
1561  * Note that we use this information to identify the node's
1562  * channel only; the caller is responsible for insuring any
1563  * required channel change is done (e.g. in sta mode when
1564  * parsing the contents of a beacon frame).
1565  */
1566 static int
1567 htinfo_update_chw(struct ieee80211_node *ni, int htflags, int vhtflags)
1568 {
1569         struct ieee80211com *ic = ni->ni_ic;
1570         struct ieee80211_channel *c;
1571         int chanflags;
1572         int ret = 0;
1573
1574         /*
1575          * First step - do HT/VHT only channel lookup based on operating mode
1576          * flags.  This involves masking out the VHT flags as well.
1577          * Otherwise we end up doing the full channel walk each time
1578          * we trigger this, which is expensive.
1579          */
1580         chanflags = (ni->ni_chan->ic_flags &~
1581             (IEEE80211_CHAN_HT | IEEE80211_CHAN_VHT)) | htflags | vhtflags;
1582
1583         if (chanflags == ni->ni_chan->ic_flags)
1584                 goto done;
1585
1586         /*
1587          * If HT /or/ VHT flags have changed then check both.
1588          * We need to start by picking a HT channel anyway.
1589          */
1590
1591         c = NULL;
1592         chanflags = (ni->ni_chan->ic_flags &~
1593             (IEEE80211_CHAN_HT | IEEE80211_CHAN_VHT)) | htflags;
1594         /* XXX not right for ht40- */
1595         c = ieee80211_find_channel(ic, ni->ni_chan->ic_freq, chanflags);
1596         if (c == NULL && (htflags & IEEE80211_CHAN_HT40)) {
1597                 /*
1598                  * No HT40 channel entry in our table; fall back
1599                  * to HT20 operation.  This should not happen.
1600                  */
1601                 c = findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT20);
1602 #if 0
1603                 IEEE80211_NOTE(ni->ni_vap,
1604                     IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
1605                     "no HT40 channel (freq %u), falling back to HT20",
1606                     ni->ni_chan->ic_freq);
1607 #endif
1608                 /* XXX stat */
1609         }
1610
1611         /* Nothing found - leave it alone; move onto VHT */
1612         if (c == NULL)
1613                 c = ni->ni_chan;
1614
1615         /*
1616          * If it's non-HT, then bail out now.
1617          */
1618         if (! IEEE80211_IS_CHAN_HT(c)) {
1619                 IEEE80211_NOTE(ni->ni_vap,
1620                     IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
1621                     "not HT; skipping VHT check (%u/0x%x)",
1622                     c->ic_freq, c->ic_flags);
1623                 goto done;
1624         }
1625
1626         /*
1627          * Next step - look at the current VHT flags and determine
1628          * if we need to upgrade.  Mask out the VHT and HT flags since
1629          * the vhtflags field will already have the correct HT
1630          * flags to use.
1631          */
1632         if (IEEE80211_CONF_VHT(ic) && ni->ni_vhtcap != 0 && vhtflags != 0) {
1633                 chanflags = (c->ic_flags
1634                     &~ (IEEE80211_CHAN_HT | IEEE80211_CHAN_VHT))
1635                     | vhtflags;
1636                 IEEE80211_NOTE(ni->ni_vap,
1637                     IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N,
1638                     ni,
1639                     "%s: VHT; chanwidth=0x%02x; vhtflags=0x%08x",
1640                     __func__, ni->ni_vht_chanwidth, vhtflags);
1641
1642                 IEEE80211_NOTE(ni->ni_vap,
1643                     IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N,
1644                     ni,
1645                     "%s: VHT; trying lookup for %d/0x%08x",
1646                     __func__, c->ic_freq, chanflags);
1647                 c = ieee80211_find_channel(ic, c->ic_freq, chanflags);
1648         }
1649
1650         /* Finally, if it's changed */
1651         if (c != NULL && c != ni->ni_chan) {
1652                 IEEE80211_NOTE(ni->ni_vap,
1653                     IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
1654                     "switch station to %s%d channel %u/0x%x",
1655                     IEEE80211_IS_CHAN_VHT(c) ? "VHT" : "HT",
1656                     IEEE80211_IS_CHAN_VHT80(c) ? 80 :
1657                       (IEEE80211_IS_CHAN_HT40(c) ? 40 : 20),
1658                     c->ic_freq, c->ic_flags);
1659                 ni->ni_chan = c;
1660                 ret = 1;
1661         }
1662         /* NB: caller responsible for forcing any channel change */
1663
1664 done:
1665         /* update node's (11n) tx channel width */
1666         ni->ni_chw = IEEE80211_IS_CHAN_HT40(ni->ni_chan)? 40 : 20;
1667         return (ret);
1668 }
1669
1670 /*
1671  * Update 11n MIMO PS state according to received htcap.
1672  */
1673 static __inline int
1674 htcap_update_mimo_ps(struct ieee80211_node *ni)
1675 {
1676         uint16_t oflags = ni->ni_flags;
1677
1678         switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
1679         case IEEE80211_HTCAP_SMPS_DYNAMIC:
1680                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1681                 ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
1682                 break;
1683         case IEEE80211_HTCAP_SMPS_ENA:
1684                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1685                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1686                 break;
1687         case IEEE80211_HTCAP_SMPS_OFF:
1688         default:                /* disable on rx of reserved value */
1689                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
1690                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1691                 break;
1692         }
1693         return (oflags ^ ni->ni_flags);
1694 }
1695
1696 /*
1697  * Update short GI state according to received htcap
1698  * and local settings.
1699  */
1700 static __inline void
1701 htcap_update_shortgi(struct ieee80211_node *ni)
1702 {
1703         struct ieee80211vap *vap = ni->ni_vap;
1704
1705         ni->ni_flags &= ~(IEEE80211_NODE_SGI20|IEEE80211_NODE_SGI40);
1706         if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) &&
1707             (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20))
1708                 ni->ni_flags |= IEEE80211_NODE_SGI20;
1709         if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40) &&
1710             (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40))
1711                 ni->ni_flags |= IEEE80211_NODE_SGI40;
1712 }
1713
1714 /*
1715  * Update LDPC state according to received htcap
1716  * and local settings.
1717  */
1718 static __inline void
1719 htcap_update_ldpc(struct ieee80211_node *ni)
1720 {
1721         struct ieee80211vap *vap = ni->ni_vap;
1722
1723         if ((ni->ni_htcap & IEEE80211_HTCAP_LDPC) &&
1724             (vap->iv_flags_ht & IEEE80211_FHT_LDPC_TX))
1725                 ni->ni_flags |= IEEE80211_NODE_LDPC;
1726 }
1727
1728 /*
1729  * Parse and update HT-related state extracted from
1730  * the HT cap and info ie's.
1731  *
1732  * This is called from the STA management path and
1733  * the ieee80211_node_join() path.  It will take into
1734  * account the IEs discovered during scanning and
1735  * adjust things accordingly.
1736  */
1737 void
1738 ieee80211_ht_updateparams(struct ieee80211_node *ni,
1739         const uint8_t *htcapie, const uint8_t *htinfoie)
1740 {
1741         struct ieee80211vap *vap = ni->ni_vap;
1742         const struct ieee80211_ie_htinfo *htinfo;
1743
1744         ieee80211_parse_htcap(ni, htcapie);
1745         if (vap->iv_htcaps & IEEE80211_HTC_SMPS)
1746                 htcap_update_mimo_ps(ni);
1747         htcap_update_shortgi(ni);
1748         htcap_update_ldpc(ni);
1749
1750         if (htinfoie[0] == IEEE80211_ELEMID_VENDOR)
1751                 htinfoie += 4;
1752         htinfo = (const struct ieee80211_ie_htinfo *) htinfoie;
1753         htinfo_parse(ni, htinfo);
1754
1755         /*
1756          * Defer the node channel change; we need to now
1757          * update VHT parameters before we do it.
1758          */
1759
1760         if ((htinfo->hi_byte1 & IEEE80211_HTINFO_RIFSMODE_PERM) &&
1761             (vap->iv_flags_ht & IEEE80211_FHT_RIFS))
1762                 ni->ni_flags |= IEEE80211_NODE_RIFS;
1763         else
1764                 ni->ni_flags &= ~IEEE80211_NODE_RIFS;
1765 }
1766
1767 static uint32_t
1768 ieee80211_vht_get_vhtflags(struct ieee80211_node *ni, uint32_t htflags)
1769 {
1770         struct ieee80211vap *vap = ni->ni_vap;
1771         uint32_t vhtflags = 0;
1772
1773         vhtflags = 0;
1774         if (ni->ni_flags & IEEE80211_NODE_VHT && vap->iv_flags_vht & IEEE80211_FVHT_VHT) {
1775                 if ((ni->ni_vht_chanwidth == IEEE80211_VHT_CHANWIDTH_160MHZ) &&
1776                     /* XXX 2 means "160MHz and 80+80MHz", 1 means "160MHz" */
1777                     (MS(vap->iv_vhtcaps,
1778                      IEEE80211_VHTCAP_SUPP_CHAN_WIDTH_MASK) >= 1) &&
1779                     (vap->iv_flags_vht & IEEE80211_FVHT_USEVHT160)) {
1780                         vhtflags = IEEE80211_CHAN_VHT160;
1781                         /* Mirror the HT40 flags */
1782                         if (htflags == IEEE80211_CHAN_HT40U) {
1783                                 vhtflags |= IEEE80211_CHAN_HT40U;
1784                         } else if (htflags == IEEE80211_CHAN_HT40D) {
1785                                 vhtflags |= IEEE80211_CHAN_HT40D;
1786                         }
1787                 } else if ((ni->ni_vht_chanwidth == IEEE80211_VHT_CHANWIDTH_80P80MHZ) &&
1788                     /* XXX 2 means "160MHz and 80+80MHz" */
1789                     (MS(vap->iv_vhtcaps,
1790                      IEEE80211_VHTCAP_SUPP_CHAN_WIDTH_MASK) == 2) &&
1791                     (vap->iv_flags_vht & IEEE80211_FVHT_USEVHT80P80)) {
1792                         vhtflags = IEEE80211_CHAN_VHT80_80;
1793                         /* Mirror the HT40 flags */
1794                         if (htflags == IEEE80211_CHAN_HT40U) {
1795                                 vhtflags |= IEEE80211_CHAN_HT40U;
1796                         } else if (htflags == IEEE80211_CHAN_HT40D) {
1797                                 vhtflags |= IEEE80211_CHAN_HT40D;
1798                         }
1799                 } else if ((ni->ni_vht_chanwidth == IEEE80211_VHT_CHANWIDTH_80MHZ) &&
1800                     (vap->iv_flags_vht & IEEE80211_FVHT_USEVHT80)) {
1801                         vhtflags = IEEE80211_CHAN_VHT80;
1802                         /* Mirror the HT40 flags */
1803                         if (htflags == IEEE80211_CHAN_HT40U) {
1804                                 vhtflags |= IEEE80211_CHAN_HT40U;
1805                         } else if (htflags == IEEE80211_CHAN_HT40D) {
1806                                 vhtflags |= IEEE80211_CHAN_HT40D;
1807                         }
1808                 } else if (ni->ni_vht_chanwidth == IEEE80211_VHT_CHANWIDTH_USE_HT) {
1809                         /* Mirror the HT40 flags */
1810                         /*
1811                          * XXX TODO: if ht40 is disabled, but vht40 isn't
1812                          * disabled then this logic will get very, very sad.
1813                          * It's quite possible the only sane thing to do is
1814                          * to not have vht40 as an option, and just obey
1815                          * 'ht40' as that flag.
1816                          */
1817                         if ((htflags == IEEE80211_CHAN_HT40U) &&
1818                             (vap->iv_flags_vht & IEEE80211_FVHT_USEVHT40)) {
1819                                 vhtflags = IEEE80211_CHAN_VHT40U
1820                                     | IEEE80211_CHAN_HT40U;
1821                         } else if (htflags == IEEE80211_CHAN_HT40D &&
1822                             (vap->iv_flags_vht & IEEE80211_FVHT_USEVHT40)) {
1823                                 vhtflags = IEEE80211_CHAN_VHT40D
1824                                     | IEEE80211_CHAN_HT40D;
1825                         } else if (htflags == IEEE80211_CHAN_HT20) {
1826                                 vhtflags = IEEE80211_CHAN_VHT20
1827                                     | IEEE80211_CHAN_HT20;
1828                         }
1829                 } else {
1830                         vhtflags = IEEE80211_CHAN_VHT20;
1831                 }
1832         }
1833         return (vhtflags);
1834 }
1835
1836 /*
1837  * Final part of updating the HT parameters.
1838  *
1839  * This is called from the STA management path and
1840  * the ieee80211_node_join() path.  It will take into
1841  * account the IEs discovered during scanning and
1842  * adjust things accordingly.
1843  *
1844  * This is done after a call to ieee80211_ht_updateparams()
1845  * because it (and the upcoming VHT version of updateparams)
1846  * needs to ensure everything is parsed before htinfo_update_chw()
1847  * is called - which will change the channel config for the
1848  * node for us.
1849  */
1850 int
1851 ieee80211_ht_updateparams_final(struct ieee80211_node *ni,
1852         const uint8_t *htcapie, const uint8_t *htinfoie)
1853 {
1854         struct ieee80211vap *vap = ni->ni_vap;
1855         const struct ieee80211_ie_htinfo *htinfo;
1856         int htflags, vhtflags;
1857         int ret = 0;
1858
1859         htinfo = (const struct ieee80211_ie_htinfo *) htinfoie;
1860
1861         htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
1862             IEEE80211_CHAN_HT20 : 0;
1863
1864         /* NB: honor operating mode constraint */
1865         if ((htinfo->hi_byte1 & IEEE80211_HTINFO_TXWIDTH_2040) &&
1866             (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
1867                 if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_ABOVE)
1868                         htflags = IEEE80211_CHAN_HT40U;
1869                 else if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_BELOW)
1870                         htflags = IEEE80211_CHAN_HT40D;
1871         }
1872
1873         /*
1874          * VHT flags - do much the same; check whether VHT is available
1875          * and if so, what our ideal channel use would be based on our
1876          * capabilities and the (pre-parsed) VHT info IE.
1877          */
1878         vhtflags = ieee80211_vht_get_vhtflags(ni, htflags);
1879
1880         if (htinfo_update_chw(ni, htflags, vhtflags))
1881                 ret = 1;
1882
1883         return (ret);
1884 }
1885
1886 /*
1887  * Parse and update HT-related state extracted from the HT cap ie
1888  * for a station joining an HT BSS.
1889  *
1890  * This is called from the hostap path for each station.
1891  */
1892 void
1893 ieee80211_ht_updatehtcap(struct ieee80211_node *ni, const uint8_t *htcapie)
1894 {
1895         struct ieee80211vap *vap = ni->ni_vap;
1896
1897         ieee80211_parse_htcap(ni, htcapie);
1898         if (vap->iv_htcaps & IEEE80211_HTC_SMPS)
1899                 htcap_update_mimo_ps(ni);
1900         htcap_update_shortgi(ni);
1901         htcap_update_ldpc(ni);
1902 }
1903
1904 /*
1905  * Called once HT and VHT capabilities are parsed in hostap mode -
1906  * this will adjust the channel configuration of the given node
1907  * based on the configuration and capabilities.
1908  */
1909 void
1910 ieee80211_ht_updatehtcap_final(struct ieee80211_node *ni)
1911 {
1912         struct ieee80211vap *vap = ni->ni_vap;
1913         int htflags;
1914         int vhtflags;
1915
1916         /* NB: honor operating mode constraint */
1917         /* XXX 40 MHz intolerant */
1918         htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
1919             IEEE80211_CHAN_HT20 : 0;
1920         if ((ni->ni_htcap & IEEE80211_HTCAP_CHWIDTH40) &&
1921             (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
1922                 if (IEEE80211_IS_CHAN_HT40U(vap->iv_bss->ni_chan))
1923                         htflags = IEEE80211_CHAN_HT40U;
1924                 else if (IEEE80211_IS_CHAN_HT40D(vap->iv_bss->ni_chan))
1925                         htflags = IEEE80211_CHAN_HT40D;
1926         }
1927         /*
1928          * VHT flags - do much the same; check whether VHT is available
1929          * and if so, what our ideal channel use would be based on our
1930          * capabilities and the (pre-parsed) VHT info IE.
1931          */
1932         vhtflags = ieee80211_vht_get_vhtflags(ni, htflags);
1933
1934         (void) htinfo_update_chw(ni, htflags, vhtflags);
1935 }
1936
1937 /*
1938  * Install received HT rate set by parsing the HT cap ie.
1939  */
1940 int
1941 ieee80211_setup_htrates(struct ieee80211_node *ni, const uint8_t *ie, int flags)
1942 {
1943         struct ieee80211com *ic = ni->ni_ic;
1944         struct ieee80211vap *vap = ni->ni_vap;
1945         const struct ieee80211_ie_htcap *htcap;
1946         struct ieee80211_htrateset *rs;
1947         int i, maxequalmcs, maxunequalmcs;
1948
1949         maxequalmcs = ic->ic_txstream * 8 - 1;
1950         maxunequalmcs = 0;
1951         if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL) {
1952                 if (ic->ic_txstream >= 2)
1953                         maxunequalmcs = 38;
1954                 if (ic->ic_txstream >= 3)
1955                         maxunequalmcs = 52;
1956                 if (ic->ic_txstream >= 4)
1957                         maxunequalmcs = 76;
1958         }
1959
1960         rs = &ni->ni_htrates;
1961         memset(rs, 0, sizeof(*rs));
1962         if (ie != NULL) {
1963                 if (ie[0] == IEEE80211_ELEMID_VENDOR)
1964                         ie += 4;
1965                 htcap = (const struct ieee80211_ie_htcap *) ie;
1966                 for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
1967                         if (isclr(htcap->hc_mcsset, i))
1968                                 continue;
1969                         if (rs->rs_nrates == IEEE80211_HTRATE_MAXSIZE) {
1970                                 IEEE80211_NOTE(vap,
1971                                     IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
1972                                     "WARNING, HT rate set too large; only "
1973                                     "using %u rates", IEEE80211_HTRATE_MAXSIZE);
1974                                 vap->iv_stats.is_rx_rstoobig++;
1975                                 break;
1976                         }
1977                         if (i <= 31 && i > maxequalmcs)
1978                                 continue;
1979                         if (i == 32 &&
1980                             (ic->ic_htcaps & IEEE80211_HTC_TXMCS32) == 0)
1981                                 continue;
1982                         if (i > 32 && i > maxunequalmcs)
1983                                 continue;
1984                         rs->rs_rates[rs->rs_nrates++] = i;
1985                 }
1986         }
1987         return ieee80211_fix_rate(ni, (struct ieee80211_rateset *) rs, flags);
1988 }
1989
1990 /*
1991  * Mark rates in a node's HT rate set as basic according
1992  * to the information in the supplied HT info ie.
1993  */
1994 void
1995 ieee80211_setup_basic_htrates(struct ieee80211_node *ni, const uint8_t *ie)
1996 {
1997         const struct ieee80211_ie_htinfo *htinfo;
1998         struct ieee80211_htrateset *rs;
1999         int i, j;
2000
2001         if (ie[0] == IEEE80211_ELEMID_VENDOR)
2002                 ie += 4;
2003         htinfo = (const struct ieee80211_ie_htinfo *) ie;
2004         rs = &ni->ni_htrates;
2005         if (rs->rs_nrates == 0) {
2006                 IEEE80211_NOTE(ni->ni_vap,
2007                     IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
2008                     "%s", "WARNING, empty HT rate set");
2009                 return;
2010         }
2011         for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
2012                 if (isclr(htinfo->hi_basicmcsset, i))
2013                         continue;
2014                 for (j = 0; j < rs->rs_nrates; j++)
2015                         if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == i)
2016                                 rs->rs_rates[j] |= IEEE80211_RATE_BASIC;
2017         }
2018 }
2019
2020 static void
2021 ampdu_tx_setup(struct ieee80211_tx_ampdu *tap)
2022 {
2023         callout_init(&tap->txa_timer, 1);
2024         tap->txa_flags |= IEEE80211_AGGR_SETUP;
2025         tap->txa_lastsample = ticks;
2026 }
2027
2028 static void
2029 ampdu_tx_stop(struct ieee80211_tx_ampdu *tap)
2030 {
2031         struct ieee80211_node *ni = tap->txa_ni;
2032         struct ieee80211com *ic = ni->ni_ic;
2033
2034         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2035             tap->txa_ni,
2036             "%s: called",
2037             __func__);
2038
2039         KASSERT(tap->txa_flags & IEEE80211_AGGR_SETUP,
2040             ("txa_flags 0x%x tid %d ac %d", tap->txa_flags, tap->txa_tid,
2041             TID_TO_WME_AC(tap->txa_tid)));
2042
2043         /*
2044          * Stop BA stream if setup so driver has a chance
2045          * to reclaim any resources it might have allocated.
2046          */
2047         ic->ic_addba_stop(ni, tap);
2048         /*
2049          * Stop any pending BAR transmit.
2050          */
2051         bar_stop_timer(tap);
2052
2053         /*
2054          * Reset packet estimate.
2055          */
2056         ieee80211_txampdu_init_pps(tap);
2057
2058         /* NB: clearing NAK means we may re-send ADDBA */ 
2059         tap->txa_flags &= ~(IEEE80211_AGGR_SETUP | IEEE80211_AGGR_NAK);
2060 }
2061
2062 /*
2063  * ADDBA response timeout.
2064  *
2065  * If software aggregation and per-TID queue management was done here,
2066  * that queue would be unpaused after the ADDBA timeout occurs.
2067  */
2068 static void
2069 addba_timeout(void *arg)
2070 {
2071         struct ieee80211_tx_ampdu *tap = arg;
2072         struct ieee80211_node *ni = tap->txa_ni;
2073         struct ieee80211com *ic = ni->ni_ic;
2074
2075         /* XXX ? */
2076         tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
2077         tap->txa_attempts++;
2078         ic->ic_addba_response_timeout(ni, tap);
2079 }
2080
2081 static void
2082 addba_start_timeout(struct ieee80211_tx_ampdu *tap)
2083 {
2084         /* XXX use CALLOUT_PENDING instead? */
2085         callout_reset(&tap->txa_timer, ieee80211_addba_timeout,
2086             addba_timeout, tap);
2087         tap->txa_flags |= IEEE80211_AGGR_XCHGPEND;
2088         tap->txa_nextrequest = ticks + ieee80211_addba_timeout;
2089 }
2090
2091 static void
2092 addba_stop_timeout(struct ieee80211_tx_ampdu *tap)
2093 {
2094         /* XXX use CALLOUT_PENDING instead? */
2095         if (tap->txa_flags & IEEE80211_AGGR_XCHGPEND) {
2096                 callout_stop(&tap->txa_timer);
2097                 tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
2098         }
2099 }
2100
2101 static void
2102 null_addba_response_timeout(struct ieee80211_node *ni,
2103     struct ieee80211_tx_ampdu *tap)
2104 {
2105 }
2106
2107 /*
2108  * Default method for requesting A-MPDU tx aggregation.
2109  * We setup the specified state block and start a timer
2110  * to wait for an ADDBA response frame.
2111  */
2112 static int
2113 ieee80211_addba_request(struct ieee80211_node *ni,
2114         struct ieee80211_tx_ampdu *tap,
2115         int dialogtoken, int baparamset, int batimeout)
2116 {
2117         int bufsiz;
2118
2119         /* XXX locking */
2120         tap->txa_token = dialogtoken;
2121         tap->txa_flags |= IEEE80211_AGGR_IMMEDIATE;
2122         bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
2123         tap->txa_wnd = (bufsiz == 0) ?
2124             IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
2125         addba_start_timeout(tap);
2126         return 1;
2127 }
2128
2129 /*
2130  * Called by drivers that wish to request an ADDBA session be
2131  * setup.  This brings it up and starts the request timer.
2132  */
2133 int
2134 ieee80211_ampdu_tx_request_ext(struct ieee80211_node *ni, int tid)
2135 {
2136         struct ieee80211_tx_ampdu *tap;
2137
2138         if (tid < 0 || tid > 15)
2139                 return (0);
2140         tap = &ni->ni_tx_ampdu[tid];
2141
2142         /* XXX locking */
2143         if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
2144                 /* do deferred setup of state */
2145                 ampdu_tx_setup(tap);
2146         }
2147         /* XXX hack for not doing proper locking */
2148         tap->txa_flags &= ~IEEE80211_AGGR_NAK;
2149         addba_start_timeout(tap);
2150         return (1);
2151 }
2152
2153 /*
2154  * Called by drivers that have marked a session as active.
2155  */
2156 int
2157 ieee80211_ampdu_tx_request_active_ext(struct ieee80211_node *ni, int tid,
2158     int status)
2159 {
2160         struct ieee80211_tx_ampdu *tap;
2161
2162         if (tid < 0 || tid > 15)
2163                 return (0);
2164         tap = &ni->ni_tx_ampdu[tid];
2165
2166         /* XXX locking */
2167         addba_stop_timeout(tap);
2168         if (status == 1) {
2169                 tap->txa_flags |= IEEE80211_AGGR_RUNNING;
2170                 tap->txa_attempts = 0;
2171         } else {
2172                 /* mark tid so we don't try again */
2173                 tap->txa_flags |= IEEE80211_AGGR_NAK;
2174         }
2175         return (1);
2176 }
2177
2178 /*
2179  * Default method for processing an A-MPDU tx aggregation
2180  * response.  We shutdown any pending timer and update the
2181  * state block according to the reply.
2182  */
2183 static int
2184 ieee80211_addba_response(struct ieee80211_node *ni,
2185         struct ieee80211_tx_ampdu *tap,
2186         int status, int baparamset, int batimeout)
2187 {
2188         struct ieee80211vap *vap = ni->ni_vap;
2189         int bufsiz, tid;
2190
2191         /* XXX locking */
2192         addba_stop_timeout(tap);
2193         if (status == IEEE80211_STATUS_SUCCESS) {
2194                 bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
2195                 /* XXX override our request? */
2196                 tap->txa_wnd = (bufsiz == 0) ?
2197                     IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
2198                 tid = MS(baparamset, IEEE80211_BAPS_TID);
2199                 tap->txa_flags |= IEEE80211_AGGR_RUNNING;
2200                 tap->txa_attempts = 0;
2201                 /* TODO: this should be a vap flag */
2202                 if ((vap->iv_htcaps & IEEE80211_HTC_TX_AMSDU_AMPDU) &&
2203                     (ni->ni_flags & IEEE80211_NODE_AMSDU_TX) &&
2204                     (MS(baparamset, IEEE80211_BAPS_AMSDU)))
2205                         tap->txa_flags |= IEEE80211_AGGR_AMSDU;
2206                 else
2207                         tap->txa_flags &= ~IEEE80211_AGGR_AMSDU;
2208         } else {
2209                 /* mark tid so we don't try again */
2210                 tap->txa_flags |= IEEE80211_AGGR_NAK;
2211         }
2212         return 1;
2213 }
2214
2215 /*
2216  * Default method for stopping A-MPDU tx aggregation.
2217  * Any timer is cleared and we drain any pending frames.
2218  */
2219 static void
2220 ieee80211_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
2221 {
2222         /* XXX locking */
2223         addba_stop_timeout(tap);
2224         if (tap->txa_flags & IEEE80211_AGGR_RUNNING) {
2225                 /* XXX clear aggregation queue */
2226                 tap->txa_flags &= ~(IEEE80211_AGGR_RUNNING | IEEE80211_AGGR_AMSDU);
2227         }
2228         tap->txa_attempts = 0;
2229 }
2230
2231 /*
2232  * Process a received action frame using the default aggregation
2233  * policy.  We intercept ADDBA-related frames and use them to
2234  * update our aggregation state.  All other frames are passed up
2235  * for processing by ieee80211_recv_action.
2236  */
2237 static int
2238 ht_recv_action_ba_addba_request(struct ieee80211_node *ni,
2239         const struct ieee80211_frame *wh,
2240         const uint8_t *frm, const uint8_t *efrm)
2241 {
2242         struct ieee80211com *ic = ni->ni_ic;
2243         struct ieee80211vap *vap = ni->ni_vap;
2244         struct ieee80211_rx_ampdu *rap;
2245         uint8_t dialogtoken;
2246         uint16_t baparamset, batimeout, baseqctl;
2247         uint16_t args[5];
2248         int tid;
2249
2250         dialogtoken = frm[2];
2251         baparamset = le16dec(frm+3);
2252         batimeout = le16dec(frm+5);
2253         baseqctl = le16dec(frm+7);
2254
2255         tid = MS(baparamset, IEEE80211_BAPS_TID);
2256
2257         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2258             "recv ADDBA request: dialogtoken %u baparamset 0x%x "
2259             "(tid %d bufsiz %d) batimeout %d baseqctl %d:%d amsdu %d",
2260             dialogtoken, baparamset,
2261             tid, MS(baparamset, IEEE80211_BAPS_BUFSIZ),
2262             batimeout,
2263             MS(baseqctl, IEEE80211_BASEQ_START),
2264             MS(baseqctl, IEEE80211_BASEQ_FRAG),
2265             MS(baparamset, IEEE80211_BAPS_AMSDU));
2266
2267         rap = &ni->ni_rx_ampdu[tid];
2268
2269         /* Send ADDBA response */
2270         args[0] = dialogtoken;
2271         /*
2272          * NB: We ack only if the sta associated with HT and
2273          * the ap is configured to do AMPDU rx (the latter
2274          * violates the 11n spec and is mostly for testing).
2275          */
2276         if ((ni->ni_flags & IEEE80211_NODE_AMPDU_RX) &&
2277             (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_RX)) {
2278                 /* XXX TODO: handle ampdu_rx_start failure */
2279                 ic->ic_ampdu_rx_start(ni, rap,
2280                     baparamset, batimeout, baseqctl);
2281
2282                 args[1] = IEEE80211_STATUS_SUCCESS;
2283         } else {
2284                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2285                     ni, "reject ADDBA request: %s",
2286                     ni->ni_flags & IEEE80211_NODE_AMPDU_RX ?
2287                        "administratively disabled" :
2288                        "not negotiated for station");
2289                 vap->iv_stats.is_addba_reject++;
2290                 args[1] = IEEE80211_STATUS_UNSPECIFIED;
2291         }
2292         /* XXX honor rap flags? */
2293         args[2] = IEEE80211_BAPS_POLICY_IMMEDIATE
2294                 | SM(tid, IEEE80211_BAPS_TID)
2295                 | SM(rap->rxa_wnd, IEEE80211_BAPS_BUFSIZ)
2296                 ;
2297
2298         /*
2299          * TODO: we're out of iv_flags_ht fields; once
2300          * this is extended we should make this configurable.
2301          */
2302         if ((baparamset & IEEE80211_BAPS_AMSDU) &&
2303             (ni->ni_flags & IEEE80211_NODE_AMSDU_RX) &&
2304             (vap->iv_htcaps & IEEE80211_HTC_RX_AMSDU_AMPDU))
2305                 args[2] |= IEEE80211_BAPS_AMSDU;
2306
2307         args[3] = 0;
2308         args[4] = 0;
2309         ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
2310                 IEEE80211_ACTION_BA_ADDBA_RESPONSE, args);
2311         return 0;
2312 }
2313
2314 static int
2315 ht_recv_action_ba_addba_response(struct ieee80211_node *ni,
2316         const struct ieee80211_frame *wh,
2317         const uint8_t *frm, const uint8_t *efrm)
2318 {
2319         struct ieee80211com *ic = ni->ni_ic;
2320         struct ieee80211vap *vap = ni->ni_vap;
2321         struct ieee80211_tx_ampdu *tap;
2322         uint8_t dialogtoken, policy;
2323         uint16_t baparamset, batimeout, code;
2324         int tid, bufsiz;
2325         int amsdu;
2326
2327         dialogtoken = frm[2];
2328         code = le16dec(frm+3);
2329         baparamset = le16dec(frm+5);
2330         tid = MS(baparamset, IEEE80211_BAPS_TID);
2331         bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
2332         policy = MS(baparamset, IEEE80211_BAPS_POLICY);
2333         amsdu = !! MS(baparamset, IEEE80211_BAPS_AMSDU);
2334         batimeout = le16dec(frm+7);
2335
2336         tap = &ni->ni_tx_ampdu[tid];
2337         if ((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
2338                 IEEE80211_DISCARD_MAC(vap,
2339                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2340                     ni->ni_macaddr, "ADDBA response",
2341                     "no pending ADDBA, tid %d dialogtoken %u "
2342                     "code %d", tid, dialogtoken, code);
2343                 vap->iv_stats.is_addba_norequest++;
2344                 return 0;
2345         }
2346         if (dialogtoken != tap->txa_token) {
2347                 IEEE80211_DISCARD_MAC(vap,
2348                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2349                     ni->ni_macaddr, "ADDBA response",
2350                     "dialogtoken mismatch: waiting for %d, "
2351                     "received %d, tid %d code %d",
2352                     tap->txa_token, dialogtoken, tid, code);
2353                 vap->iv_stats.is_addba_badtoken++;
2354                 return 0;
2355         }
2356         /* NB: assumes IEEE80211_AGGR_IMMEDIATE is 1 */
2357         if (policy != (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE)) {
2358                 IEEE80211_DISCARD_MAC(vap,
2359                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2360                     ni->ni_macaddr, "ADDBA response",
2361                     "policy mismatch: expecting %s, "
2362                     "received %s, tid %d code %d",
2363                     tap->txa_flags & IEEE80211_AGGR_IMMEDIATE,
2364                     policy, tid, code);
2365                 vap->iv_stats.is_addba_badpolicy++;
2366                 return 0;
2367         }
2368 #if 0
2369         /* XXX we take MIN in ieee80211_addba_response */
2370         if (bufsiz > IEEE80211_AGGR_BAWMAX) {
2371                 IEEE80211_DISCARD_MAC(vap,
2372                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2373                     ni->ni_macaddr, "ADDBA response",
2374                     "BA window too large: max %d, "
2375                     "received %d, tid %d code %d",
2376                     bufsiz, IEEE80211_AGGR_BAWMAX, tid, code);
2377                 vap->iv_stats.is_addba_badbawinsize++;
2378                 return 0;
2379         }
2380 #endif
2381
2382         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2383             "recv ADDBA response: dialogtoken %u code %d "
2384             "baparamset 0x%x (tid %d bufsiz %d amsdu %d) batimeout %d",
2385             dialogtoken, code, baparamset, tid,
2386             bufsiz,
2387             amsdu,
2388             batimeout);
2389         ic->ic_addba_response(ni, tap, code, baparamset, batimeout);
2390         return 0;
2391 }
2392
2393 static int
2394 ht_recv_action_ba_delba(struct ieee80211_node *ni,
2395         const struct ieee80211_frame *wh,
2396         const uint8_t *frm, const uint8_t *efrm)
2397 {
2398         struct ieee80211com *ic = ni->ni_ic;
2399         struct ieee80211_rx_ampdu *rap;
2400         struct ieee80211_tx_ampdu *tap;
2401         uint16_t baparamset, code;
2402         int tid;
2403
2404         baparamset = le16dec(frm+2);
2405         code = le16dec(frm+4);
2406
2407         tid = MS(baparamset, IEEE80211_DELBAPS_TID);
2408
2409         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2410             "recv DELBA: baparamset 0x%x (tid %d initiator %d) "
2411             "code %d", baparamset, tid,
2412             MS(baparamset, IEEE80211_DELBAPS_INIT), code);
2413
2414         if ((baparamset & IEEE80211_DELBAPS_INIT) == 0) {
2415                 tap = &ni->ni_tx_ampdu[tid];
2416                 ic->ic_addba_stop(ni, tap);
2417         } else {
2418                 rap = &ni->ni_rx_ampdu[tid];
2419                 ic->ic_ampdu_rx_stop(ni, rap);
2420         }
2421         return 0;
2422 }
2423
2424 static int
2425 ht_recv_action_ht_txchwidth(struct ieee80211_node *ni,
2426         const struct ieee80211_frame *wh,
2427         const uint8_t *frm, const uint8_t *efrm)
2428 {
2429         int chw;
2430
2431         chw = (frm[2] == IEEE80211_A_HT_TXCHWIDTH_2040) ? 40 : 20;
2432
2433         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2434             "%s: HT txchwidth, width %d%s",
2435             __func__, chw, ni->ni_chw != chw ? "*" : "");
2436         if (chw != ni->ni_chw) {
2437                 /* XXX does this need to change the ht40 station count? */
2438                 ni->ni_chw = chw;
2439                 /* XXX notify on change */
2440         }
2441         return 0;
2442 }
2443
2444 static int
2445 ht_recv_action_ht_mimopwrsave(struct ieee80211_node *ni,
2446         const struct ieee80211_frame *wh,
2447         const uint8_t *frm, const uint8_t *efrm)
2448 {
2449         const struct ieee80211_action_ht_mimopowersave *mps =
2450             (const struct ieee80211_action_ht_mimopowersave *) frm;
2451
2452         /* XXX check iv_htcaps */
2453         if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_ENA)
2454                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
2455         else
2456                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
2457         if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_MODE)
2458                 ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
2459         else
2460                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
2461         /* XXX notify on change */
2462         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2463             "%s: HT MIMO PS (%s%s)", __func__,
2464             (ni->ni_flags & IEEE80211_NODE_MIMO_PS) ?  "on" : "off",
2465             (ni->ni_flags & IEEE80211_NODE_MIMO_RTS) ?  "+rts" : ""
2466         );
2467         return 0;
2468 }
2469
2470 /*
2471  * Transmit processing.
2472  */
2473
2474 /*
2475  * Check if A-MPDU should be requested/enabled for a stream.
2476  * We require a traffic rate above a per-AC threshold and we
2477  * also handle backoff from previous failed attempts.
2478  *
2479  * Drivers may override this method to bring in information
2480  * such as link state conditions in making the decision.
2481  */
2482 static int
2483 ieee80211_ampdu_enable(struct ieee80211_node *ni,
2484         struct ieee80211_tx_ampdu *tap)
2485 {
2486         struct ieee80211vap *vap = ni->ni_vap;
2487
2488         if (tap->txa_avgpps <
2489             vap->iv_ampdu_mintraffic[TID_TO_WME_AC(tap->txa_tid)])
2490                 return 0;
2491         /* XXX check rssi? */
2492         if (tap->txa_attempts >= ieee80211_addba_maxtries &&
2493             ieee80211_time_after(ticks, tap->txa_nextrequest)) {
2494                 /*
2495                  * Don't retry too often; txa_nextrequest is set
2496                  * to the minimum interval we'll retry after
2497                  * ieee80211_addba_maxtries failed attempts are made.
2498                  */
2499                 return 0;
2500         }
2501         IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
2502             "enable AMPDU on tid %d (%s), avgpps %d pkts %d attempt %d",
2503             tap->txa_tid, ieee80211_wme_acnames[TID_TO_WME_AC(tap->txa_tid)],
2504             tap->txa_avgpps, tap->txa_pkts, tap->txa_attempts);
2505         return 1;
2506 }
2507
2508 /*
2509  * Request A-MPDU tx aggregation.  Setup local state and
2510  * issue an ADDBA request.  BA use will only happen after
2511  * the other end replies with ADDBA response.
2512  */
2513 int
2514 ieee80211_ampdu_request(struct ieee80211_node *ni,
2515         struct ieee80211_tx_ampdu *tap)
2516 {
2517         struct ieee80211com *ic = ni->ni_ic;
2518         uint16_t args[5];
2519         int tid, dialogtoken;
2520         static int tokens = 0;  /* XXX */
2521
2522         /* XXX locking */
2523         if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
2524                 /* do deferred setup of state */
2525                 ampdu_tx_setup(tap);
2526         }
2527         /* XXX hack for not doing proper locking */
2528         tap->txa_flags &= ~IEEE80211_AGGR_NAK;
2529
2530         dialogtoken = (tokens+1) % 63;          /* XXX */
2531         tid = tap->txa_tid;
2532
2533         /*
2534          * XXX TODO: This is racy with any other parallel TX going on. :(
2535          */
2536         tap->txa_start = ni->ni_txseqs[tid];
2537
2538         args[0] = dialogtoken;
2539         args[1] = 0;    /* NB: status code not used */
2540         args[2] = IEEE80211_BAPS_POLICY_IMMEDIATE
2541                 | SM(tid, IEEE80211_BAPS_TID)
2542                 | SM(IEEE80211_AGGR_BAWMAX, IEEE80211_BAPS_BUFSIZ)
2543                 ;
2544
2545         /* XXX TODO: this should be a flag, not iv_htcaps */
2546         if ((ni->ni_flags & IEEE80211_NODE_AMSDU_TX) &&
2547             (ni->ni_vap->iv_htcaps & IEEE80211_HTC_TX_AMSDU_AMPDU))
2548                 args[2] |= IEEE80211_BAPS_AMSDU;
2549
2550         args[3] = 0;    /* batimeout */
2551         /* NB: do first so there's no race against reply */
2552         if (!ic->ic_addba_request(ni, tap, dialogtoken, args[2], args[3])) {
2553                 /* unable to setup state, don't make request */
2554                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2555                     ni, "%s: could not setup BA stream for TID %d AC %d",
2556                     __func__, tap->txa_tid, TID_TO_WME_AC(tap->txa_tid));
2557                 /* defer next try so we don't slam the driver with requests */
2558                 tap->txa_attempts = ieee80211_addba_maxtries;
2559                 /* NB: check in case driver wants to override */
2560                 if (tap->txa_nextrequest <= ticks)
2561                         tap->txa_nextrequest = ticks + ieee80211_addba_backoff;
2562                 return 0;
2563         }
2564         tokens = dialogtoken;                   /* allocate token */
2565         /* NB: after calling ic_addba_request so driver can set txa_start */
2566         args[4] = SM(tap->txa_start, IEEE80211_BASEQ_START)
2567                 | SM(0, IEEE80211_BASEQ_FRAG)
2568                 ;
2569         return ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
2570                 IEEE80211_ACTION_BA_ADDBA_REQUEST, args);
2571 }
2572
2573 /*
2574  * Terminate an AMPDU tx stream.  State is reclaimed
2575  * and the peer notified with a DelBA Action frame.
2576  */
2577 void
2578 ieee80211_ampdu_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
2579         int reason)
2580 {
2581         struct ieee80211com *ic = ni->ni_ic;
2582         struct ieee80211vap *vap = ni->ni_vap;
2583         uint16_t args[4];
2584
2585         /* XXX locking */
2586         tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2587         if (IEEE80211_AMPDU_RUNNING(tap)) {
2588                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2589                     ni, "%s: stop BA stream for TID %d (reason: %d (%s))",
2590                     __func__, tap->txa_tid, reason,
2591                     ieee80211_reason_to_string(reason));
2592                 vap->iv_stats.is_ampdu_stop++;
2593
2594                 ic->ic_addba_stop(ni, tap);
2595                 args[0] = tap->txa_tid;
2596                 args[1] = IEEE80211_DELBAPS_INIT;
2597                 args[2] = reason;                       /* XXX reason code */
2598                 ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
2599                         IEEE80211_ACTION_BA_DELBA, args);
2600         } else {
2601                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
2602                     ni, "%s: BA stream for TID %d not running "
2603                     "(reason: %d (%s))", __func__, tap->txa_tid, reason,
2604                     ieee80211_reason_to_string(reason));
2605                 vap->iv_stats.is_ampdu_stop_failed++;
2606         }
2607 }
2608
2609 /* XXX */
2610 static void bar_start_timer(struct ieee80211_tx_ampdu *tap);
2611
2612 static void
2613 bar_timeout(void *arg)
2614 {
2615         struct ieee80211_tx_ampdu *tap = arg;
2616         struct ieee80211_node *ni = tap->txa_ni;
2617
2618         KASSERT((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0,
2619             ("bar/addba collision, flags 0x%x", tap->txa_flags));
2620
2621         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2622             ni, "%s: tid %u flags 0x%x attempts %d", __func__,
2623             tap->txa_tid, tap->txa_flags, tap->txa_attempts);
2624
2625         /* guard against race with bar_tx_complete */
2626         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
2627                 return;
2628         /* XXX ? */
2629         if (tap->txa_attempts >= ieee80211_bar_maxtries) {
2630                 struct ieee80211com *ic = ni->ni_ic;
2631
2632                 ni->ni_vap->iv_stats.is_ampdu_bar_tx_fail++;
2633                 /*
2634                  * If (at least) the last BAR TX timeout was due to
2635                  * an ieee80211_send_bar() failures, then we need
2636                  * to make sure we notify the driver that a BAR
2637                  * TX did occur and fail.  This gives the driver
2638                  * a chance to undo any queue pause that may
2639                  * have occurred.
2640                  */
2641                 ic->ic_bar_response(ni, tap, 1);
2642                 ieee80211_ampdu_stop(ni, tap, IEEE80211_REASON_TIMEOUT);
2643         } else {
2644                 ni->ni_vap->iv_stats.is_ampdu_bar_tx_retry++;
2645                 if (ieee80211_send_bar(ni, tap, tap->txa_seqpending) != 0) {
2646                         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2647                             ni, "%s: failed to TX, starting timer\n",
2648                             __func__);
2649                         /*
2650                          * If ieee80211_send_bar() fails here, the
2651                          * timer may have stopped and/or the pending
2652                          * flag may be clear.  Because of this,
2653                          * fake the BARPEND and reset the timer.
2654                          * A retransmission attempt will then occur
2655                          * during the next timeout.
2656                          */
2657                         /* XXX locking */
2658                         tap->txa_flags |= IEEE80211_AGGR_BARPEND;
2659                         bar_start_timer(tap);
2660                 }
2661         }
2662 }
2663
2664 static void
2665 bar_start_timer(struct ieee80211_tx_ampdu *tap)
2666 {
2667         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2668             tap->txa_ni,
2669             "%s: called",
2670             __func__);
2671         callout_reset(&tap->txa_timer, ieee80211_bar_timeout, bar_timeout, tap);
2672 }
2673
2674 static void
2675 bar_stop_timer(struct ieee80211_tx_ampdu *tap)
2676 {
2677         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2678             tap->txa_ni,
2679             "%s: called",
2680             __func__);
2681         callout_stop(&tap->txa_timer);
2682 }
2683
2684 static void
2685 bar_tx_complete(struct ieee80211_node *ni, void *arg, int status)
2686 {
2687         struct ieee80211_tx_ampdu *tap = arg;
2688
2689         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2690             ni, "%s: tid %u flags 0x%x pending %d status %d",
2691             __func__, tap->txa_tid, tap->txa_flags,
2692             callout_pending(&tap->txa_timer), status);
2693
2694         ni->ni_vap->iv_stats.is_ampdu_bar_tx++;
2695         /* XXX locking */
2696         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) &&
2697             callout_pending(&tap->txa_timer)) {
2698                 struct ieee80211com *ic = ni->ni_ic;
2699
2700                 if (status == 0)                /* ACK'd */
2701                         bar_stop_timer(tap);
2702                 ic->ic_bar_response(ni, tap, status);
2703                 /* NB: just let timer expire so we pace requests */
2704         }
2705 }
2706
2707 static void
2708 ieee80211_bar_response(struct ieee80211_node *ni,
2709         struct ieee80211_tx_ampdu *tap, int status)
2710 {
2711
2712         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2713             tap->txa_ni,
2714             "%s: called",
2715             __func__);
2716         if (status == 0) {              /* got ACK */
2717                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2718                     ni, "BAR moves BA win <%u:%u> (%u frames) txseq %u tid %u",
2719                     tap->txa_start,
2720                     IEEE80211_SEQ_ADD(tap->txa_start, tap->txa_wnd-1),
2721                     tap->txa_qframes, tap->txa_seqpending,
2722                     tap->txa_tid);
2723
2724                 /* NB: timer already stopped in bar_tx_complete */
2725                 tap->txa_start = tap->txa_seqpending;
2726                 tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2727         }
2728 }
2729
2730 /*
2731  * Transmit a BAR frame to the specified node.  The
2732  * BAR contents are drawn from the supplied aggregation
2733  * state associated with the node.
2734  *
2735  * NB: we only handle immediate ACK w/ compressed bitmap.
2736  */
2737 int
2738 ieee80211_send_bar(struct ieee80211_node *ni,
2739         struct ieee80211_tx_ampdu *tap, ieee80211_seq seq)
2740 {
2741 #define senderr(_x, _v) do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
2742         struct ieee80211vap *vap = ni->ni_vap;
2743         struct ieee80211com *ic = ni->ni_ic;
2744         struct ieee80211_frame_bar *bar;
2745         struct mbuf *m;
2746         uint16_t barctl, barseqctl;
2747         uint8_t *frm;
2748         int tid, ret;
2749
2750
2751         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2752             tap->txa_ni,
2753             "%s: called",
2754             __func__);
2755
2756         if ((tap->txa_flags & IEEE80211_AGGR_RUNNING) == 0) {
2757                 /* no ADDBA response, should not happen */
2758                 /* XXX stat+msg */
2759                 return EINVAL;
2760         }
2761         /* XXX locking */
2762         bar_stop_timer(tap);
2763
2764         ieee80211_ref_node(ni);
2765
2766         m = ieee80211_getmgtframe(&frm, ic->ic_headroom, sizeof(*bar));
2767         if (m == NULL)
2768                 senderr(ENOMEM, is_tx_nobuf);
2769
2770         if (!ieee80211_add_callback(m, bar_tx_complete, tap)) {
2771                 m_freem(m);
2772                 senderr(ENOMEM, is_tx_nobuf);   /* XXX */
2773                 /* NOTREACHED */
2774         }
2775
2776         bar = mtod(m, struct ieee80211_frame_bar *);
2777         bar->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2778                 IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR;
2779         bar->i_fc[1] = 0;
2780         IEEE80211_ADDR_COPY(bar->i_ra, ni->ni_macaddr);
2781         IEEE80211_ADDR_COPY(bar->i_ta, vap->iv_myaddr);
2782
2783         tid = tap->txa_tid;
2784         barctl  = (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE ?
2785                         0 : IEEE80211_BAR_NOACK)
2786                 | IEEE80211_BAR_COMP
2787                 | SM(tid, IEEE80211_BAR_TID)
2788                 ;
2789         barseqctl = SM(seq, IEEE80211_BAR_SEQ_START);
2790         /* NB: known to have proper alignment */
2791         bar->i_ctl = htole16(barctl);
2792         bar->i_seq = htole16(barseqctl);
2793         m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_bar);
2794
2795         M_WME_SETAC(m, WME_AC_VO);
2796
2797         IEEE80211_NODE_STAT(ni, tx_mgmt);       /* XXX tx_ctl? */
2798
2799         /* XXX locking */
2800         /* init/bump attempts counter */
2801         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
2802                 tap->txa_attempts = 1;
2803         else
2804                 tap->txa_attempts++;
2805         tap->txa_seqpending = seq;
2806         tap->txa_flags |= IEEE80211_AGGR_BARPEND;
2807
2808         IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
2809             ni, "send BAR: tid %u ctl 0x%x start %u (attempt %d)",
2810             tid, barctl, seq, tap->txa_attempts);
2811
2812         /*
2813          * ic_raw_xmit will free the node reference
2814          * regardless of queue/TX success or failure.
2815          */
2816         IEEE80211_TX_LOCK(ic);
2817         ret = ieee80211_raw_output(vap, ni, m, NULL);
2818         IEEE80211_TX_UNLOCK(ic);
2819         if (ret != 0) {
2820                 IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
2821                     ni, "send BAR: failed: (ret = %d)\n",
2822                     ret);
2823                 /* xmit failed, clear state flag */
2824                 tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2825                 vap->iv_stats.is_ampdu_bar_tx_fail++;
2826                 return ret;
2827         }
2828         /* XXX hack against tx complete happening before timer is started */
2829         if (tap->txa_flags & IEEE80211_AGGR_BARPEND)
2830                 bar_start_timer(tap);
2831         return 0;
2832 bad:
2833         IEEE80211_NOTE(tap->txa_ni->ni_vap, IEEE80211_MSG_11N,
2834             tap->txa_ni,
2835             "%s: bad! ret=%d",
2836             __func__, ret);
2837         vap->iv_stats.is_ampdu_bar_tx_fail++;
2838         ieee80211_free_node(ni);
2839         return ret;
2840 #undef senderr
2841 }
2842
2843 static int
2844 ht_action_output(struct ieee80211_node *ni, struct mbuf *m)
2845 {
2846         struct ieee80211_bpf_params params;
2847
2848         memset(&params, 0, sizeof(params));
2849         params.ibp_pri = WME_AC_VO;
2850         params.ibp_rate0 = ni->ni_txparms->mgmtrate;
2851         /* NB: we know all frames are unicast */
2852         params.ibp_try0 = ni->ni_txparms->maxretry;
2853         params.ibp_power = ni->ni_txpower;
2854         return ieee80211_mgmt_output(ni, m, IEEE80211_FC0_SUBTYPE_ACTION,
2855              &params);
2856 }
2857
2858 #define ADDSHORT(frm, v) do {                   \
2859         frm[0] = (v) & 0xff;                    \
2860         frm[1] = (v) >> 8;                      \
2861         frm += 2;                               \
2862 } while (0)
2863
2864 /*
2865  * Send an action management frame.  The arguments are stuff
2866  * into a frame without inspection; the caller is assumed to
2867  * prepare them carefully (e.g. based on the aggregation state).
2868  */
2869 static int
2870 ht_send_action_ba_addba(struct ieee80211_node *ni,
2871         int category, int action, void *arg0)
2872 {
2873         struct ieee80211vap *vap = ni->ni_vap;
2874         struct ieee80211com *ic = ni->ni_ic;
2875         uint16_t *args = arg0;
2876         struct mbuf *m;
2877         uint8_t *frm;
2878
2879         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2880             "send ADDBA %s: dialogtoken %d status %d "
2881             "baparamset 0x%x (tid %d amsdu %d) batimeout 0x%x baseqctl 0x%x",
2882             (action == IEEE80211_ACTION_BA_ADDBA_REQUEST) ?
2883                 "request" : "response",
2884             args[0], args[1], args[2], MS(args[2], IEEE80211_BAPS_TID),
2885             MS(args[2], IEEE80211_BAPS_AMSDU), args[3], args[4]);
2886
2887         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2888             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2889             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2890         ieee80211_ref_node(ni);
2891
2892         m = ieee80211_getmgtframe(&frm,
2893             ic->ic_headroom + sizeof(struct ieee80211_frame),
2894             sizeof(uint16_t)    /* action+category */
2895             /* XXX may action payload */
2896             + sizeof(struct ieee80211_action_ba_addbaresponse)
2897         );
2898         if (m != NULL) {
2899                 *frm++ = category;
2900                 *frm++ = action;
2901                 *frm++ = args[0];               /* dialog token */
2902                 if (action == IEEE80211_ACTION_BA_ADDBA_RESPONSE)
2903                         ADDSHORT(frm, args[1]); /* status code */
2904                 ADDSHORT(frm, args[2]);         /* baparamset */
2905                 ADDSHORT(frm, args[3]);         /* batimeout */
2906                 if (action == IEEE80211_ACTION_BA_ADDBA_REQUEST)
2907                         ADDSHORT(frm, args[4]); /* baseqctl */
2908                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2909                 return ht_action_output(ni, m);
2910         } else {
2911                 vap->iv_stats.is_tx_nobuf++;
2912                 ieee80211_free_node(ni);
2913                 return ENOMEM;
2914         }
2915 }
2916
2917 static int
2918 ht_send_action_ba_delba(struct ieee80211_node *ni,
2919         int category, int action, void *arg0)
2920 {
2921         struct ieee80211vap *vap = ni->ni_vap;
2922         struct ieee80211com *ic = ni->ni_ic;
2923         uint16_t *args = arg0;
2924         struct mbuf *m;
2925         uint16_t baparamset;
2926         uint8_t *frm;
2927
2928         baparamset = SM(args[0], IEEE80211_DELBAPS_TID)
2929                    | args[1]
2930                    ;
2931         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2932             "send DELBA action: tid %d, initiator %d reason %d (%s)",
2933             args[0], args[1], args[2], ieee80211_reason_to_string(args[2]));
2934
2935         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2936             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2937             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2938         ieee80211_ref_node(ni);
2939
2940         m = ieee80211_getmgtframe(&frm,
2941             ic->ic_headroom + sizeof(struct ieee80211_frame),
2942             sizeof(uint16_t)    /* action+category */
2943             /* XXX may action payload */
2944             + sizeof(struct ieee80211_action_ba_addbaresponse)
2945         );
2946         if (m != NULL) {
2947                 *frm++ = category;
2948                 *frm++ = action;
2949                 ADDSHORT(frm, baparamset);
2950                 ADDSHORT(frm, args[2]);         /* reason code */
2951                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2952                 return ht_action_output(ni, m);
2953         } else {
2954                 vap->iv_stats.is_tx_nobuf++;
2955                 ieee80211_free_node(ni);
2956                 return ENOMEM;
2957         }
2958 }
2959
2960 static int
2961 ht_send_action_ht_txchwidth(struct ieee80211_node *ni,
2962         int category, int action, void *arg0)
2963 {
2964         struct ieee80211vap *vap = ni->ni_vap;
2965         struct ieee80211com *ic = ni->ni_ic;
2966         struct mbuf *m;
2967         uint8_t *frm;
2968
2969         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2970             "send HT txchwidth: width %d",
2971             IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 40 : 20);
2972
2973         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2974             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2975             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2976         ieee80211_ref_node(ni);
2977
2978         m = ieee80211_getmgtframe(&frm,
2979             ic->ic_headroom + sizeof(struct ieee80211_frame),
2980             sizeof(uint16_t)    /* action+category */
2981             /* XXX may action payload */
2982             + sizeof(struct ieee80211_action_ba_addbaresponse)
2983         );
2984         if (m != NULL) {
2985                 *frm++ = category;
2986                 *frm++ = action;
2987                 *frm++ = IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 
2988                         IEEE80211_A_HT_TXCHWIDTH_2040 :
2989                         IEEE80211_A_HT_TXCHWIDTH_20;
2990                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2991                 return ht_action_output(ni, m);
2992         } else {
2993                 vap->iv_stats.is_tx_nobuf++;
2994                 ieee80211_free_node(ni);
2995                 return ENOMEM;
2996         }
2997 }
2998 #undef ADDSHORT
2999
3000 /*
3001  * Construct the MCS bit mask for inclusion in an HT capabilities
3002  * information element.
3003  */
3004 static void
3005 ieee80211_set_mcsset(struct ieee80211com *ic, uint8_t *frm)
3006 {
3007         int i;
3008         uint8_t txparams;
3009
3010         KASSERT((ic->ic_rxstream > 0 && ic->ic_rxstream <= 4),
3011             ("ic_rxstream %d out of range", ic->ic_rxstream));
3012         KASSERT((ic->ic_txstream > 0 && ic->ic_txstream <= 4),
3013             ("ic_txstream %d out of range", ic->ic_txstream));
3014
3015         for (i = 0; i < ic->ic_rxstream * 8; i++)
3016                 setbit(frm, i);
3017         if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
3018             (ic->ic_htcaps & IEEE80211_HTC_RXMCS32))
3019                 setbit(frm, 32);
3020         if (ic->ic_htcaps & IEEE80211_HTC_RXUNEQUAL) {
3021                 if (ic->ic_rxstream >= 2) {
3022                         for (i = 33; i <= 38; i++)
3023                                 setbit(frm, i);
3024                 }
3025                 if (ic->ic_rxstream >= 3) {
3026                         for (i = 39; i <= 52; i++)
3027                                 setbit(frm, i);
3028                 }
3029                 if (ic->ic_txstream >= 4) {
3030                         for (i = 53; i <= 76; i++)
3031                                 setbit(frm, i);
3032                 }
3033         }
3034
3035         if (ic->ic_rxstream != ic->ic_txstream) {
3036                 txparams = 0x1;                 /* TX MCS set defined */
3037                 txparams |= 0x2;                /* TX RX MCS not equal */
3038                 txparams |= (ic->ic_txstream - 1) << 2; /* num TX streams */
3039                 if (ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL)
3040                         txparams |= 0x16;       /* TX unequal modulation sup */
3041         } else
3042                 txparams = 0;
3043         frm[12] = txparams;
3044 }
3045
3046 /*
3047  * Add body of an HTCAP information element.
3048  */
3049 static uint8_t *
3050 ieee80211_add_htcap_body(uint8_t *frm, struct ieee80211_node *ni)
3051 {
3052 #define ADDSHORT(frm, v) do {                   \
3053         frm[0] = (v) & 0xff;                    \
3054         frm[1] = (v) >> 8;                      \
3055         frm += 2;                               \
3056 } while (0)
3057         struct ieee80211com *ic = ni->ni_ic;
3058         struct ieee80211vap *vap = ni->ni_vap;
3059         uint16_t caps, extcaps;
3060         int rxmax, density;
3061
3062         /* HT capabilities */
3063         caps = vap->iv_htcaps & 0xffff;
3064         /*
3065          * Note channel width depends on whether we are operating as
3066          * a sta or not.  When operating as a sta we are generating
3067          * a request based on our desired configuration.  Otherwise
3068          * we are operational and the channel attributes identify
3069          * how we've been setup (which might be different if a fixed
3070          * channel is specified).
3071          */
3072         if (vap->iv_opmode == IEEE80211_M_STA) {
3073                 /* override 20/40 use based on config */
3074                 if (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)
3075                         caps |= IEEE80211_HTCAP_CHWIDTH40;
3076                 else
3077                         caps &= ~IEEE80211_HTCAP_CHWIDTH40;
3078
3079                 /* Start by using the advertised settings */
3080                 rxmax = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU);
3081                 density = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY);
3082
3083                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_11N,
3084                     "%s: advertised rxmax=%d, density=%d, vap rxmax=%d, density=%d\n",
3085                     __func__,
3086                     rxmax,
3087                     density,
3088                     vap->iv_ampdu_rxmax,
3089                     vap->iv_ampdu_density);
3090
3091                 /* Cap at VAP rxmax */
3092                 if (rxmax > vap->iv_ampdu_rxmax)
3093                         rxmax = vap->iv_ampdu_rxmax;
3094
3095                 /*
3096                  * If the VAP ampdu density value greater, use that.
3097                  *
3098                  * (Larger density value == larger minimum gap between A-MPDU
3099                  * subframes.)
3100                  */
3101                 if (vap->iv_ampdu_density > density)
3102                         density = vap->iv_ampdu_density;
3103
3104                 /*
3105                  * NB: Hardware might support HT40 on some but not all
3106                  * channels. We can't determine this earlier because only
3107                  * after association the channel is upgraded to HT based
3108                  * on the negotiated capabilities.
3109                  */
3110                 if (ni->ni_chan != IEEE80211_CHAN_ANYC &&
3111                     findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT40U) == NULL &&
3112                     findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT40D) == NULL)
3113                         caps &= ~IEEE80211_HTCAP_CHWIDTH40;
3114         } else {
3115                 /* override 20/40 use based on current channel */
3116                 if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
3117                         caps |= IEEE80211_HTCAP_CHWIDTH40;
3118                 else
3119                         caps &= ~IEEE80211_HTCAP_CHWIDTH40;
3120
3121                 /* XXX TODO should it start by using advertised settings? */
3122                 rxmax = vap->iv_ampdu_rxmax;
3123                 density = vap->iv_ampdu_density;
3124         }
3125
3126         /* adjust short GI based on channel and config */
3127         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
3128                 caps &= ~IEEE80211_HTCAP_SHORTGI20;
3129         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0 ||
3130             (caps & IEEE80211_HTCAP_CHWIDTH40) == 0)
3131                 caps &= ~IEEE80211_HTCAP_SHORTGI40;
3132
3133         /* adjust STBC based on receive capabilities */
3134         if ((vap->iv_flags_ht & IEEE80211_FHT_STBC_RX) == 0)
3135                 caps &= ~IEEE80211_HTCAP_RXSTBC;
3136
3137         /* adjust LDPC based on receive capabilites */
3138         if ((vap->iv_flags_ht & IEEE80211_FHT_LDPC_RX) == 0)
3139                 caps &= ~IEEE80211_HTCAP_LDPC;
3140
3141         ADDSHORT(frm, caps);
3142
3143         /* HT parameters */
3144         *frm = SM(rxmax, IEEE80211_HTCAP_MAXRXAMPDU)
3145              | SM(density, IEEE80211_HTCAP_MPDUDENSITY)
3146              ;
3147         frm++;
3148
3149         /* pre-zero remainder of ie */
3150         memset(frm, 0, sizeof(struct ieee80211_ie_htcap) - 
3151                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset));
3152
3153         /* supported MCS set */
3154         /*
3155          * XXX: For sta mode the rate set should be restricted based
3156          * on the AP's capabilities, but ni_htrates isn't setup when
3157          * we're called to form an AssocReq frame so for now we're
3158          * restricted to the device capabilities.
3159          */
3160         ieee80211_set_mcsset(ni->ni_ic, frm);
3161
3162         frm += __offsetof(struct ieee80211_ie_htcap, hc_extcap) -
3163                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset);
3164
3165         /* HT extended capabilities */
3166         extcaps = vap->iv_htextcaps & 0xffff;
3167
3168         ADDSHORT(frm, extcaps);
3169
3170         frm += sizeof(struct ieee80211_ie_htcap) -
3171                 __offsetof(struct ieee80211_ie_htcap, hc_txbf);
3172
3173         return frm;
3174 #undef ADDSHORT
3175 }
3176
3177 /*
3178  * Add 802.11n HT capabilities information element
3179  */
3180 uint8_t *
3181 ieee80211_add_htcap(uint8_t *frm, struct ieee80211_node *ni)
3182 {
3183         frm[0] = IEEE80211_ELEMID_HTCAP;
3184         frm[1] = sizeof(struct ieee80211_ie_htcap) - 2;
3185         return ieee80211_add_htcap_body(frm + 2, ni);
3186 }
3187
3188 /*
3189  * Non-associated probe request - add HT capabilities based on
3190  * the current channel configuration.
3191  */
3192 static uint8_t *
3193 ieee80211_add_htcap_body_ch(uint8_t *frm, struct ieee80211vap *vap,
3194     struct ieee80211_channel *c)
3195 {
3196 #define ADDSHORT(frm, v) do {                   \
3197         frm[0] = (v) & 0xff;                    \
3198         frm[1] = (v) >> 8;                      \
3199         frm += 2;                               \
3200 } while (0)
3201         struct ieee80211com *ic = vap->iv_ic;
3202         uint16_t caps, extcaps;
3203         int rxmax, density;
3204
3205         /* HT capabilities */
3206         caps = vap->iv_htcaps & 0xffff;
3207
3208         /*
3209          * We don't use this in STA mode; only in IBSS mode.
3210          * So in IBSS mode we base our HTCAP flags on the
3211          * given channel.
3212          */
3213
3214         /* override 20/40 use based on current channel */
3215         if (IEEE80211_IS_CHAN_HT40(c))
3216                 caps |= IEEE80211_HTCAP_CHWIDTH40;
3217         else
3218                 caps &= ~IEEE80211_HTCAP_CHWIDTH40;
3219
3220         /* Use the currently configured values */
3221         rxmax = vap->iv_ampdu_rxmax;
3222         density = vap->iv_ampdu_density;
3223
3224         /* adjust short GI based on channel and config */
3225         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
3226                 caps &= ~IEEE80211_HTCAP_SHORTGI20;
3227         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0 ||
3228             (caps & IEEE80211_HTCAP_CHWIDTH40) == 0)
3229                 caps &= ~IEEE80211_HTCAP_SHORTGI40;
3230         ADDSHORT(frm, caps);
3231
3232         /* HT parameters */
3233         *frm = SM(rxmax, IEEE80211_HTCAP_MAXRXAMPDU)
3234              | SM(density, IEEE80211_HTCAP_MPDUDENSITY)
3235              ;
3236         frm++;
3237
3238         /* pre-zero remainder of ie */
3239         memset(frm, 0, sizeof(struct ieee80211_ie_htcap) - 
3240                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset));
3241
3242         /* supported MCS set */
3243         /*
3244          * XXX: For sta mode the rate set should be restricted based
3245          * on the AP's capabilities, but ni_htrates isn't setup when
3246          * we're called to form an AssocReq frame so for now we're
3247          * restricted to the device capabilities.
3248          */
3249         ieee80211_set_mcsset(ic, frm);
3250
3251         frm += __offsetof(struct ieee80211_ie_htcap, hc_extcap) -
3252                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset);
3253
3254         /* HT extended capabilities */
3255         extcaps = vap->iv_htextcaps & 0xffff;
3256
3257         ADDSHORT(frm, extcaps);
3258
3259         frm += sizeof(struct ieee80211_ie_htcap) -
3260                 __offsetof(struct ieee80211_ie_htcap, hc_txbf);
3261
3262         return frm;
3263 #undef ADDSHORT
3264 }
3265
3266 /*
3267  * Add 802.11n HT capabilities information element
3268  */
3269 uint8_t *
3270 ieee80211_add_htcap_ch(uint8_t *frm, struct ieee80211vap *vap,
3271     struct ieee80211_channel *c)
3272 {
3273         frm[0] = IEEE80211_ELEMID_HTCAP;
3274         frm[1] = sizeof(struct ieee80211_ie_htcap) - 2;
3275         return ieee80211_add_htcap_body_ch(frm + 2, vap, c);
3276 }
3277
3278 /*
3279  * Add Broadcom OUI wrapped standard HTCAP ie; this is
3280  * used for compatibility w/ pre-draft implementations.
3281  */
3282 uint8_t *
3283 ieee80211_add_htcap_vendor(uint8_t *frm, struct ieee80211_node *ni)
3284 {
3285         frm[0] = IEEE80211_ELEMID_VENDOR;
3286         frm[1] = 4 + sizeof(struct ieee80211_ie_htcap) - 2;
3287         frm[2] = (BCM_OUI >> 0) & 0xff;
3288         frm[3] = (BCM_OUI >> 8) & 0xff;
3289         frm[4] = (BCM_OUI >> 16) & 0xff;
3290         frm[5] = BCM_OUI_HTCAP;
3291         return ieee80211_add_htcap_body(frm + 6, ni);
3292 }
3293
3294 /*
3295  * Construct the MCS bit mask of basic rates
3296  * for inclusion in an HT information element.
3297  */
3298 static void
3299 ieee80211_set_basic_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
3300 {
3301         int i;
3302
3303         for (i = 0; i < rs->rs_nrates; i++) {
3304                 int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
3305                 if ((rs->rs_rates[i] & IEEE80211_RATE_BASIC) &&
3306                     r < IEEE80211_HTRATE_MAXSIZE) {
3307                         /* NB: this assumes a particular implementation */
3308                         setbit(frm, r);
3309                 }
3310         }
3311 }
3312
3313 /*
3314  * Update the HTINFO ie for a beacon frame.
3315  */
3316 void
3317 ieee80211_ht_update_beacon(struct ieee80211vap *vap,
3318         struct ieee80211_beacon_offsets *bo)
3319 {
3320 #define PROTMODE        (IEEE80211_HTINFO_OPMODE|IEEE80211_HTINFO_NONHT_PRESENT)
3321         struct ieee80211_node *ni;
3322         const struct ieee80211_channel *bsschan;
3323         struct ieee80211com *ic = vap->iv_ic;
3324         struct ieee80211_ie_htinfo *ht =
3325            (struct ieee80211_ie_htinfo *) bo->bo_htinfo;
3326
3327         ni = ieee80211_ref_node(vap->iv_bss);
3328         bsschan = ni->ni_chan;
3329
3330         /* XXX only update on channel change */
3331         ht->hi_ctrlchannel = ieee80211_chan2ieee(ic, bsschan);
3332         if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
3333                 ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PERM;
3334         else
3335                 ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PROH;
3336         if (IEEE80211_IS_CHAN_HT40U(bsschan))
3337                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
3338         else if (IEEE80211_IS_CHAN_HT40D(bsschan))
3339                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_BELOW;
3340         else
3341                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_NONE;
3342         if (IEEE80211_IS_CHAN_HT40(bsschan))
3343                 ht->hi_byte1 |= IEEE80211_HTINFO_TXWIDTH_2040;
3344
3345         /* protection mode */
3346         ht->hi_byte2 = (ht->hi_byte2 &~ PROTMODE) | ic->ic_curhtprotmode;
3347
3348         ieee80211_free_node(ni);
3349
3350         /* XXX propagate to vendor ie's */
3351 #undef PROTMODE
3352 }
3353
3354 /*
3355  * Add body of an HTINFO information element.
3356  *
3357  * NB: We don't use struct ieee80211_ie_htinfo because we can
3358  * be called to fillin both a standard ie and a compat ie that
3359  * has a vendor OUI at the front.
3360  */
3361 static uint8_t *
3362 ieee80211_add_htinfo_body(uint8_t *frm, struct ieee80211_node *ni)
3363 {
3364         struct ieee80211vap *vap = ni->ni_vap;
3365         struct ieee80211com *ic = ni->ni_ic;
3366
3367         /* pre-zero remainder of ie */
3368         memset(frm, 0, sizeof(struct ieee80211_ie_htinfo) - 2);
3369
3370         /* primary/control channel center */
3371         *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
3372
3373         if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
3374                 frm[0] = IEEE80211_HTINFO_RIFSMODE_PERM;
3375         else
3376                 frm[0] = IEEE80211_HTINFO_RIFSMODE_PROH;
3377         if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
3378                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
3379         else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
3380                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_BELOW;
3381         else
3382                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_NONE;
3383         if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
3384                 frm[0] |= IEEE80211_HTINFO_TXWIDTH_2040;
3385
3386         frm[1] = ic->ic_curhtprotmode;
3387
3388         frm += 5;
3389
3390         /* basic MCS set */
3391         ieee80211_set_basic_htrates(frm, &ni->ni_htrates);
3392         frm += sizeof(struct ieee80211_ie_htinfo) -
3393                 __offsetof(struct ieee80211_ie_htinfo, hi_basicmcsset);
3394         return frm;
3395 }
3396
3397 /*
3398  * Add 802.11n HT information element.
3399  */
3400 uint8_t *
3401 ieee80211_add_htinfo(uint8_t *frm, struct ieee80211_node *ni)
3402 {
3403         frm[0] = IEEE80211_ELEMID_HTINFO;
3404         frm[1] = sizeof(struct ieee80211_ie_htinfo) - 2;
3405         return ieee80211_add_htinfo_body(frm + 2, ni);
3406 }
3407
3408 /*
3409  * Add Broadcom OUI wrapped standard HTINFO ie; this is
3410  * used for compatibility w/ pre-draft implementations.
3411  */
3412 uint8_t *
3413 ieee80211_add_htinfo_vendor(uint8_t *frm, struct ieee80211_node *ni)
3414 {
3415         frm[0] = IEEE80211_ELEMID_VENDOR;
3416         frm[1] = 4 + sizeof(struct ieee80211_ie_htinfo) - 2;
3417         frm[2] = (BCM_OUI >> 0) & 0xff;
3418         frm[3] = (BCM_OUI >> 8) & 0xff;
3419         frm[4] = (BCM_OUI >> 16) & 0xff;
3420         frm[5] = BCM_OUI_HTINFO;
3421         return ieee80211_add_htinfo_body(frm + 6, ni);
3422 }