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