]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net80211/ieee80211_output.c
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[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     struct ieee80211_node *ni)
2161 {
2162         static const uint8_t oui[4] = { WME_OUI_BYTES, WME_OUI_TYPE };
2163         struct ieee80211vap *vap = ni->ni_vap;
2164
2165         *frm++ = IEEE80211_ELEMID_VENDOR;
2166         *frm++ = sizeof(struct ieee80211_wme_info) - 2;
2167         memcpy(frm, oui, sizeof(oui));
2168         frm += sizeof(oui);
2169         *frm++ = WME_INFO_OUI_SUBTYPE;
2170         *frm++ = WME_VERSION;
2171
2172         /* QoS info field depends upon operating mode */
2173         switch (vap->iv_opmode) {
2174         case IEEE80211_M_HOSTAP:
2175                 *frm = wme->wme_bssChanParams.cap_info;
2176                 if (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD)
2177                         *frm |= WME_CAPINFO_UAPSD_EN;
2178                 frm++;
2179                 break;
2180         case IEEE80211_M_STA:
2181                 /*
2182                  * NB: UAPSD drivers must set this up in their
2183                  * VAP creation method.
2184                  */
2185                 *frm++ = vap->iv_uapsdinfo;
2186                 break;
2187         default:
2188                 *frm++ = 0;
2189                 break;
2190         }
2191
2192         return frm;
2193 }
2194
2195 /*
2196  * Add a WME parameters element to a frame.
2197  */
2198 static uint8_t *
2199 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme,
2200     int uapsd_enable)
2201 {
2202 #define SM(_v, _f)      (((_v) << _f##_S) & _f)
2203 #define ADDSHORT(frm, v) do {   \
2204         le16enc(frm, v);        \
2205         frm += 2;               \
2206 } while (0)
2207         /* NB: this works 'cuz a param has an info at the front */
2208         static const struct ieee80211_wme_info param = {
2209                 .wme_id         = IEEE80211_ELEMID_VENDOR,
2210                 .wme_len        = sizeof(struct ieee80211_wme_param) - 2,
2211                 .wme_oui        = { WME_OUI_BYTES },
2212                 .wme_type       = WME_OUI_TYPE,
2213                 .wme_subtype    = WME_PARAM_OUI_SUBTYPE,
2214                 .wme_version    = WME_VERSION,
2215         };
2216         int i;
2217
2218         memcpy(frm, &param, sizeof(param));
2219         frm += __offsetof(struct ieee80211_wme_info, wme_info);
2220         *frm = wme->wme_bssChanParams.cap_info; /* AC info */
2221         if (uapsd_enable)
2222                 *frm |= WME_CAPINFO_UAPSD_EN;
2223         frm++;
2224         *frm++ = 0;                                     /* reserved field */
2225         /* XXX TODO - U-APSD bits - SP, flags below */
2226         for (i = 0; i < WME_NUM_AC; i++) {
2227                 const struct wmeParams *ac =
2228                        &wme->wme_bssChanParams.cap_wmeParams[i];
2229                 *frm++ = SM(i, WME_PARAM_ACI)
2230                        | SM(ac->wmep_acm, WME_PARAM_ACM)
2231                        | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
2232                        ;
2233                 *frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
2234                        | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
2235                        ;
2236                 ADDSHORT(frm, ac->wmep_txopLimit);
2237         }
2238         return frm;
2239 #undef SM
2240 #undef ADDSHORT
2241 }
2242 #undef WME_OUI_BYTES
2243
2244 /*
2245  * Add an 11h Power Constraint element to a frame.
2246  */
2247 static uint8_t *
2248 ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap)
2249 {
2250         const struct ieee80211_channel *c = vap->iv_bss->ni_chan;
2251         /* XXX per-vap tx power limit? */
2252         int8_t limit = vap->iv_ic->ic_txpowlimit / 2;
2253
2254         frm[0] = IEEE80211_ELEMID_PWRCNSTR;
2255         frm[1] = 1;
2256         frm[2] = c->ic_maxregpower > limit ?  c->ic_maxregpower - limit : 0;
2257         return frm + 3;
2258 }
2259
2260 /*
2261  * Add an 11h Power Capability element to a frame.
2262  */
2263 static uint8_t *
2264 ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c)
2265 {
2266         frm[0] = IEEE80211_ELEMID_PWRCAP;
2267         frm[1] = 2;
2268         frm[2] = c->ic_minpower;
2269         frm[3] = c->ic_maxpower;
2270         return frm + 4;
2271 }
2272
2273 /*
2274  * Add an 11h Supported Channels element to a frame.
2275  */
2276 static uint8_t *
2277 ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic)
2278 {
2279         static const int ielen = 26;
2280
2281         frm[0] = IEEE80211_ELEMID_SUPPCHAN;
2282         frm[1] = ielen;
2283         /* XXX not correct */
2284         memcpy(frm+2, ic->ic_chan_avail, ielen);
2285         return frm + 2 + ielen;
2286 }
2287
2288 /*
2289  * Add an 11h Quiet time element to a frame.
2290  */
2291 static uint8_t *
2292 ieee80211_add_quiet(uint8_t *frm, struct ieee80211vap *vap, int update)
2293 {
2294         struct ieee80211_quiet_ie *quiet = (struct ieee80211_quiet_ie *) frm;
2295
2296         quiet->quiet_ie = IEEE80211_ELEMID_QUIET;
2297         quiet->len = 6;
2298
2299         /*
2300          * Only update every beacon interval - otherwise probe responses
2301          * would update the quiet count value.
2302          */
2303         if (update) {
2304                 if (vap->iv_quiet_count_value == 1)
2305                         vap->iv_quiet_count_value = vap->iv_quiet_count;
2306                 else if (vap->iv_quiet_count_value > 1)
2307                         vap->iv_quiet_count_value--;
2308         }
2309
2310         if (vap->iv_quiet_count_value == 0) {
2311                 /* value 0 is reserved as per 802.11h standerd */
2312                 vap->iv_quiet_count_value = 1;
2313         }
2314
2315         quiet->tbttcount = vap->iv_quiet_count_value;
2316         quiet->period = vap->iv_quiet_period;
2317         quiet->duration = htole16(vap->iv_quiet_duration);
2318         quiet->offset = htole16(vap->iv_quiet_offset);
2319         return frm + sizeof(*quiet);
2320 }
2321
2322 /*
2323  * Add an 11h Channel Switch Announcement element to a frame.
2324  * Note that we use the per-vap CSA count to adjust the global
2325  * counter so we can use this routine to form probe response
2326  * frames and get the current count.
2327  */
2328 static uint8_t *
2329 ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap)
2330 {
2331         struct ieee80211com *ic = vap->iv_ic;
2332         struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm;
2333
2334         csa->csa_ie = IEEE80211_ELEMID_CSA;
2335         csa->csa_len = 3;
2336         csa->csa_mode = 1;              /* XXX force quiet on channel */
2337         csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan);
2338         csa->csa_count = ic->ic_csa_count - vap->iv_csa_count;
2339         return frm + sizeof(*csa);
2340 }
2341
2342 /*
2343  * Add an 11h country information element to a frame.
2344  */
2345 static uint8_t *
2346 ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic)
2347 {
2348
2349         if (ic->ic_countryie == NULL ||
2350             ic->ic_countryie_chan != ic->ic_bsschan) {
2351                 /*
2352                  * Handle lazy construction of ie.  This is done on
2353                  * first use and after a channel change that requires
2354                  * re-calculation.
2355                  */
2356                 if (ic->ic_countryie != NULL)
2357                         IEEE80211_FREE(ic->ic_countryie, M_80211_NODE_IE);
2358                 ic->ic_countryie = ieee80211_alloc_countryie(ic);
2359                 if (ic->ic_countryie == NULL)
2360                         return frm;
2361                 ic->ic_countryie_chan = ic->ic_bsschan;
2362         }
2363         return add_appie(frm, ic->ic_countryie);
2364 }
2365
2366 uint8_t *
2367 ieee80211_add_wpa(uint8_t *frm, const struct ieee80211vap *vap)
2368 {
2369         if (vap->iv_flags & IEEE80211_F_WPA1 && vap->iv_wpa_ie != NULL)
2370                 return (add_ie(frm, vap->iv_wpa_ie));
2371         else {
2372                 /* XXX else complain? */
2373                 return (frm);
2374         }
2375 }
2376
2377 uint8_t *
2378 ieee80211_add_rsn(uint8_t *frm, const struct ieee80211vap *vap)
2379 {
2380         if (vap->iv_flags & IEEE80211_F_WPA2 && vap->iv_rsn_ie != NULL)
2381                 return (add_ie(frm, vap->iv_rsn_ie));
2382         else {
2383                 /* XXX else complain? */
2384                 return (frm);
2385         }
2386 }
2387
2388 uint8_t *
2389 ieee80211_add_qos(uint8_t *frm, const struct ieee80211_node *ni)
2390 {
2391         if (ni->ni_flags & IEEE80211_NODE_QOS) {
2392                 *frm++ = IEEE80211_ELEMID_QOS;
2393                 *frm++ = 1;
2394                 *frm++ = 0;
2395         }
2396
2397         return (frm);
2398 }
2399
2400 /*
2401  * Send a probe request frame with the specified ssid
2402  * and any optional information element data.
2403  */
2404 int
2405 ieee80211_send_probereq(struct ieee80211_node *ni,
2406         const uint8_t sa[IEEE80211_ADDR_LEN],
2407         const uint8_t da[IEEE80211_ADDR_LEN],
2408         const uint8_t bssid[IEEE80211_ADDR_LEN],
2409         const uint8_t *ssid, size_t ssidlen)
2410 {
2411         struct ieee80211vap *vap = ni->ni_vap;
2412         struct ieee80211com *ic = ni->ni_ic;
2413         struct ieee80211_node *bss;
2414         const struct ieee80211_txparam *tp;
2415         struct ieee80211_bpf_params params;
2416         const struct ieee80211_rateset *rs;
2417         struct mbuf *m;
2418         uint8_t *frm;
2419         int ret;
2420
2421         bss = ieee80211_ref_node(vap->iv_bss);
2422
2423         if (vap->iv_state == IEEE80211_S_CAC) {
2424                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
2425                     "block %s frame in CAC state", "probe request");
2426                 vap->iv_stats.is_tx_badstate++;
2427                 ieee80211_free_node(bss);
2428                 return EIO;             /* XXX */
2429         }
2430
2431         /*
2432          * Hold a reference on the node so it doesn't go away until after
2433          * the xmit is complete all the way in the driver.  On error we
2434          * will remove our reference.
2435          */
2436         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2437                 "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2438                 __func__, __LINE__,
2439                 ni, ether_sprintf(ni->ni_macaddr),
2440                 ieee80211_node_refcnt(ni)+1);
2441         ieee80211_ref_node(ni);
2442
2443         /*
2444          * prreq frame format
2445          *      [tlv] ssid
2446          *      [tlv] supported rates
2447          *      [tlv] RSN (optional)
2448          *      [tlv] extended supported rates
2449          *      [tlv] HT cap (optional)
2450          *      [tlv] VHT cap (optional)
2451          *      [tlv] WPA (optional)
2452          *      [tlv] user-specified ie's
2453          */
2454         m = ieee80211_getmgtframe(&frm,
2455                  ic->ic_headroom + sizeof(struct ieee80211_frame),
2456                  2 + IEEE80211_NWID_LEN
2457                + 2 + IEEE80211_RATE_SIZE
2458                + sizeof(struct ieee80211_ie_htcap)
2459                + sizeof(struct ieee80211_ie_vhtcap)
2460                + sizeof(struct ieee80211_ie_htinfo)     /* XXX not needed? */
2461                + sizeof(struct ieee80211_ie_wpa)
2462                + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2463                + sizeof(struct ieee80211_ie_wpa)
2464                + (vap->iv_appie_probereq != NULL ?
2465                    vap->iv_appie_probereq->ie_len : 0)
2466         );
2467         if (m == NULL) {
2468                 vap->iv_stats.is_tx_nobuf++;
2469                 ieee80211_free_node(ni);
2470                 ieee80211_free_node(bss);
2471                 return ENOMEM;
2472         }
2473
2474         frm = ieee80211_add_ssid(frm, ssid, ssidlen);
2475         rs = ieee80211_get_suprates(ic, ic->ic_curchan);
2476         frm = ieee80211_add_rates(frm, rs);
2477         frm = ieee80211_add_rsn(frm, vap);
2478         frm = ieee80211_add_xrates(frm, rs);
2479
2480         /*
2481          * Note: we can't use bss; we don't have one yet.
2482          *
2483          * So, we should announce our capabilities
2484          * in this channel mode (2g/5g), not the
2485          * channel details itself.
2486          */
2487         if ((vap->iv_opmode == IEEE80211_M_IBSS) &&
2488             (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
2489                 struct ieee80211_channel *c;
2490
2491                 /*
2492                  * Get the HT channel that we should try upgrading to.
2493                  * If we can do 40MHz then this'll upgrade it appropriately.
2494                  */
2495                 c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
2496                     vap->iv_flags_ht);
2497                 frm = ieee80211_add_htcap_ch(frm, vap, c);
2498         }
2499
2500         /*
2501          * XXX TODO: need to figure out what/how to update the
2502          * VHT channel.
2503          */
2504 #if 0
2505         (vap->iv_flags_vht & IEEE80211_FVHT_VHT) {
2506                 struct ieee80211_channel *c;
2507
2508                 c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
2509                     vap->iv_flags_ht);
2510                 c = ieee80211_vht_adjust_channel(ic, c, vap->iv_flags_vht);
2511                 frm = ieee80211_add_vhtcap_ch(frm, vap, c);
2512         }
2513 #endif
2514
2515         frm = ieee80211_add_wpa(frm, vap);
2516         if (vap->iv_appie_probereq != NULL)
2517                 frm = add_appie(frm, vap->iv_appie_probereq);
2518         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2519
2520         KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ieee80211_frame),
2521             ("leading space %zd", M_LEADINGSPACE(m)));
2522         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
2523         if (m == NULL) {
2524                 /* NB: cannot happen */
2525                 ieee80211_free_node(ni);
2526                 ieee80211_free_node(bss);
2527                 return ENOMEM;
2528         }
2529
2530         IEEE80211_TX_LOCK(ic);
2531         ieee80211_send_setup(ni, m,
2532              IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
2533              IEEE80211_NONQOS_TID, sa, da, bssid);
2534         /* XXX power management? */
2535         m->m_flags |= M_ENCAP;          /* mark encapsulated */
2536
2537         M_WME_SETAC(m, WME_AC_BE);
2538
2539         IEEE80211_NODE_STAT(ni, tx_probereq);
2540         IEEE80211_NODE_STAT(ni, tx_mgmt);
2541
2542         IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
2543             "send probe req on channel %u bssid %s sa %6D da %6D ssid \"%.*s\"\n",
2544             ieee80211_chan2ieee(ic, ic->ic_curchan),
2545             ether_sprintf(bssid),
2546             sa, ":",
2547             da, ":",
2548             ssidlen, ssid);
2549
2550         memset(&params, 0, sizeof(params));
2551         params.ibp_pri = M_WME_GETAC(m);
2552         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
2553         params.ibp_rate0 = tp->mgmtrate;
2554         if (IEEE80211_IS_MULTICAST(da)) {
2555                 params.ibp_flags |= IEEE80211_BPF_NOACK;
2556                 params.ibp_try0 = 1;
2557         } else
2558                 params.ibp_try0 = tp->maxretry;
2559         params.ibp_power = ni->ni_txpower;
2560         ret = ieee80211_raw_output(vap, ni, m, &params);
2561         IEEE80211_TX_UNLOCK(ic);
2562         ieee80211_free_node(bss);
2563         return (ret);
2564 }
2565
2566 /*
2567  * Calculate capability information for mgt frames.
2568  */
2569 uint16_t
2570 ieee80211_getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan)
2571 {
2572         struct ieee80211com *ic = vap->iv_ic;
2573         uint16_t capinfo;
2574
2575         KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode"));
2576
2577         if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2578                 capinfo = IEEE80211_CAPINFO_ESS;
2579         else if (vap->iv_opmode == IEEE80211_M_IBSS)
2580                 capinfo = IEEE80211_CAPINFO_IBSS;
2581         else
2582                 capinfo = 0;
2583         if (vap->iv_flags & IEEE80211_F_PRIVACY)
2584                 capinfo |= IEEE80211_CAPINFO_PRIVACY;
2585         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2586             IEEE80211_IS_CHAN_2GHZ(chan))
2587                 capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2588         if (vap->iv_flags & IEEE80211_F_SHSLOT)
2589                 capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2590         if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH))
2591                 capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
2592         return capinfo;
2593 }
2594
2595 /*
2596  * Send a management frame.  The node is for the destination (or ic_bss
2597  * when in station mode).  Nodes other than ic_bss have their reference
2598  * count bumped to reflect our use for an indeterminant time.
2599  */
2600 int
2601 ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg)
2602 {
2603 #define HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
2604 #define senderr(_x, _v) do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
2605         struct ieee80211vap *vap = ni->ni_vap;
2606         struct ieee80211com *ic = ni->ni_ic;
2607         struct ieee80211_node *bss = vap->iv_bss;
2608         struct ieee80211_bpf_params params;
2609         struct mbuf *m;
2610         uint8_t *frm;
2611         uint16_t capinfo;
2612         int has_challenge, is_shared_key, ret, status;
2613
2614         KASSERT(ni != NULL, ("null node"));
2615
2616         /*
2617          * Hold a reference on the node so it doesn't go away until after
2618          * the xmit is complete all the way in the driver.  On error we
2619          * will remove our reference.
2620          */
2621         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2622                 "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2623                 __func__, __LINE__,
2624                 ni, ether_sprintf(ni->ni_macaddr),
2625                 ieee80211_node_refcnt(ni)+1);
2626         ieee80211_ref_node(ni);
2627
2628         memset(&params, 0, sizeof(params));
2629         switch (type) {
2630
2631         case IEEE80211_FC0_SUBTYPE_AUTH:
2632                 status = arg >> 16;
2633                 arg &= 0xffff;
2634                 has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
2635                     arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
2636                     ni->ni_challenge != NULL);
2637
2638                 /*
2639                  * Deduce whether we're doing open authentication or
2640                  * shared key authentication.  We do the latter if
2641                  * we're in the middle of a shared key authentication
2642                  * handshake or if we're initiating an authentication
2643                  * request and configured to use shared key.
2644                  */
2645                 is_shared_key = has_challenge ||
2646                      arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
2647                      (arg == IEEE80211_AUTH_SHARED_REQUEST &&
2648                       bss->ni_authmode == IEEE80211_AUTH_SHARED);
2649
2650                 m = ieee80211_getmgtframe(&frm,
2651                           ic->ic_headroom + sizeof(struct ieee80211_frame),
2652                           3 * sizeof(uint16_t)
2653                         + (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
2654                                 sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
2655                 );
2656                 if (m == NULL)
2657                         senderr(ENOMEM, is_tx_nobuf);
2658
2659                 ((uint16_t *)frm)[0] =
2660                     (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
2661                                     : htole16(IEEE80211_AUTH_ALG_OPEN);
2662                 ((uint16_t *)frm)[1] = htole16(arg);    /* sequence number */
2663                 ((uint16_t *)frm)[2] = htole16(status);/* status */
2664
2665                 if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
2666                         ((uint16_t *)frm)[3] =
2667                             htole16((IEEE80211_CHALLENGE_LEN << 8) |
2668                             IEEE80211_ELEMID_CHALLENGE);
2669                         memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
2670                             IEEE80211_CHALLENGE_LEN);
2671                         m->m_pkthdr.len = m->m_len =
2672                                 4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
2673                         if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
2674                                 IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2675                                     "request encrypt frame (%s)", __func__);
2676                                 /* mark frame for encryption */
2677                                 params.ibp_flags |= IEEE80211_BPF_CRYPTO;
2678                         }
2679                 } else
2680                         m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
2681
2682                 /* XXX not right for shared key */
2683                 if (status == IEEE80211_STATUS_SUCCESS)
2684                         IEEE80211_NODE_STAT(ni, tx_auth);
2685                 else
2686                         IEEE80211_NODE_STAT(ni, tx_auth_fail);
2687
2688                 if (vap->iv_opmode == IEEE80211_M_STA)
2689                         ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2690                                 (void *) vap->iv_state);
2691                 break;
2692
2693         case IEEE80211_FC0_SUBTYPE_DEAUTH:
2694                 IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2695                     "send station deauthenticate (reason: %d (%s))", arg,
2696                     ieee80211_reason_to_string(arg));
2697                 m = ieee80211_getmgtframe(&frm,
2698                         ic->ic_headroom + sizeof(struct ieee80211_frame),
2699                         sizeof(uint16_t));
2700                 if (m == NULL)
2701                         senderr(ENOMEM, is_tx_nobuf);
2702                 *(uint16_t *)frm = htole16(arg);        /* reason */
2703                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2704
2705                 IEEE80211_NODE_STAT(ni, tx_deauth);
2706                 IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
2707
2708                 ieee80211_node_unauthorize(ni);         /* port closed */
2709                 break;
2710
2711         case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2712         case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
2713                 /*
2714                  * asreq frame format
2715                  *      [2] capability information
2716                  *      [2] listen interval
2717                  *      [6*] current AP address (reassoc only)
2718                  *      [tlv] ssid
2719                  *      [tlv] supported rates
2720                  *      [tlv] extended supported rates
2721                  *      [4] power capability (optional)
2722                  *      [28] supported channels (optional)
2723                  *      [tlv] HT capabilities
2724                  *      [tlv] VHT capabilities
2725                  *      [tlv] WME (optional)
2726                  *      [tlv] Vendor OUI HT capabilities (optional)
2727                  *      [tlv] Atheros capabilities (if negotiated)
2728                  *      [tlv] AppIE's (optional)
2729                  */
2730                 m = ieee80211_getmgtframe(&frm,
2731                          ic->ic_headroom + sizeof(struct ieee80211_frame),
2732                          sizeof(uint16_t)
2733                        + sizeof(uint16_t)
2734                        + IEEE80211_ADDR_LEN
2735                        + 2 + IEEE80211_NWID_LEN
2736                        + 2 + IEEE80211_RATE_SIZE
2737                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2738                        + 4
2739                        + 2 + 26
2740                        + sizeof(struct ieee80211_wme_info)
2741                        + sizeof(struct ieee80211_ie_htcap)
2742                        + sizeof(struct ieee80211_ie_vhtcap)
2743                        + 4 + sizeof(struct ieee80211_ie_htcap)
2744 #ifdef IEEE80211_SUPPORT_SUPERG
2745                        + sizeof(struct ieee80211_ath_ie)
2746 #endif
2747                        + (vap->iv_appie_wpa != NULL ?
2748                                 vap->iv_appie_wpa->ie_len : 0)
2749                        + (vap->iv_appie_assocreq != NULL ?
2750                                 vap->iv_appie_assocreq->ie_len : 0)
2751                 );
2752                 if (m == NULL)
2753                         senderr(ENOMEM, is_tx_nobuf);
2754
2755                 KASSERT(vap->iv_opmode == IEEE80211_M_STA,
2756                     ("wrong mode %u", vap->iv_opmode));
2757                 capinfo = IEEE80211_CAPINFO_ESS;
2758                 if (vap->iv_flags & IEEE80211_F_PRIVACY)
2759                         capinfo |= IEEE80211_CAPINFO_PRIVACY;
2760                 /*
2761                  * NB: Some 11a AP's reject the request when
2762                  *     short preamble is set.
2763                  */
2764                 if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2765                     IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
2766                         capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2767                 if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
2768                     (ic->ic_caps & IEEE80211_C_SHSLOT))
2769                         capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2770                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
2771                     (vap->iv_flags & IEEE80211_F_DOTH))
2772                         capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
2773                 *(uint16_t *)frm = htole16(capinfo);
2774                 frm += 2;
2775
2776                 KASSERT(bss->ni_intval != 0, ("beacon interval is zero!"));
2777                 *(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
2778                                                     bss->ni_intval));
2779                 frm += 2;
2780
2781                 if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
2782                         IEEE80211_ADDR_COPY(frm, bss->ni_bssid);
2783                         frm += IEEE80211_ADDR_LEN;
2784                 }
2785
2786                 frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
2787                 frm = ieee80211_add_rates(frm, &ni->ni_rates);
2788                 frm = ieee80211_add_rsn(frm, vap);
2789                 frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2790                 if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) {
2791                         frm = ieee80211_add_powercapability(frm,
2792                             ic->ic_curchan);
2793                         frm = ieee80211_add_supportedchannels(frm, ic);
2794                 }
2795
2796                 /*
2797                  * Check the channel - we may be using an 11n NIC with an
2798                  * 11n capable station, but we're configured to be an 11b
2799                  * channel.
2800                  */
2801                 if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2802                     IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2803                     ni->ni_ies.htcap_ie != NULL &&
2804                     ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP) {
2805                         frm = ieee80211_add_htcap(frm, ni);
2806                 }
2807
2808                 if ((vap->iv_flags_vht & IEEE80211_FVHT_VHT) &&
2809                     IEEE80211_IS_CHAN_VHT(ni->ni_chan) &&
2810                     ni->ni_ies.vhtcap_ie != NULL &&
2811                     ni->ni_ies.vhtcap_ie[0] == IEEE80211_ELEMID_VHT_CAP) {
2812                         frm = ieee80211_add_vhtcap(frm, ni);
2813                 }
2814
2815                 frm = ieee80211_add_wpa(frm, vap);
2816                 if ((ic->ic_flags & IEEE80211_F_WME) &&
2817                     ni->ni_ies.wme_ie != NULL)
2818                         frm = ieee80211_add_wme_info(frm, &ic->ic_wme, ni);
2819
2820                 /*
2821                  * Same deal - only send HT info if we're on an 11n
2822                  * capable channel.
2823                  */
2824                 if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2825                     IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2826                     ni->ni_ies.htcap_ie != NULL &&
2827                     ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR) {
2828                         frm = ieee80211_add_htcap_vendor(frm, ni);
2829                 }
2830 #ifdef IEEE80211_SUPPORT_SUPERG
2831                 if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) {
2832                         frm = ieee80211_add_ath(frm, 
2833                                 IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2834                                 ((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2835                                  ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2836                                 vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2837                 }
2838 #endif /* IEEE80211_SUPPORT_SUPERG */
2839                 if (vap->iv_appie_assocreq != NULL)
2840                         frm = add_appie(frm, vap->iv_appie_assocreq);
2841                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2842
2843                 ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2844                         (void *) vap->iv_state);
2845                 break;
2846
2847         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2848         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
2849                 /*
2850                  * asresp frame format
2851                  *      [2] capability information
2852                  *      [2] status
2853                  *      [2] association ID
2854                  *      [tlv] supported rates
2855                  *      [tlv] extended supported rates
2856                  *      [tlv] HT capabilities (standard, if STA enabled)
2857                  *      [tlv] HT information (standard, if STA enabled)
2858                  *      [tlv] VHT capabilities (standard, if STA enabled)
2859                  *      [tlv] VHT information (standard, if STA enabled)
2860                  *      [tlv] WME (if configured and STA enabled)
2861                  *      [tlv] HT capabilities (vendor OUI, if STA enabled)
2862                  *      [tlv] HT information (vendor OUI, if STA enabled)
2863                  *      [tlv] Atheros capabilities (if STA enabled)
2864                  *      [tlv] AppIE's (optional)
2865                  */
2866                 m = ieee80211_getmgtframe(&frm,
2867                          ic->ic_headroom + sizeof(struct ieee80211_frame),
2868                          sizeof(uint16_t)
2869                        + sizeof(uint16_t)
2870                        + sizeof(uint16_t)
2871                        + 2 + IEEE80211_RATE_SIZE
2872                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2873                        + sizeof(struct ieee80211_ie_htcap) + 4
2874                        + sizeof(struct ieee80211_ie_htinfo) + 4
2875                        + sizeof(struct ieee80211_ie_vhtcap)
2876                        + sizeof(struct ieee80211_ie_vht_operation)
2877                        + sizeof(struct ieee80211_wme_param)
2878 #ifdef IEEE80211_SUPPORT_SUPERG
2879                        + sizeof(struct ieee80211_ath_ie)
2880 #endif
2881                        + (vap->iv_appie_assocresp != NULL ?
2882                                 vap->iv_appie_assocresp->ie_len : 0)
2883                 );
2884                 if (m == NULL)
2885                         senderr(ENOMEM, is_tx_nobuf);
2886
2887                 capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
2888                 *(uint16_t *)frm = htole16(capinfo);
2889                 frm += 2;
2890
2891                 *(uint16_t *)frm = htole16(arg);        /* status */
2892                 frm += 2;
2893
2894                 if (arg == IEEE80211_STATUS_SUCCESS) {
2895                         *(uint16_t *)frm = htole16(ni->ni_associd);
2896                         IEEE80211_NODE_STAT(ni, tx_assoc);
2897                 } else
2898                         IEEE80211_NODE_STAT(ni, tx_assoc_fail);
2899                 frm += 2;
2900
2901                 frm = ieee80211_add_rates(frm, &ni->ni_rates);
2902                 frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2903                 /* NB: respond according to what we received */
2904                 if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
2905                         frm = ieee80211_add_htcap(frm, ni);
2906                         frm = ieee80211_add_htinfo(frm, ni);
2907                 }
2908                 if ((vap->iv_flags & IEEE80211_F_WME) &&
2909                     ni->ni_ies.wme_ie != NULL)
2910                         frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
2911                             !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
2912                 if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
2913                         frm = ieee80211_add_htcap_vendor(frm, ni);
2914                         frm = ieee80211_add_htinfo_vendor(frm, ni);
2915                 }
2916                 if (ni->ni_flags & IEEE80211_NODE_VHT) {
2917                         frm = ieee80211_add_vhtcap(frm, ni);
2918                         frm = ieee80211_add_vhtinfo(frm, ni);
2919                 }
2920 #ifdef IEEE80211_SUPPORT_SUPERG
2921                 if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
2922                         frm = ieee80211_add_ath(frm, 
2923                                 IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2924                                 ((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2925                                  ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2926                                 vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2927 #endif /* IEEE80211_SUPPORT_SUPERG */
2928                 if (vap->iv_appie_assocresp != NULL)
2929                         frm = add_appie(frm, vap->iv_appie_assocresp);
2930                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2931                 break;
2932
2933         case IEEE80211_FC0_SUBTYPE_DISASSOC:
2934                 IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2935                     "send station disassociate (reason: %d (%s))", arg,
2936                     ieee80211_reason_to_string(arg));
2937                 m = ieee80211_getmgtframe(&frm,
2938                         ic->ic_headroom + sizeof(struct ieee80211_frame),
2939                         sizeof(uint16_t));
2940                 if (m == NULL)
2941                         senderr(ENOMEM, is_tx_nobuf);
2942                 *(uint16_t *)frm = htole16(arg);        /* reason */
2943                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2944
2945                 IEEE80211_NODE_STAT(ni, tx_disassoc);
2946                 IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
2947                 break;
2948
2949         default:
2950                 IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni,
2951                     "invalid mgmt frame type %u", type);
2952                 senderr(EINVAL, is_tx_unknownmgt);
2953                 /* NOTREACHED */
2954         }
2955
2956         /* NB: force non-ProbeResp frames to the highest queue */
2957         params.ibp_pri = WME_AC_VO;
2958         params.ibp_rate0 = bss->ni_txparms->mgmtrate;
2959         /* NB: we know all frames are unicast */
2960         params.ibp_try0 = bss->ni_txparms->maxretry;
2961         params.ibp_power = bss->ni_txpower;
2962         return ieee80211_mgmt_output(ni, m, type, &params);
2963 bad:
2964         ieee80211_free_node(ni);
2965         return ret;
2966 #undef senderr
2967 #undef HTFLAGS
2968 }
2969
2970 /*
2971  * Return an mbuf with a probe response frame in it.
2972  * Space is left to prepend and 802.11 header at the
2973  * front but it's left to the caller to fill in.
2974  */
2975 struct mbuf *
2976 ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy)
2977 {
2978         struct ieee80211vap *vap = bss->ni_vap;
2979         struct ieee80211com *ic = bss->ni_ic;
2980         const struct ieee80211_rateset *rs;
2981         struct mbuf *m;
2982         uint16_t capinfo;
2983         uint8_t *frm;
2984
2985         /*
2986          * probe response frame format
2987          *      [8] time stamp
2988          *      [2] beacon interval
2989          *      [2] cabability information
2990          *      [tlv] ssid
2991          *      [tlv] supported rates
2992          *      [tlv] parameter set (FH/DS)
2993          *      [tlv] parameter set (IBSS)
2994          *      [tlv] country (optional)
2995          *      [3] power control (optional)
2996          *      [5] channel switch announcement (CSA) (optional)
2997          *      [tlv] extended rate phy (ERP)
2998          *      [tlv] extended supported rates
2999          *      [tlv] RSN (optional)
3000          *      [tlv] HT capabilities
3001          *      [tlv] HT information
3002          *      [tlv] VHT capabilities
3003          *      [tlv] VHT information
3004          *      [tlv] WPA (optional)
3005          *      [tlv] WME (optional)
3006          *      [tlv] Vendor OUI HT capabilities (optional)
3007          *      [tlv] Vendor OUI HT information (optional)
3008          *      [tlv] Atheros capabilities
3009          *      [tlv] AppIE's (optional)
3010          *      [tlv] Mesh ID (MBSS)
3011          *      [tlv] Mesh Conf (MBSS)
3012          */
3013         m = ieee80211_getmgtframe(&frm,
3014                  ic->ic_headroom + sizeof(struct ieee80211_frame),
3015                  8
3016                + sizeof(uint16_t)
3017                + sizeof(uint16_t)
3018                + 2 + IEEE80211_NWID_LEN
3019                + 2 + IEEE80211_RATE_SIZE
3020                + 7      /* max(7,3) */
3021                + IEEE80211_COUNTRY_MAX_SIZE
3022                + 3
3023                + sizeof(struct ieee80211_csa_ie)
3024                + sizeof(struct ieee80211_quiet_ie)
3025                + 3
3026                + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
3027                + sizeof(struct ieee80211_ie_wpa)
3028                + sizeof(struct ieee80211_ie_htcap)
3029                + sizeof(struct ieee80211_ie_htinfo)
3030                + sizeof(struct ieee80211_ie_wpa)
3031                + sizeof(struct ieee80211_wme_param)
3032                + 4 + sizeof(struct ieee80211_ie_htcap)
3033                + 4 + sizeof(struct ieee80211_ie_htinfo)
3034                +  sizeof(struct ieee80211_ie_vhtcap)
3035                +  sizeof(struct ieee80211_ie_vht_operation)
3036 #ifdef IEEE80211_SUPPORT_SUPERG
3037                + sizeof(struct ieee80211_ath_ie)
3038 #endif
3039 #ifdef IEEE80211_SUPPORT_MESH
3040                + 2 + IEEE80211_MESHID_LEN
3041                + sizeof(struct ieee80211_meshconf_ie)
3042 #endif
3043                + (vap->iv_appie_proberesp != NULL ?
3044                         vap->iv_appie_proberesp->ie_len : 0)
3045         );
3046         if (m == NULL) {
3047                 vap->iv_stats.is_tx_nobuf++;
3048                 return NULL;
3049         }
3050
3051         memset(frm, 0, 8);      /* timestamp should be filled later */
3052         frm += 8;
3053         *(uint16_t *)frm = htole16(bss->ni_intval);
3054         frm += 2;
3055         capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
3056         *(uint16_t *)frm = htole16(capinfo);
3057         frm += 2;
3058
3059         frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen);
3060         rs = ieee80211_get_suprates(ic, bss->ni_chan);
3061         frm = ieee80211_add_rates(frm, rs);
3062
3063         if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) {
3064                 *frm++ = IEEE80211_ELEMID_FHPARMS;
3065                 *frm++ = 5;
3066                 *frm++ = bss->ni_fhdwell & 0x00ff;
3067                 *frm++ = (bss->ni_fhdwell >> 8) & 0x00ff;
3068                 *frm++ = IEEE80211_FH_CHANSET(
3069                     ieee80211_chan2ieee(ic, bss->ni_chan));
3070                 *frm++ = IEEE80211_FH_CHANPAT(
3071                     ieee80211_chan2ieee(ic, bss->ni_chan));
3072                 *frm++ = bss->ni_fhindex;
3073         } else {
3074                 *frm++ = IEEE80211_ELEMID_DSPARMS;
3075                 *frm++ = 1;
3076                 *frm++ = ieee80211_chan2ieee(ic, bss->ni_chan);
3077         }
3078
3079         if (vap->iv_opmode == IEEE80211_M_IBSS) {
3080                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
3081                 *frm++ = 2;
3082                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
3083         }
3084         if ((vap->iv_flags & IEEE80211_F_DOTH) ||
3085             (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
3086                 frm = ieee80211_add_countryie(frm, ic);
3087         if (vap->iv_flags & IEEE80211_F_DOTH) {
3088                 if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan))
3089                         frm = ieee80211_add_powerconstraint(frm, vap);
3090                 if (ic->ic_flags & IEEE80211_F_CSAPENDING)
3091                         frm = ieee80211_add_csa(frm, vap);
3092         }
3093         if (vap->iv_flags & IEEE80211_F_DOTH) {
3094                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3095                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
3096                         if (vap->iv_quiet)
3097                                 frm = ieee80211_add_quiet(frm, vap, 0);
3098                 }
3099         }
3100         if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan))
3101                 frm = ieee80211_add_erp(frm, ic);
3102         frm = ieee80211_add_xrates(frm, rs);
3103         frm = ieee80211_add_rsn(frm, vap);
3104         /*
3105          * NB: legacy 11b clients do not get certain ie's.
3106          *     The caller identifies such clients by passing
3107          *     a token in legacy to us.  Could expand this to be
3108          *     any legacy client for stuff like HT ie's.
3109          */
3110         if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
3111             legacy != IEEE80211_SEND_LEGACY_11B) {
3112                 frm = ieee80211_add_htcap(frm, bss);
3113                 frm = ieee80211_add_htinfo(frm, bss);
3114         }
3115         if (IEEE80211_IS_CHAN_VHT(bss->ni_chan) &&
3116             legacy != IEEE80211_SEND_LEGACY_11B) {
3117                 frm = ieee80211_add_vhtcap(frm, bss);
3118                 frm = ieee80211_add_vhtinfo(frm, bss);
3119         }
3120         frm = ieee80211_add_wpa(frm, vap);
3121         if (vap->iv_flags & IEEE80211_F_WME)
3122                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
3123                     !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
3124         if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
3125             (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT) &&
3126             legacy != IEEE80211_SEND_LEGACY_11B) {
3127                 frm = ieee80211_add_htcap_vendor(frm, bss);
3128                 frm = ieee80211_add_htinfo_vendor(frm, bss);
3129         }
3130 #ifdef IEEE80211_SUPPORT_SUPERG
3131         if ((vap->iv_flags & IEEE80211_F_ATHEROS) &&
3132             legacy != IEEE80211_SEND_LEGACY_11B)
3133                 frm = ieee80211_add_athcaps(frm, bss);
3134 #endif
3135         if (vap->iv_appie_proberesp != NULL)
3136                 frm = add_appie(frm, vap->iv_appie_proberesp);
3137 #ifdef IEEE80211_SUPPORT_MESH
3138         if (vap->iv_opmode == IEEE80211_M_MBSS) {
3139                 frm = ieee80211_add_meshid(frm, vap);
3140                 frm = ieee80211_add_meshconf(frm, vap);
3141         }
3142 #endif
3143         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
3144
3145         return m;
3146 }
3147
3148 /*
3149  * Send a probe response frame to the specified mac address.
3150  * This does not go through the normal mgt frame api so we
3151  * can specify the destination address and re-use the bss node
3152  * for the sta reference.
3153  */
3154 int
3155 ieee80211_send_proberesp(struct ieee80211vap *vap,
3156         const uint8_t da[IEEE80211_ADDR_LEN], int legacy)
3157 {
3158         struct ieee80211_node *bss = vap->iv_bss;
3159         struct ieee80211com *ic = vap->iv_ic;
3160         struct mbuf *m;
3161         int ret;
3162
3163         if (vap->iv_state == IEEE80211_S_CAC) {
3164                 IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss,
3165                     "block %s frame in CAC state", "probe response");
3166                 vap->iv_stats.is_tx_badstate++;
3167                 return EIO;             /* XXX */
3168         }
3169
3170         /*
3171          * Hold a reference on the node so it doesn't go away until after
3172          * the xmit is complete all the way in the driver.  On error we
3173          * will remove our reference.
3174          */
3175         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
3176             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
3177             __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr),
3178             ieee80211_node_refcnt(bss)+1);
3179         ieee80211_ref_node(bss);
3180
3181         m = ieee80211_alloc_proberesp(bss, legacy);
3182         if (m == NULL) {
3183                 ieee80211_free_node(bss);
3184                 return ENOMEM;
3185         }
3186
3187         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
3188         KASSERT(m != NULL, ("no room for header"));
3189
3190         IEEE80211_TX_LOCK(ic);
3191         ieee80211_send_setup(bss, m,
3192              IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP,
3193              IEEE80211_NONQOS_TID, vap->iv_myaddr, da, bss->ni_bssid);
3194         /* XXX power management? */
3195         m->m_flags |= M_ENCAP;          /* mark encapsulated */
3196
3197         M_WME_SETAC(m, WME_AC_BE);
3198
3199         IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
3200             "send probe resp on channel %u to %s%s\n",
3201             ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da),
3202             legacy ? " <legacy>" : "");
3203         IEEE80211_NODE_STAT(bss, tx_mgmt);
3204
3205         ret = ieee80211_raw_output(vap, bss, m, NULL);
3206         IEEE80211_TX_UNLOCK(ic);
3207         return (ret);
3208 }
3209
3210 /*
3211  * Allocate and build a RTS (Request To Send) control frame.
3212  */
3213 struct mbuf *
3214 ieee80211_alloc_rts(struct ieee80211com *ic,
3215         const uint8_t ra[IEEE80211_ADDR_LEN],
3216         const uint8_t ta[IEEE80211_ADDR_LEN],
3217         uint16_t dur)
3218 {
3219         struct ieee80211_frame_rts *rts;
3220         struct mbuf *m;
3221
3222         /* XXX honor ic_headroom */
3223         m = m_gethdr(M_NOWAIT, MT_DATA);
3224         if (m != NULL) {
3225                 rts = mtod(m, struct ieee80211_frame_rts *);
3226                 rts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
3227                         IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS;
3228                 rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3229                 *(u_int16_t *)rts->i_dur = htole16(dur);
3230                 IEEE80211_ADDR_COPY(rts->i_ra, ra);
3231                 IEEE80211_ADDR_COPY(rts->i_ta, ta);
3232
3233                 m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
3234         }
3235         return m;
3236 }
3237
3238 /*
3239  * Allocate and build a CTS (Clear To Send) control frame.
3240  */
3241 struct mbuf *
3242 ieee80211_alloc_cts(struct ieee80211com *ic,
3243         const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur)
3244 {
3245         struct ieee80211_frame_cts *cts;
3246         struct mbuf *m;
3247
3248         /* XXX honor ic_headroom */
3249         m = m_gethdr(M_NOWAIT, MT_DATA);
3250         if (m != NULL) {
3251                 cts = mtod(m, struct ieee80211_frame_cts *);
3252                 cts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
3253                         IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS;
3254                 cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3255                 *(u_int16_t *)cts->i_dur = htole16(dur);
3256                 IEEE80211_ADDR_COPY(cts->i_ra, ra);
3257
3258                 m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
3259         }
3260         return m;
3261 }
3262
3263 /*
3264  * Wrapper for CTS/RTS frame allocation.
3265  */
3266 struct mbuf *
3267 ieee80211_alloc_prot(struct ieee80211_node *ni, const struct mbuf *m,
3268     uint8_t rate, int prot)
3269 {
3270         struct ieee80211com *ic = ni->ni_ic;
3271         const struct ieee80211_frame *wh;
3272         struct mbuf *mprot;
3273         uint16_t dur;
3274         int pktlen, isshort;
3275
3276         KASSERT(prot == IEEE80211_PROT_RTSCTS ||
3277             prot == IEEE80211_PROT_CTSONLY,
3278             ("wrong protection type %d", prot));
3279
3280         wh = mtod(m, const struct ieee80211_frame *);
3281         pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3282         isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
3283         dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
3284             + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3285
3286         if (prot == IEEE80211_PROT_RTSCTS) {
3287                 /* NB: CTS is the same size as an ACK */
3288                 dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3289                 mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
3290         } else
3291                 mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
3292
3293         return (mprot);
3294 }
3295
3296 static void
3297 ieee80211_tx_mgt_timeout(void *arg)
3298 {
3299         struct ieee80211vap *vap = arg;
3300
3301         IEEE80211_LOCK(vap->iv_ic);
3302         if (vap->iv_state != IEEE80211_S_INIT &&
3303             (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3304                 /*
3305                  * NB: it's safe to specify a timeout as the reason here;
3306                  *     it'll only be used in the right state.
3307                  */
3308                 ieee80211_new_state_locked(vap, IEEE80211_S_SCAN,
3309                         IEEE80211_SCAN_FAIL_TIMEOUT);
3310         }
3311         IEEE80211_UNLOCK(vap->iv_ic);
3312 }
3313
3314 /*
3315  * This is the callback set on net80211-sourced transmitted
3316  * authentication request frames.
3317  *
3318  * This does a couple of things:
3319  *
3320  * + If the frame transmitted was a success, it schedules a future
3321  *   event which will transition the interface to scan.
3322  *   If a state transition _then_ occurs before that event occurs,
3323  *   said state transition will cancel this callout.
3324  *
3325  * + If the frame transmit was a failure, it immediately schedules
3326  *   the transition back to scan.
3327  */
3328 static void
3329 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
3330 {
3331         struct ieee80211vap *vap = ni->ni_vap;
3332         enum ieee80211_state ostate = (enum ieee80211_state)(uintptr_t)arg;
3333
3334         /*
3335          * Frame transmit completed; arrange timer callback.  If
3336          * transmit was successfully we wait for response.  Otherwise
3337          * we arrange an immediate callback instead of doing the
3338          * callback directly since we don't know what state the driver
3339          * is in (e.g. what locks it is holding).  This work should
3340          * not be too time-critical and not happen too often so the
3341          * added overhead is acceptable.
3342          *
3343          * XXX what happens if !acked but response shows up before callback?
3344          */
3345         if (vap->iv_state == ostate) {
3346                 callout_reset(&vap->iv_mgtsend,
3347                         status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
3348                         ieee80211_tx_mgt_timeout, vap);
3349         }
3350 }
3351
3352 static void
3353 ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm,
3354         struct ieee80211_node *ni)
3355 {
3356         struct ieee80211vap *vap = ni->ni_vap;
3357         struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
3358         struct ieee80211com *ic = ni->ni_ic;
3359         struct ieee80211_rateset *rs = &ni->ni_rates;
3360         uint16_t capinfo;
3361
3362         /*
3363          * beacon frame format
3364          *
3365          * TODO: update to 802.11-2012; a lot of stuff has changed;
3366          * vendor extensions should be at the end, etc.
3367          *
3368          *      [8] time stamp
3369          *      [2] beacon interval
3370          *      [2] cabability information
3371          *      [tlv] ssid
3372          *      [tlv] supported rates
3373          *      [3] parameter set (DS)
3374          *      [8] CF parameter set (optional)
3375          *      [tlv] parameter set (IBSS/TIM)
3376          *      [tlv] country (optional)
3377          *      [3] power control (optional)
3378          *      [5] channel switch announcement (CSA) (optional)
3379          * XXX TODO: Quiet
3380          * XXX TODO: IBSS DFS
3381          * XXX TODO: TPC report
3382          *      [tlv] extended rate phy (ERP)
3383          *      [tlv] extended supported rates
3384          *      [tlv] RSN parameters
3385          * XXX TODO: BSSLOAD
3386          * (XXX EDCA parameter set, QoS capability?)
3387          * XXX TODO: AP channel report
3388          *
3389          *      [tlv] HT capabilities
3390          *      [tlv] HT information
3391          *      XXX TODO: 20/40 BSS coexistence
3392          * Mesh:
3393          * XXX TODO: Meshid
3394          * XXX TODO: mesh config
3395          * XXX TODO: mesh awake window
3396          * XXX TODO: beacon timing (mesh, etc)
3397          * XXX TODO: MCCAOP Advertisement Overview
3398          * XXX TODO: MCCAOP Advertisement
3399          * XXX TODO: Mesh channel switch parameters
3400          * VHT:
3401          * XXX TODO: VHT capabilities
3402          * XXX TODO: VHT operation
3403          * XXX TODO: VHT transmit power envelope
3404          * XXX TODO: channel switch wrapper element
3405          * XXX TODO: extended BSS load element
3406          *
3407          * XXX Vendor-specific OIDs (e.g. Atheros)
3408          *      [tlv] WPA parameters
3409          *      [tlv] WME parameters
3410          *      [tlv] Vendor OUI HT capabilities (optional)
3411          *      [tlv] Vendor OUI HT information (optional)
3412          *      [tlv] Atheros capabilities (optional)
3413          *      [tlv] TDMA parameters (optional)
3414          *      [tlv] Mesh ID (MBSS)
3415          *      [tlv] Mesh Conf (MBSS)
3416          *      [tlv] application data (optional)
3417          */
3418
3419         memset(bo, 0, sizeof(*bo));
3420
3421         memset(frm, 0, 8);      /* XXX timestamp is set by hardware/driver */
3422         frm += 8;
3423         *(uint16_t *)frm = htole16(ni->ni_intval);
3424         frm += 2;
3425         capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
3426         bo->bo_caps = (uint16_t *)frm;
3427         *(uint16_t *)frm = htole16(capinfo);
3428         frm += 2;
3429         *frm++ = IEEE80211_ELEMID_SSID;
3430         if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) {
3431                 *frm++ = ni->ni_esslen;
3432                 memcpy(frm, ni->ni_essid, ni->ni_esslen);
3433                 frm += ni->ni_esslen;
3434         } else
3435                 *frm++ = 0;
3436         frm = ieee80211_add_rates(frm, rs);
3437         if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) {
3438                 *frm++ = IEEE80211_ELEMID_DSPARMS;
3439                 *frm++ = 1;
3440                 *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
3441         }
3442         if (ic->ic_flags & IEEE80211_F_PCF) {
3443                 bo->bo_cfp = frm;
3444                 frm = ieee80211_add_cfparms(frm, ic);
3445         }
3446         bo->bo_tim = frm;
3447         if (vap->iv_opmode == IEEE80211_M_IBSS) {
3448                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
3449                 *frm++ = 2;
3450                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
3451                 bo->bo_tim_len = 0;
3452         } else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
3453             vap->iv_opmode == IEEE80211_M_MBSS) {
3454                 /* TIM IE is the same for Mesh and Hostap */
3455                 struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
3456
3457                 tie->tim_ie = IEEE80211_ELEMID_TIM;
3458                 tie->tim_len = 4;       /* length */
3459                 tie->tim_count = 0;     /* DTIM count */ 
3460                 tie->tim_period = vap->iv_dtim_period;  /* DTIM period */
3461                 tie->tim_bitctl = 0;    /* bitmap control */
3462                 tie->tim_bitmap[0] = 0; /* Partial Virtual Bitmap */
3463                 frm += sizeof(struct ieee80211_tim_ie);
3464                 bo->bo_tim_len = 1;
3465         }
3466         bo->bo_tim_trailer = frm;
3467         if ((vap->iv_flags & IEEE80211_F_DOTH) ||
3468             (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
3469                 frm = ieee80211_add_countryie(frm, ic);
3470         if (vap->iv_flags & IEEE80211_F_DOTH) {
3471                 if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
3472                         frm = ieee80211_add_powerconstraint(frm, vap);
3473                 bo->bo_csa = frm;
3474                 if (ic->ic_flags & IEEE80211_F_CSAPENDING)
3475                         frm = ieee80211_add_csa(frm, vap);      
3476         } else
3477                 bo->bo_csa = frm;
3478
3479         bo->bo_quiet = NULL;
3480         if (vap->iv_flags & IEEE80211_F_DOTH) {
3481                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3482                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
3483                     (vap->iv_quiet == 1)) {
3484                         /*
3485                          * We only insert the quiet IE offset if
3486                          * the quiet IE is enabled.  Otherwise don't
3487                          * put it here or we'll just overwrite
3488                          * some other beacon contents.
3489                          */
3490                         if (vap->iv_quiet) {
3491                                 bo->bo_quiet = frm;
3492                                 frm = ieee80211_add_quiet(frm,vap, 0);
3493                         }
3494                 }
3495         }
3496
3497         if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) {
3498                 bo->bo_erp = frm;
3499                 frm = ieee80211_add_erp(frm, ic);
3500         }
3501         frm = ieee80211_add_xrates(frm, rs);
3502         frm = ieee80211_add_rsn(frm, vap);
3503         if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
3504                 frm = ieee80211_add_htcap(frm, ni);
3505                 bo->bo_htinfo = frm;
3506                 frm = ieee80211_add_htinfo(frm, ni);
3507         }
3508
3509         if (IEEE80211_IS_CHAN_VHT(ni->ni_chan)) {
3510                 frm = ieee80211_add_vhtcap(frm, ni);
3511                 bo->bo_vhtinfo = frm;
3512                 frm = ieee80211_add_vhtinfo(frm, ni);
3513                 /* Transmit power envelope */
3514                 /* Channel switch wrapper element */
3515                 /* Extended bss load element */
3516         }
3517
3518         frm = ieee80211_add_wpa(frm, vap);
3519         if (vap->iv_flags & IEEE80211_F_WME) {
3520                 bo->bo_wme = frm;
3521                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
3522                     !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
3523         }
3524         if (IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
3525             (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT)) {
3526                 frm = ieee80211_add_htcap_vendor(frm, ni);
3527                 frm = ieee80211_add_htinfo_vendor(frm, ni);
3528         }
3529
3530 #ifdef IEEE80211_SUPPORT_SUPERG
3531         if (vap->iv_flags & IEEE80211_F_ATHEROS) {
3532                 bo->bo_ath = frm;
3533                 frm = ieee80211_add_athcaps(frm, ni);
3534         }
3535 #endif
3536 #ifdef IEEE80211_SUPPORT_TDMA
3537         if (vap->iv_caps & IEEE80211_C_TDMA) {
3538                 bo->bo_tdma = frm;
3539                 frm = ieee80211_add_tdma(frm, vap);
3540         }
3541 #endif
3542         if (vap->iv_appie_beacon != NULL) {
3543                 bo->bo_appie = frm;
3544                 bo->bo_appie_len = vap->iv_appie_beacon->ie_len;
3545                 frm = add_appie(frm, vap->iv_appie_beacon);
3546         }
3547
3548         /* XXX TODO: move meshid/meshconf up to before vendor extensions? */
3549 #ifdef IEEE80211_SUPPORT_MESH
3550         if (vap->iv_opmode == IEEE80211_M_MBSS) {
3551                 frm = ieee80211_add_meshid(frm, vap);
3552                 bo->bo_meshconf = frm;
3553                 frm = ieee80211_add_meshconf(frm, vap);
3554         }
3555 #endif
3556         bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
3557         bo->bo_csa_trailer_len = frm - bo->bo_csa;
3558         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
3559 }
3560
3561 /*
3562  * Allocate a beacon frame and fillin the appropriate bits.
3563  */
3564 struct mbuf *
3565 ieee80211_beacon_alloc(struct ieee80211_node *ni)
3566 {
3567         struct ieee80211vap *vap = ni->ni_vap;
3568         struct ieee80211com *ic = ni->ni_ic;
3569         struct ifnet *ifp = vap->iv_ifp;
3570         struct ieee80211_frame *wh;
3571         struct mbuf *m;
3572         int pktlen;
3573         uint8_t *frm;
3574
3575         /*
3576          * Update the "We're putting the quiet IE in the beacon" state.
3577          */
3578         if (vap->iv_quiet == 1)
3579                 vap->iv_flags_ext |= IEEE80211_FEXT_QUIET_IE;
3580         else if (vap->iv_quiet == 0)
3581                 vap->iv_flags_ext &= ~IEEE80211_FEXT_QUIET_IE;
3582
3583         /*
3584          * beacon frame format
3585          *
3586          * Note: This needs updating for 802.11-2012.
3587          *
3588          *      [8] time stamp
3589          *      [2] beacon interval
3590          *      [2] cabability information
3591          *      [tlv] ssid
3592          *      [tlv] supported rates
3593          *      [3] parameter set (DS)
3594          *      [8] CF parameter set (optional)
3595          *      [tlv] parameter set (IBSS/TIM)
3596          *      [tlv] country (optional)
3597          *      [3] power control (optional)
3598          *      [5] channel switch announcement (CSA) (optional)
3599          *      [tlv] extended rate phy (ERP)
3600          *      [tlv] extended supported rates
3601          *      [tlv] RSN parameters
3602          *      [tlv] HT capabilities
3603          *      [tlv] HT information
3604          *      [tlv] VHT capabilities
3605          *      [tlv] VHT operation
3606          *      [tlv] Vendor OUI HT capabilities (optional)
3607          *      [tlv] Vendor OUI HT information (optional)
3608          * XXX Vendor-specific OIDs (e.g. Atheros)
3609          *      [tlv] WPA parameters
3610          *      [tlv] WME parameters
3611          *      [tlv] TDMA parameters (optional)
3612          *      [tlv] Mesh ID (MBSS)
3613          *      [tlv] Mesh Conf (MBSS)
3614          *      [tlv] application data (optional)
3615          * NB: we allocate the max space required for the TIM bitmap.
3616          * XXX how big is this?
3617          */
3618         pktlen =   8                                    /* time stamp */
3619                  + sizeof(uint16_t)                     /* beacon interval */
3620                  + sizeof(uint16_t)                     /* capabilities */
3621                  + 2 + ni->ni_esslen                    /* ssid */
3622                  + 2 + IEEE80211_RATE_SIZE              /* supported rates */
3623                  + 2 + 1                                /* DS parameters */
3624                  + 2 + 6                                /* CF parameters */
3625                  + 2 + 4 + vap->iv_tim_len              /* DTIM/IBSSPARMS */
3626                  + IEEE80211_COUNTRY_MAX_SIZE           /* country */
3627                  + 2 + 1                                /* power control */
3628                  + sizeof(struct ieee80211_csa_ie)      /* CSA */
3629                  + sizeof(struct ieee80211_quiet_ie)    /* Quiet */
3630                  + 2 + 1                                /* ERP */
3631                  + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
3632                  + (vap->iv_caps & IEEE80211_C_WPA ?    /* WPA 1+2 */
3633                         2*sizeof(struct ieee80211_ie_wpa) : 0)
3634                  /* XXX conditional? */
3635                  + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
3636                  + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
3637                  + sizeof(struct ieee80211_ie_vhtcap)/* VHT caps */
3638                  + sizeof(struct ieee80211_ie_vht_operation)/* VHT info */
3639                  + (vap->iv_caps & IEEE80211_C_WME ?    /* WME */
3640                         sizeof(struct ieee80211_wme_param) : 0)
3641 #ifdef IEEE80211_SUPPORT_SUPERG
3642                  + sizeof(struct ieee80211_ath_ie)      /* ATH */
3643 #endif
3644 #ifdef IEEE80211_SUPPORT_TDMA
3645                  + (vap->iv_caps & IEEE80211_C_TDMA ?   /* TDMA */
3646                         sizeof(struct ieee80211_tdma_param) : 0)
3647 #endif
3648 #ifdef IEEE80211_SUPPORT_MESH
3649                  + 2 + ni->ni_meshidlen
3650                  + sizeof(struct ieee80211_meshconf_ie)
3651 #endif
3652                  + IEEE80211_MAX_APPIE
3653                  ;
3654         m = ieee80211_getmgtframe(&frm,
3655                 ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
3656         if (m == NULL) {
3657                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
3658                         "%s: cannot get buf; size %u\n", __func__, pktlen);
3659                 vap->iv_stats.is_tx_nobuf++;
3660                 return NULL;
3661         }
3662         ieee80211_beacon_construct(m, frm, ni);
3663
3664         M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
3665         KASSERT(m != NULL, ("no space for 802.11 header?"));
3666         wh = mtod(m, struct ieee80211_frame *);
3667         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3668             IEEE80211_FC0_SUBTYPE_BEACON;
3669         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3670         *(uint16_t *)wh->i_dur = 0;
3671         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
3672         IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
3673         IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
3674         *(uint16_t *)wh->i_seq = 0;
3675
3676         return m;
3677 }
3678
3679 /*
3680  * Update the dynamic parts of a beacon frame based on the current state.
3681  */
3682 int
3683 ieee80211_beacon_update(struct ieee80211_node *ni, struct mbuf *m, int mcast)
3684 {
3685         struct ieee80211vap *vap = ni->ni_vap;
3686         struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
3687         struct ieee80211com *ic = ni->ni_ic;
3688         int len_changed = 0;
3689         uint16_t capinfo;
3690         struct ieee80211_frame *wh;
3691         ieee80211_seq seqno;
3692
3693         IEEE80211_LOCK(ic);
3694         /*
3695          * Handle 11h channel change when we've reached the count.
3696          * We must recalculate the beacon frame contents to account
3697          * for the new channel.  Note we do this only for the first
3698          * vap that reaches this point; subsequent vaps just update
3699          * their beacon state to reflect the recalculated channel.
3700          */
3701         if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) &&
3702             vap->iv_csa_count == ic->ic_csa_count) {
3703                 vap->iv_csa_count = 0;
3704                 /*
3705                  * Effect channel change before reconstructing the beacon
3706                  * frame contents as many places reference ni_chan.
3707                  */
3708                 if (ic->ic_csa_newchan != NULL)
3709                         ieee80211_csa_completeswitch(ic);
3710                 /*
3711                  * NB: ieee80211_beacon_construct clears all pending
3712                  * updates in bo_flags so we don't need to explicitly
3713                  * clear IEEE80211_BEACON_CSA.
3714                  */
3715                 ieee80211_beacon_construct(m,
3716                     mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3717
3718                 /* XXX do WME aggressive mode processing? */
3719                 IEEE80211_UNLOCK(ic);
3720                 return 1;               /* just assume length changed */
3721         }
3722
3723         /*
3724          * Handle the quiet time element being added and removed.
3725          * Again, for now we just cheat and reconstruct the whole
3726          * beacon - that way the gap is provided as appropriate.
3727          *
3728          * So, track whether we have already added the IE versus
3729          * whether we want to be adding the IE.
3730          */
3731         if ((vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE) &&
3732             (vap->iv_quiet == 0)) {
3733                 /*
3734                  * Quiet time beacon IE enabled, but it's disabled;
3735                  * recalc
3736                  */
3737                 vap->iv_flags_ext &= ~IEEE80211_FEXT_QUIET_IE;
3738                 ieee80211_beacon_construct(m,
3739                     mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3740                 /* XXX do WME aggressive mode processing? */
3741                 IEEE80211_UNLOCK(ic);
3742                 return 1;               /* just assume length changed */
3743         }
3744
3745         if (((vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE) == 0) &&
3746             (vap->iv_quiet == 1)) {
3747                 /*
3748                  * Quiet time beacon IE disabled, but it's now enabled;
3749                  * recalc
3750                  */
3751                 vap->iv_flags_ext |= IEEE80211_FEXT_QUIET_IE;
3752                 ieee80211_beacon_construct(m,
3753                     mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3754                 /* XXX do WME aggressive mode processing? */
3755                 IEEE80211_UNLOCK(ic);
3756                 return 1;               /* just assume length changed */
3757         }
3758
3759         wh = mtod(m, struct ieee80211_frame *);
3760
3761         /*
3762          * XXX TODO Strictly speaking this should be incremented with the TX
3763          * lock held so as to serialise access to the non-qos TID sequence
3764          * number space.
3765          *
3766          * If the driver identifies it does its own TX seqno management then
3767          * we can skip this (and still not do the TX seqno.)
3768          */
3769         seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
3770         *(uint16_t *)&wh->i_seq[0] =
3771                 htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
3772         M_SEQNO_SET(m, seqno);
3773
3774         /* XXX faster to recalculate entirely or just changes? */
3775         capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
3776         *bo->bo_caps = htole16(capinfo);
3777
3778         if (vap->iv_flags & IEEE80211_F_WME) {
3779                 struct ieee80211_wme_state *wme = &ic->ic_wme;
3780
3781                 /*
3782                  * Check for aggressive mode change.  When there is
3783                  * significant high priority traffic in the BSS
3784                  * throttle back BE traffic by using conservative
3785                  * parameters.  Otherwise BE uses aggressive params
3786                  * to optimize performance of legacy/non-QoS traffic.
3787                  */
3788                 if (wme->wme_flags & WME_F_AGGRMODE) {
3789                         if (wme->wme_hipri_traffic >
3790                             wme->wme_hipri_switch_thresh) {
3791                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
3792                                     "%s: traffic %u, disable aggressive mode\n",
3793                                     __func__, wme->wme_hipri_traffic);
3794                                 wme->wme_flags &= ~WME_F_AGGRMODE;
3795                                 ieee80211_wme_updateparams_locked(vap);
3796                                 wme->wme_hipri_traffic =
3797                                         wme->wme_hipri_switch_hysteresis;
3798                         } else
3799                                 wme->wme_hipri_traffic = 0;
3800                 } else {
3801                         if (wme->wme_hipri_traffic <=
3802                             wme->wme_hipri_switch_thresh) {
3803                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
3804                                     "%s: traffic %u, enable aggressive mode\n",
3805                                     __func__, wme->wme_hipri_traffic);
3806                                 wme->wme_flags |= WME_F_AGGRMODE;
3807                                 ieee80211_wme_updateparams_locked(vap);
3808                                 wme->wme_hipri_traffic = 0;
3809                         } else
3810                                 wme->wme_hipri_traffic =
3811                                         wme->wme_hipri_switch_hysteresis;
3812                 }
3813                 if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
3814                         (void) ieee80211_add_wme_param(bo->bo_wme, wme,
3815                           vap->iv_flags_ext & IEEE80211_FEXT_UAPSD);
3816                         clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
3817                 }
3818         }
3819
3820         if (isset(bo->bo_flags,  IEEE80211_BEACON_HTINFO)) {
3821                 ieee80211_ht_update_beacon(vap, bo);
3822                 clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
3823         }
3824 #ifdef IEEE80211_SUPPORT_TDMA
3825         if (vap->iv_caps & IEEE80211_C_TDMA) {
3826                 /*
3827                  * NB: the beacon is potentially updated every TBTT.
3828                  */
3829                 ieee80211_tdma_update_beacon(vap, bo);
3830         }
3831 #endif
3832 #ifdef IEEE80211_SUPPORT_MESH
3833         if (vap->iv_opmode == IEEE80211_M_MBSS)
3834                 ieee80211_mesh_update_beacon(vap, bo);
3835 #endif
3836
3837         if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
3838             vap->iv_opmode == IEEE80211_M_MBSS) {       /* NB: no IBSS support*/
3839                 struct ieee80211_tim_ie *tie =
3840                         (struct ieee80211_tim_ie *) bo->bo_tim;
3841                 if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
3842                         u_int timlen, timoff, i;
3843                         /* 
3844                          * ATIM/DTIM needs updating.  If it fits in the
3845                          * current space allocated then just copy in the
3846                          * new bits.  Otherwise we need to move any trailing
3847                          * data to make room.  Note that we know there is
3848                          * contiguous space because ieee80211_beacon_allocate
3849                          * insures there is space in the mbuf to write a
3850                          * maximal-size virtual bitmap (based on iv_max_aid).
3851                          */
3852                         /*
3853                          * Calculate the bitmap size and offset, copy any
3854                          * trailer out of the way, and then copy in the
3855                          * new bitmap and update the information element.
3856                          * Note that the tim bitmap must contain at least
3857                          * one byte and any offset must be even.
3858                          */
3859                         if (vap->iv_ps_pending != 0) {
3860                                 timoff = 128;           /* impossibly large */
3861                                 for (i = 0; i < vap->iv_tim_len; i++)
3862                                         if (vap->iv_tim_bitmap[i]) {
3863                                                 timoff = i &~ 1;
3864                                                 break;
3865                                         }
3866                                 KASSERT(timoff != 128, ("tim bitmap empty!"));
3867                                 for (i = vap->iv_tim_len-1; i >= timoff; i--)
3868                                         if (vap->iv_tim_bitmap[i])
3869                                                 break;
3870                                 timlen = 1 + (i - timoff);
3871                         } else {
3872                                 timoff = 0;
3873                                 timlen = 1;
3874                         }
3875
3876                         /*
3877                          * TODO: validate this!
3878                          */
3879                         if (timlen != bo->bo_tim_len) {
3880                                 /* copy up/down trailer */
3881                                 int adjust = tie->tim_bitmap+timlen
3882                                            - bo->bo_tim_trailer;
3883                                 ovbcopy(bo->bo_tim_trailer,
3884                                     bo->bo_tim_trailer+adjust,
3885                                     bo->bo_tim_trailer_len);
3886                                 bo->bo_tim_trailer += adjust;
3887                                 bo->bo_erp += adjust;
3888                                 bo->bo_htinfo += adjust;
3889                                 bo->bo_vhtinfo += adjust;
3890 #ifdef IEEE80211_SUPPORT_SUPERG
3891                                 bo->bo_ath += adjust;
3892 #endif
3893 #ifdef IEEE80211_SUPPORT_TDMA
3894                                 bo->bo_tdma += adjust;
3895 #endif
3896 #ifdef IEEE80211_SUPPORT_MESH
3897                                 bo->bo_meshconf += adjust;
3898 #endif
3899                                 bo->bo_appie += adjust;
3900                                 bo->bo_wme += adjust;
3901                                 bo->bo_csa += adjust;
3902                                 bo->bo_quiet += adjust;
3903                                 bo->bo_tim_len = timlen;
3904
3905                                 /* update information element */
3906                                 tie->tim_len = 3 + timlen;
3907                                 tie->tim_bitctl = timoff;
3908                                 len_changed = 1;
3909                         }
3910                         memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff,
3911                                 bo->bo_tim_len);
3912
3913                         clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
3914
3915                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER,
3916                                 "%s: TIM updated, pending %u, off %u, len %u\n",
3917                                 __func__, vap->iv_ps_pending, timoff, timlen);
3918                 }
3919                 /* count down DTIM period */
3920                 if (tie->tim_count == 0)
3921                         tie->tim_count = tie->tim_period - 1;
3922                 else
3923                         tie->tim_count--;
3924                 /* update state for buffered multicast frames on DTIM */
3925                 if (mcast && tie->tim_count == 0)
3926                         tie->tim_bitctl |= 1;
3927                 else
3928                         tie->tim_bitctl &= ~1;
3929                 if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) {
3930                         struct ieee80211_csa_ie *csa =
3931                             (struct ieee80211_csa_ie *) bo->bo_csa;
3932
3933                         /*
3934                          * Insert or update CSA ie.  If we're just starting
3935                          * to count down to the channel switch then we need
3936                          * to insert the CSA ie.  Otherwise we just need to
3937                          * drop the count.  The actual change happens above
3938                          * when the vap's count reaches the target count.
3939                          */
3940                         if (vap->iv_csa_count == 0) {
3941                                 memmove(&csa[1], csa, bo->bo_csa_trailer_len);
3942                                 bo->bo_erp += sizeof(*csa);
3943                                 bo->bo_htinfo += sizeof(*csa);
3944                                 bo->bo_vhtinfo += sizeof(*csa);
3945                                 bo->bo_wme += sizeof(*csa);
3946 #ifdef IEEE80211_SUPPORT_SUPERG
3947                                 bo->bo_ath += sizeof(*csa);
3948 #endif
3949 #ifdef IEEE80211_SUPPORT_TDMA
3950                                 bo->bo_tdma += sizeof(*csa);
3951 #endif
3952 #ifdef IEEE80211_SUPPORT_MESH
3953                                 bo->bo_meshconf += sizeof(*csa);
3954 #endif
3955                                 bo->bo_appie += sizeof(*csa);
3956                                 bo->bo_csa_trailer_len += sizeof(*csa);
3957                                 bo->bo_quiet += sizeof(*csa);
3958                                 bo->bo_tim_trailer_len += sizeof(*csa);
3959                                 m->m_len += sizeof(*csa);
3960                                 m->m_pkthdr.len += sizeof(*csa);
3961
3962                                 ieee80211_add_csa(bo->bo_csa, vap);
3963                         } else
3964                                 csa->csa_count--;
3965                         vap->iv_csa_count++;
3966                         /* NB: don't clear IEEE80211_BEACON_CSA */
3967                 }
3968
3969                 /*
3970                  * Only add the quiet time IE if we've enabled it
3971                  * as appropriate.
3972                  */
3973                 if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3974                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
3975                         if (vap->iv_quiet &&
3976                             (vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE)) {
3977                                 ieee80211_add_quiet(bo->bo_quiet, vap, 1);
3978                         }
3979                 }
3980                 if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
3981                         /*
3982                          * ERP element needs updating.
3983                          */
3984                         (void) ieee80211_add_erp(bo->bo_erp, ic);
3985                         clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
3986                 }
3987 #ifdef IEEE80211_SUPPORT_SUPERG
3988                 if (isset(bo->bo_flags,  IEEE80211_BEACON_ATH)) {
3989                         ieee80211_add_athcaps(bo->bo_ath, ni);
3990                         clrbit(bo->bo_flags, IEEE80211_BEACON_ATH);
3991                 }
3992 #endif
3993         }
3994         if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) {
3995                 const struct ieee80211_appie *aie = vap->iv_appie_beacon;
3996                 int aielen;
3997                 uint8_t *frm;
3998
3999                 aielen = 0;
4000                 if (aie != NULL)
4001                         aielen += aie->ie_len;
4002                 if (aielen != bo->bo_appie_len) {
4003                         /* copy up/down trailer */
4004                         int adjust = aielen - bo->bo_appie_len;
4005                         ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust,
4006                                 bo->bo_tim_trailer_len);
4007                         bo->bo_tim_trailer += adjust;
4008                         bo->bo_appie += adjust;
4009                         bo->bo_appie_len = aielen;
4010
4011                         len_changed = 1;
4012                 }
4013                 frm = bo->bo_appie;
4014                 if (aie != NULL)
4015                         frm  = add_appie(frm, aie);
4016                 clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE);
4017         }
4018         IEEE80211_UNLOCK(ic);
4019
4020         return len_changed;
4021 }
4022
4023 /*
4024  * Do Ethernet-LLC encapsulation for each payload in a fast frame
4025  * tunnel encapsulation.  The frame is assumed to have an Ethernet
4026  * header at the front that must be stripped before prepending the
4027  * LLC followed by the Ethernet header passed in (with an Ethernet
4028  * type that specifies the payload size).
4029  */
4030 struct mbuf *
4031 ieee80211_ff_encap1(struct ieee80211vap *vap, struct mbuf *m,
4032         const struct ether_header *eh)
4033 {
4034         struct llc *llc;
4035         uint16_t payload;
4036
4037         /* XXX optimize by combining m_adj+M_PREPEND */
4038         m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
4039         llc = mtod(m, struct llc *);
4040         llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
4041         llc->llc_control = LLC_UI;
4042         llc->llc_snap.org_code[0] = 0;
4043         llc->llc_snap.org_code[1] = 0;
4044         llc->llc_snap.org_code[2] = 0;
4045         llc->llc_snap.ether_type = eh->ether_type;
4046         payload = m->m_pkthdr.len;              /* NB: w/o Ethernet header */
4047
4048         M_PREPEND(m, sizeof(struct ether_header), M_NOWAIT);
4049         if (m == NULL) {                /* XXX cannot happen */
4050                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
4051                         "%s: no space for ether_header\n", __func__);
4052                 vap->iv_stats.is_tx_nobuf++;
4053                 return NULL;
4054         }
4055         ETHER_HEADER_COPY(mtod(m, void *), eh);
4056         mtod(m, struct ether_header *)->ether_type = htons(payload);
4057         return m;
4058 }
4059
4060 /*
4061  * Complete an mbuf transmission.
4062  *
4063  * For now, this simply processes a completed frame after the
4064  * driver has completed it's transmission and/or retransmission.
4065  * It assumes the frame is an 802.11 encapsulated frame.
4066  *
4067  * Later on it will grow to become the exit path for a given frame
4068  * from the driver and, depending upon how it's been encapsulated
4069  * and already transmitted, it may end up doing A-MPDU retransmission,
4070  * power save requeuing, etc.
4071  *
4072  * In order for the above to work, the driver entry point to this
4073  * must not hold any driver locks.  Thus, the driver needs to delay
4074  * any actual mbuf completion until it can release said locks.
4075  *
4076  * This frees the mbuf and if the mbuf has a node reference,
4077  * the node reference will be freed.
4078  */
4079 void
4080 ieee80211_tx_complete(struct ieee80211_node *ni, struct mbuf *m, int status)
4081 {
4082
4083         if (ni != NULL) {
4084                 struct ifnet *ifp = ni->ni_vap->iv_ifp;
4085
4086                 if (status == 0) {
4087                         if_inc_counter(ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len);
4088                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
4089                         if (m->m_flags & M_MCAST)
4090                                 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
4091                 } else
4092                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4093                 if (m->m_flags & M_TXCB)
4094                         ieee80211_process_callback(ni, m, status);
4095                 ieee80211_free_node(ni);
4096         }
4097         m_freem(m);
4098 }