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