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