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