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