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