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