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