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