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