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