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