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