Second pass at converting the net80211 to DragonFly.
[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, M_NOWAIT);
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         IEEE80211_LOCK_ASSERT(ic);
1048
1049         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1050                 if (vap->iv_opmode != IEEE80211_M_HOSTAP)
1051                         continue;
1052                 if (vap->iv_state != IEEE80211_S_RUN ||
1053                     !IEEE80211_IS_CHAN_HT(vap->iv_bss->ni_chan))
1054                         continue;
1055                 if (first) {
1056                         IEEE80211_NOTE(vap,
1057                             IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N,
1058                             vap->iv_bss,
1059                             "HT bss occupancy change: %d sta, %d ht, "
1060                             "%d ht40%s, HT protmode now 0x%x"
1061                             , ic->ic_sta_assoc
1062                             , ic->ic_ht_sta_assoc
1063                             , ic->ic_ht40_sta_assoc
1064                             , (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) ?
1065                                  ", non-HT sta present" : ""
1066                             , ic->ic_curhtprotmode);
1067                         first = 0;
1068                 }
1069                 ieee80211_beacon_notify(vap, IEEE80211_BEACON_HTINFO);
1070         }
1071 }
1072
1073 /*
1074  * Calculate HT protection mode from current
1075  * state and handle updates.
1076  */
1077 static void
1078 htinfo_update(struct ieee80211com *ic)
1079 {
1080         uint8_t protmode;
1081
1082         if (ic->ic_sta_assoc != ic->ic_ht_sta_assoc) {
1083                 protmode = IEEE80211_HTINFO_OPMODE_MIXED
1084                          | IEEE80211_HTINFO_NONHT_PRESENT;
1085         } else if (ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) {
1086                 protmode = IEEE80211_HTINFO_OPMODE_PROTOPT
1087                          | IEEE80211_HTINFO_NONHT_PRESENT;
1088         } else if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
1089             IEEE80211_IS_CHAN_HT40(ic->ic_bsschan) && 
1090             ic->ic_sta_assoc != ic->ic_ht40_sta_assoc) {
1091                 protmode = IEEE80211_HTINFO_OPMODE_HT20PR;
1092         } else {
1093                 protmode = IEEE80211_HTINFO_OPMODE_PURE;
1094         }
1095         if (protmode != ic->ic_curhtprotmode) {
1096                 ic->ic_curhtprotmode = protmode;
1097                 htinfo_notify(ic);
1098         }
1099 }
1100
1101 /*
1102  * Handle an HT station joining a BSS.
1103  */
1104 void
1105 ieee80211_ht_node_join(struct ieee80211_node *ni)
1106 {
1107         struct ieee80211com *ic = ni->ni_ic;
1108
1109         IEEE80211_LOCK_ASSERT(ic);
1110
1111         if (ni->ni_flags & IEEE80211_NODE_HT) {
1112                 ic->ic_ht_sta_assoc++;
1113                 if (ni->ni_chw == 40)
1114                         ic->ic_ht40_sta_assoc++;
1115         }
1116         htinfo_update(ic);
1117 }
1118
1119 /*
1120  * Handle an HT station leaving a BSS.
1121  */
1122 void
1123 ieee80211_ht_node_leave(struct ieee80211_node *ni)
1124 {
1125         struct ieee80211com *ic = ni->ni_ic;
1126
1127         IEEE80211_LOCK_ASSERT(ic);
1128
1129         if (ni->ni_flags & IEEE80211_NODE_HT) {
1130                 ic->ic_ht_sta_assoc--;
1131                 if (ni->ni_chw == 40)
1132                         ic->ic_ht40_sta_assoc--;
1133         }
1134         htinfo_update(ic);
1135 }
1136
1137 /*
1138  * Public version of htinfo_update; used for processing
1139  * beacon frames from overlapping bss.
1140  *
1141  * Caller can specify either IEEE80211_HTINFO_OPMODE_MIXED
1142  * (on receipt of a beacon that advertises MIXED) or
1143  * IEEE80211_HTINFO_OPMODE_PROTOPT (on receipt of a beacon
1144  * from an overlapping legacy bss).  We treat MIXED with
1145  * a higher precedence than PROTOPT (i.e. we will not change
1146  * change PROTOPT -> MIXED; only MIXED -> PROTOPT).  This
1147  * corresponds to how we handle things in htinfo_update.
1148  */
1149 void
1150 ieee80211_htprot_update(struct ieee80211com *ic, int protmode)
1151 {
1152 #define OPMODE(x)       SM(x, IEEE80211_HTINFO_OPMODE)
1153         IEEE80211_LOCK(ic);
1154
1155         /* track non-HT station presence */
1156         KASSERT(protmode & IEEE80211_HTINFO_NONHT_PRESENT,
1157             ("protmode 0x%x", protmode));
1158         ic->ic_flags_ht |= IEEE80211_FHT_NONHT_PR;
1159         ic->ic_lastnonht = ticks;
1160
1161         if (protmode != ic->ic_curhtprotmode &&
1162             (OPMODE(ic->ic_curhtprotmode) != IEEE80211_HTINFO_OPMODE_MIXED ||
1163              OPMODE(protmode) == IEEE80211_HTINFO_OPMODE_PROTOPT)) {
1164                 /* push beacon update */
1165                 ic->ic_curhtprotmode = protmode;
1166                 htinfo_notify(ic);
1167         }
1168         IEEE80211_UNLOCK(ic);
1169 #undef OPMODE
1170 }
1171
1172 /*
1173  * Time out presence of an overlapping bss with non-HT
1174  * stations.  When operating in hostap mode we listen for
1175  * beacons from other stations and if we identify a non-HT
1176  * station is present we update the opmode field of the
1177  * HTINFO ie.  To identify when all non-HT stations are
1178  * gone we time out this condition.
1179  */
1180 void
1181 ieee80211_ht_timeout(struct ieee80211com *ic)
1182 {
1183         IEEE80211_LOCK_ASSERT(ic);
1184
1185         if ((ic->ic_flags_ht & IEEE80211_FHT_NONHT_PR) &&
1186             time_after(ticks, ic->ic_lastnonht + IEEE80211_NONHT_PRESENT_AGE)) {
1187 #if 0
1188                 IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1189                     "%s", "time out non-HT STA present on channel");
1190 #endif
1191                 ic->ic_flags_ht &= ~IEEE80211_FHT_NONHT_PR;
1192                 htinfo_update(ic);
1193         }
1194 }
1195
1196 /* unalligned little endian access */     
1197 #define LE_READ_2(p)                                    \
1198         ((uint16_t)                                     \
1199          ((((const uint8_t *)(p))[0]      ) |           \
1200           (((const uint8_t *)(p))[1] <<  8)))
1201
1202 /*
1203  * Process an 802.11n HT capabilities ie.
1204  */
1205 void
1206 ieee80211_parse_htcap(struct ieee80211_node *ni, const uint8_t *ie)
1207 {
1208         if (ie[0] == IEEE80211_ELEMID_VENDOR) {
1209                 /*
1210                  * Station used Vendor OUI ie to associate;
1211                  * mark the node so when we respond we'll use
1212                  * the Vendor OUI's and not the standard ie's.
1213                  */
1214                 ni->ni_flags |= IEEE80211_NODE_HTCOMPAT;
1215                 ie += 4;
1216         } else
1217                 ni->ni_flags &= ~IEEE80211_NODE_HTCOMPAT;
1218
1219         ni->ni_htcap = LE_READ_2(ie +
1220                 __offsetof(struct ieee80211_ie_htcap, hc_cap));
1221         ni->ni_htparam = ie[__offsetof(struct ieee80211_ie_htcap, hc_param)];
1222 }
1223
1224 static void
1225 htinfo_parse(struct ieee80211_node *ni,
1226         const struct ieee80211_ie_htinfo *htinfo)
1227 {
1228         uint16_t w;
1229
1230         ni->ni_htctlchan = htinfo->hi_ctrlchannel;
1231         ni->ni_ht2ndchan = SM(htinfo->hi_byte1, IEEE80211_HTINFO_2NDCHAN);
1232         w = LE_READ_2(&htinfo->hi_byte2);
1233         ni->ni_htopmode = SM(w, IEEE80211_HTINFO_OPMODE);
1234         w = LE_READ_2(&htinfo->hi_byte45);
1235         ni->ni_htstbc = SM(w, IEEE80211_HTINFO_BASIC_STBCMCS);
1236 }
1237
1238 /*
1239  * Parse an 802.11n HT info ie and save useful information
1240  * to the node state.  Note this does not effect any state
1241  * changes such as for channel width change.
1242  */
1243 void
1244 ieee80211_parse_htinfo(struct ieee80211_node *ni, const uint8_t *ie)
1245 {
1246         if (ie[0] == IEEE80211_ELEMID_VENDOR)
1247                 ie += 4;
1248         htinfo_parse(ni, (const struct ieee80211_ie_htinfo *) ie);
1249 }
1250
1251 /*
1252  * Handle 11n channel switch.  Use the received HT ie's to
1253  * identify the right channel to use.  If we cannot locate it
1254  * in the channel table then fallback to legacy operation.
1255  * Note that we use this information to identify the node's
1256  * channel only; the caller is responsible for insuring any
1257  * required channel change is done (e.g. in sta mode when
1258  * parsing the contents of a beacon frame).
1259  */
1260 static void
1261 htinfo_update_chw(struct ieee80211_node *ni, int htflags)
1262 {
1263         struct ieee80211com *ic = ni->ni_ic;
1264         struct ieee80211_channel *c;
1265         int chanflags;
1266
1267         chanflags = (ni->ni_chan->ic_flags &~ IEEE80211_CHAN_HT) | htflags;
1268         if (chanflags != ni->ni_chan->ic_flags) {
1269                 /* XXX not right for ht40- */
1270                 c = ieee80211_find_channel(ic, ni->ni_chan->ic_freq, chanflags);
1271                 if (c == NULL && (htflags & IEEE80211_CHAN_HT40)) {
1272                         /*
1273                          * No HT40 channel entry in our table; fall back
1274                          * to HT20 operation.  This should not happen.
1275                          */
1276                         c = findhtchan(ic, ni->ni_chan, IEEE80211_CHAN_HT20);
1277 #if 0
1278                         IEEE80211_NOTE(ni->ni_vap,
1279                             IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
1280                             "no HT40 channel (freq %u), falling back to HT20",
1281                             ni->ni_chan->ic_freq);
1282 #endif
1283                         /* XXX stat */
1284                 }
1285                 if (c != NULL && c != ni->ni_chan) {
1286                         IEEE80211_NOTE(ni->ni_vap,
1287                             IEEE80211_MSG_ASSOC | IEEE80211_MSG_11N, ni,
1288                             "switch station to HT%d channel %u/0x%x",
1289                             IEEE80211_IS_CHAN_HT40(c) ? 40 : 20,
1290                             c->ic_freq, c->ic_flags);
1291                         ni->ni_chan = c;
1292                 }
1293                 /* NB: caller responsible for forcing any channel change */
1294         }
1295         /* update node's tx channel width */
1296         ni->ni_chw = IEEE80211_IS_CHAN_HT40(ni->ni_chan)? 40 : 20;
1297 }
1298
1299 /*
1300  * Update 11n MIMO PS state according to received htcap.
1301  */
1302 static __inline int
1303 htcap_update_mimo_ps(struct ieee80211_node *ni)
1304 {
1305         uint16_t oflags = ni->ni_flags;
1306
1307         switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
1308         case IEEE80211_HTCAP_SMPS_DYNAMIC:
1309                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1310                 ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
1311                 break;
1312         case IEEE80211_HTCAP_SMPS_ENA:
1313                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1314                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1315                 break;
1316         case IEEE80211_HTCAP_SMPS_OFF:
1317         default:                /* disable on rx of reserved value */
1318                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
1319                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1320                 break;
1321         }
1322         return (oflags ^ ni->ni_flags);
1323 }
1324
1325 /*
1326  * Update short GI state according to received htcap
1327  * and local settings.
1328  */
1329 static __inline void
1330 htcap_update_shortgi(struct ieee80211_node *ni)
1331 {
1332         struct ieee80211vap *vap = ni->ni_vap;
1333
1334         ni->ni_flags &= ~(IEEE80211_NODE_SGI20|IEEE80211_NODE_SGI40);
1335         if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) &&
1336             (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20))
1337                 ni->ni_flags |= IEEE80211_NODE_SGI20;
1338         if ((ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40) &&
1339             (vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40))
1340                 ni->ni_flags |= IEEE80211_NODE_SGI40;
1341 }
1342
1343 /*
1344  * Parse and update HT-related state extracted from
1345  * the HT cap and info ie's.
1346  */
1347 void
1348 ieee80211_ht_updateparams(struct ieee80211_node *ni,
1349         const uint8_t *htcapie, const uint8_t *htinfoie)
1350 {
1351         struct ieee80211vap *vap = ni->ni_vap;
1352         const struct ieee80211_ie_htinfo *htinfo;
1353         int htflags;
1354
1355         ieee80211_parse_htcap(ni, htcapie);
1356         if (vap->iv_htcaps & IEEE80211_HTCAP_SMPS)
1357                 htcap_update_mimo_ps(ni);
1358         htcap_update_shortgi(ni);
1359
1360         if (htinfoie[0] == IEEE80211_ELEMID_VENDOR)
1361                 htinfoie += 4;
1362         htinfo = (const struct ieee80211_ie_htinfo *) htinfoie;
1363         htinfo_parse(ni, htinfo);
1364
1365         htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
1366             IEEE80211_CHAN_HT20 : 0;
1367         /* NB: honor operating mode constraint */
1368         if ((htinfo->hi_byte1 & IEEE80211_HTINFO_TXWIDTH_2040) &&
1369             (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
1370                 if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_ABOVE)
1371                         htflags = IEEE80211_CHAN_HT40U;
1372                 else if (ni->ni_ht2ndchan == IEEE80211_HTINFO_2NDCHAN_BELOW)
1373                         htflags = IEEE80211_CHAN_HT40D;
1374         }
1375         htinfo_update_chw(ni, htflags);
1376
1377         if ((htinfo->hi_byte1 & IEEE80211_HTINFO_RIFSMODE_PERM) &&
1378             (vap->iv_flags_ht & IEEE80211_FHT_RIFS))
1379                 ni->ni_flags |= IEEE80211_NODE_RIFS;
1380         else
1381                 ni->ni_flags &= ~IEEE80211_NODE_RIFS;
1382 }
1383
1384 /*
1385  * Parse and update HT-related state extracted from the HT cap ie
1386  * for a station joining an HT BSS.
1387  */
1388 void
1389 ieee80211_ht_updatehtcap(struct ieee80211_node *ni, const uint8_t *htcapie)
1390 {
1391         struct ieee80211vap *vap = ni->ni_vap;
1392         int htflags;
1393
1394         ieee80211_parse_htcap(ni, htcapie);
1395         if (vap->iv_htcaps & IEEE80211_HTCAP_SMPS)
1396                 htcap_update_mimo_ps(ni);
1397         htcap_update_shortgi(ni);
1398
1399         /* NB: honor operating mode constraint */
1400         /* XXX 40 MHZ intolerant */
1401         htflags = (vap->iv_flags_ht & IEEE80211_FHT_HT) ?
1402             IEEE80211_CHAN_HT20 : 0;
1403         if ((ni->ni_htcap & IEEE80211_HTCAP_CHWIDTH40) &&
1404             (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)) {
1405                 if (IEEE80211_IS_CHAN_HT40U(vap->iv_bss->ni_chan))
1406                         htflags = IEEE80211_CHAN_HT40U;
1407                 else if (IEEE80211_IS_CHAN_HT40D(vap->iv_bss->ni_chan))
1408                         htflags = IEEE80211_CHAN_HT40D;
1409         }
1410         htinfo_update_chw(ni, htflags);
1411 }
1412
1413 /*
1414  * Install received HT rate set by parsing the HT cap ie.
1415  */
1416 int
1417 ieee80211_setup_htrates(struct ieee80211_node *ni, const uint8_t *ie, int flags)
1418 {
1419         struct ieee80211vap *vap = ni->ni_vap;
1420         const struct ieee80211_ie_htcap *htcap;
1421         struct ieee80211_htrateset *rs;
1422         int i;
1423
1424         rs = &ni->ni_htrates;
1425         memset(rs, 0, sizeof(*rs));
1426         if (ie != NULL) {
1427                 if (ie[0] == IEEE80211_ELEMID_VENDOR)
1428                         ie += 4;
1429                 htcap = (const struct ieee80211_ie_htcap *) ie;
1430                 for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
1431                         if (isclr(htcap->hc_mcsset, i))
1432                                 continue;
1433                         if (rs->rs_nrates == IEEE80211_HTRATE_MAXSIZE) {
1434                                 IEEE80211_NOTE(vap,
1435                                     IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
1436                                     "WARNING, HT rate set too large; only "
1437                                     "using %u rates", IEEE80211_HTRATE_MAXSIZE);
1438                                 vap->iv_stats.is_rx_rstoobig++;
1439                                 break;
1440                         }
1441                         rs->rs_rates[rs->rs_nrates++] = i;
1442                 }
1443         }
1444         return ieee80211_fix_rate(ni, (struct ieee80211_rateset *) rs, flags);
1445 }
1446
1447 /*
1448  * Mark rates in a node's HT rate set as basic according
1449  * to the information in the supplied HT info ie.
1450  */
1451 void
1452 ieee80211_setup_basic_htrates(struct ieee80211_node *ni, const uint8_t *ie)
1453 {
1454         const struct ieee80211_ie_htinfo *htinfo;
1455         struct ieee80211_htrateset *rs;
1456         int i, j;
1457
1458         if (ie[0] == IEEE80211_ELEMID_VENDOR)
1459                 ie += 4;
1460         htinfo = (const struct ieee80211_ie_htinfo *) ie;
1461         rs = &ni->ni_htrates;
1462         if (rs->rs_nrates == 0) {
1463                 IEEE80211_NOTE(ni->ni_vap,
1464                     IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
1465                     "%s", "WARNING, empty HT rate set");
1466                 return;
1467         }
1468         for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++) {
1469                 if (isclr(htinfo->hi_basicmcsset, i))
1470                         continue;
1471                 for (j = 0; j < rs->rs_nrates; j++)
1472                         if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == i)
1473                                 rs->rs_rates[j] |= IEEE80211_RATE_BASIC;
1474         }
1475 }
1476
1477 static void
1478 ampdu_tx_setup(struct ieee80211_tx_ampdu *tap)
1479 {
1480         callout_init_mp(&tap->txa_timer);
1481         tap->txa_flags |= IEEE80211_AGGR_SETUP;
1482 }
1483
1484 static void
1485 ampdu_tx_stop(struct ieee80211_tx_ampdu *tap)
1486 {
1487         struct ieee80211_node *ni = tap->txa_ni;
1488         struct ieee80211com *ic = ni->ni_ic;
1489
1490         KASSERT(tap->txa_flags & IEEE80211_AGGR_SETUP,
1491             ("txa_flags 0x%x ac %d", tap->txa_flags, tap->txa_ac));
1492
1493         /*
1494          * Stop BA stream if setup so driver has a chance
1495          * to reclaim any resources it might have allocated.
1496          */
1497         ic->ic_addba_stop(ni, tap);
1498         /*
1499          * Stop any pending BAR transmit.
1500          */
1501         bar_stop_timer(tap);
1502
1503         tap->txa_lastsample = 0;
1504         tap->txa_avgpps = 0;
1505         /* NB: clearing NAK means we may re-send ADDBA */ 
1506         tap->txa_flags &= ~(IEEE80211_AGGR_SETUP | IEEE80211_AGGR_NAK);
1507 }
1508
1509 static void
1510 addba_timeout(void *arg)
1511 {
1512         struct ieee80211_tx_ampdu *tap = arg;
1513
1514         /* XXX ? */
1515         tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
1516         tap->txa_attempts++;
1517 }
1518
1519 static void
1520 addba_start_timeout(struct ieee80211_tx_ampdu *tap)
1521 {
1522         /* XXX use CALLOUT_PENDING instead? */
1523         callout_reset(&tap->txa_timer, ieee80211_addba_timeout,
1524             addba_timeout, tap);
1525         tap->txa_flags |= IEEE80211_AGGR_XCHGPEND;
1526         tap->txa_nextrequest = ticks + ieee80211_addba_timeout;
1527 }
1528
1529 static void
1530 addba_stop_timeout(struct ieee80211_tx_ampdu *tap)
1531 {
1532         /* XXX use CALLOUT_PENDING instead? */
1533         if (tap->txa_flags & IEEE80211_AGGR_XCHGPEND) {
1534                 callout_stop(&tap->txa_timer);
1535                 tap->txa_flags &= ~IEEE80211_AGGR_XCHGPEND;
1536         }
1537 }
1538
1539 /*
1540  * Default method for requesting A-MPDU tx aggregation.
1541  * We setup the specified state block and start a timer
1542  * to wait for an ADDBA response frame.
1543  */
1544 static int
1545 ieee80211_addba_request(struct ieee80211_node *ni,
1546         struct ieee80211_tx_ampdu *tap,
1547         int dialogtoken, int baparamset, int batimeout)
1548 {
1549         int bufsiz;
1550
1551         /* XXX locking */
1552         tap->txa_token = dialogtoken;
1553         tap->txa_flags |= IEEE80211_AGGR_IMMEDIATE;
1554         bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
1555         tap->txa_wnd = (bufsiz == 0) ?
1556             IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
1557         addba_start_timeout(tap);
1558         return 1;
1559 }
1560
1561 /*
1562  * Default method for processing an A-MPDU tx aggregation
1563  * response.  We shutdown any pending timer and update the
1564  * state block according to the reply.
1565  */
1566 static int
1567 ieee80211_addba_response(struct ieee80211_node *ni,
1568         struct ieee80211_tx_ampdu *tap,
1569         int status, int baparamset, int batimeout)
1570 {
1571         int bufsiz, tid;
1572
1573         /* XXX locking */
1574         addba_stop_timeout(tap);
1575         if (status == IEEE80211_STATUS_SUCCESS) {
1576                 bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
1577                 /* XXX override our request? */
1578                 tap->txa_wnd = (bufsiz == 0) ?
1579                     IEEE80211_AGGR_BAWMAX : min(bufsiz, IEEE80211_AGGR_BAWMAX);
1580                 /* XXX AC/TID */
1581                 tid = MS(baparamset, IEEE80211_BAPS_TID);
1582                 tap->txa_flags |= IEEE80211_AGGR_RUNNING;
1583                 tap->txa_attempts = 0;
1584         } else {
1585                 /* mark tid so we don't try again */
1586                 tap->txa_flags |= IEEE80211_AGGR_NAK;
1587         }
1588         return 1;
1589 }
1590
1591 /*
1592  * Default method for stopping A-MPDU tx aggregation.
1593  * Any timer is cleared and we drain any pending frames.
1594  */
1595 static void
1596 ieee80211_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
1597 {
1598         /* XXX locking */
1599         addba_stop_timeout(tap);
1600         if (tap->txa_flags & IEEE80211_AGGR_RUNNING) {
1601                 /* XXX clear aggregation queue */
1602                 tap->txa_flags &= ~IEEE80211_AGGR_RUNNING;
1603         }
1604         tap->txa_attempts = 0;
1605 }
1606
1607 /*
1608  * Process a received action frame using the default aggregation
1609  * policy.  We intercept ADDBA-related frames and use them to
1610  * update our aggregation state.  All other frames are passed up
1611  * for processing by ieee80211_recv_action.
1612  */
1613 static int
1614 ht_recv_action_ba_addba_request(struct ieee80211_node *ni,
1615         const struct ieee80211_frame *wh,
1616         const uint8_t *frm, const uint8_t *efrm)
1617 {
1618         struct ieee80211com *ic = ni->ni_ic;
1619         struct ieee80211vap *vap = ni->ni_vap;
1620         struct ieee80211_rx_ampdu *rap;
1621         uint8_t dialogtoken;
1622         uint16_t baparamset, batimeout, baseqctl;
1623         uint16_t args[4];
1624         int tid;
1625
1626         dialogtoken = frm[2];
1627         baparamset = LE_READ_2(frm+3);
1628         batimeout = LE_READ_2(frm+5);
1629         baseqctl = LE_READ_2(frm+7);
1630
1631         tid = MS(baparamset, IEEE80211_BAPS_TID);
1632
1633         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1634             "recv ADDBA request: dialogtoken %u baparamset 0x%x "
1635             "(tid %d bufsiz %d) batimeout %d baseqctl %d:%d",
1636             dialogtoken, baparamset,
1637             tid, MS(baparamset, IEEE80211_BAPS_BUFSIZ),
1638             batimeout,
1639             MS(baseqctl, IEEE80211_BASEQ_START),
1640             MS(baseqctl, IEEE80211_BASEQ_FRAG));
1641
1642         rap = &ni->ni_rx_ampdu[tid];
1643
1644         /* Send ADDBA response */
1645         args[0] = dialogtoken;
1646         /*
1647          * NB: We ack only if the sta associated with HT and
1648          * the ap is configured to do AMPDU rx (the latter
1649          * violates the 11n spec and is mostly for testing).
1650          */
1651         if ((ni->ni_flags & IEEE80211_NODE_AMPDU_RX) &&
1652             (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_RX)) {
1653                 /* XXX handle ampdu_rx_start failure */
1654                 ic->ic_ampdu_rx_start(ni, rap,
1655                     baparamset, batimeout, baseqctl);
1656
1657                 args[1] = IEEE80211_STATUS_SUCCESS;
1658         } else {
1659                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1660                     ni, "reject ADDBA request: %s",
1661                     ni->ni_flags & IEEE80211_NODE_AMPDU_RX ?
1662                        "administratively disabled" :
1663                        "not negotiated for station");
1664                 vap->iv_stats.is_addba_reject++;
1665                 args[1] = IEEE80211_STATUS_UNSPECIFIED;
1666         }
1667         /* XXX honor rap flags? */
1668         args[2] = IEEE80211_BAPS_POLICY_IMMEDIATE
1669                 | SM(tid, IEEE80211_BAPS_TID)
1670                 | SM(rap->rxa_wnd, IEEE80211_BAPS_BUFSIZ)
1671                 ;
1672         args[3] = 0;
1673         ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
1674                 IEEE80211_ACTION_BA_ADDBA_RESPONSE, args);
1675         return 0;
1676 }
1677
1678 static int
1679 ht_recv_action_ba_addba_response(struct ieee80211_node *ni,
1680         const struct ieee80211_frame *wh,
1681         const uint8_t *frm, const uint8_t *efrm)
1682 {
1683         struct ieee80211com *ic = ni->ni_ic;
1684         struct ieee80211vap *vap = ni->ni_vap;
1685         struct ieee80211_tx_ampdu *tap;
1686         uint8_t dialogtoken, policy;
1687         uint16_t baparamset, batimeout, code;
1688         int tid, ac, bufsiz;
1689
1690         dialogtoken = frm[2];
1691         code = LE_READ_2(frm+3);
1692         baparamset = LE_READ_2(frm+5);
1693         tid = MS(baparamset, IEEE80211_BAPS_TID);
1694         bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
1695         policy = MS(baparamset, IEEE80211_BAPS_POLICY);
1696         batimeout = LE_READ_2(frm+7);
1697
1698         ac = TID_TO_WME_AC(tid);
1699         tap = &ni->ni_tx_ampdu[ac];
1700         if ((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0) {
1701                 IEEE80211_DISCARD_MAC(vap,
1702                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1703                     ni->ni_macaddr, "ADDBA response",
1704                     "no pending ADDBA, tid %d dialogtoken %u "
1705                     "code %d", tid, dialogtoken, code);
1706                 vap->iv_stats.is_addba_norequest++;
1707                 return 0;
1708         }
1709         if (dialogtoken != tap->txa_token) {
1710                 IEEE80211_DISCARD_MAC(vap,
1711                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1712                     ni->ni_macaddr, "ADDBA response",
1713                     "dialogtoken mismatch: waiting for %d, "
1714                     "received %d, tid %d code %d",
1715                     tap->txa_token, dialogtoken, tid, code);
1716                 vap->iv_stats.is_addba_badtoken++;
1717                 return 0;
1718         }
1719         /* NB: assumes IEEE80211_AGGR_IMMEDIATE is 1 */
1720         if (policy != (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE)) {
1721                 IEEE80211_DISCARD_MAC(vap,
1722                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1723                     ni->ni_macaddr, "ADDBA response",
1724                     "policy mismatch: expecting %s, "
1725                     "received %s, tid %d code %d",
1726                     tap->txa_flags & IEEE80211_AGGR_IMMEDIATE,
1727                     policy, tid, code);
1728                 vap->iv_stats.is_addba_badpolicy++;
1729                 return 0;
1730         }
1731 #if 0
1732         /* XXX we take MIN in ieee80211_addba_response */
1733         if (bufsiz > IEEE80211_AGGR_BAWMAX) {
1734                 IEEE80211_DISCARD_MAC(vap,
1735                     IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1736                     ni->ni_macaddr, "ADDBA response",
1737                     "BA window too large: max %d, "
1738                     "received %d, tid %d code %d",
1739                     bufsiz, IEEE80211_AGGR_BAWMAX, tid, code);
1740                 vap->iv_stats.is_addba_badbawinsize++;
1741                 return 0;
1742         }
1743 #endif
1744         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1745             "recv ADDBA response: dialogtoken %u code %d "
1746             "baparamset 0x%x (tid %d bufsiz %d) batimeout %d",
1747             dialogtoken, code, baparamset, tid, bufsiz,
1748             batimeout);
1749         ic->ic_addba_response(ni, tap, code, baparamset, batimeout);
1750         return 0;
1751 }
1752
1753 static int
1754 ht_recv_action_ba_delba(struct ieee80211_node *ni,
1755         const struct ieee80211_frame *wh,
1756         const uint8_t *frm, const uint8_t *efrm)
1757 {
1758         struct ieee80211com *ic = ni->ni_ic;
1759         struct ieee80211_rx_ampdu *rap;
1760         struct ieee80211_tx_ampdu *tap;
1761         uint16_t baparamset, code;
1762         int tid, ac;
1763
1764         baparamset = LE_READ_2(frm+2);
1765         code = LE_READ_2(frm+4);
1766
1767         tid = MS(baparamset, IEEE80211_DELBAPS_TID);
1768
1769         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1770             "recv DELBA: baparamset 0x%x (tid %d initiator %d) "
1771             "code %d", baparamset, tid,
1772             MS(baparamset, IEEE80211_DELBAPS_INIT), code);
1773
1774         if ((baparamset & IEEE80211_DELBAPS_INIT) == 0) {
1775                 ac = TID_TO_WME_AC(tid);
1776                 tap = &ni->ni_tx_ampdu[ac];
1777                 ic->ic_addba_stop(ni, tap);
1778         } else {
1779                 rap = &ni->ni_rx_ampdu[tid];
1780                 ic->ic_ampdu_rx_stop(ni, rap);
1781         }
1782         return 0;
1783 }
1784
1785 static int
1786 ht_recv_action_ht_txchwidth(struct ieee80211_node *ni,
1787         const struct ieee80211_frame *wh,
1788         const uint8_t *frm, const uint8_t *efrm)
1789 {
1790         int chw;
1791
1792         chw = (frm[2] == IEEE80211_A_HT_TXCHWIDTH_2040) ? 40 : 20;
1793
1794         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1795             "%s: HT txchwidth, width %d%s",
1796             __func__, chw, ni->ni_chw != chw ? "*" : "");
1797         if (chw != ni->ni_chw) {
1798                 ni->ni_chw = chw;
1799                 /* XXX notify on change */
1800         }
1801         return 0;
1802 }
1803
1804 static int
1805 ht_recv_action_ht_mimopwrsave(struct ieee80211_node *ni,
1806         const struct ieee80211_frame *wh,
1807         const uint8_t *frm, const uint8_t *efrm)
1808 {
1809         const struct ieee80211_action_ht_mimopowersave *mps =
1810             (const struct ieee80211_action_ht_mimopowersave *) frm;
1811
1812         /* XXX check iv_htcaps */
1813         if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_ENA)
1814                 ni->ni_flags |= IEEE80211_NODE_MIMO_PS;
1815         else
1816                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_PS;
1817         if (mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_MODE)
1818                 ni->ni_flags |= IEEE80211_NODE_MIMO_RTS;
1819         else
1820                 ni->ni_flags &= ~IEEE80211_NODE_MIMO_RTS;
1821         /* XXX notify on change */
1822         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
1823             "%s: HT MIMO PS (%s%s)", __func__,
1824             (ni->ni_flags & IEEE80211_NODE_MIMO_PS) ?  "on" : "off",
1825             (ni->ni_flags & IEEE80211_NODE_MIMO_RTS) ?  "+rts" : ""
1826         );
1827         return 0;
1828 }
1829
1830 /*
1831  * Transmit processing.
1832  */
1833
1834 /*
1835  * Check if A-MPDU should be requested/enabled for a stream.
1836  * We require a traffic rate above a per-AC threshold and we
1837  * also handle backoff from previous failed attempts.
1838  *
1839  * Drivers may override this method to bring in information
1840  * such as link state conditions in making the decision.
1841  */
1842 static int
1843 ieee80211_ampdu_enable(struct ieee80211_node *ni,
1844         struct ieee80211_tx_ampdu *tap)
1845 {
1846         struct ieee80211vap *vap = ni->ni_vap;
1847
1848         if (tap->txa_avgpps < vap->iv_ampdu_mintraffic[tap->txa_ac])
1849                 return 0;
1850         /* XXX check rssi? */
1851         if (tap->txa_attempts >= ieee80211_addba_maxtries &&
1852             ticks < tap->txa_nextrequest) {
1853                 /*
1854                  * Don't retry too often; txa_nextrequest is set
1855                  * to the minimum interval we'll retry after
1856                  * ieee80211_addba_maxtries failed attempts are made.
1857                  */
1858                 return 0;
1859         }
1860         IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
1861             "enable AMPDU on %s, avgpps %d pkts %d",
1862             ieee80211_wme_acnames[tap->txa_ac], tap->txa_avgpps, tap->txa_pkts);
1863         return 1;
1864 }
1865
1866 /*
1867  * Request A-MPDU tx aggregation.  Setup local state and
1868  * issue an ADDBA request.  BA use will only happen after
1869  * the other end replies with ADDBA response.
1870  */
1871 int
1872 ieee80211_ampdu_request(struct ieee80211_node *ni,
1873         struct ieee80211_tx_ampdu *tap)
1874 {
1875         struct ieee80211com *ic = ni->ni_ic;
1876         uint16_t args[4];
1877         int tid, dialogtoken;
1878         static int tokens = 0;  /* XXX */
1879
1880         /* XXX locking */
1881         if ((tap->txa_flags & IEEE80211_AGGR_SETUP) == 0) {
1882                 /* do deferred setup of state */
1883                 ampdu_tx_setup(tap);
1884         }
1885         /* XXX hack for not doing proper locking */
1886         tap->txa_flags &= ~IEEE80211_AGGR_NAK;
1887
1888         dialogtoken = (tokens+1) % 63;          /* XXX */
1889         tid = WME_AC_TO_TID(tap->txa_ac);
1890         tap->txa_start = ni->ni_txseqs[tid];
1891
1892         args[0] = dialogtoken;
1893         args[1] = IEEE80211_BAPS_POLICY_IMMEDIATE
1894                 | SM(tid, IEEE80211_BAPS_TID)
1895                 | SM(IEEE80211_AGGR_BAWMAX, IEEE80211_BAPS_BUFSIZ)
1896                 ;
1897         args[2] = 0;    /* batimeout */
1898         /* NB: do first so there's no race against reply */
1899         if (!ic->ic_addba_request(ni, tap, dialogtoken, args[1], args[2])) {
1900                 /* unable to setup state, don't make request */
1901                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1902                     ni, "%s: could not setup BA stream for AC %d",
1903                     __func__, tap->txa_ac);
1904                 /* defer next try so we don't slam the driver with requests */
1905                 tap->txa_attempts = ieee80211_addba_maxtries;
1906                 /* NB: check in case driver wants to override */
1907                 if (tap->txa_nextrequest <= ticks)
1908                         tap->txa_nextrequest = ticks + ieee80211_addba_backoff;
1909                 return 0;
1910         }
1911         tokens = dialogtoken;                   /* allocate token */
1912         /* NB: after calling ic_addba_request so driver can set txa_start */
1913         args[3] = SM(tap->txa_start, IEEE80211_BASEQ_START)
1914                 | SM(0, IEEE80211_BASEQ_FRAG)
1915                 ;
1916         return ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
1917                 IEEE80211_ACTION_BA_ADDBA_REQUEST, args);
1918 }
1919
1920 /*
1921  * Terminate an AMPDU tx stream.  State is reclaimed
1922  * and the peer notified with a DelBA Action frame.
1923  */
1924 void
1925 ieee80211_ampdu_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
1926         int reason)
1927 {
1928         struct ieee80211com *ic = ni->ni_ic;
1929         struct ieee80211vap *vap = ni->ni_vap;
1930         uint16_t args[4];
1931
1932         /* XXX locking */
1933         tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
1934         if (IEEE80211_AMPDU_RUNNING(tap)) {
1935                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1936                     ni, "%s: stop BA stream for AC %d (reason %d)",
1937                     __func__, tap->txa_ac, reason);
1938                 vap->iv_stats.is_ampdu_stop++;
1939
1940                 ic->ic_addba_stop(ni, tap);
1941                 args[0] = WME_AC_TO_TID(tap->txa_ac);
1942                 args[1] = IEEE80211_DELBAPS_INIT;
1943                 args[2] = reason;                       /* XXX reason code */
1944                 ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
1945                         IEEE80211_ACTION_BA_DELBA, args);
1946         } else {
1947                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
1948                     ni, "%s: BA stream for AC %d not running (reason %d)",
1949                     __func__, tap->txa_ac, reason);
1950                 vap->iv_stats.is_ampdu_stop_failed++;
1951         }
1952 }
1953
1954 static void
1955 bar_timeout(void *arg)
1956 {
1957         struct ieee80211_tx_ampdu *tap = arg;
1958         struct ieee80211_node *ni = tap->txa_ni;
1959
1960         KASSERT((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) == 0,
1961             ("bar/addba collision, flags 0x%x", tap->txa_flags));
1962
1963         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1964             ni, "%s: tid %u flags 0x%x attempts %d", __func__,
1965             tap->txa_ac, tap->txa_flags, tap->txa_attempts);
1966
1967         /* guard against race with bar_tx_complete */
1968         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
1969                 return;
1970         /* XXX ? */
1971         if (tap->txa_attempts >= ieee80211_bar_maxtries)
1972                 ieee80211_ampdu_stop(ni, tap, IEEE80211_REASON_TIMEOUT);
1973         else
1974                 ieee80211_send_bar(ni, tap, tap->txa_seqpending);
1975 }
1976
1977 static void
1978 bar_start_timer(struct ieee80211_tx_ampdu *tap)
1979 {
1980         callout_reset(&tap->txa_timer, ieee80211_bar_timeout, bar_timeout, tap);
1981 }
1982
1983 static void
1984 bar_stop_timer(struct ieee80211_tx_ampdu *tap)
1985 {
1986         callout_stop(&tap->txa_timer);
1987 }
1988
1989 static void
1990 bar_tx_complete(struct ieee80211_node *ni, void *arg, int status)
1991 {
1992         struct ieee80211_tx_ampdu *tap = arg;
1993
1994         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
1995             ni, "%s: tid %u flags 0x%x pending %d status %d",
1996             __func__, tap->txa_ac, tap->txa_flags,
1997             callout_pending(&tap->txa_timer), status);
1998
1999         /* XXX locking */
2000         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) &&
2001             callout_pending(&tap->txa_timer)) {
2002                 struct ieee80211com *ic = ni->ni_ic;
2003
2004                 if (status)             /* ACK'd */
2005                         bar_stop_timer(tap);
2006                 ic->ic_bar_response(ni, tap, status);
2007                 /* NB: just let timer expire so we pace requests */
2008         }
2009 }
2010
2011 static void
2012 ieee80211_bar_response(struct ieee80211_node *ni,
2013         struct ieee80211_tx_ampdu *tap, int status)
2014 {
2015
2016         if (status != 0) {              /* got ACK */
2017                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
2018                     ni, "BAR moves BA win <%u:%u> (%u frames) txseq %u tid %u",
2019                     tap->txa_start,
2020                     IEEE80211_SEQ_ADD(tap->txa_start, tap->txa_wnd-1),
2021                     tap->txa_qframes, tap->txa_seqpending,
2022                     WME_AC_TO_TID(tap->txa_ac));
2023
2024                 /* NB: timer already stopped in bar_tx_complete */
2025                 tap->txa_start = tap->txa_seqpending;
2026                 tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2027         }
2028 }
2029
2030 /*
2031  * Transmit a BAR frame to the specified node.  The
2032  * BAR contents are drawn from the supplied aggregation
2033  * state associated with the node.
2034  *
2035  * NB: we only handle immediate ACK w/ compressed bitmap.
2036  */
2037 int
2038 ieee80211_send_bar(struct ieee80211_node *ni,
2039         struct ieee80211_tx_ampdu *tap, ieee80211_seq seq)
2040 {
2041 #define senderr(_x, _v) do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
2042         struct ieee80211vap *vap = ni->ni_vap;
2043         struct ieee80211com *ic = ni->ni_ic;
2044         struct ieee80211_frame_bar *bar;
2045         struct mbuf *m;
2046         uint16_t barctl, barseqctl;
2047         uint8_t *frm;
2048         int tid, ret;
2049
2050         if ((tap->txa_flags & IEEE80211_AGGR_RUNNING) == 0) {
2051                 /* no ADDBA response, should not happen */
2052                 /* XXX stat+msg */
2053                 return EINVAL;
2054         }
2055         /* XXX locking */
2056         bar_stop_timer(tap);
2057
2058         ieee80211_ref_node(ni);
2059
2060         m = ieee80211_getmgtframe(&frm, ic->ic_headroom, sizeof(*bar));
2061         if (m == NULL)
2062                 senderr(ENOMEM, is_tx_nobuf);
2063
2064         if (!ieee80211_add_callback(m, bar_tx_complete, tap)) {
2065                 m_freem(m);
2066                 senderr(ENOMEM, is_tx_nobuf);   /* XXX */
2067                 /* NOTREACHED */
2068         }
2069
2070         bar = mtod(m, struct ieee80211_frame_bar *);
2071         bar->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2072                 IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR;
2073         bar->i_fc[1] = 0;
2074         IEEE80211_ADDR_COPY(bar->i_ra, ni->ni_macaddr);
2075         IEEE80211_ADDR_COPY(bar->i_ta, vap->iv_myaddr);
2076
2077         tid = WME_AC_TO_TID(tap->txa_ac);
2078         barctl  = (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE ?
2079                         0 : IEEE80211_BAR_NOACK)
2080                 | IEEE80211_BAR_COMP
2081                 | SM(tid, IEEE80211_BAR_TID)
2082                 ;
2083         barseqctl = SM(seq, IEEE80211_BAR_SEQ_START);
2084         /* NB: known to have proper alignment */
2085         bar->i_ctl = htole16(barctl);
2086         bar->i_seq = htole16(barseqctl);
2087         m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_bar);
2088
2089         M_WME_SETAC(m, WME_AC_VO);
2090
2091         IEEE80211_NODE_STAT(ni, tx_mgmt);       /* XXX tx_ctl? */
2092
2093         /* XXX locking */
2094         /* init/bump attempts counter */
2095         if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) == 0)
2096                 tap->txa_attempts = 1;
2097         else
2098                 tap->txa_attempts++;
2099         tap->txa_seqpending = seq;
2100         tap->txa_flags |= IEEE80211_AGGR_BARPEND;
2101
2102         IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_11N,
2103             ni, "send BAR: tid %u ctl 0x%x start %u (attempt %d)",
2104             tid, barctl, seq, tap->txa_attempts);
2105
2106         ret = ic->ic_raw_xmit(ni, m, NULL);
2107         if (ret != 0) {
2108                 /* xmit failed, clear state flag */
2109                 tap->txa_flags &= ~IEEE80211_AGGR_BARPEND;
2110                 goto bad;
2111         }
2112         /* XXX hack against tx complete happening before timer is started */
2113         if (tap->txa_flags & IEEE80211_AGGR_BARPEND)
2114                 bar_start_timer(tap);
2115         return 0;
2116 bad:
2117         ieee80211_free_node(ni);
2118         return ret;
2119 #undef senderr
2120 }
2121
2122 static int
2123 ht_action_output(struct ieee80211_node *ni, struct mbuf *m)
2124 {
2125         struct ieee80211_bpf_params params;
2126
2127         memset(&params, 0, sizeof(params));
2128         params.ibp_pri = WME_AC_VO;
2129         params.ibp_rate0 = ni->ni_txparms->mgmtrate;
2130         /* NB: we know all frames are unicast */
2131         params.ibp_try0 = ni->ni_txparms->maxretry;
2132         params.ibp_power = ni->ni_txpower;
2133         return ieee80211_mgmt_output(ni, m, IEEE80211_FC0_SUBTYPE_ACTION,
2134              &params);
2135 }
2136
2137 #define ADDSHORT(frm, v) do {                   \
2138         frm[0] = (v) & 0xff;                    \
2139         frm[1] = (v) >> 8;                      \
2140         frm += 2;                               \
2141 } while (0)
2142
2143 /*
2144  * Send an action management frame.  The arguments are stuff
2145  * into a frame without inspection; the caller is assumed to
2146  * prepare them carefully (e.g. based on the aggregation state).
2147  */
2148 static int
2149 ht_send_action_ba_addba(struct ieee80211_node *ni,
2150         int category, int action, void *arg0)
2151 {
2152         struct ieee80211vap *vap = ni->ni_vap;
2153         struct ieee80211com *ic = ni->ni_ic;
2154         uint16_t *args = arg0;
2155         struct mbuf *m;
2156         uint8_t *frm;
2157
2158         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2159             "send ADDBA %s: dialogtoken %d "
2160             "baparamset 0x%x (tid %d) batimeout 0x%x baseqctl 0x%x",
2161             (action == IEEE80211_ACTION_BA_ADDBA_REQUEST) ?
2162                 "request" : "response",
2163             args[0], args[1], MS(args[1], IEEE80211_BAPS_TID),
2164             args[2], args[3]);
2165
2166         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2167             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2168             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2169         ieee80211_ref_node(ni);
2170
2171         m = ieee80211_getmgtframe(&frm,
2172             ic->ic_headroom + sizeof(struct ieee80211_frame),
2173             sizeof(uint16_t)    /* action+category */
2174             /* XXX may action payload */
2175             + sizeof(struct ieee80211_action_ba_addbaresponse)
2176         );
2177         if (m != NULL) {
2178                 *frm++ = category;
2179                 *frm++ = action;
2180                 *frm++ = args[0];               /* dialog token */
2181                 ADDSHORT(frm, args[1]);         /* baparamset */
2182                 ADDSHORT(frm, args[2]);         /* batimeout */
2183                 if (action == IEEE80211_ACTION_BA_ADDBA_REQUEST)
2184                         ADDSHORT(frm, args[3]); /* baseqctl */
2185                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2186                 return ht_action_output(ni, m);
2187         } else {
2188                 vap->iv_stats.is_tx_nobuf++;
2189                 ieee80211_free_node(ni);
2190                 return ENOMEM;
2191         }
2192 }
2193
2194 static int
2195 ht_send_action_ba_delba(struct ieee80211_node *ni,
2196         int category, int action, void *arg0)
2197 {
2198         struct ieee80211vap *vap = ni->ni_vap;
2199         struct ieee80211com *ic = ni->ni_ic;
2200         uint16_t *args = arg0;
2201         struct mbuf *m;
2202         uint16_t baparamset;
2203         uint8_t *frm;
2204
2205         baparamset = SM(args[0], IEEE80211_DELBAPS_TID)
2206                    | args[1]
2207                    ;
2208         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2209             "send DELBA action: tid %d, initiator %d reason %d",
2210             args[0], args[1], args[2]);
2211
2212         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2213             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2214             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2215         ieee80211_ref_node(ni);
2216
2217         m = ieee80211_getmgtframe(&frm,
2218             ic->ic_headroom + sizeof(struct ieee80211_frame),
2219             sizeof(uint16_t)    /* action+category */
2220             /* XXX may action payload */
2221             + sizeof(struct ieee80211_action_ba_addbaresponse)
2222         );
2223         if (m != NULL) {
2224                 *frm++ = category;
2225                 *frm++ = action;
2226                 ADDSHORT(frm, baparamset);
2227                 ADDSHORT(frm, args[2]);         /* reason code */
2228                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2229                 return ht_action_output(ni, m);
2230         } else {
2231                 vap->iv_stats.is_tx_nobuf++;
2232                 ieee80211_free_node(ni);
2233                 return ENOMEM;
2234         }
2235 }
2236
2237 static int
2238 ht_send_action_ht_txchwidth(struct ieee80211_node *ni,
2239         int category, int action, void *arg0)
2240 {
2241         struct ieee80211vap *vap = ni->ni_vap;
2242         struct ieee80211com *ic = ni->ni_ic;
2243         struct mbuf *m;
2244         uint8_t *frm;
2245
2246         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N, ni,
2247             "send HT txchwidth: width %d",
2248             IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 40 : 20);
2249
2250         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2251             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2252             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2253         ieee80211_ref_node(ni);
2254
2255         m = ieee80211_getmgtframe(&frm,
2256             ic->ic_headroom + sizeof(struct ieee80211_frame),
2257             sizeof(uint16_t)    /* action+category */
2258             /* XXX may action payload */
2259             + sizeof(struct ieee80211_action_ba_addbaresponse)
2260         );
2261         if (m != NULL) {
2262                 *frm++ = category;
2263                 *frm++ = action;
2264                 *frm++ = IEEE80211_IS_CHAN_HT40(ni->ni_chan) ? 
2265                         IEEE80211_A_HT_TXCHWIDTH_2040 :
2266                         IEEE80211_A_HT_TXCHWIDTH_20;
2267                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2268                 return ht_action_output(ni, m);
2269         } else {
2270                 vap->iv_stats.is_tx_nobuf++;
2271                 ieee80211_free_node(ni);
2272                 return ENOMEM;
2273         }
2274 }
2275 #undef ADDSHORT
2276
2277 /*
2278  * Construct the MCS bit mask for inclusion
2279  * in an HT information element.
2280  */
2281 static void 
2282 ieee80211_set_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
2283 {
2284         int i;
2285
2286         for (i = 0; i < rs->rs_nrates; i++) {
2287                 int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2288                 if (r < IEEE80211_HTRATE_MAXSIZE) {     /* XXX? */
2289                         /* NB: this assumes a particular implementation */
2290                         setbit(frm, r);
2291                 }
2292         }
2293 }
2294
2295 /*
2296  * Add body of an HTCAP information element.
2297  */
2298 static uint8_t *
2299 ieee80211_add_htcap_body(uint8_t *frm, struct ieee80211_node *ni)
2300 {
2301 #define ADDSHORT(frm, v) do {                   \
2302         frm[0] = (v) & 0xff;                    \
2303         frm[1] = (v) >> 8;                      \
2304         frm += 2;                               \
2305 } while (0)
2306         struct ieee80211vap *vap = ni->ni_vap;
2307         uint16_t caps;
2308         int rxmax, density;
2309
2310         /* HT capabilities */
2311         caps = vap->iv_htcaps & 0xffff;
2312         /*
2313          * Note channel width depends on whether we are operating as
2314          * a sta or not.  When operating as a sta we are generating
2315          * a request based on our desired configuration.  Otherwise
2316          * we are operational and the channel attributes identify
2317          * how we've been setup (which might be different if a fixed
2318          * channel is specified).
2319          */
2320         if (vap->iv_opmode == IEEE80211_M_STA) {
2321                 /* override 20/40 use based on config */
2322                 if (vap->iv_flags_ht & IEEE80211_FHT_USEHT40)
2323                         caps |= IEEE80211_HTCAP_CHWIDTH40;
2324                 else
2325                         caps &= ~IEEE80211_HTCAP_CHWIDTH40;
2326                 /* use advertised setting (XXX locally constraint) */
2327                 rxmax = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU);
2328                 density = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY);
2329         } else {
2330                 /* override 20/40 use based on current channel */
2331                 if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
2332                         caps |= IEEE80211_HTCAP_CHWIDTH40;
2333                 else
2334                         caps &= ~IEEE80211_HTCAP_CHWIDTH40;
2335                 rxmax = vap->iv_ampdu_rxmax;
2336                 density = vap->iv_ampdu_density;
2337         }
2338         /* adjust short GI based on channel and config */
2339         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
2340                 caps &= ~IEEE80211_HTCAP_SHORTGI20;
2341         if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0 ||
2342             (caps & IEEE80211_HTCAP_CHWIDTH40) == 0)
2343                 caps &= ~IEEE80211_HTCAP_SHORTGI40;
2344         ADDSHORT(frm, caps);
2345
2346         /* HT parameters */
2347         *frm = SM(rxmax, IEEE80211_HTCAP_MAXRXAMPDU)
2348              | SM(density, IEEE80211_HTCAP_MPDUDENSITY)
2349              ;
2350         frm++;
2351
2352         /* pre-zero remainder of ie */
2353         memset(frm, 0, sizeof(struct ieee80211_ie_htcap) - 
2354                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset));
2355
2356         /* supported MCS set */
2357         /*
2358          * XXX it would better to get the rate set from ni_htrates
2359          * so we can restrict it but for sta mode ni_htrates isn't
2360          * setup when we're called to form an AssocReq frame so for
2361          * now we're restricted to the default HT rate set.
2362          */
2363         ieee80211_set_htrates(frm, &ieee80211_rateset_11n);
2364
2365         frm += sizeof(struct ieee80211_ie_htcap) -
2366                 __offsetof(struct ieee80211_ie_htcap, hc_mcsset);
2367         return frm;
2368 #undef ADDSHORT
2369 }
2370
2371 /*
2372  * Add 802.11n HT capabilities information element
2373  */
2374 uint8_t *
2375 ieee80211_add_htcap(uint8_t *frm, struct ieee80211_node *ni)
2376 {
2377         frm[0] = IEEE80211_ELEMID_HTCAP;
2378         frm[1] = sizeof(struct ieee80211_ie_htcap) - 2;
2379         return ieee80211_add_htcap_body(frm + 2, ni);
2380 }
2381
2382 /*
2383  * Add Broadcom OUI wrapped standard HTCAP ie; this is
2384  * used for compatibility w/ pre-draft implementations.
2385  */
2386 uint8_t *
2387 ieee80211_add_htcap_vendor(uint8_t *frm, struct ieee80211_node *ni)
2388 {
2389         frm[0] = IEEE80211_ELEMID_VENDOR;
2390         frm[1] = 4 + sizeof(struct ieee80211_ie_htcap) - 2;
2391         frm[2] = (BCM_OUI >> 0) & 0xff;
2392         frm[3] = (BCM_OUI >> 8) & 0xff;
2393         frm[4] = (BCM_OUI >> 16) & 0xff;
2394         frm[5] = BCM_OUI_HTCAP;
2395         return ieee80211_add_htcap_body(frm + 6, ni);
2396 }
2397
2398 /*
2399  * Construct the MCS bit mask of basic rates
2400  * for inclusion in an HT information element.
2401  */
2402 static void
2403 ieee80211_set_basic_htrates(uint8_t *frm, const struct ieee80211_htrateset *rs)
2404 {
2405         int i;
2406
2407         for (i = 0; i < rs->rs_nrates; i++) {
2408                 int r = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2409                 if ((rs->rs_rates[i] & IEEE80211_RATE_BASIC) &&
2410                     r < IEEE80211_HTRATE_MAXSIZE) {
2411                         /* NB: this assumes a particular implementation */
2412                         setbit(frm, r);
2413                 }
2414         }
2415 }
2416
2417 /*
2418  * Update the HTINFO ie for a beacon frame.
2419  */
2420 void
2421 ieee80211_ht_update_beacon(struct ieee80211vap *vap,
2422         struct ieee80211_beacon_offsets *bo)
2423 {
2424 #define PROTMODE        (IEEE80211_HTINFO_OPMODE|IEEE80211_HTINFO_NONHT_PRESENT)
2425         const struct ieee80211_channel *bsschan = vap->iv_bss->ni_chan;
2426         struct ieee80211com *ic = vap->iv_ic;
2427         struct ieee80211_ie_htinfo *ht =
2428            (struct ieee80211_ie_htinfo *) bo->bo_htinfo;
2429
2430         /* XXX only update on channel change */
2431         ht->hi_ctrlchannel = ieee80211_chan2ieee(ic, bsschan);
2432         if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
2433                 ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PERM;
2434         else
2435                 ht->hi_byte1 = IEEE80211_HTINFO_RIFSMODE_PROH;
2436         if (IEEE80211_IS_CHAN_HT40U(bsschan))
2437                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
2438         else if (IEEE80211_IS_CHAN_HT40D(bsschan))
2439                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_BELOW;
2440         else
2441                 ht->hi_byte1 |= IEEE80211_HTINFO_2NDCHAN_NONE;
2442         if (IEEE80211_IS_CHAN_HT40(bsschan))
2443                 ht->hi_byte1 |= IEEE80211_HTINFO_TXWIDTH_2040;
2444
2445         /* protection mode */
2446         ht->hi_byte2 = (ht->hi_byte2 &~ PROTMODE) | ic->ic_curhtprotmode;
2447
2448         /* XXX propagate to vendor ie's */
2449 #undef PROTMODE
2450 }
2451
2452 /*
2453  * Add body of an HTINFO information element.
2454  *
2455  * NB: We don't use struct ieee80211_ie_htinfo because we can
2456  * be called to fillin both a standard ie and a compat ie that
2457  * has a vendor OUI at the front.
2458  */
2459 static uint8_t *
2460 ieee80211_add_htinfo_body(uint8_t *frm, struct ieee80211_node *ni)
2461 {
2462         struct ieee80211vap *vap = ni->ni_vap;
2463         struct ieee80211com *ic = ni->ni_ic;
2464
2465         /* pre-zero remainder of ie */
2466         memset(frm, 0, sizeof(struct ieee80211_ie_htinfo) - 2);
2467
2468         /* primary/control channel center */
2469         *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
2470
2471         if (vap->iv_flags_ht & IEEE80211_FHT_RIFS)
2472                 frm[0] = IEEE80211_HTINFO_RIFSMODE_PERM;
2473         else
2474                 frm[0] = IEEE80211_HTINFO_RIFSMODE_PROH;
2475         if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
2476                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_ABOVE;
2477         else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
2478                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_BELOW;
2479         else
2480                 frm[0] |= IEEE80211_HTINFO_2NDCHAN_NONE;
2481         if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
2482                 frm[0] |= IEEE80211_HTINFO_TXWIDTH_2040;
2483
2484         frm[1] = ic->ic_curhtprotmode;
2485
2486         frm += 5;
2487
2488         /* basic MCS set */
2489         ieee80211_set_basic_htrates(frm, &ni->ni_htrates);
2490         frm += sizeof(struct ieee80211_ie_htinfo) -
2491                 __offsetof(struct ieee80211_ie_htinfo, hi_basicmcsset);
2492         return frm;
2493 }
2494
2495 /*
2496  * Add 802.11n HT information information element.
2497  */
2498 uint8_t *
2499 ieee80211_add_htinfo(uint8_t *frm, struct ieee80211_node *ni)
2500 {
2501         frm[0] = IEEE80211_ELEMID_HTINFO;
2502         frm[1] = sizeof(struct ieee80211_ie_htinfo) - 2;
2503         return ieee80211_add_htinfo_body(frm + 2, ni);
2504 }
2505
2506 /*
2507  * Add Broadcom OUI wrapped standard HTINFO ie; this is
2508  * used for compatibility w/ pre-draft implementations.
2509  */
2510 uint8_t *
2511 ieee80211_add_htinfo_vendor(uint8_t *frm, struct ieee80211_node *ni)
2512 {
2513         frm[0] = IEEE80211_ELEMID_VENDOR;
2514         frm[1] = 4 + sizeof(struct ieee80211_ie_htinfo) - 2;
2515         frm[2] = (BCM_OUI >> 0) & 0xff;
2516         frm[3] = (BCM_OUI >> 8) & 0xff;
2517         frm[4] = (BCM_OUI >> 16) & 0xff;
2518         frm[5] = BCM_OUI_HTINFO;
2519         return ieee80211_add_htinfo_body(frm + 6, ni);
2520 }