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