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