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