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