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