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