]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net80211/ieee80211_output.c
Merge ACPICA 20130214.
[FreeBSD/FreeBSD.git] / sys / net80211 / ieee80211_output.c
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32 #include "opt_wlan.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h> 
36 #include <sys/mbuf.h>   
37 #include <sys/kernel.h>
38 #include <sys/endian.h>
39
40 #include <sys/socket.h>
41  
42 #include <net/bpf.h>
43 #include <net/ethernet.h>
44 #include <net/if.h>
45 #include <net/if_llc.h>
46 #include <net/if_media.h>
47 #include <net/if_vlan_var.h>
48
49 #include <net80211/ieee80211_var.h>
50 #include <net80211/ieee80211_regdomain.h>
51 #ifdef IEEE80211_SUPPORT_SUPERG
52 #include <net80211/ieee80211_superg.h>
53 #endif
54 #ifdef IEEE80211_SUPPORT_TDMA
55 #include <net80211/ieee80211_tdma.h>
56 #endif
57 #include <net80211/ieee80211_wds.h>
58 #include <net80211/ieee80211_mesh.h>
59
60 #if defined(INET) || defined(INET6)
61 #include <netinet/in.h> 
62 #endif
63
64 #ifdef INET
65 #include <netinet/if_ether.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #endif
69 #ifdef INET6
70 #include <netinet/ip6.h>
71 #endif
72
73 #include <security/mac/mac_framework.h>
74
75 #define ETHER_HEADER_COPY(dst, src) \
76         memcpy(dst, src, sizeof(struct ether_header))
77
78 /* unalligned little endian access */     
79 #define LE_WRITE_2(p, v) do {                           \
80         ((uint8_t *)(p))[0] = (v) & 0xff;               \
81         ((uint8_t *)(p))[1] = ((v) >> 8) & 0xff;        \
82 } while (0)
83 #define LE_WRITE_4(p, v) do {                           \
84         ((uint8_t *)(p))[0] = (v) & 0xff;               \
85         ((uint8_t *)(p))[1] = ((v) >> 8) & 0xff;        \
86         ((uint8_t *)(p))[2] = ((v) >> 16) & 0xff;       \
87         ((uint8_t *)(p))[3] = ((v) >> 24) & 0xff;       \
88 } while (0)
89
90 static int ieee80211_fragment(struct ieee80211vap *, struct mbuf *,
91         u_int hdrsize, u_int ciphdrsize, u_int mtu);
92 static  void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
93
94 #ifdef IEEE80211_DEBUG
95 /*
96  * Decide if an outbound management frame should be
97  * printed when debugging is enabled.  This filters some
98  * of the less interesting frames that come frequently
99  * (e.g. beacons).
100  */
101 static __inline int
102 doprint(struct ieee80211vap *vap, int subtype)
103 {
104         switch (subtype) {
105         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
106                 return (vap->iv_opmode == IEEE80211_M_IBSS);
107         }
108         return 1;
109 }
110 #endif
111
112 /*
113  * Start method for vap's.  All packets from the stack come
114  * through here.  We handle common processing of the packets
115  * before dispatching them to the underlying device.
116  */
117 void
118 ieee80211_start(struct ifnet *ifp)
119 {
120 #define IS_DWDS(vap) \
121         (vap->iv_opmode == IEEE80211_M_WDS && \
122          (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) == 0)
123         struct ieee80211vap *vap = ifp->if_softc;
124         struct ieee80211com *ic = vap->iv_ic;
125         struct ifnet *parent = ic->ic_ifp;
126         struct ieee80211_node *ni;
127         struct mbuf *m;
128         struct ether_header *eh;
129         int error;
130
131         /* NB: parent must be up and running */
132         if (!IFNET_IS_UP_RUNNING(parent)) {
133                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
134                     "%s: ignore queue, parent %s not up+running\n",
135                     __func__, parent->if_xname);
136                 /* XXX stat */
137                 return;
138         }
139         if (vap->iv_state == IEEE80211_S_SLEEP) {
140                 /*
141                  * In power save, wakeup device for transmit.
142                  */
143                 ieee80211_new_state(vap, IEEE80211_S_RUN, 0);
144                 return;
145         }
146         /*
147          * No data frames go out unless we're running.
148          * Note in particular this covers CAC and CSA
149          * states (though maybe we should check muting
150          * for CSA).
151          */
152         if (vap->iv_state != IEEE80211_S_RUN) {
153                 IEEE80211_LOCK(ic);
154                 /* re-check under the com lock to avoid races */
155                 if (vap->iv_state != IEEE80211_S_RUN) {
156                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
157                             "%s: ignore queue, in %s state\n",
158                             __func__, ieee80211_state_name[vap->iv_state]);
159                         vap->iv_stats.is_tx_badstate++;
160                         IEEE80211_UNLOCK(ic);
161                         IFQ_LOCK(&ifp->if_snd);
162                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
163                         IFQ_UNLOCK(&ifp->if_snd);
164                         return;
165                 }
166                 IEEE80211_UNLOCK(ic);
167         }
168         for (;;) {
169                 IFQ_DEQUEUE(&ifp->if_snd, m);
170                 if (m == NULL)
171                         break;
172                 /*
173                  * Sanitize mbuf flags for net80211 use.  We cannot
174                  * clear M_PWR_SAV or M_MORE_DATA because these may
175                  * be set for frames that are re-submitted from the
176                  * power save queue.
177                  *
178                  * NB: This must be done before ieee80211_classify as
179                  *     it marks EAPOL in frames with M_EAPOL.
180                  */
181                 m->m_flags &= ~(M_80211_TX - M_PWR_SAV - M_MORE_DATA);
182                 /*
183                  * Cancel any background scan.
184                  */
185                 if (ic->ic_flags & IEEE80211_F_SCAN)
186                         ieee80211_cancel_anyscan(vap);
187                 /* 
188                  * Find the node for the destination so we can do
189                  * things like power save and fast frames aggregation.
190                  *
191                  * NB: past this point various code assumes the first
192                  *     mbuf has the 802.3 header present (and contiguous).
193                  */
194                 ni = NULL;
195                 if (m->m_len < sizeof(struct ether_header) &&
196                    (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
197                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
198                             "discard frame, %s\n", "m_pullup failed");
199                         vap->iv_stats.is_tx_nobuf++;    /* XXX */
200                         ifp->if_oerrors++;
201                         continue;
202                 }
203                 eh = mtod(m, struct ether_header *);
204                 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
205                         if (IS_DWDS(vap)) {
206                                 /*
207                                  * Only unicast frames from the above go out
208                                  * DWDS vaps; multicast frames are handled by
209                                  * dispatching the frame as it comes through
210                                  * the AP vap (see below).
211                                  */
212                                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_WDS,
213                                     eh->ether_dhost, "mcast", "%s", "on DWDS");
214                                 vap->iv_stats.is_dwds_mcast++;
215                                 m_freem(m);
216                                 continue;
217                         }
218                         if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
219                                 /*
220                                  * Spam DWDS vap's w/ multicast traffic.
221                                  */
222                                 /* XXX only if dwds in use? */
223                                 ieee80211_dwds_mcast(vap, m);
224                         }
225                 }
226 #ifdef IEEE80211_SUPPORT_MESH
227                 if (vap->iv_opmode != IEEE80211_M_MBSS) {
228 #endif
229                         ni = ieee80211_find_txnode(vap, eh->ether_dhost);
230                         if (ni == NULL) {
231                                 /* NB: ieee80211_find_txnode does stat+msg */
232                                 ifp->if_oerrors++;
233                                 m_freem(m);
234                                 continue;
235                         }
236                         if (ni->ni_associd == 0 &&
237                             (ni->ni_flags & IEEE80211_NODE_ASSOCID)) {
238                                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
239                                     eh->ether_dhost, NULL,
240                                     "sta not associated (type 0x%04x)",
241                                     htons(eh->ether_type));
242                                 vap->iv_stats.is_tx_notassoc++;
243                                 ifp->if_oerrors++;
244                                 m_freem(m);
245                                 ieee80211_free_node(ni);
246                                 continue;
247                         }
248 #ifdef IEEE80211_SUPPORT_MESH
249                 } else {
250                         if (!IEEE80211_ADDR_EQ(eh->ether_shost, vap->iv_myaddr)) {
251                                 /*
252                                  * Proxy station only if configured.
253                                  */
254                                 if (!ieee80211_mesh_isproxyena(vap)) {
255                                         IEEE80211_DISCARD_MAC(vap,
256                                             IEEE80211_MSG_OUTPUT |
257                                             IEEE80211_MSG_MESH,
258                                             eh->ether_dhost, NULL,
259                                             "%s", "proxy not enabled");
260                                         vap->iv_stats.is_mesh_notproxy++;
261                                         ifp->if_oerrors++;
262                                         m_freem(m);
263                                         continue;
264                                 }
265                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
266                                     "forward frame from DS SA(%6D), DA(%6D)\n",
267                                     eh->ether_shost, ":",
268                                     eh->ether_dhost, ":");
269                                 ieee80211_mesh_proxy_check(vap, eh->ether_shost);
270                         }
271                         ni = ieee80211_mesh_discover(vap, eh->ether_dhost, m);
272                         if (ni == NULL) {
273                                 /*
274                                  * NB: ieee80211_mesh_discover holds/disposes
275                                  * frame (e.g. queueing on path discovery).
276                                  */
277                                 ifp->if_oerrors++;
278                                 continue;
279                         }
280                 }
281 #endif
282                 if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
283                     (m->m_flags & M_PWR_SAV) == 0) {
284                         /*
285                          * Station in power save mode; pass the frame
286                          * to the 802.11 layer and continue.  We'll get
287                          * the frame back when the time is right.
288                          * XXX lose WDS vap linkage?
289                          */
290                         (void) ieee80211_pwrsave(ni, m);
291                         ieee80211_free_node(ni);
292                         continue;
293                 }
294                 /* calculate priority so drivers can find the tx queue */
295                 if (ieee80211_classify(ni, m)) {
296                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
297                             eh->ether_dhost, NULL,
298                             "%s", "classification failure");
299                         vap->iv_stats.is_tx_classify++;
300                         ifp->if_oerrors++;
301                         m_freem(m);
302                         ieee80211_free_node(ni);
303                         continue;
304                 }
305                 /*
306                  * Stash the node pointer.  Note that we do this after
307                  * any call to ieee80211_dwds_mcast because that code
308                  * uses any existing value for rcvif to identify the
309                  * interface it (might have been) received on.
310                  */
311                 m->m_pkthdr.rcvif = (void *)ni;
312
313                 BPF_MTAP(ifp, m);               /* 802.3 tx */
314  
315                 /*
316                  * Check if A-MPDU tx aggregation is setup or if we
317                  * should try to enable it.  The sta must be associated
318                  * with HT and A-MPDU enabled for use.  When the policy
319                  * routine decides we should enable A-MPDU we issue an
320                  * ADDBA request and wait for a reply.  The frame being
321                  * encapsulated will go out w/o using A-MPDU, or possibly
322                  * it might be collected by the driver and held/retransmit.
323                  * The default ic_ampdu_enable routine handles staggering
324                  * ADDBA requests in case the receiver NAK's us or we are
325                  * otherwise unable to establish a BA stream.
326                  */
327                 if ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) &&
328                     (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_TX) &&
329                     (m->m_flags & M_EAPOL) == 0) {
330                         int tid = WME_AC_TO_TID(M_WME_GETAC(m));
331                         struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
332
333                         ieee80211_txampdu_count_packet(tap);
334                         if (IEEE80211_AMPDU_RUNNING(tap)) {
335                                 /*
336                                  * Operational, mark frame for aggregation.
337                                  *
338                                  * XXX do tx aggregation here
339                                  */
340                                 m->m_flags |= M_AMPDU_MPDU;
341                         } else if (!IEEE80211_AMPDU_REQUESTED(tap) &&
342                             ic->ic_ampdu_enable(ni, tap)) {
343                                 /*
344                                  * Not negotiated yet, request service.
345                                  */
346                                 ieee80211_ampdu_request(ni, tap);
347                                 /* XXX hold frame for reply? */
348                         }
349                 }
350 #ifdef IEEE80211_SUPPORT_SUPERG
351                 else if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF)) {
352                         m = ieee80211_ff_check(ni, m);
353                         if (m == NULL) {
354                                 /* NB: any ni ref held on stageq */
355                                 continue;
356                         }
357                 }
358 #endif /* IEEE80211_SUPPORT_SUPERG */
359                 if (__predict_true((vap->iv_caps & IEEE80211_C_8023ENCAP) == 0)) {
360                         /*
361                          * Encapsulate the packet in prep for transmission.
362                          */
363                         m = ieee80211_encap(vap, ni, m);
364                         if (m == NULL) {
365                                 /* NB: stat+msg handled in ieee80211_encap */
366                                 ieee80211_free_node(ni);
367                                 continue;
368                         }
369                 }
370                 error = parent->if_transmit(parent, m);
371                 if (error != 0) {
372                         /* NB: IFQ_HANDOFF reclaims mbuf */
373                         ieee80211_free_node(ni);
374                 } else {
375                         ifp->if_opackets++;
376                 }
377                 ic->ic_lastdata = ticks;
378         }
379 #undef IS_DWDS
380 }
381
382 /*
383  * 802.11 output routine. This is (currently) used only to
384  * connect bpf write calls to the 802.11 layer for injecting
385  * raw 802.11 frames.
386  */
387 int
388 ieee80211_output(struct ifnet *ifp, struct mbuf *m,
389         struct sockaddr *dst, struct route *ro)
390 {
391 #define senderr(e) do { error = (e); goto bad;} while (0)
392         struct ieee80211_node *ni = NULL;
393         struct ieee80211vap *vap;
394         struct ieee80211_frame *wh;
395         int error;
396
397         IFQ_LOCK(&ifp->if_snd);
398         if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
399                 IFQ_UNLOCK(&ifp->if_snd);
400                 /*
401                  * Short-circuit requests if the vap is marked OACTIVE
402                  * as this can happen because a packet came down through
403                  * ieee80211_start before the vap entered RUN state in
404                  * which case it's ok to just drop the frame.  This
405                  * should not be necessary but callers of if_output don't
406                  * check OACTIVE.
407                  */
408                 senderr(ENETDOWN);
409         }
410         IFQ_UNLOCK(&ifp->if_snd);
411         vap = ifp->if_softc;
412         /*
413          * Hand to the 802.3 code if not tagged as
414          * a raw 802.11 frame.
415          */
416         if (dst->sa_family != AF_IEEE80211)
417                 return vap->iv_output(ifp, m, dst, ro);
418 #ifdef MAC
419         error = mac_ifnet_check_transmit(ifp, m);
420         if (error)
421                 senderr(error);
422 #endif
423         if (ifp->if_flags & IFF_MONITOR)
424                 senderr(ENETDOWN);
425         if (!IFNET_IS_UP_RUNNING(ifp))
426                 senderr(ENETDOWN);
427         if (vap->iv_state == IEEE80211_S_CAC) {
428                 IEEE80211_DPRINTF(vap,
429                     IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
430                     "block %s frame in CAC state\n", "raw data");
431                 vap->iv_stats.is_tx_badstate++;
432                 senderr(EIO);           /* XXX */
433         } else if (vap->iv_state == IEEE80211_S_SCAN)
434                 senderr(EIO);
435         /* XXX bypass bridge, pfil, carp, etc. */
436
437         if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
438                 senderr(EIO);   /* XXX */
439         wh = mtod(m, struct ieee80211_frame *);
440         if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
441             IEEE80211_FC0_VERSION_0)
442                 senderr(EIO);   /* XXX */
443
444         /* locate destination node */
445         switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
446         case IEEE80211_FC1_DIR_NODS:
447         case IEEE80211_FC1_DIR_FROMDS:
448                 ni = ieee80211_find_txnode(vap, wh->i_addr1);
449                 break;
450         case IEEE80211_FC1_DIR_TODS:
451         case IEEE80211_FC1_DIR_DSTODS:
452                 if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
453                         senderr(EIO);   /* XXX */
454                 ni = ieee80211_find_txnode(vap, wh->i_addr3);
455                 break;
456         default:
457                 senderr(EIO);   /* XXX */
458         }
459         if (ni == NULL) {
460                 /*
461                  * Permit packets w/ bpf params through regardless
462                  * (see below about sa_len).
463                  */
464                 if (dst->sa_len == 0)
465                         senderr(EHOSTUNREACH);
466                 ni = ieee80211_ref_node(vap->iv_bss);
467         }
468
469         /*
470          * Sanitize mbuf for net80211 flags leaked from above.
471          *
472          * NB: This must be done before ieee80211_classify as
473          *     it marks EAPOL in frames with M_EAPOL.
474          */
475         m->m_flags &= ~M_80211_TX;
476
477         /* calculate priority so drivers can find the tx queue */
478         /* XXX assumes an 802.3 frame */
479         if (ieee80211_classify(ni, m))
480                 senderr(EIO);           /* XXX */
481
482         ifp->if_opackets++;
483         IEEE80211_NODE_STAT(ni, tx_data);
484         if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
485                 IEEE80211_NODE_STAT(ni, tx_mcast);
486                 m->m_flags |= M_MCAST;
487         } else
488                 IEEE80211_NODE_STAT(ni, tx_ucast);
489         /* NB: ieee80211_encap does not include 802.11 header */
490         IEEE80211_NODE_STAT_ADD(ni, tx_bytes, m->m_pkthdr.len);
491
492         /*
493          * NB: DLT_IEEE802_11_RADIO identifies the parameters are
494          * present by setting the sa_len field of the sockaddr (yes,
495          * this is a hack).
496          * NB: we assume sa_data is suitably aligned to cast.
497          */
498         return vap->iv_ic->ic_raw_xmit(ni, m,
499             (const struct ieee80211_bpf_params *)(dst->sa_len ?
500                 dst->sa_data : NULL));
501 bad:
502         if (m != NULL)
503                 m_freem(m);
504         if (ni != NULL)
505                 ieee80211_free_node(ni);
506         ifp->if_oerrors++;
507         return error;
508 #undef senderr
509 }
510
511 /*
512  * Set the direction field and address fields of an outgoing
513  * frame.  Note this should be called early on in constructing
514  * a frame as it sets i_fc[1]; other bits can then be or'd in.
515  */
516 void
517 ieee80211_send_setup(
518         struct ieee80211_node *ni,
519         struct mbuf *m,
520         int type, int tid,
521         const uint8_t sa[IEEE80211_ADDR_LEN],
522         const uint8_t da[IEEE80211_ADDR_LEN],
523         const uint8_t bssid[IEEE80211_ADDR_LEN])
524 {
525 #define WH4(wh) ((struct ieee80211_frame_addr4 *)wh)
526         struct ieee80211vap *vap = ni->ni_vap;
527         struct ieee80211_tx_ampdu *tap;
528         struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
529         ieee80211_seq seqno;
530
531         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
532         if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
533                 switch (vap->iv_opmode) {
534                 case IEEE80211_M_STA:
535                         wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
536                         IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
537                         IEEE80211_ADDR_COPY(wh->i_addr2, sa);
538                         IEEE80211_ADDR_COPY(wh->i_addr3, da);
539                         break;
540                 case IEEE80211_M_IBSS:
541                 case IEEE80211_M_AHDEMO:
542                         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
543                         IEEE80211_ADDR_COPY(wh->i_addr1, da);
544                         IEEE80211_ADDR_COPY(wh->i_addr2, sa);
545                         IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
546                         break;
547                 case IEEE80211_M_HOSTAP:
548                         wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
549                         IEEE80211_ADDR_COPY(wh->i_addr1, da);
550                         IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
551                         IEEE80211_ADDR_COPY(wh->i_addr3, sa);
552                         break;
553                 case IEEE80211_M_WDS:
554                         wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
555                         IEEE80211_ADDR_COPY(wh->i_addr1, da);
556                         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
557                         IEEE80211_ADDR_COPY(wh->i_addr3, da);
558                         IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
559                         break;
560                 case IEEE80211_M_MBSS:
561 #ifdef IEEE80211_SUPPORT_MESH
562                         if (IEEE80211_IS_MULTICAST(da)) {
563                                 wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
564                                 /* XXX next hop */
565                                 IEEE80211_ADDR_COPY(wh->i_addr1, da);
566                                 IEEE80211_ADDR_COPY(wh->i_addr2,
567                                     vap->iv_myaddr);
568                         } else {
569                                 wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
570                                 IEEE80211_ADDR_COPY(wh->i_addr1, da);
571                                 IEEE80211_ADDR_COPY(wh->i_addr2,
572                                     vap->iv_myaddr);
573                                 IEEE80211_ADDR_COPY(wh->i_addr3, da);
574                                 IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
575                         }
576 #endif
577                         break;
578                 case IEEE80211_M_MONITOR:       /* NB: to quiet compiler */
579                         break;
580                 }
581         } else {
582                 wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
583                 IEEE80211_ADDR_COPY(wh->i_addr1, da);
584                 IEEE80211_ADDR_COPY(wh->i_addr2, sa);
585 #ifdef IEEE80211_SUPPORT_MESH
586                 if (vap->iv_opmode == IEEE80211_M_MBSS)
587                         IEEE80211_ADDR_COPY(wh->i_addr3, sa);
588                 else
589 #endif
590                         IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
591         }
592         *(uint16_t *)&wh->i_dur[0] = 0;
593
594         tap = &ni->ni_tx_ampdu[tid];
595         if (tid != IEEE80211_NONQOS_TID && IEEE80211_AMPDU_RUNNING(tap))
596                 m->m_flags |= M_AMPDU_MPDU;
597         else {
598                 seqno = ni->ni_txseqs[tid]++;
599                 *(uint16_t *)&wh->i_seq[0] =
600                     htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
601                 M_SEQNO_SET(m, seqno);
602         }
603
604         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
605                 m->m_flags |= M_MCAST;
606 #undef WH4
607 }
608
609 /*
610  * Send a management frame to the specified node.  The node pointer
611  * must have a reference as the pointer will be passed to the driver
612  * and potentially held for a long time.  If the frame is successfully
613  * dispatched to the driver, then it is responsible for freeing the
614  * reference (and potentially free'ing up any associated storage);
615  * otherwise deal with reclaiming any reference (on error).
616  */
617 int
618 ieee80211_mgmt_output(struct ieee80211_node *ni, struct mbuf *m, int type,
619         struct ieee80211_bpf_params *params)
620 {
621         struct ieee80211vap *vap = ni->ni_vap;
622         struct ieee80211com *ic = ni->ni_ic;
623         struct ieee80211_frame *wh;
624
625         KASSERT(ni != NULL, ("null node"));
626
627         if (vap->iv_state == IEEE80211_S_CAC) {
628                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
629                     ni, "block %s frame in CAC state",
630                         ieee80211_mgt_subtype_name[
631                             (type & IEEE80211_FC0_SUBTYPE_MASK) >>
632                                 IEEE80211_FC0_SUBTYPE_SHIFT]);
633                 vap->iv_stats.is_tx_badstate++;
634                 ieee80211_free_node(ni);
635                 m_freem(m);
636                 return EIO;             /* XXX */
637         }
638
639         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
640         if (m == NULL) {
641                 ieee80211_free_node(ni);
642                 return ENOMEM;
643         }
644
645         wh = mtod(m, struct ieee80211_frame *);
646         ieee80211_send_setup(ni, m,
647              IEEE80211_FC0_TYPE_MGT | type, IEEE80211_NONQOS_TID,
648              vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
649         if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
650                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_AUTH, wh->i_addr1,
651                     "encrypting frame (%s)", __func__);
652                 wh->i_fc[1] |= IEEE80211_FC1_WEP;
653         }
654         m->m_flags |= M_ENCAP;          /* mark encapsulated */
655
656         KASSERT(type != IEEE80211_FC0_SUBTYPE_PROBE_RESP, ("probe response?"));
657         M_WME_SETAC(m, params->ibp_pri);
658
659 #ifdef IEEE80211_DEBUG
660         /* avoid printing too many frames */
661         if ((ieee80211_msg_debug(vap) && doprint(vap, type)) ||
662             ieee80211_msg_dumppkts(vap)) {
663                 printf("[%s] send %s on channel %u\n",
664                     ether_sprintf(wh->i_addr1),
665                     ieee80211_mgt_subtype_name[
666                         (type & IEEE80211_FC0_SUBTYPE_MASK) >>
667                                 IEEE80211_FC0_SUBTYPE_SHIFT],
668                     ieee80211_chan2ieee(ic, ic->ic_curchan));
669         }
670 #endif
671         IEEE80211_NODE_STAT(ni, tx_mgmt);
672
673         return ic->ic_raw_xmit(ni, m, params);
674 }
675
676 /*
677  * Send a null data frame to the specified node.  If the station
678  * is setup for QoS then a QoS Null Data frame is constructed.
679  * If this is a WDS station then a 4-address frame is constructed.
680  *
681  * NB: the caller is assumed to have setup a node reference
682  *     for use; this is necessary to deal with a race condition
683  *     when probing for inactive stations.  Like ieee80211_mgmt_output
684  *     we must cleanup any node reference on error;  however we
685  *     can safely just unref it as we know it will never be the
686  *     last reference to the node.
687  */
688 int
689 ieee80211_send_nulldata(struct ieee80211_node *ni)
690 {
691         struct ieee80211vap *vap = ni->ni_vap;
692         struct ieee80211com *ic = ni->ni_ic;
693         struct mbuf *m;
694         struct ieee80211_frame *wh;
695         int hdrlen;
696         uint8_t *frm;
697
698         if (vap->iv_state == IEEE80211_S_CAC) {
699                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
700                     ni, "block %s frame in CAC state", "null data");
701                 ieee80211_unref_node(&ni);
702                 vap->iv_stats.is_tx_badstate++;
703                 return EIO;             /* XXX */
704         }
705
706         if (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT))
707                 hdrlen = sizeof(struct ieee80211_qosframe);
708         else
709                 hdrlen = sizeof(struct ieee80211_frame);
710         /* NB: only WDS vap's get 4-address frames */
711         if (vap->iv_opmode == IEEE80211_M_WDS)
712                 hdrlen += IEEE80211_ADDR_LEN;
713         if (ic->ic_flags & IEEE80211_F_DATAPAD)
714                 hdrlen = roundup(hdrlen, sizeof(uint32_t));
715
716         m = ieee80211_getmgtframe(&frm, ic->ic_headroom + hdrlen, 0);
717         if (m == NULL) {
718                 /* XXX debug msg */
719                 ieee80211_unref_node(&ni);
720                 vap->iv_stats.is_tx_nobuf++;
721                 return ENOMEM;
722         }
723         KASSERT(M_LEADINGSPACE(m) >= hdrlen,
724             ("leading space %zd", M_LEADINGSPACE(m)));
725         M_PREPEND(m, hdrlen, M_NOWAIT);
726         if (m == NULL) {
727                 /* NB: cannot happen */
728                 ieee80211_free_node(ni);
729                 return ENOMEM;
730         }
731
732         wh = mtod(m, struct ieee80211_frame *);         /* NB: a little lie */
733         if (ni->ni_flags & IEEE80211_NODE_QOS) {
734                 const int tid = WME_AC_TO_TID(WME_AC_BE);
735                 uint8_t *qos;
736
737                 ieee80211_send_setup(ni, m,
738                     IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_QOS_NULL,
739                     tid, vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
740
741                 if (vap->iv_opmode == IEEE80211_M_WDS)
742                         qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
743                 else
744                         qos = ((struct ieee80211_qosframe *) wh)->i_qos;
745                 qos[0] = tid & IEEE80211_QOS_TID;
746                 if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[WME_AC_BE].wmep_noackPolicy)
747                         qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
748                 qos[1] = 0;
749         } else {
750                 ieee80211_send_setup(ni, m,
751                     IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
752                     IEEE80211_NONQOS_TID,
753                     vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
754         }
755         if (vap->iv_opmode != IEEE80211_M_WDS) {
756                 /* NB: power management bit is never sent by an AP */
757                 if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
758                     vap->iv_opmode != IEEE80211_M_HOSTAP)
759                         wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
760         }
761         m->m_len = m->m_pkthdr.len = hdrlen;
762         m->m_flags |= M_ENCAP;          /* mark encapsulated */
763
764         M_WME_SETAC(m, WME_AC_BE);
765
766         IEEE80211_NODE_STAT(ni, tx_data);
767
768         IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, ni,
769             "send %snull data frame on channel %u, pwr mgt %s",
770             ni->ni_flags & IEEE80211_NODE_QOS ? "QoS " : "",
771             ieee80211_chan2ieee(ic, ic->ic_curchan),
772             wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
773
774         return ic->ic_raw_xmit(ni, m, NULL);
775 }
776
777 /* 
778  * Assign priority to a frame based on any vlan tag assigned
779  * to the station and/or any Diffserv setting in an IP header.
780  * Finally, if an ACM policy is setup (in station mode) it's
781  * applied.
782  */
783 int
784 ieee80211_classify(struct ieee80211_node *ni, struct mbuf *m)
785 {
786         const struct ether_header *eh = mtod(m, struct ether_header *);
787         int v_wme_ac, d_wme_ac, ac;
788
789         /*
790          * Always promote PAE/EAPOL frames to high priority.
791          */
792         if (eh->ether_type == htons(ETHERTYPE_PAE)) {
793                 /* NB: mark so others don't need to check header */
794                 m->m_flags |= M_EAPOL;
795                 ac = WME_AC_VO;
796                 goto done;
797         }
798         /*
799          * Non-qos traffic goes to BE.
800          */
801         if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
802                 ac = WME_AC_BE;
803                 goto done;
804         }
805
806         /* 
807          * If node has a vlan tag then all traffic
808          * to it must have a matching tag.
809          */
810         v_wme_ac = 0;
811         if (ni->ni_vlan != 0) {
812                  if ((m->m_flags & M_VLANTAG) == 0) {
813                         IEEE80211_NODE_STAT(ni, tx_novlantag);
814                         return 1;
815                 }
816                 if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
817                     EVL_VLANOFTAG(ni->ni_vlan)) {
818                         IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
819                         return 1;
820                 }
821                 /* map vlan priority to AC */
822                 v_wme_ac = TID_TO_WME_AC(EVL_PRIOFTAG(ni->ni_vlan));
823         }
824
825         /* XXX m_copydata may be too slow for fast path */
826 #ifdef INET
827         if (eh->ether_type == htons(ETHERTYPE_IP)) {
828                 uint8_t tos;
829                 /*
830                  * IP frame, map the DSCP bits from the TOS field.
831                  */
832                 /* NB: ip header may not be in first mbuf */
833                 m_copydata(m, sizeof(struct ether_header) +
834                     offsetof(struct ip, ip_tos), sizeof(tos), &tos);
835                 tos >>= 5;              /* NB: ECN + low 3 bits of DSCP */
836                 d_wme_ac = TID_TO_WME_AC(tos);
837         } else {
838 #endif /* INET */
839 #ifdef INET6
840         if (eh->ether_type == htons(ETHERTYPE_IPV6)) {
841                 uint32_t flow;
842                 uint8_t tos;
843                 /*
844                  * IPv6 frame, map the DSCP bits from the traffic class field.
845                  */
846                 m_copydata(m, sizeof(struct ether_header) +
847                     offsetof(struct ip6_hdr, ip6_flow), sizeof(flow),
848                     (caddr_t) &flow);
849                 tos = (uint8_t)(ntohl(flow) >> 20);
850                 tos >>= 5;              /* NB: ECN + low 3 bits of DSCP */
851                 d_wme_ac = TID_TO_WME_AC(tos);
852         } else {
853 #endif /* INET6 */
854                 d_wme_ac = WME_AC_BE;
855 #ifdef INET6
856         }
857 #endif
858 #ifdef INET
859         }
860 #endif
861         /*
862          * Use highest priority AC.
863          */
864         if (v_wme_ac > d_wme_ac)
865                 ac = v_wme_ac;
866         else
867                 ac = d_wme_ac;
868
869         /*
870          * Apply ACM policy.
871          */
872         if (ni->ni_vap->iv_opmode == IEEE80211_M_STA) {
873                 static const int acmap[4] = {
874                         WME_AC_BK,      /* WME_AC_BE */
875                         WME_AC_BK,      /* WME_AC_BK */
876                         WME_AC_BE,      /* WME_AC_VI */
877                         WME_AC_VI,      /* WME_AC_VO */
878                 };
879                 struct ieee80211com *ic = ni->ni_ic;
880
881                 while (ac != WME_AC_BK &&
882                     ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
883                         ac = acmap[ac];
884         }
885 done:
886         M_WME_SETAC(m, ac);
887         return 0;
888 }
889
890 /*
891  * Insure there is sufficient contiguous space to encapsulate the
892  * 802.11 data frame.  If room isn't already there, arrange for it.
893  * Drivers and cipher modules assume we have done the necessary work
894  * and fail rudely if they don't find the space they need.
895  */
896 struct mbuf *
897 ieee80211_mbuf_adjust(struct ieee80211vap *vap, int hdrsize,
898         struct ieee80211_key *key, struct mbuf *m)
899 {
900 #define TO_BE_RECLAIMED (sizeof(struct ether_header) - sizeof(struct llc))
901         int needed_space = vap->iv_ic->ic_headroom + hdrsize;
902
903         if (key != NULL) {
904                 /* XXX belongs in crypto code? */
905                 needed_space += key->wk_cipher->ic_header;
906                 /* XXX frags */
907                 /*
908                  * When crypto is being done in the host we must insure
909                  * the data are writable for the cipher routines; clone
910                  * a writable mbuf chain.
911                  * XXX handle SWMIC specially
912                  */
913                 if (key->wk_flags & (IEEE80211_KEY_SWENCRYPT|IEEE80211_KEY_SWENMIC)) {
914                         m = m_unshare(m, M_NOWAIT);
915                         if (m == NULL) {
916                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
917                                     "%s: cannot get writable mbuf\n", __func__);
918                                 vap->iv_stats.is_tx_nobuf++; /* XXX new stat */
919                                 return NULL;
920                         }
921                 }
922         }
923         /*
924          * We know we are called just before stripping an Ethernet
925          * header and prepending an LLC header.  This means we know
926          * there will be
927          *      sizeof(struct ether_header) - sizeof(struct llc)
928          * bytes recovered to which we need additional space for the
929          * 802.11 header and any crypto header.
930          */
931         /* XXX check trailing space and copy instead? */
932         if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
933                 struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
934                 if (n == NULL) {
935                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
936                             "%s: cannot expand storage\n", __func__);
937                         vap->iv_stats.is_tx_nobuf++;
938                         m_freem(m);
939                         return NULL;
940                 }
941                 KASSERT(needed_space <= MHLEN,
942                     ("not enough room, need %u got %zu\n", needed_space, MHLEN));
943                 /*
944                  * Setup new mbuf to have leading space to prepend the
945                  * 802.11 header and any crypto header bits that are
946                  * required (the latter are added when the driver calls
947                  * back to ieee80211_crypto_encap to do crypto encapsulation).
948                  */
949                 /* NB: must be first 'cuz it clobbers m_data */
950                 m_move_pkthdr(n, m);
951                 n->m_len = 0;                   /* NB: m_gethdr does not set */
952                 n->m_data += needed_space;
953                 /*
954                  * Pull up Ethernet header to create the expected layout.
955                  * We could use m_pullup but that's overkill (i.e. we don't
956                  * need the actual data) and it cannot fail so do it inline
957                  * for speed.
958                  */
959                 /* NB: struct ether_header is known to be contiguous */
960                 n->m_len += sizeof(struct ether_header);
961                 m->m_len -= sizeof(struct ether_header);
962                 m->m_data += sizeof(struct ether_header);
963                 /*
964                  * Replace the head of the chain.
965                  */
966                 n->m_next = m;
967                 m = n;
968         }
969         return m;
970 #undef TO_BE_RECLAIMED
971 }
972
973 /*
974  * Return the transmit key to use in sending a unicast frame.
975  * If a unicast key is set we use that.  When no unicast key is set
976  * we fall back to the default transmit key.
977  */ 
978 static __inline struct ieee80211_key *
979 ieee80211_crypto_getucastkey(struct ieee80211vap *vap,
980         struct ieee80211_node *ni)
981 {
982         if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
983                 if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
984                     IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
985                         return NULL;
986                 return &vap->iv_nw_keys[vap->iv_def_txkey];
987         } else {
988                 return &ni->ni_ucastkey;
989         }
990 }
991
992 /*
993  * Return the transmit key to use in sending a multicast frame.
994  * Multicast traffic always uses the group key which is installed as
995  * the default tx key.
996  */ 
997 static __inline struct ieee80211_key *
998 ieee80211_crypto_getmcastkey(struct ieee80211vap *vap,
999         struct ieee80211_node *ni)
1000 {
1001         if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
1002             IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
1003                 return NULL;
1004         return &vap->iv_nw_keys[vap->iv_def_txkey];
1005 }
1006
1007 /*
1008  * Encapsulate an outbound data frame.  The mbuf chain is updated.
1009  * If an error is encountered NULL is returned.  The caller is required
1010  * to provide a node reference and pullup the ethernet header in the
1011  * first mbuf.
1012  *
1013  * NB: Packet is assumed to be processed by ieee80211_classify which
1014  *     marked EAPOL frames w/ M_EAPOL.
1015  */
1016 struct mbuf *
1017 ieee80211_encap(struct ieee80211vap *vap, struct ieee80211_node *ni,
1018     struct mbuf *m)
1019 {
1020 #define WH4(wh) ((struct ieee80211_frame_addr4 *)(wh))
1021 #define MC01(mc)        ((struct ieee80211_meshcntl_ae01 *)mc)
1022         struct ieee80211com *ic = ni->ni_ic;
1023 #ifdef IEEE80211_SUPPORT_MESH
1024         struct ieee80211_mesh_state *ms = vap->iv_mesh;
1025         struct ieee80211_meshcntl_ae10 *mc;
1026         struct ieee80211_mesh_route *rt = NULL;
1027         int dir = -1;
1028 #endif
1029         struct ether_header eh;
1030         struct ieee80211_frame *wh;
1031         struct ieee80211_key *key;
1032         struct llc *llc;
1033         int hdrsize, hdrspace, datalen, addqos, txfrag, is4addr;
1034         ieee80211_seq seqno;
1035         int meshhdrsize, meshae;
1036         uint8_t *qos;
1037
1038         /*
1039          * Copy existing Ethernet header to a safe place.  The
1040          * rest of the code assumes it's ok to strip it when
1041          * reorganizing state for the final encapsulation.
1042          */
1043         KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
1044         ETHER_HEADER_COPY(&eh, mtod(m, caddr_t));
1045
1046         /*
1047          * Insure space for additional headers.  First identify
1048          * transmit key to use in calculating any buffer adjustments
1049          * required.  This is also used below to do privacy
1050          * encapsulation work.  Then calculate the 802.11 header
1051          * size and any padding required by the driver.
1052          *
1053          * Note key may be NULL if we fall back to the default
1054          * transmit key and that is not set.  In that case the
1055          * buffer may not be expanded as needed by the cipher
1056          * routines, but they will/should discard it.
1057          */
1058         if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1059                 if (vap->iv_opmode == IEEE80211_M_STA ||
1060                     !IEEE80211_IS_MULTICAST(eh.ether_dhost) ||
1061                     (vap->iv_opmode == IEEE80211_M_WDS &&
1062                      (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY)))
1063                         key = ieee80211_crypto_getucastkey(vap, ni);
1064                 else
1065                         key = ieee80211_crypto_getmcastkey(vap, ni);
1066                 if (key == NULL && (m->m_flags & M_EAPOL) == 0) {
1067                         IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO,
1068                             eh.ether_dhost,
1069                             "no default transmit key (%s) deftxkey %u",
1070                             __func__, vap->iv_def_txkey);
1071                         vap->iv_stats.is_tx_nodefkey++;
1072                         goto bad;
1073                 }
1074         } else
1075                 key = NULL;
1076         /*
1077          * XXX Some ap's don't handle QoS-encapsulated EAPOL
1078          * frames so suppress use.  This may be an issue if other
1079          * ap's require all data frames to be QoS-encapsulated
1080          * once negotiated in which case we'll need to make this
1081          * configurable.
1082          * NB: mesh data frames are QoS.
1083          */
1084         addqos = ((ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) ||
1085             (vap->iv_opmode == IEEE80211_M_MBSS)) &&
1086             (m->m_flags & M_EAPOL) == 0;
1087         if (addqos)
1088                 hdrsize = sizeof(struct ieee80211_qosframe);
1089         else
1090                 hdrsize = sizeof(struct ieee80211_frame);
1091 #ifdef IEEE80211_SUPPORT_MESH
1092         if (vap->iv_opmode == IEEE80211_M_MBSS) {
1093                 /*
1094                  * Mesh data frames are encapsulated according to the
1095                  * rules of Section 11B.8.5 (p.139 of D3.0 spec).
1096                  * o Group Addressed data (aka multicast) originating
1097                  *   at the local sta are sent w/ 3-address format and
1098                  *   address extension mode 00
1099                  * o Individually Addressed data (aka unicast) originating
1100                  *   at the local sta are sent w/ 4-address format and
1101                  *   address extension mode 00
1102                  * o Group Addressed data forwarded from a non-mesh sta are
1103                  *   sent w/ 3-address format and address extension mode 01
1104                  * o Individually Address data from another sta are sent
1105                  *   w/ 4-address format and address extension mode 10
1106                  */
1107                 is4addr = 0;            /* NB: don't use, disable */
1108                 if (!IEEE80211_IS_MULTICAST(eh.ether_dhost)) {
1109                         rt = ieee80211_mesh_rt_find(vap, eh.ether_dhost);
1110                         KASSERT(rt != NULL, ("route is NULL"));
1111                         dir = IEEE80211_FC1_DIR_DSTODS;
1112                         hdrsize += IEEE80211_ADDR_LEN;
1113                         if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) {
1114                                 if (IEEE80211_ADDR_EQ(rt->rt_mesh_gate,
1115                                     vap->iv_myaddr)) {
1116                                         IEEE80211_NOTE_MAC(vap,
1117                                             IEEE80211_MSG_MESH,
1118                                             eh.ether_dhost,
1119                                             "%s", "trying to send to ourself");
1120                                         goto bad;
1121                                 }
1122                                 meshae = IEEE80211_MESH_AE_10;
1123                                 meshhdrsize =
1124                                     sizeof(struct ieee80211_meshcntl_ae10);
1125                         } else {
1126                                 meshae = IEEE80211_MESH_AE_00;
1127                                 meshhdrsize =
1128                                     sizeof(struct ieee80211_meshcntl);
1129                         }
1130                 } else {
1131                         dir = IEEE80211_FC1_DIR_FROMDS;
1132                         if (!IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr)) {
1133                                 /* proxy group */
1134                                 meshae = IEEE80211_MESH_AE_01;
1135                                 meshhdrsize =
1136                                     sizeof(struct ieee80211_meshcntl_ae01);
1137                         } else {
1138                                 /* group */
1139                                 meshae = IEEE80211_MESH_AE_00;
1140                                 meshhdrsize = sizeof(struct ieee80211_meshcntl);
1141                         }
1142                 }
1143         } else {
1144 #endif
1145                 /*
1146                  * 4-address frames need to be generated for:
1147                  * o packets sent through a WDS vap (IEEE80211_M_WDS)
1148                  * o packets sent through a vap marked for relaying
1149                  *   (e.g. a station operating with dynamic WDS)
1150                  */
1151                 is4addr = vap->iv_opmode == IEEE80211_M_WDS ||
1152                     ((vap->iv_flags_ext & IEEE80211_FEXT_4ADDR) &&
1153                      !IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr));
1154                 if (is4addr)
1155                         hdrsize += IEEE80211_ADDR_LEN;
1156                 meshhdrsize = meshae = 0;
1157 #ifdef IEEE80211_SUPPORT_MESH
1158         }
1159 #endif
1160         /*
1161          * Honor driver DATAPAD requirement.
1162          */
1163         if (ic->ic_flags & IEEE80211_F_DATAPAD)
1164                 hdrspace = roundup(hdrsize, sizeof(uint32_t));
1165         else
1166                 hdrspace = hdrsize;
1167
1168         if (__predict_true((m->m_flags & M_FF) == 0)) {
1169                 /*
1170                  * Normal frame.
1171                  */
1172                 m = ieee80211_mbuf_adjust(vap, hdrspace + meshhdrsize, key, m);
1173                 if (m == NULL) {
1174                         /* NB: ieee80211_mbuf_adjust handles msgs+statistics */
1175                         goto bad;
1176                 }
1177                 /* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
1178                 m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
1179                 llc = mtod(m, struct llc *);
1180                 llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1181                 llc->llc_control = LLC_UI;
1182                 llc->llc_snap.org_code[0] = 0;
1183                 llc->llc_snap.org_code[1] = 0;
1184                 llc->llc_snap.org_code[2] = 0;
1185                 llc->llc_snap.ether_type = eh.ether_type;
1186         } else {
1187 #ifdef IEEE80211_SUPPORT_SUPERG
1188                 /*
1189                  * Aggregated frame.
1190                  */
1191                 m = ieee80211_ff_encap(vap, m, hdrspace + meshhdrsize, key);
1192                 if (m == NULL)
1193 #endif
1194                         goto bad;
1195         }
1196         datalen = m->m_pkthdr.len;              /* NB: w/o 802.11 header */
1197
1198         M_PREPEND(m, hdrspace + meshhdrsize, M_NOWAIT);
1199         if (m == NULL) {
1200                 vap->iv_stats.is_tx_nobuf++;
1201                 goto bad;
1202         }
1203         wh = mtod(m, struct ieee80211_frame *);
1204         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
1205         *(uint16_t *)wh->i_dur = 0;
1206         qos = NULL;     /* NB: quiet compiler */
1207         if (is4addr) {
1208                 wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
1209                 IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
1210                 IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1211                 IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1212                 IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost);
1213         } else switch (vap->iv_opmode) {
1214         case IEEE80211_M_STA:
1215                 wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
1216                 IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
1217                 IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1218                 IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1219                 break;
1220         case IEEE80211_M_IBSS:
1221         case IEEE80211_M_AHDEMO:
1222                 wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1223                 IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1224                 IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1225                 /*
1226                  * NB: always use the bssid from iv_bss as the
1227                  *     neighbor's may be stale after an ibss merge
1228                  */
1229                 IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_bssid);
1230                 break;
1231         case IEEE80211_M_HOSTAP:
1232                 wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1233                 IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1234                 IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
1235                 IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
1236                 break;
1237 #ifdef IEEE80211_SUPPORT_MESH
1238         case IEEE80211_M_MBSS:
1239                 /* NB: offset by hdrspace to deal with DATAPAD */
1240                 mc = (struct ieee80211_meshcntl_ae10 *)
1241                      (mtod(m, uint8_t *) + hdrspace);
1242                 wh->i_fc[1] = dir;
1243                 switch (meshae) {
1244                 case IEEE80211_MESH_AE_00:      /* no proxy */
1245                         mc->mc_flags = 0;
1246                         if (dir == IEEE80211_FC1_DIR_DSTODS) { /* ucast */
1247                                 IEEE80211_ADDR_COPY(wh->i_addr1,
1248                                     ni->ni_macaddr);
1249                                 IEEE80211_ADDR_COPY(wh->i_addr2,
1250                                     vap->iv_myaddr);
1251                                 IEEE80211_ADDR_COPY(wh->i_addr3,
1252                                     eh.ether_dhost);
1253                                 IEEE80211_ADDR_COPY(WH4(wh)->i_addr4,
1254                                     eh.ether_shost);
1255                                 qos =((struct ieee80211_qosframe_addr4 *)
1256                                     wh)->i_qos;
1257                         } else if (dir == IEEE80211_FC1_DIR_FROMDS) {
1258                                  /* mcast */
1259                                 IEEE80211_ADDR_COPY(wh->i_addr1,
1260                                     eh.ether_dhost);
1261                                 IEEE80211_ADDR_COPY(wh->i_addr2,
1262                                     vap->iv_myaddr);
1263                                 IEEE80211_ADDR_COPY(wh->i_addr3,
1264                                     eh.ether_shost);
1265                                 qos = ((struct ieee80211_qosframe *)
1266                                     wh)->i_qos;
1267                         }
1268                         break;
1269                 case IEEE80211_MESH_AE_01:      /* mcast, proxy */
1270                         wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1271                         IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1272                         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1273                         IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_myaddr);
1274                         mc->mc_flags = 1;
1275                         IEEE80211_ADDR_COPY(MC01(mc)->mc_addr4,
1276                             eh.ether_shost);
1277                         qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1278                         break;
1279                 case IEEE80211_MESH_AE_10:      /* ucast, proxy */
1280                         KASSERT(rt != NULL, ("route is NULL"));
1281                         IEEE80211_ADDR_COPY(wh->i_addr1, rt->rt_nexthop);
1282                         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1283                         IEEE80211_ADDR_COPY(wh->i_addr3, rt->rt_mesh_gate);
1284                         IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, vap->iv_myaddr);
1285                         mc->mc_flags = IEEE80211_MESH_AE_10;
1286                         IEEE80211_ADDR_COPY(mc->mc_addr5, eh.ether_dhost);
1287                         IEEE80211_ADDR_COPY(mc->mc_addr6, eh.ether_shost);
1288                         qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1289                         break;
1290                 default:
1291                         KASSERT(0, ("meshae %d", meshae));
1292                         break;
1293                 }
1294                 mc->mc_ttl = ms->ms_ttl;
1295                 ms->ms_seq++;
1296                 LE_WRITE_4(mc->mc_seq, ms->ms_seq);
1297                 break;
1298 #endif
1299         case IEEE80211_M_WDS:           /* NB: is4addr should always be true */
1300         default:
1301                 goto bad;
1302         }
1303         if (m->m_flags & M_MORE_DATA)
1304                 wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
1305         if (addqos) {
1306                 int ac, tid;
1307
1308                 if (is4addr) {
1309                         qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1310                 /* NB: mesh case handled earlier */
1311                 } else if (vap->iv_opmode != IEEE80211_M_MBSS)
1312                         qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1313                 ac = M_WME_GETAC(m);
1314                 /* map from access class/queue to 11e header priorty value */
1315                 tid = WME_AC_TO_TID(ac);
1316                 qos[0] = tid & IEEE80211_QOS_TID;
1317                 if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
1318                         qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
1319 #ifdef IEEE80211_SUPPORT_MESH
1320                 if (vap->iv_opmode == IEEE80211_M_MBSS)
1321                         qos[1] = IEEE80211_QOS_MC;
1322                 else
1323 #endif
1324                         qos[1] = 0;
1325                 wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
1326
1327                 if ((m->m_flags & M_AMPDU_MPDU) == 0) {
1328                         /*
1329                          * NB: don't assign a sequence # to potential
1330                          * aggregates; we expect this happens at the
1331                          * point the frame comes off any aggregation q
1332                          * as otherwise we may introduce holes in the
1333                          * BA sequence space and/or make window accouting
1334                          * more difficult.
1335                          *
1336                          * XXX may want to control this with a driver
1337                          * capability; this may also change when we pull
1338                          * aggregation up into net80211
1339                          */
1340                         seqno = ni->ni_txseqs[tid]++;
1341                         *(uint16_t *)wh->i_seq =
1342                             htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1343                         M_SEQNO_SET(m, seqno);
1344                 }
1345         } else {
1346                 seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
1347                 *(uint16_t *)wh->i_seq =
1348                     htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1349                 M_SEQNO_SET(m, seqno);
1350         }
1351
1352
1353         /* check if xmit fragmentation is required */
1354         txfrag = (m->m_pkthdr.len > vap->iv_fragthreshold &&
1355             !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1356             (vap->iv_caps & IEEE80211_C_TXFRAG) &&
1357             (m->m_flags & (M_FF | M_AMPDU_MPDU)) == 0);
1358         if (key != NULL) {
1359                 /*
1360                  * IEEE 802.1X: send EAPOL frames always in the clear.
1361                  * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
1362                  */
1363                 if ((m->m_flags & M_EAPOL) == 0 ||
1364                     ((vap->iv_flags & IEEE80211_F_WPA) &&
1365                      (vap->iv_opmode == IEEE80211_M_STA ?
1366                       !IEEE80211_KEY_UNDEFINED(key) :
1367                       !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
1368                         wh->i_fc[1] |= IEEE80211_FC1_WEP;
1369                         if (!ieee80211_crypto_enmic(vap, key, m, txfrag)) {
1370                                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT,
1371                                     eh.ether_dhost,
1372                                     "%s", "enmic failed, discard frame");
1373                                 vap->iv_stats.is_crypto_enmicfail++;
1374                                 goto bad;
1375                         }
1376                 }
1377         }
1378         if (txfrag && !ieee80211_fragment(vap, m, hdrsize,
1379             key != NULL ? key->wk_cipher->ic_header : 0, vap->iv_fragthreshold))
1380                 goto bad;
1381
1382         m->m_flags |= M_ENCAP;          /* mark encapsulated */
1383
1384         IEEE80211_NODE_STAT(ni, tx_data);
1385         if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1386                 IEEE80211_NODE_STAT(ni, tx_mcast);
1387                 m->m_flags |= M_MCAST;
1388         } else
1389                 IEEE80211_NODE_STAT(ni, tx_ucast);
1390         IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
1391
1392         return m;
1393 bad:
1394         if (m != NULL)
1395                 m_freem(m);
1396         return NULL;
1397 #undef WH4
1398 #undef MC01
1399 }
1400
1401 /*
1402  * Fragment the frame according to the specified mtu.
1403  * The size of the 802.11 header (w/o padding) is provided
1404  * so we don't need to recalculate it.  We create a new
1405  * mbuf for each fragment and chain it through m_nextpkt;
1406  * we might be able to optimize this by reusing the original
1407  * packet's mbufs but that is significantly more complicated.
1408  */
1409 static int
1410 ieee80211_fragment(struct ieee80211vap *vap, struct mbuf *m0,
1411         u_int hdrsize, u_int ciphdrsize, u_int mtu)
1412 {
1413         struct ieee80211_frame *wh, *whf;
1414         struct mbuf *m, *prev, *next;
1415         u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1416
1417         KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1418         KASSERT(m0->m_pkthdr.len > mtu,
1419                 ("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1420
1421         wh = mtod(m0, struct ieee80211_frame *);
1422         /* NB: mark the first frag; it will be propagated below */
1423         wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1424         totalhdrsize = hdrsize + ciphdrsize;
1425         fragno = 1;
1426         off = mtu - ciphdrsize;
1427         remainder = m0->m_pkthdr.len - off;
1428         prev = m0;
1429         do {
1430                 fragsize = totalhdrsize + remainder;
1431                 if (fragsize > mtu)
1432                         fragsize = mtu;
1433                 /* XXX fragsize can be >2048! */
1434                 KASSERT(fragsize < MCLBYTES,
1435                         ("fragment size %u too big!", fragsize));
1436                 if (fragsize > MHLEN)
1437                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1438                 else
1439                         m = m_gethdr(M_NOWAIT, MT_DATA);
1440                 if (m == NULL)
1441                         goto bad;
1442                 /* leave room to prepend any cipher header */
1443                 m_align(m, fragsize - ciphdrsize);
1444
1445                 /*
1446                  * Form the header in the fragment.  Note that since
1447                  * we mark the first fragment with the MORE_FRAG bit
1448                  * it automatically is propagated to each fragment; we
1449                  * need only clear it on the last fragment (done below).
1450                  * NB: frag 1+ dont have Mesh Control field present.
1451                  */
1452                 whf = mtod(m, struct ieee80211_frame *);
1453                 memcpy(whf, wh, hdrsize);
1454 #ifdef IEEE80211_SUPPORT_MESH
1455                 if (vap->iv_opmode == IEEE80211_M_MBSS) {
1456                         if (IEEE80211_IS_DSTODS(wh))
1457                                 ((struct ieee80211_qosframe_addr4 *)
1458                                     whf)->i_qos[1] &= ~IEEE80211_QOS_MC;
1459                         else
1460                                 ((struct ieee80211_qosframe *)
1461                                     whf)->i_qos[1] &= ~IEEE80211_QOS_MC;
1462                 }
1463 #endif
1464                 *(uint16_t *)&whf->i_seq[0] |= htole16(
1465                         (fragno & IEEE80211_SEQ_FRAG_MASK) <<
1466                                 IEEE80211_SEQ_FRAG_SHIFT);
1467                 fragno++;
1468
1469                 payload = fragsize - totalhdrsize;
1470                 /* NB: destination is known to be contiguous */
1471                 m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize);
1472                 m->m_len = hdrsize + payload;
1473                 m->m_pkthdr.len = hdrsize + payload;
1474                 m->m_flags |= M_FRAG;
1475
1476                 /* chain up the fragment */
1477                 prev->m_nextpkt = m;
1478                 prev = m;
1479
1480                 /* deduct fragment just formed */
1481                 remainder -= payload;
1482                 off += payload;
1483         } while (remainder != 0);
1484
1485         /* set the last fragment */
1486         m->m_flags |= M_LASTFRAG;
1487         whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
1488
1489         /* strip first mbuf now that everything has been copied */
1490         m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
1491         m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1492
1493         vap->iv_stats.is_tx_fragframes++;
1494         vap->iv_stats.is_tx_frags += fragno-1;
1495
1496         return 1;
1497 bad:
1498         /* reclaim fragments but leave original frame for caller to free */
1499         for (m = m0->m_nextpkt; m != NULL; m = next) {
1500                 next = m->m_nextpkt;
1501                 m->m_nextpkt = NULL;            /* XXX paranoid */
1502                 m_freem(m);
1503         }
1504         m0->m_nextpkt = NULL;
1505         return 0;
1506 }
1507
1508 /*
1509  * Add a supported rates element id to a frame.
1510  */
1511 uint8_t *
1512 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
1513 {
1514         int nrates;
1515
1516         *frm++ = IEEE80211_ELEMID_RATES;
1517         nrates = rs->rs_nrates;
1518         if (nrates > IEEE80211_RATE_SIZE)
1519                 nrates = IEEE80211_RATE_SIZE;
1520         *frm++ = nrates;
1521         memcpy(frm, rs->rs_rates, nrates);
1522         return frm + nrates;
1523 }
1524
1525 /*
1526  * Add an extended supported rates element id to a frame.
1527  */
1528 uint8_t *
1529 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
1530 {
1531         /*
1532          * Add an extended supported rates element if operating in 11g mode.
1533          */
1534         if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1535                 int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1536                 *frm++ = IEEE80211_ELEMID_XRATES;
1537                 *frm++ = nrates;
1538                 memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1539                 frm += nrates;
1540         }
1541         return frm;
1542 }
1543
1544 /* 
1545  * Add an ssid element to a frame.
1546  */
1547 static uint8_t *
1548 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
1549 {
1550         *frm++ = IEEE80211_ELEMID_SSID;
1551         *frm++ = len;
1552         memcpy(frm, ssid, len);
1553         return frm + len;
1554 }
1555
1556 /*
1557  * Add an erp element to a frame.
1558  */
1559 static uint8_t *
1560 ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
1561 {
1562         uint8_t erp;
1563
1564         *frm++ = IEEE80211_ELEMID_ERP;
1565         *frm++ = 1;
1566         erp = 0;
1567         if (ic->ic_nonerpsta != 0)
1568                 erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1569         if (ic->ic_flags & IEEE80211_F_USEPROT)
1570                 erp |= IEEE80211_ERP_USE_PROTECTION;
1571         if (ic->ic_flags & IEEE80211_F_USEBARKER)
1572                 erp |= IEEE80211_ERP_LONG_PREAMBLE;
1573         *frm++ = erp;
1574         return frm;
1575 }
1576
1577 /*
1578  * Add a CFParams element to a frame.
1579  */
1580 static uint8_t *
1581 ieee80211_add_cfparms(uint8_t *frm, struct ieee80211com *ic)
1582 {
1583 #define ADDSHORT(frm, v) do {   \
1584         LE_WRITE_2(frm, v);     \
1585         frm += 2;               \
1586 } while (0)
1587         *frm++ = IEEE80211_ELEMID_CFPARMS;
1588         *frm++ = 6;
1589         *frm++ = 0;             /* CFP count */
1590         *frm++ = 2;             /* CFP period */
1591         ADDSHORT(frm, 0);       /* CFP MaxDuration (TU) */
1592         ADDSHORT(frm, 0);       /* CFP CurRemaining (TU) */
1593         return frm;
1594 #undef ADDSHORT
1595 }
1596
1597 static __inline uint8_t *
1598 add_appie(uint8_t *frm, const struct ieee80211_appie *ie)
1599 {
1600         memcpy(frm, ie->ie_data, ie->ie_len);
1601         return frm + ie->ie_len;
1602 }
1603
1604 static __inline uint8_t *
1605 add_ie(uint8_t *frm, const uint8_t *ie)
1606 {
1607         memcpy(frm, ie, 2 + ie[1]);
1608         return frm + 2 + ie[1];
1609 }
1610
1611 #define WME_OUI_BYTES           0x00, 0x50, 0xf2
1612 /*
1613  * Add a WME information element to a frame.
1614  */
1615 static uint8_t *
1616 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
1617 {
1618         static const struct ieee80211_wme_info info = {
1619                 .wme_id         = IEEE80211_ELEMID_VENDOR,
1620                 .wme_len        = sizeof(struct ieee80211_wme_info) - 2,
1621                 .wme_oui        = { WME_OUI_BYTES },
1622                 .wme_type       = WME_OUI_TYPE,
1623                 .wme_subtype    = WME_INFO_OUI_SUBTYPE,
1624                 .wme_version    = WME_VERSION,
1625                 .wme_info       = 0,
1626         };
1627         memcpy(frm, &info, sizeof(info));
1628         return frm + sizeof(info); 
1629 }
1630
1631 /*
1632  * Add a WME parameters element to a frame.
1633  */
1634 static uint8_t *
1635 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
1636 {
1637 #define SM(_v, _f)      (((_v) << _f##_S) & _f)
1638 #define ADDSHORT(frm, v) do {   \
1639         LE_WRITE_2(frm, v);     \
1640         frm += 2;               \
1641 } while (0)
1642         /* NB: this works 'cuz a param has an info at the front */
1643         static const struct ieee80211_wme_info param = {
1644                 .wme_id         = IEEE80211_ELEMID_VENDOR,
1645                 .wme_len        = sizeof(struct ieee80211_wme_param) - 2,
1646                 .wme_oui        = { WME_OUI_BYTES },
1647                 .wme_type       = WME_OUI_TYPE,
1648                 .wme_subtype    = WME_PARAM_OUI_SUBTYPE,
1649                 .wme_version    = WME_VERSION,
1650         };
1651         int i;
1652
1653         memcpy(frm, &param, sizeof(param));
1654         frm += __offsetof(struct ieee80211_wme_info, wme_info);
1655         *frm++ = wme->wme_bssChanParams.cap_info;       /* AC info */
1656         *frm++ = 0;                                     /* reserved field */
1657         for (i = 0; i < WME_NUM_AC; i++) {
1658                 const struct wmeParams *ac =
1659                        &wme->wme_bssChanParams.cap_wmeParams[i];
1660                 *frm++ = SM(i, WME_PARAM_ACI)
1661                        | SM(ac->wmep_acm, WME_PARAM_ACM)
1662                        | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1663                        ;
1664                 *frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1665                        | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1666                        ;
1667                 ADDSHORT(frm, ac->wmep_txopLimit);
1668         }
1669         return frm;
1670 #undef SM
1671 #undef ADDSHORT
1672 }
1673 #undef WME_OUI_BYTES
1674
1675 /*
1676  * Add an 11h Power Constraint element to a frame.
1677  */
1678 static uint8_t *
1679 ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap)
1680 {
1681         const struct ieee80211_channel *c = vap->iv_bss->ni_chan;
1682         /* XXX per-vap tx power limit? */
1683         int8_t limit = vap->iv_ic->ic_txpowlimit / 2;
1684
1685         frm[0] = IEEE80211_ELEMID_PWRCNSTR;
1686         frm[1] = 1;
1687         frm[2] = c->ic_maxregpower > limit ?  c->ic_maxregpower - limit : 0;
1688         return frm + 3;
1689 }
1690
1691 /*
1692  * Add an 11h Power Capability element to a frame.
1693  */
1694 static uint8_t *
1695 ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c)
1696 {
1697         frm[0] = IEEE80211_ELEMID_PWRCAP;
1698         frm[1] = 2;
1699         frm[2] = c->ic_minpower;
1700         frm[3] = c->ic_maxpower;
1701         return frm + 4;
1702 }
1703
1704 /*
1705  * Add an 11h Supported Channels element to a frame.
1706  */
1707 static uint8_t *
1708 ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic)
1709 {
1710         static const int ielen = 26;
1711
1712         frm[0] = IEEE80211_ELEMID_SUPPCHAN;
1713         frm[1] = ielen;
1714         /* XXX not correct */
1715         memcpy(frm+2, ic->ic_chan_avail, ielen);
1716         return frm + 2 + ielen;
1717 }
1718
1719 /*
1720  * Add an 11h Quiet time element to a frame.
1721  */
1722 static uint8_t *
1723 ieee80211_add_quiet(uint8_t *frm, struct ieee80211vap *vap)
1724 {
1725         struct ieee80211_quiet_ie *quiet = (struct ieee80211_quiet_ie *) frm;
1726
1727         quiet->quiet_ie = IEEE80211_ELEMID_QUIET;
1728         quiet->len = 6;
1729         if (vap->iv_quiet_count_value == 1)
1730                 vap->iv_quiet_count_value = vap->iv_quiet_count;
1731         else if (vap->iv_quiet_count_value > 1)
1732                 vap->iv_quiet_count_value--;
1733
1734         if (vap->iv_quiet_count_value == 0) {
1735                 /* value 0 is reserved as per 802.11h standerd */
1736                 vap->iv_quiet_count_value = 1;
1737         }
1738
1739         quiet->tbttcount = vap->iv_quiet_count_value;
1740         quiet->period = vap->iv_quiet_period;
1741         quiet->duration = htole16(vap->iv_quiet_duration);
1742         quiet->offset = htole16(vap->iv_quiet_offset);
1743         return frm + sizeof(*quiet);
1744 }
1745
1746 /*
1747  * Add an 11h Channel Switch Announcement element to a frame.
1748  * Note that we use the per-vap CSA count to adjust the global
1749  * counter so we can use this routine to form probe response
1750  * frames and get the current count.
1751  */
1752 static uint8_t *
1753 ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap)
1754 {
1755         struct ieee80211com *ic = vap->iv_ic;
1756         struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm;
1757
1758         csa->csa_ie = IEEE80211_ELEMID_CSA;
1759         csa->csa_len = 3;
1760         csa->csa_mode = 1;              /* XXX force quiet on channel */
1761         csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan);
1762         csa->csa_count = ic->ic_csa_count - vap->iv_csa_count;
1763         return frm + sizeof(*csa);
1764 }
1765
1766 /*
1767  * Add an 11h country information element to a frame.
1768  */
1769 static uint8_t *
1770 ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic)
1771 {
1772
1773         if (ic->ic_countryie == NULL ||
1774             ic->ic_countryie_chan != ic->ic_bsschan) {
1775                 /*
1776                  * Handle lazy construction of ie.  This is done on
1777                  * first use and after a channel change that requires
1778                  * re-calculation.
1779                  */
1780                 if (ic->ic_countryie != NULL)
1781                         free(ic->ic_countryie, M_80211_NODE_IE);
1782                 ic->ic_countryie = ieee80211_alloc_countryie(ic);
1783                 if (ic->ic_countryie == NULL)
1784                         return frm;
1785                 ic->ic_countryie_chan = ic->ic_bsschan;
1786         }
1787         return add_appie(frm, ic->ic_countryie);
1788 }
1789
1790 /*
1791  * Send a probe request frame with the specified ssid
1792  * and any optional information element data.
1793  */
1794 int
1795 ieee80211_send_probereq(struct ieee80211_node *ni,
1796         const uint8_t sa[IEEE80211_ADDR_LEN],
1797         const uint8_t da[IEEE80211_ADDR_LEN],
1798         const uint8_t bssid[IEEE80211_ADDR_LEN],
1799         const uint8_t *ssid, size_t ssidlen)
1800 {
1801         struct ieee80211vap *vap = ni->ni_vap;
1802         struct ieee80211com *ic = ni->ni_ic;
1803         const struct ieee80211_txparam *tp;
1804         struct ieee80211_bpf_params params;
1805         struct ieee80211_frame *wh;
1806         const struct ieee80211_rateset *rs;
1807         struct mbuf *m;
1808         uint8_t *frm;
1809
1810         if (vap->iv_state == IEEE80211_S_CAC) {
1811                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
1812                     "block %s frame in CAC state", "probe request");
1813                 vap->iv_stats.is_tx_badstate++;
1814                 return EIO;             /* XXX */
1815         }
1816
1817         /*
1818          * Hold a reference on the node so it doesn't go away until after
1819          * the xmit is complete all the way in the driver.  On error we
1820          * will remove our reference.
1821          */
1822         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1823                 "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1824                 __func__, __LINE__,
1825                 ni, ether_sprintf(ni->ni_macaddr),
1826                 ieee80211_node_refcnt(ni)+1);
1827         ieee80211_ref_node(ni);
1828
1829         /*
1830          * prreq frame format
1831          *      [tlv] ssid
1832          *      [tlv] supported rates
1833          *      [tlv] RSN (optional)
1834          *      [tlv] extended supported rates
1835          *      [tlv] WPA (optional)
1836          *      [tlv] user-specified ie's
1837          */
1838         m = ieee80211_getmgtframe(&frm,
1839                  ic->ic_headroom + sizeof(struct ieee80211_frame),
1840                  2 + IEEE80211_NWID_LEN
1841                + 2 + IEEE80211_RATE_SIZE
1842                + sizeof(struct ieee80211_ie_wpa)
1843                + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1844                + sizeof(struct ieee80211_ie_wpa)
1845                + (vap->iv_appie_probereq != NULL ?
1846                    vap->iv_appie_probereq->ie_len : 0)
1847         );
1848         if (m == NULL) {
1849                 vap->iv_stats.is_tx_nobuf++;
1850                 ieee80211_free_node(ni);
1851                 return ENOMEM;
1852         }
1853
1854         frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1855         rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1856         frm = ieee80211_add_rates(frm, rs);
1857         if (vap->iv_flags & IEEE80211_F_WPA2) {
1858                 if (vap->iv_rsn_ie != NULL)
1859                         frm = add_ie(frm, vap->iv_rsn_ie);
1860                 /* XXX else complain? */
1861         }
1862         frm = ieee80211_add_xrates(frm, rs);
1863         if (vap->iv_flags & IEEE80211_F_WPA1) {
1864                 if (vap->iv_wpa_ie != NULL)
1865                         frm = add_ie(frm, vap->iv_wpa_ie);
1866                 /* XXX else complain? */
1867         }
1868         if (vap->iv_appie_probereq != NULL)
1869                 frm = add_appie(frm, vap->iv_appie_probereq);
1870         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1871
1872         KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ieee80211_frame),
1873             ("leading space %zd", M_LEADINGSPACE(m)));
1874         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
1875         if (m == NULL) {
1876                 /* NB: cannot happen */
1877                 ieee80211_free_node(ni);
1878                 return ENOMEM;
1879         }
1880
1881         wh = mtod(m, struct ieee80211_frame *);
1882         ieee80211_send_setup(ni, m,
1883              IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1884              IEEE80211_NONQOS_TID, sa, da, bssid);
1885         /* XXX power management? */
1886         m->m_flags |= M_ENCAP;          /* mark encapsulated */
1887
1888         M_WME_SETAC(m, WME_AC_BE);
1889
1890         IEEE80211_NODE_STAT(ni, tx_probereq);
1891         IEEE80211_NODE_STAT(ni, tx_mgmt);
1892
1893         IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1894             "send probe req on channel %u bssid %s ssid \"%.*s\"\n",
1895             ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(bssid),
1896             ssidlen, ssid);
1897
1898         memset(&params, 0, sizeof(params));
1899         params.ibp_pri = M_WME_GETAC(m);
1900         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1901         params.ibp_rate0 = tp->mgmtrate;
1902         if (IEEE80211_IS_MULTICAST(da)) {
1903                 params.ibp_flags |= IEEE80211_BPF_NOACK;
1904                 params.ibp_try0 = 1;
1905         } else
1906                 params.ibp_try0 = tp->maxretry;
1907         params.ibp_power = ni->ni_txpower;
1908         return ic->ic_raw_xmit(ni, m, &params);
1909 }
1910
1911 /*
1912  * Calculate capability information for mgt frames.
1913  */
1914 uint16_t
1915 ieee80211_getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan)
1916 {
1917         struct ieee80211com *ic = vap->iv_ic;
1918         uint16_t capinfo;
1919
1920         KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode"));
1921
1922         if (vap->iv_opmode == IEEE80211_M_HOSTAP)
1923                 capinfo = IEEE80211_CAPINFO_ESS;
1924         else if (vap->iv_opmode == IEEE80211_M_IBSS)
1925                 capinfo = IEEE80211_CAPINFO_IBSS;
1926         else
1927                 capinfo = 0;
1928         if (vap->iv_flags & IEEE80211_F_PRIVACY)
1929                 capinfo |= IEEE80211_CAPINFO_PRIVACY;
1930         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1931             IEEE80211_IS_CHAN_2GHZ(chan))
1932                 capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1933         if (ic->ic_flags & IEEE80211_F_SHSLOT)
1934                 capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1935         if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH))
1936                 capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
1937         return capinfo;
1938 }
1939
1940 /*
1941  * Send a management frame.  The node is for the destination (or ic_bss
1942  * when in station mode).  Nodes other than ic_bss have their reference
1943  * count bumped to reflect our use for an indeterminant time.
1944  */
1945 int
1946 ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg)
1947 {
1948 #define HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
1949 #define senderr(_x, _v) do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
1950         struct ieee80211vap *vap = ni->ni_vap;
1951         struct ieee80211com *ic = ni->ni_ic;
1952         struct ieee80211_node *bss = vap->iv_bss;
1953         struct ieee80211_bpf_params params;
1954         struct mbuf *m;
1955         uint8_t *frm;
1956         uint16_t capinfo;
1957         int has_challenge, is_shared_key, ret, status;
1958
1959         KASSERT(ni != NULL, ("null node"));
1960
1961         /*
1962          * Hold a reference on the node so it doesn't go away until after
1963          * the xmit is complete all the way in the driver.  On error we
1964          * will remove our reference.
1965          */
1966         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1967                 "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1968                 __func__, __LINE__,
1969                 ni, ether_sprintf(ni->ni_macaddr),
1970                 ieee80211_node_refcnt(ni)+1);
1971         ieee80211_ref_node(ni);
1972
1973         memset(&params, 0, sizeof(params));
1974         switch (type) {
1975
1976         case IEEE80211_FC0_SUBTYPE_AUTH:
1977                 status = arg >> 16;
1978                 arg &= 0xffff;
1979                 has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1980                     arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1981                     ni->ni_challenge != NULL);
1982
1983                 /*
1984                  * Deduce whether we're doing open authentication or
1985                  * shared key authentication.  We do the latter if
1986                  * we're in the middle of a shared key authentication
1987                  * handshake or if we're initiating an authentication
1988                  * request and configured to use shared key.
1989                  */
1990                 is_shared_key = has_challenge ||
1991                      arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1992                      (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1993                       bss->ni_authmode == IEEE80211_AUTH_SHARED);
1994
1995                 m = ieee80211_getmgtframe(&frm,
1996                           ic->ic_headroom + sizeof(struct ieee80211_frame),
1997                           3 * sizeof(uint16_t)
1998                         + (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1999                                 sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
2000                 );
2001                 if (m == NULL)
2002                         senderr(ENOMEM, is_tx_nobuf);
2003
2004                 ((uint16_t *)frm)[0] =
2005                     (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
2006                                     : htole16(IEEE80211_AUTH_ALG_OPEN);
2007                 ((uint16_t *)frm)[1] = htole16(arg);    /* sequence number */
2008                 ((uint16_t *)frm)[2] = htole16(status);/* status */
2009
2010                 if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
2011                         ((uint16_t *)frm)[3] =
2012                             htole16((IEEE80211_CHALLENGE_LEN << 8) |
2013                             IEEE80211_ELEMID_CHALLENGE);
2014                         memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
2015                             IEEE80211_CHALLENGE_LEN);
2016                         m->m_pkthdr.len = m->m_len =
2017                                 4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
2018                         if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
2019                                 IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2020                                     "request encrypt frame (%s)", __func__);
2021                                 /* mark frame for encryption */
2022                                 params.ibp_flags |= IEEE80211_BPF_CRYPTO;
2023                         }
2024                 } else
2025                         m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
2026
2027                 /* XXX not right for shared key */
2028                 if (status == IEEE80211_STATUS_SUCCESS)
2029                         IEEE80211_NODE_STAT(ni, tx_auth);
2030                 else
2031                         IEEE80211_NODE_STAT(ni, tx_auth_fail);
2032
2033                 if (vap->iv_opmode == IEEE80211_M_STA)
2034                         ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2035                                 (void *) vap->iv_state);
2036                 break;
2037
2038         case IEEE80211_FC0_SUBTYPE_DEAUTH:
2039                 IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2040                     "send station deauthenticate (reason %d)", arg);
2041                 m = ieee80211_getmgtframe(&frm,
2042                         ic->ic_headroom + sizeof(struct ieee80211_frame),
2043                         sizeof(uint16_t));
2044                 if (m == NULL)
2045                         senderr(ENOMEM, is_tx_nobuf);
2046                 *(uint16_t *)frm = htole16(arg);        /* reason */
2047                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2048
2049                 IEEE80211_NODE_STAT(ni, tx_deauth);
2050                 IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
2051
2052                 ieee80211_node_unauthorize(ni);         /* port closed */
2053                 break;
2054
2055         case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2056         case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
2057                 /*
2058                  * asreq frame format
2059                  *      [2] capability information
2060                  *      [2] listen interval
2061                  *      [6*] current AP address (reassoc only)
2062                  *      [tlv] ssid
2063                  *      [tlv] supported rates
2064                  *      [tlv] extended supported rates
2065                  *      [4] power capability (optional)
2066                  *      [28] supported channels (optional)
2067                  *      [tlv] HT capabilities
2068                  *      [tlv] WME (optional)
2069                  *      [tlv] Vendor OUI HT capabilities (optional)
2070                  *      [tlv] Atheros capabilities (if negotiated)
2071                  *      [tlv] AppIE's (optional)
2072                  */
2073                 m = ieee80211_getmgtframe(&frm,
2074                          ic->ic_headroom + sizeof(struct ieee80211_frame),
2075                          sizeof(uint16_t)
2076                        + sizeof(uint16_t)
2077                        + IEEE80211_ADDR_LEN
2078                        + 2 + IEEE80211_NWID_LEN
2079                        + 2 + IEEE80211_RATE_SIZE
2080                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2081                        + 4
2082                        + 2 + 26
2083                        + sizeof(struct ieee80211_wme_info)
2084                        + sizeof(struct ieee80211_ie_htcap)
2085                        + 4 + sizeof(struct ieee80211_ie_htcap)
2086 #ifdef IEEE80211_SUPPORT_SUPERG
2087                        + sizeof(struct ieee80211_ath_ie)
2088 #endif
2089                        + (vap->iv_appie_wpa != NULL ?
2090                                 vap->iv_appie_wpa->ie_len : 0)
2091                        + (vap->iv_appie_assocreq != NULL ?
2092                                 vap->iv_appie_assocreq->ie_len : 0)
2093                 );
2094                 if (m == NULL)
2095                         senderr(ENOMEM, is_tx_nobuf);
2096
2097                 KASSERT(vap->iv_opmode == IEEE80211_M_STA,
2098                     ("wrong mode %u", vap->iv_opmode));
2099                 capinfo = IEEE80211_CAPINFO_ESS;
2100                 if (vap->iv_flags & IEEE80211_F_PRIVACY)
2101                         capinfo |= IEEE80211_CAPINFO_PRIVACY;
2102                 /*
2103                  * NB: Some 11a AP's reject the request when
2104                  *     short premable is set.
2105                  */
2106                 if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2107                     IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
2108                         capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2109                 if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
2110                     (ic->ic_caps & IEEE80211_C_SHSLOT))
2111                         capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2112                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
2113                     (vap->iv_flags & IEEE80211_F_DOTH))
2114                         capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
2115                 *(uint16_t *)frm = htole16(capinfo);
2116                 frm += 2;
2117
2118                 KASSERT(bss->ni_intval != 0, ("beacon interval is zero!"));
2119                 *(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
2120                                                     bss->ni_intval));
2121                 frm += 2;
2122
2123                 if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
2124                         IEEE80211_ADDR_COPY(frm, bss->ni_bssid);
2125                         frm += IEEE80211_ADDR_LEN;
2126                 }
2127
2128                 frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
2129                 frm = ieee80211_add_rates(frm, &ni->ni_rates);
2130                 if (vap->iv_flags & IEEE80211_F_WPA2) {
2131                         if (vap->iv_rsn_ie != NULL)
2132                                 frm = add_ie(frm, vap->iv_rsn_ie);
2133                         /* XXX else complain? */
2134                 }
2135                 frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2136                 if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) {
2137                         frm = ieee80211_add_powercapability(frm,
2138                             ic->ic_curchan);
2139                         frm = ieee80211_add_supportedchannels(frm, ic);
2140                 }
2141                 if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2142                     ni->ni_ies.htcap_ie != NULL &&
2143                     ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP)
2144                         frm = ieee80211_add_htcap(frm, ni);
2145                 if (vap->iv_flags & IEEE80211_F_WPA1) {
2146                         if (vap->iv_wpa_ie != NULL)
2147                                 frm = add_ie(frm, vap->iv_wpa_ie);
2148                         /* XXX else complain */
2149                 }
2150                 if ((ic->ic_flags & IEEE80211_F_WME) &&
2151                     ni->ni_ies.wme_ie != NULL)
2152                         frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
2153                 if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2154                     ni->ni_ies.htcap_ie != NULL &&
2155                     ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR)
2156                         frm = ieee80211_add_htcap_vendor(frm, ni);
2157 #ifdef IEEE80211_SUPPORT_SUPERG
2158                 if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) {
2159                         frm = ieee80211_add_ath(frm, 
2160                                 IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2161                                 ((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2162                                  ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2163                                 vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2164                 }
2165 #endif /* IEEE80211_SUPPORT_SUPERG */
2166                 if (vap->iv_appie_assocreq != NULL)
2167                         frm = add_appie(frm, vap->iv_appie_assocreq);
2168                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2169
2170                 ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2171                         (void *) vap->iv_state);
2172                 break;
2173
2174         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2175         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
2176                 /*
2177                  * asresp frame format
2178                  *      [2] capability information
2179                  *      [2] status
2180                  *      [2] association ID
2181                  *      [tlv] supported rates
2182                  *      [tlv] extended supported rates
2183                  *      [tlv] HT capabilities (standard, if STA enabled)
2184                  *      [tlv] HT information (standard, if STA enabled)
2185                  *      [tlv] WME (if configured and STA enabled)
2186                  *      [tlv] HT capabilities (vendor OUI, if STA enabled)
2187                  *      [tlv] HT information (vendor OUI, if STA enabled)
2188                  *      [tlv] Atheros capabilities (if STA enabled)
2189                  *      [tlv] AppIE's (optional)
2190                  */
2191                 m = ieee80211_getmgtframe(&frm,
2192                          ic->ic_headroom + sizeof(struct ieee80211_frame),
2193                          sizeof(uint16_t)
2194                        + sizeof(uint16_t)
2195                        + sizeof(uint16_t)
2196                        + 2 + IEEE80211_RATE_SIZE
2197                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2198                        + sizeof(struct ieee80211_ie_htcap) + 4
2199                        + sizeof(struct ieee80211_ie_htinfo) + 4
2200                        + sizeof(struct ieee80211_wme_param)
2201 #ifdef IEEE80211_SUPPORT_SUPERG
2202                        + sizeof(struct ieee80211_ath_ie)
2203 #endif
2204                        + (vap->iv_appie_assocresp != NULL ?
2205                                 vap->iv_appie_assocresp->ie_len : 0)
2206                 );
2207                 if (m == NULL)
2208                         senderr(ENOMEM, is_tx_nobuf);
2209
2210                 capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
2211                 *(uint16_t *)frm = htole16(capinfo);
2212                 frm += 2;
2213
2214                 *(uint16_t *)frm = htole16(arg);        /* status */
2215                 frm += 2;
2216
2217                 if (arg == IEEE80211_STATUS_SUCCESS) {
2218                         *(uint16_t *)frm = htole16(ni->ni_associd);
2219                         IEEE80211_NODE_STAT(ni, tx_assoc);
2220                 } else
2221                         IEEE80211_NODE_STAT(ni, tx_assoc_fail);
2222                 frm += 2;
2223
2224                 frm = ieee80211_add_rates(frm, &ni->ni_rates);
2225                 frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2226                 /* NB: respond according to what we received */
2227                 if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
2228                         frm = ieee80211_add_htcap(frm, ni);
2229                         frm = ieee80211_add_htinfo(frm, ni);
2230                 }
2231                 if ((vap->iv_flags & IEEE80211_F_WME) &&
2232                     ni->ni_ies.wme_ie != NULL)
2233                         frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2234                 if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
2235                         frm = ieee80211_add_htcap_vendor(frm, ni);
2236                         frm = ieee80211_add_htinfo_vendor(frm, ni);
2237                 }
2238 #ifdef IEEE80211_SUPPORT_SUPERG
2239                 if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
2240                         frm = ieee80211_add_ath(frm, 
2241                                 IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2242                                 ((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2243                                  ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2244                                 vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2245 #endif /* IEEE80211_SUPPORT_SUPERG */
2246                 if (vap->iv_appie_assocresp != NULL)
2247                         frm = add_appie(frm, vap->iv_appie_assocresp);
2248                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2249                 break;
2250
2251         case IEEE80211_FC0_SUBTYPE_DISASSOC:
2252                 IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2253                     "send station disassociate (reason %d)", arg);
2254                 m = ieee80211_getmgtframe(&frm,
2255                         ic->ic_headroom + sizeof(struct ieee80211_frame),
2256                         sizeof(uint16_t));
2257                 if (m == NULL)
2258                         senderr(ENOMEM, is_tx_nobuf);
2259                 *(uint16_t *)frm = htole16(arg);        /* reason */
2260                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2261
2262                 IEEE80211_NODE_STAT(ni, tx_disassoc);
2263                 IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
2264                 break;
2265
2266         default:
2267                 IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni,
2268                     "invalid mgmt frame type %u", type);
2269                 senderr(EINVAL, is_tx_unknownmgt);
2270                 /* NOTREACHED */
2271         }
2272
2273         /* NB: force non-ProbeResp frames to the highest queue */
2274         params.ibp_pri = WME_AC_VO;
2275         params.ibp_rate0 = bss->ni_txparms->mgmtrate;
2276         /* NB: we know all frames are unicast */
2277         params.ibp_try0 = bss->ni_txparms->maxretry;
2278         params.ibp_power = bss->ni_txpower;
2279         return ieee80211_mgmt_output(ni, m, type, &params);
2280 bad:
2281         ieee80211_free_node(ni);
2282         return ret;
2283 #undef senderr
2284 #undef HTFLAGS
2285 }
2286
2287 /*
2288  * Return an mbuf with a probe response frame in it.
2289  * Space is left to prepend and 802.11 header at the
2290  * front but it's left to the caller to fill in.
2291  */
2292 struct mbuf *
2293 ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy)
2294 {
2295         struct ieee80211vap *vap = bss->ni_vap;
2296         struct ieee80211com *ic = bss->ni_ic;
2297         const struct ieee80211_rateset *rs;
2298         struct mbuf *m;
2299         uint16_t capinfo;
2300         uint8_t *frm;
2301
2302         /*
2303          * probe response frame format
2304          *      [8] time stamp
2305          *      [2] beacon interval
2306          *      [2] cabability information
2307          *      [tlv] ssid
2308          *      [tlv] supported rates
2309          *      [tlv] parameter set (FH/DS)
2310          *      [tlv] parameter set (IBSS)
2311          *      [tlv] country (optional)
2312          *      [3] power control (optional)
2313          *      [5] channel switch announcement (CSA) (optional)
2314          *      [tlv] extended rate phy (ERP)
2315          *      [tlv] extended supported rates
2316          *      [tlv] RSN (optional)
2317          *      [tlv] HT capabilities
2318          *      [tlv] HT information
2319          *      [tlv] WPA (optional)
2320          *      [tlv] WME (optional)
2321          *      [tlv] Vendor OUI HT capabilities (optional)
2322          *      [tlv] Vendor OUI HT information (optional)
2323          *      [tlv] Atheros capabilities
2324          *      [tlv] AppIE's (optional)
2325          *      [tlv] Mesh ID (MBSS)
2326          *      [tlv] Mesh Conf (MBSS)
2327          */
2328         m = ieee80211_getmgtframe(&frm,
2329                  ic->ic_headroom + sizeof(struct ieee80211_frame),
2330                  8
2331                + sizeof(uint16_t)
2332                + sizeof(uint16_t)
2333                + 2 + IEEE80211_NWID_LEN
2334                + 2 + IEEE80211_RATE_SIZE
2335                + 7      /* max(7,3) */
2336                + IEEE80211_COUNTRY_MAX_SIZE
2337                + 3
2338                + sizeof(struct ieee80211_csa_ie)
2339                + sizeof(struct ieee80211_quiet_ie)
2340                + 3
2341                + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2342                + sizeof(struct ieee80211_ie_wpa)
2343                + sizeof(struct ieee80211_ie_htcap)
2344                + sizeof(struct ieee80211_ie_htinfo)
2345                + sizeof(struct ieee80211_ie_wpa)
2346                + sizeof(struct ieee80211_wme_param)
2347                + 4 + sizeof(struct ieee80211_ie_htcap)
2348                + 4 + sizeof(struct ieee80211_ie_htinfo)
2349 #ifdef IEEE80211_SUPPORT_SUPERG
2350                + sizeof(struct ieee80211_ath_ie)
2351 #endif
2352 #ifdef IEEE80211_SUPPORT_MESH
2353                + 2 + IEEE80211_MESHID_LEN
2354                + sizeof(struct ieee80211_meshconf_ie)
2355 #endif
2356                + (vap->iv_appie_proberesp != NULL ?
2357                         vap->iv_appie_proberesp->ie_len : 0)
2358         );
2359         if (m == NULL) {
2360                 vap->iv_stats.is_tx_nobuf++;
2361                 return NULL;
2362         }
2363
2364         memset(frm, 0, 8);      /* timestamp should be filled later */
2365         frm += 8;
2366         *(uint16_t *)frm = htole16(bss->ni_intval);
2367         frm += 2;
2368         capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
2369         *(uint16_t *)frm = htole16(capinfo);
2370         frm += 2;
2371
2372         frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen);
2373         rs = ieee80211_get_suprates(ic, bss->ni_chan);
2374         frm = ieee80211_add_rates(frm, rs);
2375
2376         if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) {
2377                 *frm++ = IEEE80211_ELEMID_FHPARMS;
2378                 *frm++ = 5;
2379                 *frm++ = bss->ni_fhdwell & 0x00ff;
2380                 *frm++ = (bss->ni_fhdwell >> 8) & 0x00ff;
2381                 *frm++ = IEEE80211_FH_CHANSET(
2382                     ieee80211_chan2ieee(ic, bss->ni_chan));
2383                 *frm++ = IEEE80211_FH_CHANPAT(
2384                     ieee80211_chan2ieee(ic, bss->ni_chan));
2385                 *frm++ = bss->ni_fhindex;
2386         } else {
2387                 *frm++ = IEEE80211_ELEMID_DSPARMS;
2388                 *frm++ = 1;
2389                 *frm++ = ieee80211_chan2ieee(ic, bss->ni_chan);
2390         }
2391
2392         if (vap->iv_opmode == IEEE80211_M_IBSS) {
2393                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
2394                 *frm++ = 2;
2395                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
2396         }
2397         if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2398             (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2399                 frm = ieee80211_add_countryie(frm, ic);
2400         if (vap->iv_flags & IEEE80211_F_DOTH) {
2401                 if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan))
2402                         frm = ieee80211_add_powerconstraint(frm, vap);
2403                 if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2404                         frm = ieee80211_add_csa(frm, vap);
2405         }
2406         if (vap->iv_flags & IEEE80211_F_DOTH) {
2407                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
2408                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
2409                         if (vap->iv_quiet)
2410                                 frm = ieee80211_add_quiet(frm, vap);
2411                 }
2412         }
2413         if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan))
2414                 frm = ieee80211_add_erp(frm, ic);
2415         frm = ieee80211_add_xrates(frm, rs);
2416         if (vap->iv_flags & IEEE80211_F_WPA2) {
2417                 if (vap->iv_rsn_ie != NULL)
2418                         frm = add_ie(frm, vap->iv_rsn_ie);
2419                 /* XXX else complain? */
2420         }
2421         /*
2422          * NB: legacy 11b clients do not get certain ie's.
2423          *     The caller identifies such clients by passing
2424          *     a token in legacy to us.  Could expand this to be
2425          *     any legacy client for stuff like HT ie's.
2426          */
2427         if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2428             legacy != IEEE80211_SEND_LEGACY_11B) {
2429                 frm = ieee80211_add_htcap(frm, bss);
2430                 frm = ieee80211_add_htinfo(frm, bss);
2431         }
2432         if (vap->iv_flags & IEEE80211_F_WPA1) {
2433                 if (vap->iv_wpa_ie != NULL)
2434                         frm = add_ie(frm, vap->iv_wpa_ie);
2435                 /* XXX else complain? */
2436         }
2437         if (vap->iv_flags & IEEE80211_F_WME)
2438                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2439         if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2440             (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT) &&
2441             legacy != IEEE80211_SEND_LEGACY_11B) {
2442                 frm = ieee80211_add_htcap_vendor(frm, bss);
2443                 frm = ieee80211_add_htinfo_vendor(frm, bss);
2444         }
2445 #ifdef IEEE80211_SUPPORT_SUPERG
2446         if ((vap->iv_flags & IEEE80211_F_ATHEROS) &&
2447             legacy != IEEE80211_SEND_LEGACY_11B)
2448                 frm = ieee80211_add_athcaps(frm, bss);
2449 #endif
2450         if (vap->iv_appie_proberesp != NULL)
2451                 frm = add_appie(frm, vap->iv_appie_proberesp);
2452 #ifdef IEEE80211_SUPPORT_MESH
2453         if (vap->iv_opmode == IEEE80211_M_MBSS) {
2454                 frm = ieee80211_add_meshid(frm, vap);
2455                 frm = ieee80211_add_meshconf(frm, vap);
2456         }
2457 #endif
2458         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2459
2460         return m;
2461 }
2462
2463 /*
2464  * Send a probe response frame to the specified mac address.
2465  * This does not go through the normal mgt frame api so we
2466  * can specify the destination address and re-use the bss node
2467  * for the sta reference.
2468  */
2469 int
2470 ieee80211_send_proberesp(struct ieee80211vap *vap,
2471         const uint8_t da[IEEE80211_ADDR_LEN], int legacy)
2472 {
2473         struct ieee80211_node *bss = vap->iv_bss;
2474         struct ieee80211com *ic = vap->iv_ic;
2475         struct ieee80211_frame *wh;
2476         struct mbuf *m;
2477
2478         if (vap->iv_state == IEEE80211_S_CAC) {
2479                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss,
2480                     "block %s frame in CAC state", "probe response");
2481                 vap->iv_stats.is_tx_badstate++;
2482                 return EIO;             /* XXX */
2483         }
2484
2485         /*
2486          * Hold a reference on the node so it doesn't go away until after
2487          * the xmit is complete all the way in the driver.  On error we
2488          * will remove our reference.
2489          */
2490         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2491             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2492             __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr),
2493             ieee80211_node_refcnt(bss)+1);
2494         ieee80211_ref_node(bss);
2495
2496         m = ieee80211_alloc_proberesp(bss, legacy);
2497         if (m == NULL) {
2498                 ieee80211_free_node(bss);
2499                 return ENOMEM;
2500         }
2501
2502         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
2503         KASSERT(m != NULL, ("no room for header"));
2504
2505         wh = mtod(m, struct ieee80211_frame *);
2506         ieee80211_send_setup(bss, m,
2507              IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP,
2508              IEEE80211_NONQOS_TID, vap->iv_myaddr, da, bss->ni_bssid);
2509         /* XXX power management? */
2510         m->m_flags |= M_ENCAP;          /* mark encapsulated */
2511
2512         M_WME_SETAC(m, WME_AC_BE);
2513
2514         IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
2515             "send probe resp on channel %u to %s%s\n",
2516             ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da),
2517             legacy ? " <legacy>" : "");
2518         IEEE80211_NODE_STAT(bss, tx_mgmt);
2519
2520         return ic->ic_raw_xmit(bss, m, NULL);
2521 }
2522
2523 /*
2524  * Allocate and build a RTS (Request To Send) control frame.
2525  */
2526 struct mbuf *
2527 ieee80211_alloc_rts(struct ieee80211com *ic,
2528         const uint8_t ra[IEEE80211_ADDR_LEN],
2529         const uint8_t ta[IEEE80211_ADDR_LEN],
2530         uint16_t dur)
2531 {
2532         struct ieee80211_frame_rts *rts;
2533         struct mbuf *m;
2534
2535         /* XXX honor ic_headroom */
2536         m = m_gethdr(M_NOWAIT, MT_DATA);
2537         if (m != NULL) {
2538                 rts = mtod(m, struct ieee80211_frame_rts *);
2539                 rts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2540                         IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS;
2541                 rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2542                 *(u_int16_t *)rts->i_dur = htole16(dur);
2543                 IEEE80211_ADDR_COPY(rts->i_ra, ra);
2544                 IEEE80211_ADDR_COPY(rts->i_ta, ta);
2545
2546                 m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
2547         }
2548         return m;
2549 }
2550
2551 /*
2552  * Allocate and build a CTS (Clear To Send) control frame.
2553  */
2554 struct mbuf *
2555 ieee80211_alloc_cts(struct ieee80211com *ic,
2556         const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur)
2557 {
2558         struct ieee80211_frame_cts *cts;
2559         struct mbuf *m;
2560
2561         /* XXX honor ic_headroom */
2562         m = m_gethdr(M_NOWAIT, MT_DATA);
2563         if (m != NULL) {
2564                 cts = mtod(m, struct ieee80211_frame_cts *);
2565                 cts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2566                         IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS;
2567                 cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2568                 *(u_int16_t *)cts->i_dur = htole16(dur);
2569                 IEEE80211_ADDR_COPY(cts->i_ra, ra);
2570
2571                 m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
2572         }
2573         return m;
2574 }
2575
2576 static void
2577 ieee80211_tx_mgt_timeout(void *arg)
2578 {
2579         struct ieee80211_node *ni = arg;
2580         struct ieee80211vap *vap = ni->ni_vap;
2581
2582         if (vap->iv_state != IEEE80211_S_INIT &&
2583             (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2584                 /*
2585                  * NB: it's safe to specify a timeout as the reason here;
2586                  *     it'll only be used in the right state.
2587                  */
2588                 ieee80211_new_state(vap, IEEE80211_S_SCAN,
2589                         IEEE80211_SCAN_FAIL_TIMEOUT);
2590         }
2591 }
2592
2593 static void
2594 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
2595 {
2596         struct ieee80211vap *vap = ni->ni_vap;
2597         enum ieee80211_state ostate = (enum ieee80211_state) arg;
2598
2599         /*
2600          * Frame transmit completed; arrange timer callback.  If
2601          * transmit was successfuly we wait for response.  Otherwise
2602          * we arrange an immediate callback instead of doing the
2603          * callback directly since we don't know what state the driver
2604          * is in (e.g. what locks it is holding).  This work should
2605          * not be too time-critical and not happen too often so the
2606          * added overhead is acceptable.
2607          *
2608          * XXX what happens if !acked but response shows up before callback?
2609          */
2610         if (vap->iv_state == ostate)
2611                 callout_reset(&vap->iv_mgtsend,
2612                         status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
2613                         ieee80211_tx_mgt_timeout, ni);
2614 }
2615
2616 static void
2617 ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm,
2618         struct ieee80211_beacon_offsets *bo, struct ieee80211_node *ni)
2619 {
2620         struct ieee80211vap *vap = ni->ni_vap;
2621         struct ieee80211com *ic = ni->ni_ic;
2622         struct ieee80211_rateset *rs = &ni->ni_rates;
2623         uint16_t capinfo;
2624
2625         /*
2626          * beacon frame format
2627          *      [8] time stamp
2628          *      [2] beacon interval
2629          *      [2] cabability information
2630          *      [tlv] ssid
2631          *      [tlv] supported rates
2632          *      [3] parameter set (DS)
2633          *      [8] CF parameter set (optional)
2634          *      [tlv] parameter set (IBSS/TIM)
2635          *      [tlv] country (optional)
2636          *      [3] power control (optional)
2637          *      [5] channel switch announcement (CSA) (optional)
2638          *      [tlv] extended rate phy (ERP)
2639          *      [tlv] extended supported rates
2640          *      [tlv] RSN parameters
2641          *      [tlv] HT capabilities
2642          *      [tlv] HT information
2643          * XXX Vendor-specific OIDs (e.g. Atheros)
2644          *      [tlv] WPA parameters
2645          *      [tlv] WME parameters
2646          *      [tlv] Vendor OUI HT capabilities (optional)
2647          *      [tlv] Vendor OUI HT information (optional)
2648          *      [tlv] Atheros capabilities (optional)
2649          *      [tlv] TDMA parameters (optional)
2650          *      [tlv] Mesh ID (MBSS)
2651          *      [tlv] Mesh Conf (MBSS)
2652          *      [tlv] application data (optional)
2653          */
2654
2655         memset(bo, 0, sizeof(*bo));
2656
2657         memset(frm, 0, 8);      /* XXX timestamp is set by hardware/driver */
2658         frm += 8;
2659         *(uint16_t *)frm = htole16(ni->ni_intval);
2660         frm += 2;
2661         capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
2662         bo->bo_caps = (uint16_t *)frm;
2663         *(uint16_t *)frm = htole16(capinfo);
2664         frm += 2;
2665         *frm++ = IEEE80211_ELEMID_SSID;
2666         if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) {
2667                 *frm++ = ni->ni_esslen;
2668                 memcpy(frm, ni->ni_essid, ni->ni_esslen);
2669                 frm += ni->ni_esslen;
2670         } else
2671                 *frm++ = 0;
2672         frm = ieee80211_add_rates(frm, rs);
2673         if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) {
2674                 *frm++ = IEEE80211_ELEMID_DSPARMS;
2675                 *frm++ = 1;
2676                 *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
2677         }
2678         if (ic->ic_flags & IEEE80211_F_PCF) {
2679                 bo->bo_cfp = frm;
2680                 frm = ieee80211_add_cfparms(frm, ic);
2681         }
2682         bo->bo_tim = frm;
2683         if (vap->iv_opmode == IEEE80211_M_IBSS) {
2684                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
2685                 *frm++ = 2;
2686                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
2687                 bo->bo_tim_len = 0;
2688         } else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
2689             vap->iv_opmode == IEEE80211_M_MBSS) {
2690                 /* TIM IE is the same for Mesh and Hostap */
2691                 struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
2692
2693                 tie->tim_ie = IEEE80211_ELEMID_TIM;
2694                 tie->tim_len = 4;       /* length */
2695                 tie->tim_count = 0;     /* DTIM count */ 
2696                 tie->tim_period = vap->iv_dtim_period;  /* DTIM period */
2697                 tie->tim_bitctl = 0;    /* bitmap control */
2698                 tie->tim_bitmap[0] = 0; /* Partial Virtual Bitmap */
2699                 frm += sizeof(struct ieee80211_tim_ie);
2700                 bo->bo_tim_len = 1;
2701         }
2702         bo->bo_tim_trailer = frm;
2703         if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2704             (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2705                 frm = ieee80211_add_countryie(frm, ic);
2706         if (vap->iv_flags & IEEE80211_F_DOTH) {
2707                 if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
2708                         frm = ieee80211_add_powerconstraint(frm, vap);
2709                 bo->bo_csa = frm;
2710                 if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2711                         frm = ieee80211_add_csa(frm, vap);      
2712         } else
2713                 bo->bo_csa = frm;
2714
2715         if (vap->iv_flags & IEEE80211_F_DOTH) {
2716                 bo->bo_quiet = frm;
2717                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
2718                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
2719                         if (vap->iv_quiet)
2720                                 frm = ieee80211_add_quiet(frm,vap);
2721                 }
2722         } else
2723                 bo->bo_quiet = frm;
2724
2725         if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) {
2726                 bo->bo_erp = frm;
2727                 frm = ieee80211_add_erp(frm, ic);
2728         }
2729         frm = ieee80211_add_xrates(frm, rs);
2730         if (vap->iv_flags & IEEE80211_F_WPA2) {
2731                 if (vap->iv_rsn_ie != NULL)
2732                         frm = add_ie(frm, vap->iv_rsn_ie);
2733                 /* XXX else complain */
2734         }
2735         if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
2736                 frm = ieee80211_add_htcap(frm, ni);
2737                 bo->bo_htinfo = frm;
2738                 frm = ieee80211_add_htinfo(frm, ni);
2739         }
2740         if (vap->iv_flags & IEEE80211_F_WPA1) {
2741                 if (vap->iv_wpa_ie != NULL)
2742                         frm = add_ie(frm, vap->iv_wpa_ie);
2743                 /* XXX else complain */
2744         }
2745         if (vap->iv_flags & IEEE80211_F_WME) {
2746                 bo->bo_wme = frm;
2747                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2748         }
2749         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2750             (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT)) {
2751                 frm = ieee80211_add_htcap_vendor(frm, ni);
2752                 frm = ieee80211_add_htinfo_vendor(frm, ni);
2753         }
2754 #ifdef IEEE80211_SUPPORT_SUPERG
2755         if (vap->iv_flags & IEEE80211_F_ATHEROS) {
2756                 bo->bo_ath = frm;
2757                 frm = ieee80211_add_athcaps(frm, ni);
2758         }
2759 #endif
2760 #ifdef IEEE80211_SUPPORT_TDMA
2761         if (vap->iv_caps & IEEE80211_C_TDMA) {
2762                 bo->bo_tdma = frm;
2763                 frm = ieee80211_add_tdma(frm, vap);
2764         }
2765 #endif
2766         if (vap->iv_appie_beacon != NULL) {
2767                 bo->bo_appie = frm;
2768                 bo->bo_appie_len = vap->iv_appie_beacon->ie_len;
2769                 frm = add_appie(frm, vap->iv_appie_beacon);
2770         }
2771 #ifdef IEEE80211_SUPPORT_MESH
2772         if (vap->iv_opmode == IEEE80211_M_MBSS) {
2773                 frm = ieee80211_add_meshid(frm, vap);
2774                 bo->bo_meshconf = frm;
2775                 frm = ieee80211_add_meshconf(frm, vap);
2776         }
2777 #endif
2778         bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
2779         bo->bo_csa_trailer_len = frm - bo->bo_csa;
2780         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2781 }
2782
2783 /*
2784  * Allocate a beacon frame and fillin the appropriate bits.
2785  */
2786 struct mbuf *
2787 ieee80211_beacon_alloc(struct ieee80211_node *ni,
2788         struct ieee80211_beacon_offsets *bo)
2789 {
2790         struct ieee80211vap *vap = ni->ni_vap;
2791         struct ieee80211com *ic = ni->ni_ic;
2792         struct ifnet *ifp = vap->iv_ifp;
2793         struct ieee80211_frame *wh;
2794         struct mbuf *m;
2795         int pktlen;
2796         uint8_t *frm;
2797
2798         /*
2799          * beacon frame format
2800          *      [8] time stamp
2801          *      [2] beacon interval
2802          *      [2] cabability information
2803          *      [tlv] ssid
2804          *      [tlv] supported rates
2805          *      [3] parameter set (DS)
2806          *      [8] CF parameter set (optional)
2807          *      [tlv] parameter set (IBSS/TIM)
2808          *      [tlv] country (optional)
2809          *      [3] power control (optional)
2810          *      [5] channel switch announcement (CSA) (optional)
2811          *      [tlv] extended rate phy (ERP)
2812          *      [tlv] extended supported rates
2813          *      [tlv] RSN parameters
2814          *      [tlv] HT capabilities
2815          *      [tlv] HT information
2816          *      [tlv] Vendor OUI HT capabilities (optional)
2817          *      [tlv] Vendor OUI HT information (optional)
2818          * XXX Vendor-specific OIDs (e.g. Atheros)
2819          *      [tlv] WPA parameters
2820          *      [tlv] WME parameters
2821          *      [tlv] TDMA parameters (optional)
2822          *      [tlv] Mesh ID (MBSS)
2823          *      [tlv] Mesh Conf (MBSS)
2824          *      [tlv] application data (optional)
2825          * NB: we allocate the max space required for the TIM bitmap.
2826          * XXX how big is this?
2827          */
2828         pktlen =   8                                    /* time stamp */
2829                  + sizeof(uint16_t)                     /* beacon interval */
2830                  + sizeof(uint16_t)                     /* capabilities */
2831                  + 2 + ni->ni_esslen                    /* ssid */
2832                  + 2 + IEEE80211_RATE_SIZE              /* supported rates */
2833                  + 2 + 1                                /* DS parameters */
2834                  + 2 + 6                                /* CF parameters */
2835                  + 2 + 4 + vap->iv_tim_len              /* DTIM/IBSSPARMS */
2836                  + IEEE80211_COUNTRY_MAX_SIZE           /* country */
2837                  + 2 + 1                                /* power control */
2838                  + sizeof(struct ieee80211_csa_ie)      /* CSA */
2839                  + sizeof(struct ieee80211_quiet_ie)    /* Quiet */
2840                  + 2 + 1                                /* ERP */
2841                  + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2842                  + (vap->iv_caps & IEEE80211_C_WPA ?    /* WPA 1+2 */
2843                         2*sizeof(struct ieee80211_ie_wpa) : 0)
2844                  /* XXX conditional? */
2845                  + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
2846                  + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
2847                  + (vap->iv_caps & IEEE80211_C_WME ?    /* WME */
2848                         sizeof(struct ieee80211_wme_param) : 0)
2849 #ifdef IEEE80211_SUPPORT_SUPERG
2850                  + sizeof(struct ieee80211_ath_ie)      /* ATH */
2851 #endif
2852 #ifdef IEEE80211_SUPPORT_TDMA
2853                  + (vap->iv_caps & IEEE80211_C_TDMA ?   /* TDMA */
2854                         sizeof(struct ieee80211_tdma_param) : 0)
2855 #endif
2856 #ifdef IEEE80211_SUPPORT_MESH
2857                  + 2 + ni->ni_meshidlen
2858                  + sizeof(struct ieee80211_meshconf_ie)
2859 #endif
2860                  + IEEE80211_MAX_APPIE
2861                  ;
2862         m = ieee80211_getmgtframe(&frm,
2863                 ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
2864         if (m == NULL) {
2865                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
2866                         "%s: cannot get buf; size %u\n", __func__, pktlen);
2867                 vap->iv_stats.is_tx_nobuf++;
2868                 return NULL;
2869         }
2870         ieee80211_beacon_construct(m, frm, bo, ni);
2871
2872         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
2873         KASSERT(m != NULL, ("no space for 802.11 header?"));
2874         wh = mtod(m, struct ieee80211_frame *);
2875         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2876             IEEE80211_FC0_SUBTYPE_BEACON;
2877         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2878         *(uint16_t *)wh->i_dur = 0;
2879         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2880         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
2881         IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
2882         *(uint16_t *)wh->i_seq = 0;
2883
2884         return m;
2885 }
2886
2887 /*
2888  * Update the dynamic parts of a beacon frame based on the current state.
2889  */
2890 int
2891 ieee80211_beacon_update(struct ieee80211_node *ni,
2892         struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
2893 {
2894         struct ieee80211vap *vap = ni->ni_vap;
2895         struct ieee80211com *ic = ni->ni_ic;
2896         int len_changed = 0;
2897         uint16_t capinfo;
2898         struct ieee80211_frame *wh;
2899         ieee80211_seq seqno;
2900
2901         IEEE80211_LOCK(ic);
2902         /*
2903          * Handle 11h channel change when we've reached the count.
2904          * We must recalculate the beacon frame contents to account
2905          * for the new channel.  Note we do this only for the first
2906          * vap that reaches this point; subsequent vaps just update
2907          * their beacon state to reflect the recalculated channel.
2908          */
2909         if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) &&
2910             vap->iv_csa_count == ic->ic_csa_count) {
2911                 vap->iv_csa_count = 0;
2912                 /*
2913                  * Effect channel change before reconstructing the beacon
2914                  * frame contents as many places reference ni_chan.
2915                  */
2916                 if (ic->ic_csa_newchan != NULL)
2917                         ieee80211_csa_completeswitch(ic);
2918                 /*
2919                  * NB: ieee80211_beacon_construct clears all pending
2920                  * updates in bo_flags so we don't need to explicitly
2921                  * clear IEEE80211_BEACON_CSA.
2922                  */
2923                 ieee80211_beacon_construct(m,
2924                     mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), bo, ni);
2925
2926                 /* XXX do WME aggressive mode processing? */
2927                 IEEE80211_UNLOCK(ic);
2928                 return 1;               /* just assume length changed */
2929         }
2930
2931         wh = mtod(m, struct ieee80211_frame *);
2932         seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
2933         *(uint16_t *)&wh->i_seq[0] =
2934                 htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
2935         M_SEQNO_SET(m, seqno);
2936
2937         /* XXX faster to recalculate entirely or just changes? */
2938         capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
2939         *bo->bo_caps = htole16(capinfo);
2940
2941         if (vap->iv_flags & IEEE80211_F_WME) {
2942                 struct ieee80211_wme_state *wme = &ic->ic_wme;
2943
2944                 /*
2945                  * Check for agressive mode change.  When there is
2946                  * significant high priority traffic in the BSS
2947                  * throttle back BE traffic by using conservative
2948                  * parameters.  Otherwise BE uses agressive params
2949                  * to optimize performance of legacy/non-QoS traffic.
2950                  */
2951                 if (wme->wme_flags & WME_F_AGGRMODE) {
2952                         if (wme->wme_hipri_traffic >
2953                             wme->wme_hipri_switch_thresh) {
2954                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2955                                     "%s: traffic %u, disable aggressive mode\n",
2956                                     __func__, wme->wme_hipri_traffic);
2957                                 wme->wme_flags &= ~WME_F_AGGRMODE;
2958                                 ieee80211_wme_updateparams_locked(vap);
2959                                 wme->wme_hipri_traffic =
2960                                         wme->wme_hipri_switch_hysteresis;
2961                         } else
2962                                 wme->wme_hipri_traffic = 0;
2963                 } else {
2964                         if (wme->wme_hipri_traffic <=
2965                             wme->wme_hipri_switch_thresh) {
2966                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2967                                     "%s: traffic %u, enable aggressive mode\n",
2968                                     __func__, wme->wme_hipri_traffic);
2969                                 wme->wme_flags |= WME_F_AGGRMODE;
2970                                 ieee80211_wme_updateparams_locked(vap);
2971                                 wme->wme_hipri_traffic = 0;
2972                         } else
2973                                 wme->wme_hipri_traffic =
2974                                         wme->wme_hipri_switch_hysteresis;
2975                 }
2976                 if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
2977                         (void) ieee80211_add_wme_param(bo->bo_wme, wme);
2978                         clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
2979                 }
2980         }
2981
2982         if (isset(bo->bo_flags,  IEEE80211_BEACON_HTINFO)) {
2983                 ieee80211_ht_update_beacon(vap, bo);
2984                 clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
2985         }
2986 #ifdef IEEE80211_SUPPORT_TDMA
2987         if (vap->iv_caps & IEEE80211_C_TDMA) {
2988                 /*
2989                  * NB: the beacon is potentially updated every TBTT.
2990                  */
2991                 ieee80211_tdma_update_beacon(vap, bo);
2992         }
2993 #endif
2994 #ifdef IEEE80211_SUPPORT_MESH
2995         if (vap->iv_opmode == IEEE80211_M_MBSS)
2996                 ieee80211_mesh_update_beacon(vap, bo);
2997 #endif
2998
2999         if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
3000             vap->iv_opmode == IEEE80211_M_MBSS) {       /* NB: no IBSS support*/
3001                 struct ieee80211_tim_ie *tie =
3002                         (struct ieee80211_tim_ie *) bo->bo_tim;
3003                 if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
3004                         u_int timlen, timoff, i;
3005                         /* 
3006                          * ATIM/DTIM needs updating.  If it fits in the
3007                          * current space allocated then just copy in the
3008                          * new bits.  Otherwise we need to move any trailing
3009                          * data to make room.  Note that we know there is
3010                          * contiguous space because ieee80211_beacon_allocate
3011                          * insures there is space in the mbuf to write a
3012                          * maximal-size virtual bitmap (based on iv_max_aid).
3013                          */
3014                         /*
3015                          * Calculate the bitmap size and offset, copy any
3016                          * trailer out of the way, and then copy in the
3017                          * new bitmap and update the information element.
3018                          * Note that the tim bitmap must contain at least
3019                          * one byte and any offset must be even.
3020                          */
3021                         if (vap->iv_ps_pending != 0) {
3022                                 timoff = 128;           /* impossibly large */
3023                                 for (i = 0; i < vap->iv_tim_len; i++)
3024                                         if (vap->iv_tim_bitmap[i]) {
3025                                                 timoff = i &~ 1;
3026                                                 break;
3027                                         }
3028                                 KASSERT(timoff != 128, ("tim bitmap empty!"));
3029                                 for (i = vap->iv_tim_len-1; i >= timoff; i--)
3030                                         if (vap->iv_tim_bitmap[i])
3031                                                 break;
3032                                 timlen = 1 + (i - timoff);
3033                         } else {
3034                                 timoff = 0;
3035                                 timlen = 1;
3036                         }
3037                         if (timlen != bo->bo_tim_len) {
3038                                 /* copy up/down trailer */
3039                                 int adjust = tie->tim_bitmap+timlen
3040                                            - bo->bo_tim_trailer;
3041                                 ovbcopy(bo->bo_tim_trailer,
3042                                     bo->bo_tim_trailer+adjust,
3043                                     bo->bo_tim_trailer_len);
3044                                 bo->bo_tim_trailer += adjust;
3045                                 bo->bo_erp += adjust;
3046                                 bo->bo_htinfo += adjust;
3047 #ifdef IEEE80211_SUPPORT_SUPERG
3048                                 bo->bo_ath += adjust;
3049 #endif
3050 #ifdef IEEE80211_SUPPORT_TDMA
3051                                 bo->bo_tdma += adjust;
3052 #endif
3053 #ifdef IEEE80211_SUPPORT_MESH
3054                                 bo->bo_meshconf += adjust;
3055 #endif
3056                                 bo->bo_appie += adjust;
3057                                 bo->bo_wme += adjust;
3058                                 bo->bo_csa += adjust;
3059                                 bo->bo_quiet += adjust;
3060                                 bo->bo_tim_len = timlen;
3061
3062                                 /* update information element */
3063                                 tie->tim_len = 3 + timlen;
3064                                 tie->tim_bitctl = timoff;
3065                                 len_changed = 1;
3066                         }
3067                         memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff,
3068                                 bo->bo_tim_len);
3069
3070                         clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
3071
3072                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER,
3073                                 "%s: TIM updated, pending %u, off %u, len %u\n",
3074                                 __func__, vap->iv_ps_pending, timoff, timlen);
3075                 }
3076                 /* count down DTIM period */
3077                 if (tie->tim_count == 0)
3078                         tie->tim_count = tie->tim_period - 1;
3079                 else
3080                         tie->tim_count--;
3081                 /* update state for buffered multicast frames on DTIM */
3082                 if (mcast && tie->tim_count == 0)
3083                         tie->tim_bitctl |= 1;
3084                 else
3085                         tie->tim_bitctl &= ~1;
3086                 if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) {
3087                         struct ieee80211_csa_ie *csa =
3088                             (struct ieee80211_csa_ie *) bo->bo_csa;
3089
3090                         /*
3091                          * Insert or update CSA ie.  If we're just starting
3092                          * to count down to the channel switch then we need
3093                          * to insert the CSA ie.  Otherwise we just need to
3094                          * drop the count.  The actual change happens above
3095                          * when the vap's count reaches the target count.
3096                          */
3097                         if (vap->iv_csa_count == 0) {
3098                                 memmove(&csa[1], csa, bo->bo_csa_trailer_len);
3099                                 bo->bo_erp += sizeof(*csa);
3100                                 bo->bo_htinfo += sizeof(*csa);
3101                                 bo->bo_wme += sizeof(*csa);
3102 #ifdef IEEE80211_SUPPORT_SUPERG
3103                                 bo->bo_ath += sizeof(*csa);
3104 #endif
3105 #ifdef IEEE80211_SUPPORT_TDMA
3106                                 bo->bo_tdma += sizeof(*csa);
3107 #endif
3108 #ifdef IEEE80211_SUPPORT_MESH
3109                                 bo->bo_meshconf += sizeof(*csa);
3110 #endif
3111                                 bo->bo_appie += sizeof(*csa);
3112                                 bo->bo_csa_trailer_len += sizeof(*csa);
3113                                 bo->bo_quiet += sizeof(*csa);
3114                                 bo->bo_tim_trailer_len += sizeof(*csa);
3115                                 m->m_len += sizeof(*csa);
3116                                 m->m_pkthdr.len += sizeof(*csa);
3117
3118                                 ieee80211_add_csa(bo->bo_csa, vap);
3119                         } else
3120                                 csa->csa_count--;
3121                         vap->iv_csa_count++;
3122                         /* NB: don't clear IEEE80211_BEACON_CSA */
3123                 }
3124                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3125                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS) ){
3126                         if (vap->iv_quiet)
3127                                 ieee80211_add_quiet(bo->bo_quiet, vap);
3128                 }
3129                 if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
3130                         /*
3131                          * ERP element needs updating.
3132                          */
3133                         (void) ieee80211_add_erp(bo->bo_erp, ic);
3134                         clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
3135                 }
3136 #ifdef IEEE80211_SUPPORT_SUPERG
3137                 if (isset(bo->bo_flags,  IEEE80211_BEACON_ATH)) {
3138                         ieee80211_add_athcaps(bo->bo_ath, ni);
3139                         clrbit(bo->bo_flags, IEEE80211_BEACON_ATH);
3140                 }
3141 #endif
3142         }
3143         if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) {
3144                 const struct ieee80211_appie *aie = vap->iv_appie_beacon;
3145                 int aielen;
3146                 uint8_t *frm;
3147
3148                 aielen = 0;
3149                 if (aie != NULL)
3150                         aielen += aie->ie_len;
3151                 if (aielen != bo->bo_appie_len) {
3152                         /* copy up/down trailer */
3153                         int adjust = aielen - bo->bo_appie_len;
3154                         ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust,
3155                                 bo->bo_tim_trailer_len);
3156                         bo->bo_tim_trailer += adjust;
3157                         bo->bo_appie += adjust;
3158                         bo->bo_appie_len = aielen;
3159
3160                         len_changed = 1;
3161                 }
3162                 frm = bo->bo_appie;
3163                 if (aie != NULL)
3164                         frm  = add_appie(frm, aie);
3165                 clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE);
3166         }
3167         IEEE80211_UNLOCK(ic);
3168
3169         return len_changed;
3170 }