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