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