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