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