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