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