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