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