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