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