ieee80211_output.c revision 172231
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2007 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 172231 2007-09-18 21:07:41Z sam $");
29
30#include "opt_inet.h"
31
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/mbuf.h>
35#include <sys/kernel.h>
36#include <sys/endian.h>
37
38#include <sys/socket.h>
39
40#include <net/bpf.h>
41#include <net/ethernet.h>
42#include <net/if.h>
43#include <net/if_llc.h>
44#include <net/if_media.h>
45#include <net/if_vlan_var.h>
46
47#include <net80211/ieee80211_var.h>
48#include <net80211/ieee80211_regdomain.h>
49
50#ifdef INET
51#include <netinet/in.h>
52#include <netinet/if_ether.h>
53#include <netinet/in_systm.h>
54#include <netinet/ip.h>
55#endif
56
57#define	ETHER_HEADER_COPY(dst, src) \
58	memcpy(dst, src, sizeof(struct ether_header))
59
60static struct mbuf *ieee80211_encap_fastframe(struct ieee80211com *ic,
61	struct mbuf *m1, const struct ether_header *eh1,
62	struct mbuf *m2, const struct ether_header *eh2);
63static int ieee80211_fragment(struct ieee80211com *, struct mbuf *,
64	u_int hdrsize, u_int ciphdrsize, u_int mtu);
65static	void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
66
67#ifdef IEEE80211_DEBUG
68/*
69 * Decide if an outbound management frame should be
70 * printed when debugging is enabled.  This filters some
71 * of the less interesting frames that come frequently
72 * (e.g. beacons).
73 */
74static __inline int
75doprint(struct ieee80211com *ic, int subtype)
76{
77	switch (subtype) {
78	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
79		return (ic->ic_opmode == IEEE80211_M_IBSS);
80	}
81	return 1;
82}
83#endif
84
85/*
86 * Set the direction field and address fields of an outgoing
87 * non-QoS frame.  Note this should be called early on in
88 * constructing a frame as it sets i_fc[1]; other bits can
89 * then be or'd in.
90 */
91static void
92ieee80211_send_setup(struct ieee80211com *ic,
93	struct ieee80211_node *ni,
94	struct ieee80211_frame *wh,
95	int type,
96	const uint8_t sa[IEEE80211_ADDR_LEN],
97	const uint8_t da[IEEE80211_ADDR_LEN],
98	const uint8_t bssid[IEEE80211_ADDR_LEN])
99{
100#define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
101
102	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
103	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
104		switch (ic->ic_opmode) {
105		case IEEE80211_M_STA:
106			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
107			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
108			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
109			IEEE80211_ADDR_COPY(wh->i_addr3, da);
110			break;
111		case IEEE80211_M_IBSS:
112		case IEEE80211_M_AHDEMO:
113			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
114			IEEE80211_ADDR_COPY(wh->i_addr1, da);
115			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
116			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
117			break;
118		case IEEE80211_M_HOSTAP:
119			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
120			IEEE80211_ADDR_COPY(wh->i_addr1, da);
121			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
122			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
123			break;
124		case IEEE80211_M_WDS:
125			wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
126			/* XXX cheat, bssid holds RA */
127			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
128			IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
129			IEEE80211_ADDR_COPY(wh->i_addr3, da);
130			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
131			break;
132		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
133			break;
134		}
135	} else {
136		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
137		IEEE80211_ADDR_COPY(wh->i_addr1, da);
138		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
139		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
140	}
141	*(uint16_t *)&wh->i_dur[0] = 0;
142	/* NB: use non-QoS tid */
143	*(uint16_t *)&wh->i_seq[0] =
144	    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
145	ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
146#undef WH4
147}
148
149/*
150 * Send a management frame to the specified node.  The node pointer
151 * must have a reference as the pointer will be passed to the driver
152 * and potentially held for a long time.  If the frame is successfully
153 * dispatched to the driver, then it is responsible for freeing the
154 * reference (and potentially free'ing up any associated storage).
155 */
156int
157ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
158    struct mbuf *m, int type)
159{
160	struct ifnet *ifp = ic->ic_ifp;
161	struct ieee80211_frame *wh;
162
163	KASSERT(ni != NULL, ("null node"));
164
165	/*
166	 * Yech, hack alert!  We want to pass the node down to the
167	 * driver's start routine.  If we don't do so then the start
168	 * routine must immediately look it up again and that can
169	 * cause a lock order reversal if, for example, this frame
170	 * is being sent because the station is being timedout and
171	 * the frame being sent is a DEAUTH message.  We could stick
172	 * this in an m_tag and tack that on to the mbuf.  However
173	 * that's rather expensive to do for every frame so instead
174	 * we stuff it in the rcvif field since outbound frames do
175	 * not (presently) use this.
176	 */
177	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
178	if (m == NULL)
179		return ENOMEM;
180	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
181	m->m_pkthdr.rcvif = (void *)ni;
182
183	wh = mtod(m, struct ieee80211_frame *);
184	ieee80211_send_setup(ic, ni, wh,
185		IEEE80211_FC0_TYPE_MGT | type,
186		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
187	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
188		m->m_flags &= ~M_LINK0;
189		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
190			"[%s] encrypting frame (%s)\n",
191			ether_sprintf(wh->i_addr1), __func__);
192		wh->i_fc[1] |= IEEE80211_FC1_WEP;
193	}
194	if (ni->ni_flags & IEEE80211_NODE_QOS) {
195		/* NB: force all management frames to the highest queue */
196		M_WME_SETAC(m, WME_AC_VO);
197	} else
198		M_WME_SETAC(m, WME_AC_BE);
199#ifdef IEEE80211_DEBUG
200	/* avoid printing too many frames */
201	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
202	    ieee80211_msg_dumppkts(ic)) {
203		printf("[%s] send %s on channel %u\n",
204		    ether_sprintf(wh->i_addr1),
205		    ieee80211_mgt_subtype_name[
206			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
207				IEEE80211_FC0_SUBTYPE_SHIFT],
208		    ieee80211_chan2ieee(ic, ic->ic_curchan));
209	}
210#endif
211	IEEE80211_NODE_STAT(ni, tx_mgmt);
212	IF_ENQUEUE(&ic->ic_mgtq, m);
213	if_start(ifp);
214	ifp->if_opackets++;
215
216	return 0;
217}
218
219/*
220 * Raw packet transmit stub for legacy drivers.
221 * Send the packet through the mgt q so we bypass
222 * the normal encapsulation work.
223 */
224int
225ieee80211_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
226	const struct ieee80211_bpf_params *params)
227{
228	struct ieee80211com *ic = ni->ni_ic;
229	struct ifnet *ifp = ic->ic_ifp;
230
231	m->m_pkthdr.rcvif = (void *) ni;
232	IF_ENQUEUE(&ic->ic_mgtq, m);
233	if_start(ifp);
234	ifp->if_opackets++;
235
236	return 0;
237}
238
239/*
240 * 802.11 output routine. This is (currently) used only to
241 * connect bpf write calls to the 802.11 layer for injecting
242 * raw 802.11 frames.  Note we locate the ieee80211com from
243 * the ifnet using a spare field setup at attach time.  This
244 * will go away when the virtual ap support comes in.
245 */
246int
247ieee80211_output(struct ifnet *ifp, struct mbuf *m,
248	struct sockaddr *dst, struct rtentry *rt0)
249{
250#define senderr(e) do { error = (e); goto bad;} while (0)
251	struct ieee80211com *ic = ifp->if_spare2;	/* XXX */
252	struct ieee80211_node *ni = NULL;
253	struct ieee80211_frame *wh;
254	int error;
255
256	/*
257	 * Hand to the 802.3 code if not tagged as
258	 * a raw 802.11 frame.
259	 */
260	if (dst->sa_family != AF_IEEE80211)
261		return ether_output(ifp, m, dst, rt0);
262#ifdef MAC
263	error = mac_check_ifnet_transmit(ifp, m);
264	if (error)
265		senderr(error);
266#endif
267	if (ifp->if_flags & IFF_MONITOR)
268		senderr(ENETDOWN);
269	if ((ifp->if_flags & IFF_UP) == 0)
270		senderr(ENETDOWN);
271
272	/* XXX bypass bridge, pfil, carp, etc. */
273
274	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
275		senderr(EIO);	/* XXX */
276	wh = mtod(m, struct ieee80211_frame *);
277	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
278	    IEEE80211_FC0_VERSION_0)
279		senderr(EIO);	/* XXX */
280
281	/* locate destination node */
282	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
283	case IEEE80211_FC1_DIR_NODS:
284	case IEEE80211_FC1_DIR_FROMDS:
285		ni = ieee80211_find_txnode(ic, wh->i_addr1);
286		break;
287	case IEEE80211_FC1_DIR_TODS:
288	case IEEE80211_FC1_DIR_DSTODS:
289		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
290			senderr(EIO);	/* XXX */
291		ni = ieee80211_find_txnode(ic, wh->i_addr3);
292		break;
293	default:
294		senderr(EIO);	/* XXX */
295	}
296	if (ni == NULL) {
297		/*
298		 * Permit packets w/ bpf params through regardless
299		 * (see below about sa_len).
300		 */
301		if (dst->sa_len == 0)
302			senderr(EHOSTUNREACH);
303		ni = ieee80211_ref_node(ic->ic_bss);
304	}
305
306	/* XXX ctrl frames should go through */
307	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
308	    (m->m_flags & M_PWR_SAV) == 0) {
309		/*
310		 * Station in power save mode; pass the frame
311		 * to the 802.11 layer and continue.  We'll get
312		 * the frame back when the time is right.
313		 */
314		ieee80211_pwrsave(ni, m);
315		error = 0;
316		goto reclaim;
317	}
318
319	/* calculate priority so drivers can find the tx queue */
320	/* XXX assumes an 802.3 frame */
321	if (ieee80211_classify(ic, m, ni))
322		senderr(EIO);		/* XXX */
323
324	BPF_MTAP(ifp, m);
325	/*
326	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
327	 * present by setting the sa_len field of the sockaddr (yes,
328	 * this is a hack).
329	 * NB: we assume sa_data is suitably aligned to cast.
330	 */
331	return ic->ic_raw_xmit(ni, m, (const struct ieee80211_bpf_params *)
332		(dst->sa_len ? dst->sa_data : NULL));
333bad:
334	if (m != NULL)
335		m_freem(m);
336reclaim:
337	if (ni != NULL)
338		ieee80211_free_node(ni);
339	return error;
340#undef senderr
341}
342
343/*
344 * Send a null data frame to the specified node.
345 *
346 * NB: the caller is assumed to have setup a node reference
347 *     for use; this is necessary to deal with a race condition
348 *     when probing for inactive stations.
349 */
350int
351ieee80211_send_nulldata(struct ieee80211_node *ni)
352{
353	struct ieee80211com *ic = ni->ni_ic;
354	struct ifnet *ifp = ic->ic_ifp;
355	struct mbuf *m;
356	struct ieee80211_frame *wh;
357
358	MGETHDR(m, M_NOWAIT, MT_DATA);
359	if (m == NULL) {
360		/* XXX debug msg */
361		ieee80211_unref_node(&ni);
362		ic->ic_stats.is_tx_nobuf++;
363		return ENOMEM;
364	}
365	MH_ALIGN(m, sizeof(struct ieee80211_frame));
366	m->m_pkthdr.rcvif = (void *) ni;
367
368	wh = mtod(m, struct ieee80211_frame *);
369	ieee80211_send_setup(ic, ni, wh,
370		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
371		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
372	/* NB: power management bit is never sent by an AP */
373	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
374	    ic->ic_opmode != IEEE80211_M_HOSTAP &&
375	    ic->ic_opmode != IEEE80211_M_WDS)
376		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
377	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
378	M_WME_SETAC(m, WME_AC_BE);
379
380	IEEE80211_NODE_STAT(ni, tx_data);
381
382	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
383	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
384	    ether_sprintf(ni->ni_macaddr),
385	    ieee80211_chan2ieee(ic, ic->ic_curchan),
386	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
387
388	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
389	if_start(ifp);
390
391	return 0;
392}
393
394/*
395 * Assign priority to a frame based on any vlan tag assigned
396 * to the station and/or any Diffserv setting in an IP header.
397 * Finally, if an ACM policy is setup (in station mode) it's
398 * applied.
399 */
400int
401ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
402{
403	int v_wme_ac, d_wme_ac, ac;
404#ifdef INET
405	struct ether_header *eh;
406#endif
407
408	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
409		ac = WME_AC_BE;
410		goto done;
411	}
412
413	/*
414	 * If node has a vlan tag then all traffic
415	 * to it must have a matching tag.
416	 */
417	v_wme_ac = 0;
418	if (ni->ni_vlan != 0) {
419		 if ((m->m_flags & M_VLANTAG) == 0) {
420			IEEE80211_NODE_STAT(ni, tx_novlantag);
421			return 1;
422		}
423		if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
424		    EVL_VLANOFTAG(ni->ni_vlan)) {
425			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
426			return 1;
427		}
428		/* map vlan priority to AC */
429		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
430		case 1:
431		case 2:
432			v_wme_ac = WME_AC_BK;
433			break;
434		case 0:
435		case 3:
436			v_wme_ac = WME_AC_BE;
437			break;
438		case 4:
439		case 5:
440			v_wme_ac = WME_AC_VI;
441			break;
442		case 6:
443		case 7:
444			v_wme_ac = WME_AC_VO;
445			break;
446		}
447	}
448
449#ifdef INET
450	eh = mtod(m, struct ether_header *);
451	if (eh->ether_type == htons(ETHERTYPE_IP)) {
452		const struct ip *ip = (struct ip *)
453			(mtod(m, uint8_t *) + sizeof (*eh));
454		/*
455		 * IP frame, map the TOS field.
456		 */
457		switch (ip->ip_tos) {
458		case 0x08:
459		case 0x20:
460			d_wme_ac = WME_AC_BK;	/* background */
461			break;
462		case 0x28:
463		case 0xa0:
464			d_wme_ac = WME_AC_VI;	/* video */
465			break;
466		case 0x30:			/* voice */
467		case 0xe0:
468		case 0x88:			/* XXX UPSD */
469		case 0xb8:
470			d_wme_ac = WME_AC_VO;
471			break;
472		default:
473			d_wme_ac = WME_AC_BE;
474			break;
475		}
476	} else {
477#endif /* INET */
478		d_wme_ac = WME_AC_BE;
479#ifdef INET
480	}
481#endif
482	/*
483	 * Use highest priority AC.
484	 */
485	if (v_wme_ac > d_wme_ac)
486		ac = v_wme_ac;
487	else
488		ac = d_wme_ac;
489
490	/*
491	 * Apply ACM policy.
492	 */
493	if (ic->ic_opmode == IEEE80211_M_STA) {
494		static const int acmap[4] = {
495			WME_AC_BK,	/* WME_AC_BE */
496			WME_AC_BK,	/* WME_AC_BK */
497			WME_AC_BE,	/* WME_AC_VI */
498			WME_AC_VI,	/* WME_AC_VO */
499		};
500		while (ac != WME_AC_BK &&
501		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
502			ac = acmap[ac];
503	}
504done:
505	M_WME_SETAC(m, ac);
506	return 0;
507}
508
509/*
510 * Insure there is sufficient contiguous space to encapsulate the
511 * 802.11 data frame.  If room isn't already there, arrange for it.
512 * Drivers and cipher modules assume we have done the necessary work
513 * and fail rudely if they don't find the space they need.
514 */
515static struct mbuf *
516ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
517	struct ieee80211_key *key, struct mbuf *m)
518{
519#define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
520	int needed_space = ic->ic_headroom + hdrsize;
521
522	if (key != NULL) {
523		/* XXX belongs in crypto code? */
524		needed_space += key->wk_cipher->ic_header;
525		/* XXX frags */
526		/*
527		 * When crypto is being done in the host we must insure
528		 * the data are writable for the cipher routines; clone
529		 * a writable mbuf chain.
530		 * XXX handle SWMIC specially
531		 */
532		if (key->wk_flags & (IEEE80211_KEY_SWCRYPT|IEEE80211_KEY_SWMIC)) {
533			m = m_unshare(m, M_NOWAIT);
534			if (m == NULL) {
535				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
536				    "%s: cannot get writable mbuf\n", __func__);
537				ic->ic_stats.is_tx_nobuf++; /* XXX new stat */
538				return NULL;
539			}
540		}
541	}
542	/*
543	 * We know we are called just before stripping an Ethernet
544	 * header and prepending an LLC header.  This means we know
545	 * there will be
546	 *	sizeof(struct ether_header) - sizeof(struct llc)
547	 * bytes recovered to which we need additional space for the
548	 * 802.11 header and any crypto header.
549	 */
550	/* XXX check trailing space and copy instead? */
551	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
552		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
553		if (n == NULL) {
554			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
555			    "%s: cannot expand storage\n", __func__);
556			ic->ic_stats.is_tx_nobuf++;
557			m_freem(m);
558			return NULL;
559		}
560		KASSERT(needed_space <= MHLEN,
561		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
562		/*
563		 * Setup new mbuf to have leading space to prepend the
564		 * 802.11 header and any crypto header bits that are
565		 * required (the latter are added when the driver calls
566		 * back to ieee80211_crypto_encap to do crypto encapsulation).
567		 */
568		/* NB: must be first 'cuz it clobbers m_data */
569		m_move_pkthdr(n, m);
570		n->m_len = 0;			/* NB: m_gethdr does not set */
571		n->m_data += needed_space;
572		/*
573		 * Pull up Ethernet header to create the expected layout.
574		 * We could use m_pullup but that's overkill (i.e. we don't
575		 * need the actual data) and it cannot fail so do it inline
576		 * for speed.
577		 */
578		/* NB: struct ether_header is known to be contiguous */
579		n->m_len += sizeof(struct ether_header);
580		m->m_len -= sizeof(struct ether_header);
581		m->m_data += sizeof(struct ether_header);
582		/*
583		 * Replace the head of the chain.
584		 */
585		n->m_next = m;
586		m = n;
587	}
588	return m;
589#undef TO_BE_RECLAIMED
590}
591
592/*
593 * Return the transmit key to use in sending a unicast frame.
594 * If a unicast key is set we use that.  When no unicast key is set
595 * we fall back to the default transmit key.
596 */
597static __inline struct ieee80211_key *
598ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
599{
600	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
601		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
602		    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
603			return NULL;
604		return &ic->ic_nw_keys[ic->ic_def_txkey];
605	} else {
606		return &ni->ni_ucastkey;
607	}
608}
609
610/*
611 * Return the transmit key to use in sending a multicast frame.
612 * Multicast traffic always uses the group key which is installed as
613 * the default tx key.
614 */
615static __inline struct ieee80211_key *
616ieee80211_crypto_getmcastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
617{
618	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
619	    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
620		return NULL;
621	return &ic->ic_nw_keys[ic->ic_def_txkey];
622}
623
624/*
625 * Encapsulate an outbound data frame.  The mbuf chain is updated.
626 * If an error is encountered NULL is returned.  The caller is required
627 * to provide a node reference and pullup the ethernet header in the
628 * first mbuf.
629 */
630struct mbuf *
631ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
632	struct ieee80211_node *ni)
633{
634	struct ether_header eh;
635	struct ieee80211_frame *wh;
636	struct ieee80211_key *key;
637	struct llc *llc;
638	int hdrsize, datalen, addqos, txfrag, isff;
639
640	/*
641	 * Copy existing Ethernet header to a safe place.  The
642	 * rest of the code assumes it's ok to strip it when
643	 * reorganizing state for the final encapsulation.
644	 */
645	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
646	memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
647
648	/*
649	 * Insure space for additional headers.  First identify
650	 * transmit key to use in calculating any buffer adjustments
651	 * required.  This is also used below to do privacy
652	 * encapsulation work.  Then calculate the 802.11 header
653	 * size and any padding required by the driver.
654	 *
655	 * Note key may be NULL if we fall back to the default
656	 * transmit key and that is not set.  In that case the
657	 * buffer may not be expanded as needed by the cipher
658	 * routines, but they will/should discard it.
659	 */
660	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
661		if (ic->ic_opmode == IEEE80211_M_STA ||
662		    !IEEE80211_IS_MULTICAST(eh.ether_dhost))
663			key = ieee80211_crypto_getucastkey(ic, ni);
664		else
665			key = ieee80211_crypto_getmcastkey(ic, ni);
666		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
667			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
668			    "[%s] no default transmit key (%s) deftxkey %u\n",
669			    ether_sprintf(eh.ether_dhost), __func__,
670			    ic->ic_def_txkey);
671			ic->ic_stats.is_tx_nodefkey++;
672			goto bad;
673		}
674	} else
675		key = NULL;
676	/* XXX 4-address format */
677	/*
678	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
679	 * frames so suppress use.  This may be an issue if other
680	 * ap's require all data frames to be QoS-encapsulated
681	 * once negotiated in which case we'll need to make this
682	 * configurable.
683	 */
684	addqos = (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) &&
685		 eh.ether_type != htons(ETHERTYPE_PAE);
686	if (addqos)
687		hdrsize = sizeof(struct ieee80211_qosframe);
688	else
689		hdrsize = sizeof(struct ieee80211_frame);
690	if (ic->ic_flags & IEEE80211_F_DATAPAD)
691		hdrsize = roundup(hdrsize, sizeof(uint32_t));
692
693	if ((isff = m->m_flags & M_FF) != 0) {
694		struct mbuf *m2;
695		struct ether_header eh2;
696
697		/*
698		 * Fast frame encapsulation.  There must be two packets
699		 * chained with m_nextpkt.  We do header adjustment for
700		 * each, add the tunnel encapsulation, and then concatenate
701		 * the mbuf chains to form a single frame for transmission.
702		 */
703		m2 = m->m_nextpkt;
704		if (m2 == NULL) {
705			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
706				"%s: only one frame\n", __func__);
707			goto bad;
708		}
709		m->m_nextpkt = NULL;
710		/*
711		 * Include fast frame headers in adjusting header
712		 * layout; this allocates space according to what
713		 * ieee80211_encap_fastframe will do.
714		 */
715		m = ieee80211_mbuf_adjust(ic,
716			hdrsize + sizeof(struct llc) + sizeof(uint32_t) + 2 +
717			    sizeof(struct ether_header),
718			key, m);
719		if (m == NULL) {
720			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
721			m_freem(m2);
722			goto bad;
723		}
724		/*
725		 * Copy second frame's Ethernet header out of line
726		 * and adjust for encapsulation headers.  Note that
727		 * we make room for padding in case there isn't room
728		 * at the end of first frame.
729		 */
730		KASSERT(m2->m_len >= sizeof(eh2), ("no ethernet header!"));
731		memcpy(&eh2, mtod(m2, caddr_t), sizeof(struct ether_header));
732		m2 = ieee80211_mbuf_adjust(ic,
733			ATH_FF_MAX_HDR_PAD + sizeof(struct ether_header),
734			NULL, m2);
735		if (m2 == NULL) {
736			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
737			goto bad;
738		}
739		m = ieee80211_encap_fastframe(ic, m, &eh, m2, &eh2);
740		if (m == NULL)
741			goto bad;
742	} else {
743		/*
744		 * Normal frame.
745		 */
746		m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
747		if (m == NULL) {
748			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
749			goto bad;
750		}
751		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
752		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
753		llc = mtod(m, struct llc *);
754		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
755		llc->llc_control = LLC_UI;
756		llc->llc_snap.org_code[0] = 0;
757		llc->llc_snap.org_code[1] = 0;
758		llc->llc_snap.org_code[2] = 0;
759		llc->llc_snap.ether_type = eh.ether_type;
760	}
761	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
762
763	M_PREPEND(m, hdrsize, M_DONTWAIT);
764	if (m == NULL) {
765		ic->ic_stats.is_tx_nobuf++;
766		goto bad;
767	}
768	wh = mtod(m, struct ieee80211_frame *);
769	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
770	*(uint16_t *)wh->i_dur = 0;
771	switch (ic->ic_opmode) {
772	case IEEE80211_M_STA:
773		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
774		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
775		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
776		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
777		break;
778	case IEEE80211_M_IBSS:
779	case IEEE80211_M_AHDEMO:
780		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
781		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
782		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
783		/*
784		 * NB: always use the bssid from ic_bss as the
785		 *     neighbor's may be stale after an ibss merge
786		 */
787		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
788		break;
789	case IEEE80211_M_HOSTAP:
790		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
791		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
792		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
793		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
794		break;
795	case IEEE80211_M_MONITOR:
796	case IEEE80211_M_WDS:
797		goto bad;
798	}
799	if (m->m_flags & M_MORE_DATA)
800		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
801	if (addqos) {
802		struct ieee80211_qosframe *qwh =
803			(struct ieee80211_qosframe *) wh;
804		int ac, tid;
805
806		ac = M_WME_GETAC(m);
807		/* map from access class/queue to 11e header priorty value */
808		tid = WME_AC_TO_TID(ac);
809		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
810		/*
811		 * Check if A-MPDU tx aggregation is setup or if we
812		 * should try to enable it.  The sta must be associated
813		 * with HT and A-MPDU enabled for use.  On the first
814		 * frame that goes out We issue an ADDBA request and
815		 * wait for a reply.  The frame being encapsulated
816		 * will go out w/o using A-MPDU, or possibly it might
817		 * be collected by the driver and held/retransmit.
818		 * ieee80211_ampdu_request handles staggering requests
819		 * in case the receiver NAK's us or we are otherwise
820		 * unable to establish a BA stream.
821		 */
822		if ((ni->ni_flags & IEEE80211_NODE_HT) &&
823		    (ic->ic_flags_ext & IEEE80211_FEXT_AMPDU_TX)) {
824			struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
825
826			if (IEEE80211_AMPDU_RUNNING(tap)) {
827				/*
828				 * Operational, mark frame for aggregation.
829				 */
830				qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_BA;
831			} else if (!IEEE80211_AMPDU_REQUESTED(tap)) {
832				/*
833				 * Not negotiated yet, request service.
834				 */
835				ieee80211_ampdu_request(ni, tap);
836			}
837		}
838		/* XXX works even when BA marked above */
839		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
840			qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
841		qwh->i_qos[1] = 0;
842		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
843
844		*(uint16_t *)wh->i_seq =
845		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
846		ni->ni_txseqs[tid]++;
847	} else {
848		*(uint16_t *)wh->i_seq =
849		    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
850		ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
851	}
852	/* check if xmit fragmentation is required */
853	txfrag = (m->m_pkthdr.len > ic->ic_fragthreshold &&
854	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
855	    !isff);		/* NB: don't fragment ff's */
856	if (key != NULL) {
857		/*
858		 * IEEE 802.1X: send EAPOL frames always in the clear.
859		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
860		 */
861		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
862		    ((ic->ic_flags & IEEE80211_F_WPA) &&
863		     (ic->ic_opmode == IEEE80211_M_STA ?
864		      !IEEE80211_KEY_UNDEFINED(key) :
865		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
866			wh->i_fc[1] |= IEEE80211_FC1_WEP;
867			if (!ieee80211_crypto_enmic(ic, key, m, txfrag)) {
868				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
869				    "[%s] enmic failed, discard frame\n",
870				    ether_sprintf(eh.ether_dhost));
871				ic->ic_stats.is_crypto_enmicfail++;
872				goto bad;
873			}
874		}
875	}
876	/*
877	 * NB: frag flags may leak from above; they should only
878	 *     be set on return to the caller if we fragment at
879	 *     the 802.11 layer.
880	 */
881	m->m_flags &= ~(M_FRAG | M_FIRSTFRAG);
882	if (txfrag && !ieee80211_fragment(ic, m, hdrsize,
883	    key != NULL ? key->wk_cipher->ic_header : 0, ic->ic_fragthreshold))
884		goto bad;
885
886	IEEE80211_NODE_STAT(ni, tx_data);
887	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
888		IEEE80211_NODE_STAT(ni, tx_mcast);
889	else
890		IEEE80211_NODE_STAT(ni, tx_ucast);
891	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
892
893	return m;
894bad:
895	if (m != NULL)
896		m_freem(m);
897	return NULL;
898}
899
900/*
901 * Do Ethernet-LLC encapsulation for each payload in a fast frame
902 * tunnel encapsulation.  The frame is assumed to have an Ethernet
903 * header at the front that must be stripped before prepending the
904 * LLC followed by the Ethernet header passed in (with an Ethernet
905 * type that specifies the payload size).
906 */
907static struct mbuf *
908ieee80211_encap1(struct ieee80211com *ic, struct mbuf *m,
909	const struct ether_header *eh)
910{
911	struct llc *llc;
912	uint16_t payload;
913
914	/* XXX optimize by combining m_adj+M_PREPEND */
915	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
916	llc = mtod(m, struct llc *);
917	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
918	llc->llc_control = LLC_UI;
919	llc->llc_snap.org_code[0] = 0;
920	llc->llc_snap.org_code[1] = 0;
921	llc->llc_snap.org_code[2] = 0;
922	llc->llc_snap.ether_type = eh->ether_type;
923	payload = m->m_pkthdr.len;		/* NB: w/o Ethernet header */
924
925	M_PREPEND(m, sizeof(struct ether_header), M_DONTWAIT);
926	if (m == NULL) {		/* XXX cannot happen */
927		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
928			"%s: no space for ether_header\n", __func__);
929		ic->ic_stats.is_tx_nobuf++;
930		return NULL;
931	}
932	ETHER_HEADER_COPY(mtod(m, void *), eh);
933	mtod(m, struct ether_header *)->ether_type = htons(payload);
934	return m;
935}
936
937/*
938 * Do fast frame tunnel encapsulation.  The two frames and
939 * Ethernet headers are supplied.  The caller is assumed to
940 * have arrange for space in the mbuf chains for encapsulating
941 * headers (to avoid major mbuf fragmentation).
942 *
943 * The encapsulated frame is returned or NULL if there is a
944 * problem (should not happen).
945 */
946static struct mbuf *
947ieee80211_encap_fastframe(struct ieee80211com *ic,
948	struct mbuf *m1, const struct ether_header *eh1,
949	struct mbuf *m2, const struct ether_header *eh2)
950{
951	struct llc *llc;
952	struct mbuf *m;
953	int pad;
954
955	/*
956	 * First, each frame gets a standard encapsulation.
957	 */
958	m1 = ieee80211_encap1(ic, m1, eh1);
959	if (m1 == NULL) {
960		m_freem(m2);
961		return NULL;
962	}
963	m2 = ieee80211_encap1(ic, m2, eh2);
964	if (m2 == NULL) {
965		m_freem(m1);
966		return NULL;
967	}
968
969	/*
970	 * Pad leading frame to a 4-byte boundary.  If there
971	 * is space at the end of the first frame, put it
972	 * there; otherwise prepend to the front of the second
973	 * frame.  We know doing the second will always work
974	 * because we reserve space above.  We prefer appending
975	 * as this typically has better DMA alignment properties.
976	 */
977	for (m = m1; m->m_next != NULL; m = m->m_next)
978		;
979	pad = roundup2(m1->m_pkthdr.len, 4) - m1->m_pkthdr.len;
980	if (pad) {
981		if (M_TRAILINGSPACE(m) < pad) {		/* prepend to second */
982			m2->m_data -= pad;
983			m2->m_len += pad;
984			m2->m_pkthdr.len += pad;
985		} else {				/* append to first */
986			m->m_len += pad;
987			m1->m_pkthdr.len += pad;
988		}
989	}
990
991	/*
992	 * Now, stick 'em together and prepend the tunnel headers;
993	 * first the Atheros tunnel header (all zero for now) and
994	 * then a special fast frame LLC.
995	 *
996	 * XXX optimize by prepending together
997	 */
998	m->m_next = m2;			/* NB: last mbuf from above */
999	m1->m_pkthdr.len += m2->m_pkthdr.len;
1000	M_PREPEND(m1, sizeof(uint32_t)+2, M_DONTWAIT);
1001	if (m1 == NULL) {		/* XXX cannot happen */
1002		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
1003			"%s: no space for tunnel header\n", __func__);
1004		ic->ic_stats.is_tx_nobuf++;
1005		return NULL;
1006	}
1007	memset(mtod(m1, void *), 0, sizeof(uint32_t)+2);
1008
1009	M_PREPEND(m1, sizeof(struct llc), M_DONTWAIT);
1010	if (m1 == NULL) {		/* XXX cannot happen */
1011		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
1012			"%s: no space for llc header\n", __func__);
1013		ic->ic_stats.is_tx_nobuf++;
1014		return NULL;
1015	}
1016	llc = mtod(m1, struct llc *);
1017	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1018	llc->llc_control = LLC_UI;
1019	llc->llc_snap.org_code[0] = ATH_FF_SNAP_ORGCODE_0;
1020	llc->llc_snap.org_code[1] = ATH_FF_SNAP_ORGCODE_1;
1021	llc->llc_snap.org_code[2] = ATH_FF_SNAP_ORGCODE_2;
1022	llc->llc_snap.ether_type = htons(ATH_FF_ETH_TYPE);
1023
1024	ic->ic_stats.is_ff_encap++;
1025
1026	return m1;
1027}
1028
1029/*
1030 * Fragment the frame according to the specified mtu.
1031 * The size of the 802.11 header (w/o padding) is provided
1032 * so we don't need to recalculate it.  We create a new
1033 * mbuf for each fragment and chain it through m_nextpkt;
1034 * we might be able to optimize this by reusing the original
1035 * packet's mbufs but that is significantly more complicated.
1036 */
1037static int
1038ieee80211_fragment(struct ieee80211com *ic, struct mbuf *m0,
1039	u_int hdrsize, u_int ciphdrsize, u_int mtu)
1040{
1041	struct ieee80211_frame *wh, *whf;
1042	struct mbuf *m, *prev, *next;
1043	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1044
1045	KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1046	KASSERT(m0->m_pkthdr.len > mtu,
1047		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1048
1049	wh = mtod(m0, struct ieee80211_frame *);
1050	/* NB: mark the first frag; it will be propagated below */
1051	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1052	totalhdrsize = hdrsize + ciphdrsize;
1053	fragno = 1;
1054	off = mtu - ciphdrsize;
1055	remainder = m0->m_pkthdr.len - off;
1056	prev = m0;
1057	do {
1058		fragsize = totalhdrsize + remainder;
1059		if (fragsize > mtu)
1060			fragsize = mtu;
1061		KASSERT(fragsize < MCLBYTES,
1062			("fragment size %u too big!", fragsize));
1063		if (fragsize > MHLEN)
1064			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1065		else
1066			m = m_gethdr(M_DONTWAIT, MT_DATA);
1067		if (m == NULL)
1068			goto bad;
1069		/* leave room to prepend any cipher header */
1070		m_align(m, fragsize - ciphdrsize);
1071
1072		/*
1073		 * Form the header in the fragment.  Note that since
1074		 * we mark the first fragment with the MORE_FRAG bit
1075		 * it automatically is propagated to each fragment; we
1076		 * need only clear it on the last fragment (done below).
1077		 */
1078		whf = mtod(m, struct ieee80211_frame *);
1079		memcpy(whf, wh, hdrsize);
1080		*(uint16_t *)&whf->i_seq[0] |= htole16(
1081			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
1082				IEEE80211_SEQ_FRAG_SHIFT);
1083		fragno++;
1084
1085		payload = fragsize - totalhdrsize;
1086		/* NB: destination is known to be contiguous */
1087		m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize);
1088		m->m_len = hdrsize + payload;
1089		m->m_pkthdr.len = hdrsize + payload;
1090		m->m_flags |= M_FRAG;
1091
1092		/* chain up the fragment */
1093		prev->m_nextpkt = m;
1094		prev = m;
1095
1096		/* deduct fragment just formed */
1097		remainder -= payload;
1098		off += payload;
1099	} while (remainder != 0);
1100	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
1101
1102	/* strip first mbuf now that everything has been copied */
1103	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
1104	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1105
1106	ic->ic_stats.is_tx_fragframes++;
1107	ic->ic_stats.is_tx_frags += fragno-1;
1108
1109	return 1;
1110bad:
1111	/* reclaim fragments but leave original frame for caller to free */
1112	for (m = m0->m_nextpkt; m != NULL; m = next) {
1113		next = m->m_nextpkt;
1114		m->m_nextpkt = NULL;		/* XXX paranoid */
1115		m_freem(m);
1116	}
1117	m0->m_nextpkt = NULL;
1118	return 0;
1119}
1120
1121/*
1122 * Add a supported rates element id to a frame.
1123 */
1124static uint8_t *
1125ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
1126{
1127	int nrates;
1128
1129	*frm++ = IEEE80211_ELEMID_RATES;
1130	nrates = rs->rs_nrates;
1131	if (nrates > IEEE80211_RATE_SIZE)
1132		nrates = IEEE80211_RATE_SIZE;
1133	*frm++ = nrates;
1134	memcpy(frm, rs->rs_rates, nrates);
1135	return frm + nrates;
1136}
1137
1138/*
1139 * Add an extended supported rates element id to a frame.
1140 */
1141static uint8_t *
1142ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
1143{
1144	/*
1145	 * Add an extended supported rates element if operating in 11g mode.
1146	 */
1147	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1148		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1149		*frm++ = IEEE80211_ELEMID_XRATES;
1150		*frm++ = nrates;
1151		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1152		frm += nrates;
1153	}
1154	return frm;
1155}
1156
1157/*
1158 * Add an ssid elemet to a frame.
1159 */
1160static uint8_t *
1161ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
1162{
1163	*frm++ = IEEE80211_ELEMID_SSID;
1164	*frm++ = len;
1165	memcpy(frm, ssid, len);
1166	return frm + len;
1167}
1168
1169/*
1170 * Add an erp element to a frame.
1171 */
1172static uint8_t *
1173ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
1174{
1175	uint8_t erp;
1176
1177	*frm++ = IEEE80211_ELEMID_ERP;
1178	*frm++ = 1;
1179	erp = 0;
1180	if (ic->ic_nonerpsta != 0)
1181		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1182	if (ic->ic_flags & IEEE80211_F_USEPROT)
1183		erp |= IEEE80211_ERP_USE_PROTECTION;
1184	if (ic->ic_flags & IEEE80211_F_USEBARKER)
1185		erp |= IEEE80211_ERP_LONG_PREAMBLE;
1186	*frm++ = erp;
1187	return frm;
1188}
1189
1190static uint8_t *
1191ieee80211_setup_wpa_ie(struct ieee80211com *ic, uint8_t *ie)
1192{
1193#define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
1194#define	ADDSHORT(frm, v) do {			\
1195	frm[0] = (v) & 0xff;			\
1196	frm[1] = (v) >> 8;			\
1197	frm += 2;				\
1198} while (0)
1199#define	ADDSELECTOR(frm, sel) do {		\
1200	memcpy(frm, sel, 4);			\
1201	frm += 4;				\
1202} while (0)
1203	static const uint8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
1204	static const uint8_t cipher_suite[][4] = {
1205		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
1206		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
1207		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
1208		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
1209		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1210		{ WPA_OUI_BYTES, WPA_CSE_NULL },
1211	};
1212	static const uint8_t wep104_suite[4] =
1213		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
1214	static const uint8_t key_mgt_unspec[4] =
1215		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
1216	static const uint8_t key_mgt_psk[4] =
1217		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
1218	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1219	uint8_t *frm = ie;
1220	uint8_t *selcnt;
1221
1222	*frm++ = IEEE80211_ELEMID_VENDOR;
1223	*frm++ = 0;				/* length filled in below */
1224	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
1225	frm += sizeof(oui);
1226	ADDSHORT(frm, WPA_VERSION);
1227
1228	/* XXX filter out CKIP */
1229
1230	/* multicast cipher */
1231	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1232	    rsn->rsn_mcastkeylen >= 13)
1233		ADDSELECTOR(frm, wep104_suite);
1234	else
1235		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1236
1237	/* unicast cipher list */
1238	selcnt = frm;
1239	ADDSHORT(frm, 0);			/* selector count */
1240	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
1241		selcnt[0]++;
1242		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1243	}
1244	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
1245		selcnt[0]++;
1246		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1247	}
1248
1249	/* authenticator selector list */
1250	selcnt = frm;
1251	ADDSHORT(frm, 0);			/* selector count */
1252	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1253		selcnt[0]++;
1254		ADDSELECTOR(frm, key_mgt_unspec);
1255	}
1256	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1257		selcnt[0]++;
1258		ADDSELECTOR(frm, key_mgt_psk);
1259	}
1260
1261	/* optional capabilities */
1262	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
1263		ADDSHORT(frm, rsn->rsn_caps);
1264
1265	/* calculate element length */
1266	ie[1] = frm - ie - 2;
1267	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1268		("WPA IE too big, %u > %zu",
1269		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1270	return frm;
1271#undef ADDSHORT
1272#undef ADDSELECTOR
1273#undef WPA_OUI_BYTES
1274}
1275
1276static uint8_t *
1277ieee80211_setup_rsn_ie(struct ieee80211com *ic, uint8_t *ie)
1278{
1279#define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
1280#define	ADDSHORT(frm, v) do {			\
1281	frm[0] = (v) & 0xff;			\
1282	frm[1] = (v) >> 8;			\
1283	frm += 2;				\
1284} while (0)
1285#define	ADDSELECTOR(frm, sel) do {		\
1286	memcpy(frm, sel, 4);			\
1287	frm += 4;				\
1288} while (0)
1289	static const uint8_t cipher_suite[][4] = {
1290		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
1291		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
1292		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
1293		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
1294		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1295		{ RSN_OUI_BYTES, RSN_CSE_NULL },
1296	};
1297	static const uint8_t wep104_suite[4] =
1298		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
1299	static const uint8_t key_mgt_unspec[4] =
1300		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
1301	static const uint8_t key_mgt_psk[4] =
1302		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
1303	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1304	uint8_t *frm = ie;
1305	uint8_t *selcnt;
1306
1307	*frm++ = IEEE80211_ELEMID_RSN;
1308	*frm++ = 0;				/* length filled in below */
1309	ADDSHORT(frm, RSN_VERSION);
1310
1311	/* XXX filter out CKIP */
1312
1313	/* multicast cipher */
1314	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1315	    rsn->rsn_mcastkeylen >= 13)
1316		ADDSELECTOR(frm, wep104_suite);
1317	else
1318		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1319
1320	/* unicast cipher list */
1321	selcnt = frm;
1322	ADDSHORT(frm, 0);			/* selector count */
1323	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
1324		selcnt[0]++;
1325		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1326	}
1327	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
1328		selcnt[0]++;
1329		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1330	}
1331
1332	/* authenticator selector list */
1333	selcnt = frm;
1334	ADDSHORT(frm, 0);			/* selector count */
1335	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1336		selcnt[0]++;
1337		ADDSELECTOR(frm, key_mgt_unspec);
1338	}
1339	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1340		selcnt[0]++;
1341		ADDSELECTOR(frm, key_mgt_psk);
1342	}
1343
1344	/* optional capabilities */
1345	ADDSHORT(frm, rsn->rsn_caps);
1346	/* XXX PMKID */
1347
1348	/* calculate element length */
1349	ie[1] = frm - ie - 2;
1350	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1351		("RSN IE too big, %u > %zu",
1352		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1353	return frm;
1354#undef ADDSELECTOR
1355#undef ADDSHORT
1356#undef RSN_OUI_BYTES
1357}
1358
1359/*
1360 * Add a WPA/RSN element to a frame.
1361 */
1362static uint8_t *
1363ieee80211_add_wpa(uint8_t *frm, struct ieee80211com *ic)
1364{
1365
1366	KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
1367	if (ic->ic_flags & IEEE80211_F_WPA2)
1368		frm = ieee80211_setup_rsn_ie(ic, frm);
1369	if (ic->ic_flags & IEEE80211_F_WPA1)
1370		frm = ieee80211_setup_wpa_ie(ic, frm);
1371	return frm;
1372}
1373
1374#define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1375/*
1376 * Add a WME information element to a frame.
1377 */
1378static uint8_t *
1379ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
1380{
1381	static const struct ieee80211_wme_info info = {
1382		.wme_id		= IEEE80211_ELEMID_VENDOR,
1383		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1384		.wme_oui	= { WME_OUI_BYTES },
1385		.wme_type	= WME_OUI_TYPE,
1386		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1387		.wme_version	= WME_VERSION,
1388		.wme_info	= 0,
1389	};
1390	memcpy(frm, &info, sizeof(info));
1391	return frm + sizeof(info);
1392}
1393
1394/*
1395 * Add a WME parameters element to a frame.
1396 */
1397static uint8_t *
1398ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
1399{
1400#define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1401#define	ADDSHORT(frm, v) do {			\
1402	frm[0] = (v) & 0xff;			\
1403	frm[1] = (v) >> 8;			\
1404	frm += 2;				\
1405} while (0)
1406	/* NB: this works 'cuz a param has an info at the front */
1407	static const struct ieee80211_wme_info param = {
1408		.wme_id		= IEEE80211_ELEMID_VENDOR,
1409		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1410		.wme_oui	= { WME_OUI_BYTES },
1411		.wme_type	= WME_OUI_TYPE,
1412		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1413		.wme_version	= WME_VERSION,
1414	};
1415	int i;
1416
1417	memcpy(frm, &param, sizeof(param));
1418	frm += __offsetof(struct ieee80211_wme_info, wme_info);
1419	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1420	*frm++ = 0;					/* reserved field */
1421	for (i = 0; i < WME_NUM_AC; i++) {
1422		const struct wmeParams *ac =
1423		       &wme->wme_bssChanParams.cap_wmeParams[i];
1424		*frm++ = SM(i, WME_PARAM_ACI)
1425		       | SM(ac->wmep_acm, WME_PARAM_ACM)
1426		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1427		       ;
1428		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1429		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1430		       ;
1431		ADDSHORT(frm, ac->wmep_txopLimit);
1432	}
1433	return frm;
1434#undef SM
1435#undef ADDSHORT
1436}
1437#undef WME_OUI_BYTES
1438
1439#define	ATH_OUI_BYTES		0x00, 0x03, 0x7f
1440/*
1441 * Add a WME information element to a frame.
1442 */
1443static uint8_t *
1444ieee80211_add_ath(uint8_t *frm, uint8_t caps, uint16_t defkeyix)
1445{
1446	static const struct ieee80211_ath_ie info = {
1447		.ath_id		= IEEE80211_ELEMID_VENDOR,
1448		.ath_len	= sizeof(struct ieee80211_ath_ie) - 2,
1449		.ath_oui	= { ATH_OUI_BYTES },
1450		.ath_oui_type	= ATH_OUI_TYPE,
1451		.ath_oui_subtype= ATH_OUI_SUBTYPE,
1452		.ath_version	= ATH_OUI_VERSION,
1453	};
1454	struct ieee80211_ath_ie *ath = (struct ieee80211_ath_ie *) frm;
1455
1456	memcpy(frm, &info, sizeof(info));
1457	ath->ath_capability = caps;
1458	ath->ath_defkeyix[0] = (defkeyix & 0xff);
1459	ath->ath_defkeyix[1] = ((defkeyix >> 8) & 0xff);
1460	return frm + sizeof(info);
1461}
1462#undef ATH_OUI_BYTES
1463
1464/*
1465 * Send a probe request frame with the specified ssid
1466 * and any optional information element data.
1467 */
1468int
1469ieee80211_send_probereq(struct ieee80211_node *ni,
1470	const uint8_t sa[IEEE80211_ADDR_LEN],
1471	const uint8_t da[IEEE80211_ADDR_LEN],
1472	const uint8_t bssid[IEEE80211_ADDR_LEN],
1473	const uint8_t *ssid, size_t ssidlen,
1474	const void *optie, size_t optielen)
1475{
1476	struct ieee80211com *ic = ni->ni_ic;
1477	struct ieee80211_frame *wh;
1478	const struct ieee80211_rateset *rs;
1479	struct mbuf *m;
1480	uint8_t *frm;
1481
1482	/*
1483	 * Hold a reference on the node so it doesn't go away until after
1484	 * the xmit is complete all the way in the driver.  On error we
1485	 * will remove our reference.
1486	 */
1487	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1488		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1489		__func__, __LINE__,
1490		ni, ether_sprintf(ni->ni_macaddr),
1491		ieee80211_node_refcnt(ni)+1);
1492	ieee80211_ref_node(ni);
1493
1494	/*
1495	 * prreq frame format
1496	 *	[tlv] ssid
1497	 *	[tlv] supported rates
1498	 *	[tlv] extended supported rates
1499	 *	[tlv] user-specified ie's
1500	 */
1501	m = ieee80211_getmgtframe(&frm,
1502		 ic->ic_headroom + sizeof(struct ieee80211_frame),
1503		 2 + IEEE80211_NWID_LEN
1504	       + 2 + IEEE80211_RATE_SIZE
1505	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1506	       + (optie != NULL ? optielen : 0)
1507	);
1508	if (m == NULL) {
1509		ic->ic_stats.is_tx_nobuf++;
1510		ieee80211_free_node(ni);
1511		return ENOMEM;
1512	}
1513
1514	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1515	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1516	frm = ieee80211_add_rates(frm, rs);
1517	frm = ieee80211_add_xrates(frm, rs);
1518
1519	if (optie != NULL) {
1520		memcpy(frm, optie, optielen);
1521		frm += optielen;
1522	}
1523	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1524
1525	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1526	if (m == NULL)
1527		return ENOMEM;
1528	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
1529	m->m_pkthdr.rcvif = (void *)ni;
1530
1531	wh = mtod(m, struct ieee80211_frame *);
1532	ieee80211_send_setup(ic, ni, wh,
1533		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1534		sa, da, bssid);
1535	/* XXX power management? */
1536
1537	IEEE80211_NODE_STAT(ni, tx_probereq);
1538	IEEE80211_NODE_STAT(ni, tx_mgmt);
1539
1540	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1541	    "[%s] send probe req on channel %u\n",
1542	    ether_sprintf(wh->i_addr1),
1543	    ieee80211_chan2ieee(ic, ic->ic_curchan));
1544
1545	IF_ENQUEUE(&ic->ic_mgtq, m);
1546	if_start(ic->ic_ifp);
1547	return 0;
1548}
1549
1550/*
1551 * Calculate capability information for mgt frames.
1552 */
1553static uint16_t
1554getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
1555{
1556	uint16_t capinfo;
1557
1558	KASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
1559
1560	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1561		capinfo = IEEE80211_CAPINFO_ESS;
1562	else if (ic->ic_opmode == IEEE80211_M_IBSS)
1563		capinfo = IEEE80211_CAPINFO_IBSS;
1564	else
1565		capinfo = 0;
1566	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1567		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1568	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1569	    IEEE80211_IS_CHAN_2GHZ(chan))
1570		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1571	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1572		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1573	return capinfo;
1574}
1575
1576/*
1577 * Send a management frame.  The node is for the destination (or ic_bss
1578 * when in station mode).  Nodes other than ic_bss have their reference
1579 * count bumped to reflect our use for an indeterminant time.
1580 */
1581int
1582ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1583	int type, int arg)
1584{
1585#define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1586	struct mbuf *m;
1587	uint8_t *frm;
1588	uint16_t capinfo;
1589	int has_challenge, is_shared_key, ret, status;
1590
1591	KASSERT(ni != NULL, ("null node"));
1592
1593	/*
1594	 * Hold a reference on the node so it doesn't go away until after
1595	 * the xmit is complete all the way in the driver.  On error we
1596	 * will remove our reference.
1597	 */
1598	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1599		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1600		__func__, __LINE__,
1601		ni, ether_sprintf(ni->ni_macaddr),
1602		ieee80211_node_refcnt(ni)+1);
1603	ieee80211_ref_node(ni);
1604
1605	switch (type) {
1606	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1607		/*
1608		 * probe response frame format
1609		 *	[8] time stamp
1610		 *	[2] beacon interval
1611		 *	[2] cabability information
1612		 *	[tlv] ssid
1613		 *	[tlv] supported rates
1614		 *	[tlv] parameter set (FH/DS)
1615		 *	[tlv] parameter set (IBSS)
1616		 *	[tlv] extended rate phy (ERP)
1617		 *	[tlv] extended supported rates
1618		 *	[tlv] WPA
1619		 *	[tlv] WME (optional)
1620		 *	[tlv] HT capabilities
1621		 *	[tlv] HT information
1622		 *	[tlv] Vendor OUI HT capabilities (optional)
1623		 *	[tlv] Vendor OUI HT information (optional)
1624		 *	[tlv] Atheros capabilities
1625		 */
1626		m = ieee80211_getmgtframe(&frm,
1627			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1628			 8
1629		       + sizeof(uint16_t)
1630		       + sizeof(uint16_t)
1631		       + 2 + IEEE80211_NWID_LEN
1632		       + 2 + IEEE80211_RATE_SIZE
1633		       + 7	/* max(7,3) */
1634		       + 6
1635		       + 3
1636		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1637		       /* XXX !WPA1+WPA2 fits w/o a cluster */
1638		       + (ic->ic_flags & IEEE80211_F_WPA ?
1639				2*sizeof(struct ieee80211_ie_wpa) : 0)
1640		       + sizeof(struct ieee80211_wme_param)
1641		       /* XXX check for cluster requirement */
1642		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
1643		       + 2*sizeof(struct ieee80211_ie_htinfo) + 4
1644		       + sizeof(struct ieee80211_ath_ie)
1645		);
1646		if (m == NULL)
1647			senderr(ENOMEM, is_tx_nobuf);
1648
1649		memset(frm, 0, 8);	/* timestamp should be filled later */
1650		frm += 8;
1651		*(uint16_t *)frm = htole16(ic->ic_bss->ni_intval);
1652		frm += 2;
1653		capinfo = getcapinfo(ic, ic->ic_curchan);
1654		*(uint16_t *)frm = htole16(capinfo);
1655		frm += 2;
1656
1657		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1658				ic->ic_bss->ni_esslen);
1659		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1660
1661		if (IEEE80211_IS_CHAN_FHSS(ic->ic_curchan)) {
1662                        *frm++ = IEEE80211_ELEMID_FHPARMS;
1663                        *frm++ = 5;
1664                        *frm++ = ni->ni_fhdwell & 0x00ff;
1665                        *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1666                        *frm++ = IEEE80211_FH_CHANSET(
1667			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1668                        *frm++ = IEEE80211_FH_CHANPAT(
1669			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1670                        *frm++ = ni->ni_fhindex;
1671		} else {
1672			*frm++ = IEEE80211_ELEMID_DSPARMS;
1673			*frm++ = 1;
1674			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
1675		}
1676
1677		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1678			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1679			*frm++ = 2;
1680			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1681		}
1682		if (ic->ic_flags & IEEE80211_F_WPA)
1683			frm = ieee80211_add_wpa(frm, ic);
1684		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
1685			frm = ieee80211_add_erp(frm, ic);
1686		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1687		if (ic->ic_flags & IEEE80211_F_WME)
1688			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1689		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1690			frm = ieee80211_add_htcap(frm, ni);
1691			frm = ieee80211_add_htinfo(frm, ni);
1692			if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT) {
1693				frm = ieee80211_add_htcap_vendor(frm, ni);
1694				frm = ieee80211_add_htinfo_vendor(frm, ni);
1695			}
1696		}
1697		if (ni->ni_ath_ie != NULL)
1698			frm = ieee80211_add_ath(frm, ni->ni_ath_flags,
1699				ni->ni_ath_defkeyix);
1700		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1701		break;
1702
1703	case IEEE80211_FC0_SUBTYPE_AUTH:
1704		status = arg >> 16;
1705		arg &= 0xffff;
1706		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1707		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1708		    ni->ni_challenge != NULL);
1709
1710		/*
1711		 * Deduce whether we're doing open authentication or
1712		 * shared key authentication.  We do the latter if
1713		 * we're in the middle of a shared key authentication
1714		 * handshake or if we're initiating an authentication
1715		 * request and configured to use shared key.
1716		 */
1717		is_shared_key = has_challenge ||
1718		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1719		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1720		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1721
1722		m = ieee80211_getmgtframe(&frm,
1723			  ic->ic_headroom + sizeof(struct ieee80211_frame),
1724			  3 * sizeof(uint16_t)
1725			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1726				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
1727		);
1728		if (m == NULL)
1729			senderr(ENOMEM, is_tx_nobuf);
1730
1731		((uint16_t *)frm)[0] =
1732		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1733		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1734		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
1735		((uint16_t *)frm)[2] = htole16(status);/* status */
1736
1737		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1738			((uint16_t *)frm)[3] =
1739			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1740			    IEEE80211_ELEMID_CHALLENGE);
1741			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
1742			    IEEE80211_CHALLENGE_LEN);
1743			m->m_pkthdr.len = m->m_len =
1744				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
1745			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1746				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1747				    "[%s] request encrypt frame (%s)\n",
1748				    ether_sprintf(ni->ni_macaddr), __func__);
1749				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1750			}
1751		} else
1752			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
1753
1754		/* XXX not right for shared key */
1755		if (status == IEEE80211_STATUS_SUCCESS)
1756			IEEE80211_NODE_STAT(ni, tx_auth);
1757		else
1758			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1759
1760		if (ic->ic_opmode == IEEE80211_M_STA)
1761			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1762				(void *) ic->ic_state);
1763		break;
1764
1765	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1766		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1767			"[%s] send station deauthenticate (reason %d)\n",
1768			ether_sprintf(ni->ni_macaddr), arg);
1769		m = ieee80211_getmgtframe(&frm,
1770			ic->ic_headroom + sizeof(struct ieee80211_frame),
1771			sizeof(uint16_t));
1772		if (m == NULL)
1773			senderr(ENOMEM, is_tx_nobuf);
1774		*(uint16_t *)frm = htole16(arg);	/* reason */
1775		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1776
1777		IEEE80211_NODE_STAT(ni, tx_deauth);
1778		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1779
1780		ieee80211_node_unauthorize(ni);		/* port closed */
1781		break;
1782
1783	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1784	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1785		/*
1786		 * asreq frame format
1787		 *	[2] capability information
1788		 *	[2] listen interval
1789		 *	[6*] current AP address (reassoc only)
1790		 *	[tlv] ssid
1791		 *	[tlv] supported rates
1792		 *	[tlv] extended supported rates
1793		 *	[tlv] WME
1794		 *	[tlv] HT capabilities
1795		 *	[tlv] Vendor OUI HT capabilities (optional)
1796		 *	[tlv] Atheros capabilities (if negotiated)
1797		 *	[tlv] user-specified ie's
1798		 */
1799		m = ieee80211_getmgtframe(&frm,
1800			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1801			 sizeof(uint16_t)
1802		       + sizeof(uint16_t)
1803		       + IEEE80211_ADDR_LEN
1804		       + 2 + IEEE80211_NWID_LEN
1805		       + 2 + IEEE80211_RATE_SIZE
1806		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1807		       + sizeof(struct ieee80211_wme_info)
1808		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
1809		       + sizeof(struct ieee80211_ath_ie)
1810		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1811		);
1812		if (m == NULL)
1813			senderr(ENOMEM, is_tx_nobuf);
1814
1815		KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1816		    ("wrong mode %u", ic->ic_opmode));
1817		capinfo = IEEE80211_CAPINFO_ESS;
1818		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1819			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1820		/*
1821		 * NB: Some 11a AP's reject the request when
1822		 *     short premable is set.
1823		 */
1824		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1825		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1826			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1827		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
1828		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1829			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1830		*(uint16_t *)frm = htole16(capinfo);
1831		frm += 2;
1832
1833		KASSERT(ic->ic_bss->ni_intval != 0,
1834			("beacon interval is zero!"));
1835		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
1836						   ic->ic_bss->ni_intval));
1837		frm += 2;
1838
1839		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1840			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1841			frm += IEEE80211_ADDR_LEN;
1842		}
1843
1844		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1845		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1846		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1847		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1848			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1849		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1850			frm = ieee80211_add_htcap(frm, ni);
1851			if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT)
1852				frm = ieee80211_add_htcap_vendor(frm, ni);
1853		}
1854		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
1855			frm = ieee80211_add_ath(frm,
1856				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
1857				(ic->ic_flags & IEEE80211_F_WPA) == 0 &&
1858				ni->ni_authmode != IEEE80211_AUTH_8021X &&
1859				ic->ic_def_txkey != IEEE80211_KEYIX_NONE ?
1860				ic->ic_def_txkey : 0x7fff);
1861		if (ic->ic_opt_ie != NULL) {
1862			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1863			frm += ic->ic_opt_ie_len;
1864		}
1865		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1866
1867		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1868			(void *) ic->ic_state);
1869		break;
1870
1871	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1872	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1873		/*
1874		 * asresp frame format
1875		 *	[2] capability information
1876		 *	[2] status
1877		 *	[2] association ID
1878		 *	[tlv] supported rates
1879		 *	[tlv] extended supported rates
1880		 *	[tlv] WME (if enabled and STA enabled)
1881		 *	[tlv] HT capabilities (standard or vendor OUI)
1882		 *	[tlv] HT information (standard or vendor OUI)
1883		 *	[tlv] Atheros capabilities (if enabled and STA enabled)
1884		 */
1885		m = ieee80211_getmgtframe(&frm,
1886			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1887			 sizeof(uint16_t)
1888		       + sizeof(uint16_t)
1889		       + sizeof(uint16_t)
1890		       + 2 + IEEE80211_RATE_SIZE
1891		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1892		       + sizeof(struct ieee80211_wme_param)
1893		       + sizeof(struct ieee80211_ie_htcap) + 4
1894		       + sizeof(struct ieee80211_ie_htinfo) + 4
1895		       + sizeof(struct ieee80211_ath_ie)
1896		);
1897		if (m == NULL)
1898			senderr(ENOMEM, is_tx_nobuf);
1899
1900		capinfo = getcapinfo(ic, ic->ic_curchan);
1901		*(uint16_t *)frm = htole16(capinfo);
1902		frm += 2;
1903
1904		*(uint16_t *)frm = htole16(arg);	/* status */
1905		frm += 2;
1906
1907		if (arg == IEEE80211_STATUS_SUCCESS) {
1908			*(uint16_t *)frm = htole16(ni->ni_associd);
1909			IEEE80211_NODE_STAT(ni, tx_assoc);
1910		} else
1911			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1912		frm += 2;
1913
1914		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1915		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1916		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1917			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1918		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1919			/* NB: respond according to what we received */
1920			if (ni->ni_flags & IEEE80211_NODE_HTCOMPAT) {
1921				frm = ieee80211_add_htcap_vendor(frm, ni);
1922				frm = ieee80211_add_htinfo_vendor(frm, ni);
1923			} else {
1924				frm = ieee80211_add_htcap(frm, ni);
1925				frm = ieee80211_add_htinfo(frm, ni);
1926			}
1927		}
1928		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
1929			frm = ieee80211_add_ath(frm,
1930				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
1931				ni->ni_ath_defkeyix);
1932		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1933		break;
1934
1935	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1936		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1937			"[%s] send station disassociate (reason %d)\n",
1938			ether_sprintf(ni->ni_macaddr), arg);
1939		m = ieee80211_getmgtframe(&frm,
1940			ic->ic_headroom + sizeof(struct ieee80211_frame),
1941			sizeof(uint16_t));
1942		if (m == NULL)
1943			senderr(ENOMEM, is_tx_nobuf);
1944		*(uint16_t *)frm = htole16(arg);	/* reason */
1945		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1946
1947		IEEE80211_NODE_STAT(ni, tx_disassoc);
1948		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1949		break;
1950
1951	default:
1952		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1953			"[%s] invalid mgmt frame type %u\n",
1954			ether_sprintf(ni->ni_macaddr), type);
1955		senderr(EINVAL, is_tx_unknownmgt);
1956		/* NOTREACHED */
1957	}
1958
1959	ret = ieee80211_mgmt_output(ic, ni, m, type);
1960	if (ret != 0)
1961		goto bad;
1962	return 0;
1963bad:
1964	ieee80211_free_node(ni);
1965	return ret;
1966#undef senderr
1967}
1968
1969static void
1970ieee80211_tx_mgt_timeout(void *arg)
1971{
1972	struct ieee80211_node *ni = arg;
1973	struct ieee80211com *ic	= ni->ni_ic;
1974
1975	if (ic->ic_state != IEEE80211_S_INIT &&
1976	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1977		/*
1978		 * NB: it's safe to specify a timeout as the reason here;
1979		 *     it'll only be used in the right state.
1980		 */
1981		ieee80211_new_state(ic, IEEE80211_S_SCAN,
1982			IEEE80211_SCAN_FAIL_TIMEOUT);
1983	}
1984}
1985
1986static void
1987ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
1988{
1989	struct ieee80211com *ic = ni->ni_ic;
1990	enum ieee80211_state ostate = (enum ieee80211_state) arg;
1991
1992	/*
1993	 * Frame transmit completed; arrange timer callback.  If
1994	 * transmit was successfuly we wait for response.  Otherwise
1995	 * we arrange an immediate callback instead of doing the
1996	 * callback directly since we don't know what state the driver
1997	 * is in (e.g. what locks it is holding).  This work should
1998	 * not be too time-critical and not happen too often so the
1999	 * added overhead is acceptable.
2000	 *
2001	 * XXX what happens if !acked but response shows up before callback?
2002	 */
2003	if (ic->ic_state == ostate)
2004		callout_reset(&ic->ic_mgtsend,
2005			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
2006			ieee80211_tx_mgt_timeout, ni);
2007}
2008
2009/*
2010 * Allocate a beacon frame and fillin the appropriate bits.
2011 */
2012struct mbuf *
2013ieee80211_beacon_alloc(struct ieee80211_node *ni,
2014	struct ieee80211_beacon_offsets *bo)
2015{
2016	struct ieee80211com *ic = ni->ni_ic;
2017	struct ifnet *ifp = ic->ic_ifp;
2018	struct ieee80211_frame *wh;
2019	struct mbuf *m;
2020	int pktlen;
2021	uint8_t *frm;
2022	uint16_t capinfo;
2023	struct ieee80211_rateset *rs;
2024
2025	/*
2026	 * beacon frame format
2027	 *	[8] time stamp
2028	 *	[2] beacon interval
2029	 *	[2] cabability information
2030	 *	[tlv] ssid
2031	 *	[tlv] supported rates
2032	 *	[3] parameter set (DS)
2033	 *	[tlv] parameter set (IBSS/TIM)
2034	 *	[tlv] country code
2035	 *	[tlv] extended rate phy (ERP)
2036	 *	[tlv] extended supported rates
2037	 *	[tlv] WME parameters
2038	 *	[tlv] WPA/RSN parameters
2039	 *	[tlv] HT capabilities
2040	 *	[tlv] HT information
2041	 *	[tlv] Vendor OUI HT capabilities (optional)
2042	 *	[tlv] Vendor OUI HT information (optional)
2043	 * XXX Vendor-specific OIDs (e.g. Atheros)
2044	 * NB: we allocate the max space required for the TIM bitmap.
2045	 */
2046	rs = &ni->ni_rates;
2047	pktlen =   8					/* time stamp */
2048		 + sizeof(uint16_t)			/* beacon interval */
2049		 + sizeof(uint16_t)			/* capabilities */
2050		 + 2 + ni->ni_esslen			/* ssid */
2051	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
2052	         + 2 + 1				/* DS parameters */
2053		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
2054		 + sizeof(struct ieee80211_country_ie)	/* country code */
2055		 + 2 + 1				/* ERP */
2056	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2057		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
2058			sizeof(struct ieee80211_wme_param) : 0)
2059		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
2060			2*sizeof(struct ieee80211_ie_wpa) : 0)
2061		 /* XXX conditional? */
2062		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
2063		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
2064		 ;
2065	m = ieee80211_getmgtframe(&frm,
2066		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
2067	if (m == NULL) {
2068		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2069			"%s: cannot get buf; size %u\n", __func__, pktlen);
2070		ic->ic_stats.is_tx_nobuf++;
2071		return NULL;
2072	}
2073
2074	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
2075	frm += 8;
2076	*(uint16_t *)frm = htole16(ni->ni_intval);
2077	frm += 2;
2078	capinfo = getcapinfo(ic, ni->ni_chan);
2079	bo->bo_caps = (uint16_t *)frm;
2080	*(uint16_t *)frm = htole16(capinfo);
2081	frm += 2;
2082	*frm++ = IEEE80211_ELEMID_SSID;
2083	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
2084		*frm++ = ni->ni_esslen;
2085		memcpy(frm, ni->ni_essid, ni->ni_esslen);
2086		frm += ni->ni_esslen;
2087	} else
2088		*frm++ = 0;
2089	frm = ieee80211_add_rates(frm, rs);
2090	if (!IEEE80211_IS_CHAN_FHSS(ic->ic_bsschan)) {
2091		*frm++ = IEEE80211_ELEMID_DSPARMS;
2092		*frm++ = 1;
2093		*frm++ = ieee80211_chan2ieee(ic, ic->ic_bsschan);
2094	}
2095	bo->bo_tim = frm;
2096	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2097		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2098		*frm++ = 2;
2099		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2100		bo->bo_tim_len = 0;
2101	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2102		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
2103
2104		tie->tim_ie = IEEE80211_ELEMID_TIM;
2105		tie->tim_len = 4;	/* length */
2106		tie->tim_count = 0;	/* DTIM count */
2107		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
2108		tie->tim_bitctl = 0;	/* bitmap control */
2109		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
2110		frm += sizeof(struct ieee80211_tim_ie);
2111		bo->bo_tim_len = 1;
2112	}
2113	bo->bo_tim_trailer = frm;
2114	if (ic->ic_flags & IEEE80211_F_DOTH)
2115		frm = ieee80211_add_countryie(frm, ic,
2116			ic->ic_countrycode, ic->ic_location);
2117	if (ic->ic_flags & IEEE80211_F_WME) {
2118		bo->bo_wme = frm;
2119		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2120	} else
2121		bo->bo_wme = NULL;
2122	if (ic->ic_flags & IEEE80211_F_WPA)
2123		frm = ieee80211_add_wpa(frm, ic);
2124	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan)) {
2125		bo->bo_erp = frm;
2126		frm = ieee80211_add_erp(frm, ic);
2127	} else
2128		bo->bo_erp = NULL;
2129	frm = ieee80211_add_xrates(frm, rs);
2130	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan)) {
2131		frm = ieee80211_add_htcap(frm, ni);
2132		bo->bo_htinfo = frm;
2133		frm = ieee80211_add_htinfo(frm, ni);
2134		if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT) {
2135			frm = ieee80211_add_htcap_vendor(frm, ni);
2136			frm = ieee80211_add_htinfo_vendor(frm, ni);
2137		}
2138	} else
2139		bo->bo_htinfo = NULL;
2140	bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
2141	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2142
2143	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2144	KASSERT(m != NULL, ("no space for 802.11 header?"));
2145	wh = mtod(m, struct ieee80211_frame *);
2146	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2147	    IEEE80211_FC0_SUBTYPE_BEACON;
2148	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2149	*(uint16_t *)wh->i_dur = 0;
2150	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2151	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
2152	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
2153	*(uint16_t *)wh->i_seq = 0;
2154
2155	return m;
2156}
2157
2158/*
2159 * Update the dynamic parts of a beacon frame based on the current state.
2160 */
2161int
2162ieee80211_beacon_update(struct ieee80211_node *ni,
2163	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
2164{
2165	struct ieee80211com *ic = ni->ni_ic;
2166	int len_changed = 0;
2167	uint16_t capinfo;
2168
2169	IEEE80211_BEACON_LOCK(ic);
2170	/* XXX faster to recalculate entirely or just changes? */
2171	capinfo = getcapinfo(ic, ni->ni_chan);
2172	*bo->bo_caps = htole16(capinfo);
2173
2174	if (ic->ic_flags & IEEE80211_F_WME) {
2175		struct ieee80211_wme_state *wme = &ic->ic_wme;
2176
2177		/*
2178		 * Check for agressive mode change.  When there is
2179		 * significant high priority traffic in the BSS
2180		 * throttle back BE traffic by using conservative
2181		 * parameters.  Otherwise BE uses agressive params
2182		 * to optimize performance of legacy/non-QoS traffic.
2183		 */
2184		if (wme->wme_flags & WME_F_AGGRMODE) {
2185			if (wme->wme_hipri_traffic >
2186			    wme->wme_hipri_switch_thresh) {
2187				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2188				    "%s: traffic %u, disable aggressive mode\n",
2189				    __func__, wme->wme_hipri_traffic);
2190				wme->wme_flags &= ~WME_F_AGGRMODE;
2191				ieee80211_wme_updateparams_locked(ic);
2192				wme->wme_hipri_traffic =
2193					wme->wme_hipri_switch_hysteresis;
2194			} else
2195				wme->wme_hipri_traffic = 0;
2196		} else {
2197			if (wme->wme_hipri_traffic <=
2198			    wme->wme_hipri_switch_thresh) {
2199				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2200				    "%s: traffic %u, enable aggressive mode\n",
2201				    __func__, wme->wme_hipri_traffic);
2202				wme->wme_flags |= WME_F_AGGRMODE;
2203				ieee80211_wme_updateparams_locked(ic);
2204				wme->wme_hipri_traffic = 0;
2205			} else
2206				wme->wme_hipri_traffic =
2207					wme->wme_hipri_switch_hysteresis;
2208		}
2209		if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
2210			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
2211			clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
2212		}
2213	}
2214
2215	if (isset(bo->bo_flags, IEEE80211_BEACON_HTINFO)) {
2216		ieee80211_ht_update_beacon(ic, bo);
2217		clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
2218	}
2219
2220	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
2221		struct ieee80211_tim_ie *tie =
2222			(struct ieee80211_tim_ie *) bo->bo_tim;
2223		if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
2224			u_int timlen, timoff, i;
2225			/*
2226			 * ATIM/DTIM needs updating.  If it fits in the
2227			 * current space allocated then just copy in the
2228			 * new bits.  Otherwise we need to move any trailing
2229			 * data to make room.  Note that we know there is
2230			 * contiguous space because ieee80211_beacon_allocate
2231			 * insures there is space in the mbuf to write a
2232			 * maximal-size virtual bitmap (based on ic_max_aid).
2233			 */
2234			/*
2235			 * Calculate the bitmap size and offset, copy any
2236			 * trailer out of the way, and then copy in the
2237			 * new bitmap and update the information element.
2238			 * Note that the tim bitmap must contain at least
2239			 * one byte and any offset must be even.
2240			 */
2241			if (ic->ic_ps_pending != 0) {
2242				timoff = 128;		/* impossibly large */
2243				for (i = 0; i < ic->ic_tim_len; i++)
2244					if (ic->ic_tim_bitmap[i]) {
2245						timoff = i &~ 1;
2246						break;
2247					}
2248				KASSERT(timoff != 128, ("tim bitmap empty!"));
2249				for (i = ic->ic_tim_len-1; i >= timoff; i--)
2250					if (ic->ic_tim_bitmap[i])
2251						break;
2252				timlen = 1 + (i - timoff);
2253			} else {
2254				timoff = 0;
2255				timlen = 1;
2256			}
2257			if (timlen != bo->bo_tim_len) {
2258				/* copy up/down trailer */
2259				int adjust = tie->tim_bitmap+timlen
2260					   - bo->bo_tim_trailer;
2261				ovbcopy(bo->bo_tim_trailer,
2262				    bo->bo_tim_trailer+adjust,
2263				    bo->bo_tim_trailer_len);
2264				bo->bo_tim_trailer += adjust;
2265				bo->bo_wme += adjust;
2266				bo->bo_erp += adjust;
2267				bo->bo_htinfo += adjust;
2268				bo->bo_tim_len = timlen;
2269
2270				/* update information element */
2271				tie->tim_len = 3 + timlen;
2272				tie->tim_bitctl = timoff;
2273				len_changed = 1;
2274			}
2275			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
2276				bo->bo_tim_len);
2277
2278			clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
2279
2280			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2281				"%s: TIM updated, pending %u, off %u, len %u\n",
2282				__func__, ic->ic_ps_pending, timoff, timlen);
2283		}
2284		/* count down DTIM period */
2285		if (tie->tim_count == 0)
2286			tie->tim_count = tie->tim_period - 1;
2287		else
2288			tie->tim_count--;
2289		/* update state for buffered multicast frames on DTIM */
2290		if (mcast && tie->tim_count == 0)
2291			tie->tim_bitctl |= 1;
2292		else
2293			tie->tim_bitctl &= ~1;
2294		if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
2295			/*
2296			 * ERP element needs updating.
2297			 */
2298			(void) ieee80211_add_erp(bo->bo_erp, ic);
2299			clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
2300		}
2301	}
2302	IEEE80211_BEACON_UNLOCK(ic);
2303
2304	return len_changed;
2305}
2306