source: rtems-libbsd/freebsd/sys/net80211/ieee80211_output.c @ a241ea8

55-freebsd-126-freebsd-12
Last change on this file since a241ea8 was a241ea8, checked in by Christian Mauderer <Christian.Mauderer@…>, on 11/14/16 at 12:46:13

Import IEEE 802.11 from FreeBSD.

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