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, code;
1756 	int tid, ac;
1757 
1758 	baparamset = LE_READ_2(frm+2);
1759 	code = LE_READ_2(frm+4);
1760 
1761 	tid = MS(baparamset, IEEE80211_DELBAPS_TID);
1762 
1763 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1764 	    "recv DELBA: baparamset 0x%x (tid %d initiator %d) "
1765 	    "code %d", baparamset, tid,
1766 	    MS(baparamset, IEEE80211_DELBAPS_INIT), code);
1767 
1768 	if ((baparamset & IEEE80211_DELBAPS_INIT) == 0) {
1769 		ac = TID_TO_WME_AC(tid);
1770 		tap = &ni->ni_tx_ampdu[ac];
1771 		ic->ic_addba_stop(ni, tap);
1772 	} else {
1773 		rap = &ni->ni_rx_ampdu[tid];
1774 		ic->ic_ampdu_rx_stop(ni, rap);
1775 	}
1776 	return 0;
1777 }
1778 
1779 static int
1780 ht_recv_action_ht_txchwidth(struct ieee80211_node *ni,
1781 	const struct ieee80211_frame *wh,
1782 	const uint8_t *frm, const uint8_t *efrm)
1783 {
1784 	int chw;
1785 
1786 	chw = (frm[2] == IEEE80211_A_HT_TXCHWIDTH_2040) ? 40 : 20;
1787 
1788 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1789 	    "%s: HT txchwidth, width %d%s",
1790 	    __func__, chw, ni->ni_chw != chw ? "*" : "");
1791 	if (chw != ni->ni_chw) {
1792 		ni->ni_chw = chw;
1793 		/* XXX notify on change */
1794 	}
1795 	return 0;
1796 }
1797 
1798 static int
1799 ht_recv_action_ht_mimopwrsave(struct ieee80211_node *ni,
1800 	const struct ieee80211_frame *wh,
1801 	const uint8_t *frm, const uint8_t *efrm)
1802 {
1803 	const struct ieee80211_action_ht_mimopowersave *mps =
1804 	    (const struct ieee80211_action_ht_mimopowersave *) frm;
1805 
1806 	/* XXX check iv_htcaps */
1807 	if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_ENA)
1808 		ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1809 	else
1810 		ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
1811 	if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_MODE)
1812 		ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
1813 	else
1814 		ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1815 	/* XXX notify on change */
1816 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1817 	    "%s: HT MIMO PS (%s%s)", __func__,
1818 	    (ni->ni_flags & IEEE80211_NODE_MIMO_PS) ?  "on" : "off",
1819 	    (ni->ni_flags & IEEE80211_NODE_MIMO_RTS) ?  "+rts" : ""
1820 	);
1821 	return 0;
1822 }
1823 
1824 /*
1825  * Transmit processing.
1826  */
1827 
1828 /*
1829  * Check if A-MPDU should be requested/enabled for a stream.
1830  * We require a traffic rate above a per-AC threshold and we
1831  * also handle backoff from previous failed attempts.
1832  *
1833  * Drivers may override this method to bring in information
1834  * such as link state conditions in making the decision.
1835  */
1836 static int
1837 ieee80211_ampdu_enable(struct ieee80211_node *ni,
1838 	struct ieee80211_tx_ampdu *tap)
1839 {
1840 	struct ieee80211vap *vap = ni->ni_vap;
1841 
1842 	if (tap->txa_avgpps < vap->iv_ampdu_mintraffic[tap->txa_ac])
1843 		return 0;
1844 	/* XXX check rssi? */
1845 	if (tap->txa_attempts >= ieee80211_addba_maxtries &&
1846 	    ticks < tap->txa_nextrequest) {
1847 		/*
1848 		 * Don't retry too often; txa_nextrequest is set
1849 		 * to the minimum interval we'll retry after
1850 		 * ieee80211_addba_maxtries failed attempts are made.
1851 		 */
1852 		return 0;
1853 	}
1854 	IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1855 	    "enable AMPDU on %s, avgpps %d pkts %d",
1856 	    ieee80211_wme_acnames[tap->txa_ac], tap->txa_avgpps, tap->txa_pkts);
1857 	return 1;
1858 }
1859 
1860 /*
1861  * Request A-MPDU tx aggregation.  Setup local state and
1862  * issue an ADDBA request.  BA use will only happen after
1863  * the other end replies with ADDBA response.
1864  */
1865 int
1866 ieee80211_ampdu_request(struct ieee80211_node *ni,
1867 	struct ieee80211_tx_ampdu *tap)
1868 {
1869 	struct ieee80211com *ic = ni->ni_ic;
1870 	uint16_t args[4];
1871 	int tid, dialogtoken;
1872 	static int tokens = 0;	/* XXX */
1873 
1874 	/* XXX locking */
1875 	if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
1876 		/* do deferred setup of state */
1877 		ampdu_tx_setup(tap);
1878 	}
1879 	/* XXX hack for not doing proper locking */
1880 	tap->txa_flags &= ~IEEE80211_AGGR_NAK;
1881 
1882 	dialogtoken = (tokens+1) % 63;		/* XXX */
1883 	tid = WME_AC_TO_TID(tap->txa_ac);
1884 	tap->txa_start = ni->ni_txseqs[tid];
1885 
1886 	args[0] = dialogtoken;
1887 	args[1]	= IEEE80211_BAPS_POLICY_IMMEDIATE
1888 		| SM(tid, IEEE80211_BAPS_TID)
1889 		| SM(IEEE80211_AGGR_BAWMAX, IEEE80211_BAPS_BUFSIZ)
1890 		;
1891 	args[2] = 0;	/* batimeout */
1892 	/* NB: do first so there's no race against reply */
1893 	if (!ic->ic_addba_request(ni, tap, dialogtoken, args[1], args[2])) {
1894 		/* unable to setup state, don't make request */
1895 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1896 		    ni, "%s: could not setup BA stream for AC %d",
1897 		    __func__, tap->txa_ac);
1898 		/* defer next try so we don't slam the driver with requests */
1899 		tap->txa_attempts = ieee80211_addba_maxtries;
1900 		/* NB: check in case driver wants to override */
1901 		if (tap->txa_nextrequest <= ticks)
1902 			tap->txa_nextrequest = ticks + ieee80211_addba_backoff;
1903 		return 0;
1904 	}
1905 	tokens = dialogtoken;			/* allocate token */
1906 	/* NB: after calling ic_addba_request so driver can set txa_start */
1907 	args[3] = SM(tap->txa_start, IEEE80211_BASEQ_START)
1908 		| SM(0, IEEE80211_BASEQ_FRAG)
1909 		;
1910 	return ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
1911 		IEEE80211_ACTION_BA_ADDBA_REQUEST, args);
1912 }
1913 
1914 /*
1915  * Terminate an AMPDU tx stream.  State is reclaimed
1916  * and the peer notified with a DelBA Action frame.
1917  */
1918 void
1919 ieee80211_ampdu_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
1920 	int reason)
1921 {
1922 	struct ieee80211com *ic = ni->ni_ic;
1923 	struct ieee80211vap *vap = ni->ni_vap;
1924 	uint16_t args[4];
1925 
1926 	/* XXX locking */
1927 	tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
1928 	if (IEEE80211_AMPDU_RUNNING(tap)) {
1929 		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1930 		    ni, "%s: stop BA stream for AC %d (reason %d)",
1931 		    __func__, tap->txa_ac, reason);
1932 		vap->iv_stats.is_ampdu_stop++;
1933 
1934 		ic->ic_addba_stop(ni, tap);
1935 		args[0] = WME_AC_TO_TID(tap->txa_ac);
1936 		args[1] = IEEE80211_DELBAPS_INIT;
1937 		args[2] = reason;			/* XXX reason code */
1938 		ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
1939 			IEEE80211_ACTION_BA_DELBA, args);
1940 	} else {
1941 		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1942 		    ni, "%s: BA stream for AC %d not running (reason %d)",
1943 		    __func__, tap->txa_ac, reason);
1944 		vap->iv_stats.is_ampdu_stop_failed++;
1945 	}
1946 }
1947 
1948 static void
1949 bar_timeout_callout(void *arg)
1950 {
1951 	struct ieee80211_tx_ampdu *tap = arg;
1952 	struct ieee80211_node *ni;
1953 
1954 	wlan_serialize_enter();
1955 	ni = tap->txa_ni;
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) {
1965 		/* XXX ? */
1966 		if (tap->txa_attempts >= ieee80211_bar_maxtries)
1967 			ieee80211_ampdu_stop(ni, tap, IEEE80211_REASON_TIMEOUT);
1968 		else
1969 			ieee80211_send_bar(ni, tap, tap->txa_seqpending);
1970 	}
1971 	wlan_serialize_exit();
1972 }
1973 
1974 static void
1975 bar_start_timer(struct ieee80211_tx_ampdu *tap)
1976 {
1977 	callout_reset(&tap->txa_timer, ieee80211_bar_timeout,
1978 			bar_timeout_callout, tap);
1979 }
1980 
1981 static void
1982 bar_stop_timer(struct ieee80211_tx_ampdu *tap)
1983 {
1984 	callout_stop(&tap->txa_timer);
1985 }
1986 
1987 static void
1988 bar_tx_complete(struct ieee80211_node *ni, void *arg, int status)
1989 {
1990 	struct ieee80211_tx_ampdu *tap = arg;
1991 
1992 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1993 	    ni, "%s: tid %u flags 0x%x pending %d status %d",
1994 	    __func__, tap->txa_ac, tap->txa_flags,
1995 	    callout_pending(&tap->txa_timer), status);
1996 
1997 	/* XXX locking */
1998 	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) &&
1999 	    callout_pending(&tap->txa_timer)) {
2000 		struct ieee80211com *ic = ni->ni_ic;
2001 
2002 		if (status)		/* ACK'd */
2003 			bar_stop_timer(tap);
2004 		ic->ic_bar_response(ni, tap, status);
2005 		/* NB: just let timer expire so we pace requests */
2006 	}
2007 }
2008 
2009 static void
2010 ieee80211_bar_response(struct ieee80211_node *ni,
2011 	struct ieee80211_tx_ampdu *tap, int status)
2012 {
2013 
2014 	if (status != 0) {		/* got ACK */
2015 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2016 		    ni, "BAR moves BA win <%u:%u> (%u frames) txseq %u tid %u",
2017 		    tap->txa_start,
2018 		    IEEE80211_SEQ_ADD(tap->txa_start, tap->txa_wnd-1),
2019 		    tap->txa_qframes, tap->txa_seqpending,
2020 		    WME_AC_TO_TID(tap->txa_ac));
2021 
2022 		/* NB: timer already stopped in bar_tx_complete */
2023 		tap->txa_start = tap->txa_seqpending;
2024 		tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2025 	}
2026 }
2027 
2028 /*
2029  * Transmit a BAR frame to the specified node.  The
2030  * BAR contents are drawn from the supplied aggregation
2031  * state associated with the node.
2032  *
2033  * NB: we only handle immediate ACK w/ compressed bitmap.
2034  */
2035 int
2036 ieee80211_send_bar(struct ieee80211_node *ni,
2037 	struct ieee80211_tx_ampdu *tap, ieee80211_seq seq)
2038 {
2039 #define	senderr(_x, _v)	do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
2040 	struct ieee80211vap *vap = ni->ni_vap;
2041 	struct ieee80211com *ic = ni->ni_ic;
2042 	struct ieee80211_frame_bar *bar;
2043 	struct mbuf *m;
2044 	uint16_t barctl, barseqctl;
2045 	uint8_t *frm;
2046 	int tid, ret;
2047 
2048 	if ((tap->txa_flags & IEEE80211_AGGR_RUNNING) == 0) {
2049 		/* no ADDBA response, should not happen */
2050 		/* XXX stat+msg */
2051 		return EINVAL;
2052 	}
2053 	/* XXX locking */
2054 	bar_stop_timer(tap);
2055 
2056 	ieee80211_ref_node(ni);
2057 
2058 	m = ieee80211_getmgtframe(&frm, ic->ic_headroom, sizeof(*bar));
2059 	if (m == NULL)
2060 		senderr(ENOMEM, is_tx_nobuf);
2061 
2062 	if (!ieee80211_add_callback(m, bar_tx_complete, tap)) {
2063 		m_freem(m);
2064 		senderr(ENOMEM, is_tx_nobuf);	/* XXX */
2065 		/* NOTREACHED */
2066 	}
2067 
2068 	bar = mtod(m, struct ieee80211_frame_bar *);
2069 	bar->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2070 		IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR;
2071 	bar->i_fc[1] = 0;
2072 	IEEE80211_ADDR_COPY(bar->i_ra, ni->ni_macaddr);
2073 	IEEE80211_ADDR_COPY(bar->i_ta, vap->iv_myaddr);
2074 
2075 	tid = WME_AC_TO_TID(tap->txa_ac);
2076 	barctl 	= (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE ?
2077 			0 : IEEE80211_BAR_NOACK)
2078 		| IEEE80211_BAR_COMP
2079 		| SM(tid, IEEE80211_BAR_TID)
2080 		;
2081 	barseqctl = SM(seq, IEEE80211_BAR_SEQ_START);
2082 	/* NB: known to have proper alignment */
2083 	bar->i_ctl = htole16(barctl);
2084 	bar->i_seq = htole16(barseqctl);
2085 	m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_bar);
2086 
2087 	M_WME_SETAC(m, WME_AC_VO);
2088 
2089 	IEEE80211_NODE_STAT(ni, tx_mgmt);	/* XXX tx_ctl? */
2090 
2091 	/* XXX locking */
2092 	/* init/bump attempts counter */
2093 	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
2094 		tap->txa_attempts = 1;
2095 	else
2096 		tap->txa_attempts++;
2097 	tap->txa_seqpending = seq;
2098 	tap->txa_flags |= IEEE80211_AGGR_BARPEND;
2099 
2100 	IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
2101 	    ni, "send BAR: tid %u ctl 0x%x start %u (attempt %d)",
2102 	    tid, barctl, seq, tap->txa_attempts);
2103 
2104 	ret = ic->ic_raw_xmit(ni, m, NULL);
2105 	if (ret != 0) {
2106 		/* xmit failed, clear state flag */
2107 		tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2108 		goto bad;
2109 	}
2110 	/* XXX hack against tx complete happening before timer is started */
2111 	if (tap->txa_flags & IEEE80211_AGGR_BARPEND)
2112 		bar_start_timer(tap);
2113 	return 0;
2114 bad:
2115 	ieee80211_free_node(ni);
2116 	return ret;
2117 #undef senderr
2118 }
2119 
2120 static int
2121 ht_action_output(struct ieee80211_node *ni, struct mbuf *m)
2122 {
2123 	struct ieee80211_bpf_params params;
2124 
2125 	memset(&params, 0, sizeof(params));
2126 	params.ibp_pri = WME_AC_VO;
2127 	params.ibp_rate0 = ni->ni_txparms->mgmtrate;
2128 	/* NB: we know all frames are unicast */
2129 	params.ibp_try0 = ni->ni_txparms->maxretry;
2130 	params.ibp_power = ni->ni_txpower;
2131 	return ieee80211_mgmt_output(ni, m, IEEE80211_FC0_SUBTYPE_ACTION,
2132 	     &params);
2133 }
2134 
2135 #define	ADDSHORT(frm, v) do {			\
2136 	frm[0] = (v) & 0xff;			\
2137 	frm[1] = (v) >> 8;			\
2138 	frm += 2;				\
2139 } while (0)
2140 
2141 /*
2142  * Send an action management frame.  The arguments are stuff
2143  * into a frame without inspection; the caller is assumed to
2144  * prepare them carefully (e.g. based on the aggregation state).
2145  */
2146 static int
2147 ht_send_action_ba_addba(struct ieee80211_node *ni,
2148 	int category, int action, void *arg0)
2149 {
2150 	struct ieee80211vap *vap = ni->ni_vap;
2151 	struct ieee80211com *ic = ni->ni_ic;
2152 	uint16_t *args = arg0;
2153 	struct mbuf *m;
2154 	uint8_t *frm;
2155 #ifdef IEEE80211_DEBUG
2156 	char ethstr[ETHER_ADDRSTRLEN + 1];
2157 #endif
2158 
2159 	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2160 	    "send ADDBA %s: dialogtoken %d "
2161 	    "baparamset 0x%x (tid %d) batimeout 0x%x baseqctl 0x%x",
2162 	    (action == IEEE80211_ACTION_BA_ADDBA_REQUEST) ?
2163 		"request" : "response",
2164 	    args[0], args[1], MS(args[1], IEEE80211_BAPS_TID),
2165 	    args[2], args[3]);
2166 
2167 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2168 	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2169 	    ni, kether_ntoa(ni->ni_macaddr, ethstr), ieee80211_node_refcnt(ni)+1);
2170 	ieee80211_ref_node(ni);
2171 
2172 	m = ieee80211_getmgtframe(&frm,
2173 	    ic->ic_headroom + sizeof(struct ieee80211_frame),
2174 	    sizeof(uint16_t)	/* action+category */
2175 	    /* XXX may action payload */
2176 	    + sizeof(struct ieee80211_action_ba_addbaresponse)
2177 	);
2178 	if (m != NULL) {
2179 		*frm++ = category;
2180 		*frm++ = action;
2181 		*frm++ = args[0];		/* dialog token */
2182 		ADDSHORT(frm, args[1]);		/* baparamset */
2183 		ADDSHORT(frm, args[2]);		/* batimeout */
2184 		if (action == IEEE80211_ACTION_BA_ADDBA_REQUEST)
2185 			ADDSHORT(frm, args[3]);	/* baseqctl */
2186 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2187 		return ht_action_output(ni, m);
2188 	} else {
2189 		vap->iv_stats.is_tx_nobuf++;
2190 		ieee80211_free_node(ni);
2191 		return ENOMEM;
2192 	}
2193 }
2194 
2195 static int
2196 ht_send_action_ba_delba(struct ieee80211_node *ni,
2197 	int category, int action, void *arg0)
2198 {
2199 	struct ieee80211vap *vap = ni->ni_vap;
2200 	struct ieee80211com *ic = ni->ni_ic;
2201 	uint16_t *args = arg0;
2202 	struct mbuf *m;
2203 	uint16_t baparamset;
2204 	uint8_t *frm;
2205 #ifdef IEEE80211_DEBUG
2206 	char ethstr[ETHER_ADDRSTRLEN + 1];
2207 #endif
2208 
2209 	baparamset = SM(args[0], IEEE80211_DELBAPS_TID)
2210 		   | args[1]
2211 		   ;
2212 	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2213 	    "send DELBA action: tid %d, initiator %d reason %d",
2214 	    args[0], args[1], args[2]);
2215 
2216 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2217 	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2218 	    ni, kether_ntoa(ni->ni_macaddr, ethstr), ieee80211_node_refcnt(ni)+1);
2219 	ieee80211_ref_node(ni);
2220 
2221 	m = ieee80211_getmgtframe(&frm,
2222 	    ic->ic_headroom + sizeof(struct ieee80211_frame),
2223 	    sizeof(uint16_t)	/* action+category */
2224 	    /* XXX may action payload */
2225 	    + sizeof(struct ieee80211_action_ba_addbaresponse)
2226 	);
2227 	if (m != NULL) {
2228 		*frm++ = category;
2229 		*frm++ = action;
2230 		ADDSHORT(frm, baparamset);
2231 		ADDSHORT(frm, args[2]);		/* reason code */
2232 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2233 		return ht_action_output(ni, m);
2234 	} else {
2235 		vap->iv_stats.is_tx_nobuf++;
2236 		ieee80211_free_node(ni);
2237 		return ENOMEM;
2238 	}
2239 }
2240 
2241 static int
2242 ht_send_action_ht_txchwidth(struct ieee80211_node *ni,
2243 	int category, int action, void *arg0)
2244 {
2245 	struct ieee80211vap *vap = ni->ni_vap;
2246 	struct ieee80211com *ic = ni->ni_ic;
2247 	struct mbuf *m;
2248 	uint8_t *frm;
2249 #ifdef IEEE80211_DEBUG
2250 	char ethstr[ETHER_ADDRSTRLEN + 1];
2251 #endif
2252 
2253 	IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2254 	    "send HT txchwidth: width %d",
2255 	    IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 40 : 20);
2256 
2257 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2258 	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2259 	    ni, kether_ntoa(ni->ni_macaddr, ethstr), ieee80211_node_refcnt(ni)+1);
2260 	ieee80211_ref_node(ni);
2261 
2262 	m = ieee80211_getmgtframe(&frm,
2263 	    ic->ic_headroom + sizeof(struct ieee80211_frame),
2264 	    sizeof(uint16_t)	/* action+category */
2265 	    /* XXX may action payload */
2266 	    + sizeof(struct ieee80211_action_ba_addbaresponse)
2267 	);
2268 	if (m != NULL) {
2269 		*frm++ = category;
2270 		*frm++ = action;
2271 		*frm++ = IEEE80211_IS_CHAN_HT40(ni->ni_chan) ?
2272 			IEEE80211_A_HT_TXCHWIDTH_2040 :
2273 			IEEE80211_A_HT_TXCHWIDTH_20;
2274 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2275 		return ht_action_output(ni, m);
2276 	} else {
2277 		vap->iv_stats.is_tx_nobuf++;
2278 		ieee80211_free_node(ni);
2279 		return ENOMEM;
2280 	}
2281 }
2282 #undef ADDSHORT
2283 
2284 /*
2285  * Construct the MCS bit mask for inclusion
2286  * in an HT information element.
2287  */
2288 static void
2289 ieee80211_set_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
2290 {
2291 	int i;
2292 
2293 	for (i = 0; i < rs->rs_nrates; i++) {
2294 		int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2295 		if (r < IEEE80211_HTRATE_MAXSIZE) {	/* XXX? */
2296 			/* NB: this assumes a particular implementation */
2297 			setbit(frm, r);
2298 		}
2299 	}
2300 }
2301 
2302 /*
2303  * Add body of an HTCAP information element.
2304  */
2305 static uint8_t *
2306 ieee80211_add_htcap_body(uint8_t *frm, struct ieee80211_node *ni)
2307 {
2308 #define	ADDSHORT(frm, v) do {			\
2309 	frm[0] = (v) & 0xff;			\
2310 	frm[1] = (v) >> 8;			\
2311 	frm += 2;				\
2312 } while (0)
2313 	struct ieee80211vap *vap = ni->ni_vap;
2314 	uint16_t caps;
2315 	int rxmax, density;
2316 
2317 	/* HT capabilities */
2318 	caps = vap->iv_htcaps & 0xffff;
2319 	/*
2320 	 * Note channel width depends on whether we are operating as
2321 	 * a sta or not.  When operating as a sta we are generating
2322 	 * a request based on our desired configuration.  Otherwise
2323 	 * we are operational and the channel attributes identify
2324 	 * how we've been setup (which might be different if a fixed
2325 	 * channel is specified).
2326 	 */
2327 	if (vap->iv_opmode == IEEE80211_M_STA) {
2328 		/* override 20/40 use based on config */
2329 		if (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)
2330 			caps |= IEEE80211_HTCAP_CHWIDTH40;
2331 		else
2332 			caps &= ~IEEE80211_HTCAP_CHWIDTH40;
2333 		/* use advertised setting (XXX locally constraint) */
2334 		rxmax = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU);
2335 		density = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY);
2336 	} else {
2337 		/* override 20/40 use based on current channel */
2338 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
2339 			caps |= IEEE80211_HTCAP_CHWIDTH40;
2340 		else
2341 			caps &= ~IEEE80211_HTCAP_CHWIDTH40;
2342 		rxmax = vap->iv_ampdu_rxmax;
2343 		density = vap->iv_ampdu_density;
2344 	}
2345 	/* adjust short GI based on channel and config */
2346 	if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
2347 		caps &= ~IEEE80211_HTCAP_SHORTGI20;
2348 	if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0 ||
2349 	    (caps & IEEE80211_HTCAP_CHWIDTH40) == 0)
2350 		caps &= ~IEEE80211_HTCAP_SHORTGI40;
2351 	ADDSHORT(frm, caps);
2352 
2353 	/* HT parameters */
2354 	*frm = SM(rxmax, IEEE80211_HTCAP_MAXRXAMPDU)
2355 	     | SM(density, IEEE80211_HTCAP_MPDUDENSITY)
2356 	     ;
2357 	frm++;
2358 
2359 	/* pre-zero remainder of ie */
2360 	memset(frm, 0, sizeof(struct ieee80211_ie_htcap) -
2361 		__offsetof(struct ieee80211_ie_htcap, hc_mcsset));
2362 
2363 	/* supported MCS set */
2364 	/*
2365 	 * XXX it would better to get the rate set from ni_htrates
2366 	 * so we can restrict it but for sta mode ni_htrates isn't
2367 	 * setup when we're called to form an AssocReq frame so for
2368 	 * now we're restricted to the default HT rate set.
2369 	 */
2370 	ieee80211_set_htrates(frm, &ieee80211_rateset_11n);
2371 
2372 	frm += sizeof(struct ieee80211_ie_htcap) -
2373 		__offsetof(struct ieee80211_ie_htcap, hc_mcsset);
2374 	return frm;
2375 #undef ADDSHORT
2376 }
2377 
2378 /*
2379  * Add 802.11n HT capabilities information element
2380  */
2381 uint8_t *
2382 ieee80211_add_htcap(uint8_t *frm, struct ieee80211_node *ni)
2383 {
2384 	frm[0] = IEEE80211_ELEMID_HTCAP;
2385 	frm[1] = sizeof(struct ieee80211_ie_htcap) - 2;
2386 	return ieee80211_add_htcap_body(frm + 2, ni);
2387 }
2388 
2389 /*
2390  * Add Broadcom OUI wrapped standard HTCAP ie; this is
2391  * used for compatibility w/ pre-draft implementations.
2392  */
2393 uint8_t *
2394 ieee80211_add_htcap_vendor(uint8_t *frm, struct ieee80211_node *ni)
2395 {
2396 	frm[0] = IEEE80211_ELEMID_VENDOR;
2397 	frm[1] = 4 + sizeof(struct ieee80211_ie_htcap) - 2;
2398 	frm[2] = (BCM_OUI >> 0) & 0xff;
2399 	frm[3] = (BCM_OUI >> 8) & 0xff;
2400 	frm[4] = (BCM_OUI >> 16) & 0xff;
2401 	frm[5] = BCM_OUI_HTCAP;
2402 	return ieee80211_add_htcap_body(frm + 6, ni);
2403 }
2404 
2405 /*
2406  * Construct the MCS bit mask of basic rates
2407  * for inclusion in an HT information element.
2408  */
2409 static void
2410 ieee80211_set_basic_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
2411 {
2412 	int i;
2413 
2414 	for (i = 0; i < rs->rs_nrates; i++) {
2415 		int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2416 		if ((rs->rs_rates[i] & IEEE80211_RATE_BASIC) &&
2417 		    r < IEEE80211_HTRATE_MAXSIZE) {
2418 			/* NB: this assumes a particular implementation */
2419 			setbit(frm, r);
2420 		}
2421 	}
2422 }
2423 
2424 /*
2425  * Update the HTINFO ie for a beacon frame.
2426  */
2427 void
2428 ieee80211_ht_update_beacon(struct ieee80211vap *vap,
2429 	struct ieee80211_beacon_offsets *bo)
2430 {
2431 #define	PROTMODE	(IEEE80211_HTINFO_OPMODE|IEEE80211_HTINFO_NONHT_PRESENT)
2432 	const struct ieee80211_channel *bsschan = vap->iv_bss->ni_chan;
2433 	struct ieee80211com *ic = vap->iv_ic;
2434 	struct ieee80211_ie_htinfo *ht =
2435 	   (struct ieee80211_ie_htinfo *) bo->bo_htinfo;
2436 
2437 	/* XXX only update on channel change */
2438 	ht->hi_ctrlchannel = ieee80211_chan2ieee(ic, bsschan);
2439 	if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
2440 		ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PERM;
2441 	else
2442 		ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PROH;
2443 	if (IEEE80211_IS_CHAN_HT40U(bsschan))
2444 		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
2445 	else if (IEEE80211_IS_CHAN_HT40D(bsschan))
2446 		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_BELOW;
2447 	else
2448 		ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_NONE;
2449 	if (IEEE80211_IS_CHAN_HT40(bsschan))
2450 		ht->hi_byte1 |= IEEE80211_HTINFO_TXWIDTH_2040;
2451 
2452 	/* protection mode */
2453 	ht->hi_byte2 = (ht->hi_byte2 &~ PROTMODE) | ic->ic_curhtprotmode;
2454 
2455 	/* XXX propagate to vendor ie's */
2456 #undef PROTMODE
2457 }
2458 
2459 /*
2460  * Add body of an HTINFO information element.
2461  *
2462  * NB: We don't use struct ieee80211_ie_htinfo because we can
2463  * be called to fillin both a standard ie and a compat ie that
2464  * has a vendor OUI at the front.
2465  */
2466 static uint8_t *
2467 ieee80211_add_htinfo_body(uint8_t *frm, struct ieee80211_node *ni)
2468 {
2469 	struct ieee80211vap *vap = ni->ni_vap;
2470 	struct ieee80211com *ic = ni->ni_ic;
2471 
2472 	/* pre-zero remainder of ie */
2473 	memset(frm, 0, sizeof(struct ieee80211_ie_htinfo) - 2);
2474 
2475 	/* primary/control channel center */
2476 	*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
2477 
2478 	if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
2479 		frm[0] = IEEE80211_HTINFO_RIFSMODE_PERM;
2480 	else
2481 		frm[0] = IEEE80211_HTINFO_RIFSMODE_PROH;
2482 	if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
2483 		frm[0] |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
2484 	else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
2485 		frm[0] |= IEEE80211_HTINFO_2NDCHAN_BELOW;
2486 	else
2487 		frm[0] |= IEEE80211_HTINFO_2NDCHAN_NONE;
2488 	if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
2489 		frm[0] |= IEEE80211_HTINFO_TXWIDTH_2040;
2490 
2491 	frm[1] = ic->ic_curhtprotmode;
2492 
2493 	frm += 5;
2494 
2495 	/* basic MCS set */
2496 	ieee80211_set_basic_htrates(frm, &ni->ni_htrates);
2497 	frm += sizeof(struct ieee80211_ie_htinfo) -
2498 		__offsetof(struct ieee80211_ie_htinfo, hi_basicmcsset);
2499 	return frm;
2500 }
2501 
2502 /*
2503  * Add 802.11n HT information information element.
2504  */
2505 uint8_t *
2506 ieee80211_add_htinfo(uint8_t *frm, struct ieee80211_node *ni)
2507 {
2508 	frm[0] = IEEE80211_ELEMID_HTINFO;
2509 	frm[1] = sizeof(struct ieee80211_ie_htinfo) - 2;
2510 	return ieee80211_add_htinfo_body(frm + 2, ni);
2511 }
2512 
2513 /*
2514  * Add Broadcom OUI wrapped standard HTINFO ie; this is
2515  * used for compatibility w/ pre-draft implementations.
2516  */
2517 uint8_t *
2518 ieee80211_add_htinfo_vendor(uint8_t *frm, struct ieee80211_node *ni)
2519 {
2520 	frm[0] = IEEE80211_ELEMID_VENDOR;
2521 	frm[1] = 4 + sizeof(struct ieee80211_ie_htinfo) - 2;
2522 	frm[2] = (BCM_OUI >> 0) & 0xff;
2523 	frm[3] = (BCM_OUI >> 8) & 0xff;
2524 	frm[4] = (BCM_OUI >> 16) & 0xff;
2525 	frm[5] = BCM_OUI_HTINFO;
2526 	return ieee80211_add_htinfo_body(frm + 6, ni);
2527 }
2528