ieee80211_output.c revision 155999
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2005 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 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * Alternatively, this software may be distributed under the terms of the
18 * GNU General Public License ("GPL") version 2 as published by the Free
19 * Software Foundation.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_output.c 155999 2006-02-25 05:36:43Z sam $");
35
36#include "opt_inet.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/mbuf.h>
41#include <sys/kernel.h>
42#include <sys/endian.h>
43
44#include <sys/socket.h>
45
46#include <net/bpf.h>
47#include <net/ethernet.h>
48#include <net/if.h>
49#include <net/if_llc.h>
50#include <net/if_media.h>
51#include <net/if_vlan_var.h>
52
53#include <net80211/ieee80211_var.h>
54
55#ifdef INET
56#include <netinet/in.h>
57#include <netinet/if_ether.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#endif
61
62#ifdef IEEE80211_DEBUG
63/*
64 * Decide if an outbound management frame should be
65 * printed when debugging is enabled.  This filters some
66 * of the less interesting frames that come frequently
67 * (e.g. beacons).
68 */
69static __inline int
70doprint(struct ieee80211com *ic, int subtype)
71{
72	switch (subtype) {
73	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
74		return (ic->ic_opmode == IEEE80211_M_IBSS);
75	}
76	return 1;
77}
78#endif
79
80/*
81 * Set the direction field and address fields of an outgoing
82 * non-QoS frame.  Note this should be called early on in
83 * constructing a frame as it sets i_fc[1]; other bits can
84 * then be or'd in.
85 */
86static void
87ieee80211_send_setup(struct ieee80211com *ic,
88	struct ieee80211_node *ni,
89	struct ieee80211_frame *wh,
90	int type,
91	const u_int8_t sa[IEEE80211_ADDR_LEN],
92	const u_int8_t da[IEEE80211_ADDR_LEN],
93	const u_int8_t bssid[IEEE80211_ADDR_LEN])
94{
95#define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
96
97	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
98	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
99		switch (ic->ic_opmode) {
100		case IEEE80211_M_STA:
101			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
102			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
103			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
104			IEEE80211_ADDR_COPY(wh->i_addr3, da);
105			break;
106		case IEEE80211_M_IBSS:
107		case IEEE80211_M_AHDEMO:
108			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
109			IEEE80211_ADDR_COPY(wh->i_addr1, da);
110			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
111			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
112			break;
113		case IEEE80211_M_HOSTAP:
114			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
115			IEEE80211_ADDR_COPY(wh->i_addr1, da);
116			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
117			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
118			break;
119		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
120			break;
121		}
122	} else {
123		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
124		IEEE80211_ADDR_COPY(wh->i_addr1, da);
125		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
126		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
127	}
128	*(u_int16_t *)&wh->i_dur[0] = 0;
129	/* NB: use non-QoS tid */
130	*(u_int16_t *)&wh->i_seq[0] =
131	    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
132	ni->ni_txseqs[0]++;
133#undef WH4
134}
135
136/*
137 * Send a management frame to the specified node.  The node pointer
138 * must have a reference as the pointer will be passed to the driver
139 * and potentially held for a long time.  If the frame is successfully
140 * dispatched to the driver, then it is responsible for freeing the
141 * reference (and potentially free'ing up any associated storage).
142 */
143static int
144ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
145    struct mbuf *m, int type, int timer)
146{
147	struct ifnet *ifp = ic->ic_ifp;
148	struct ieee80211_frame *wh;
149
150	KASSERT(ni != NULL, ("null node"));
151
152	/*
153	 * Yech, hack alert!  We want to pass the node down to the
154	 * driver's start routine.  If we don't do so then the start
155	 * routine must immediately look it up again and that can
156	 * cause a lock order reversal if, for example, this frame
157	 * is being sent because the station is being timedout and
158	 * the frame being sent is a DEAUTH message.  We could stick
159	 * this in an m_tag and tack that on to the mbuf.  However
160	 * that's rather expensive to do for every frame so instead
161	 * we stuff it in the rcvif field since outbound frames do
162	 * not (presently) use this.
163	 */
164	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
165	if (m == NULL)
166		return ENOMEM;
167	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
168	m->m_pkthdr.rcvif = (void *)ni;
169
170	wh = mtod(m, struct ieee80211_frame *);
171	ieee80211_send_setup(ic, ni, wh,
172		IEEE80211_FC0_TYPE_MGT | type,
173		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
174	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
175		m->m_flags &= ~M_LINK0;
176		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
177			"[%s] encrypting frame (%s)\n",
178			ether_sprintf(wh->i_addr1), __func__);
179		wh->i_fc[1] |= IEEE80211_FC1_WEP;
180	}
181#ifdef IEEE80211_DEBUG
182	/* avoid printing too many frames */
183	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
184	    ieee80211_msg_dumppkts(ic)) {
185		printf("[%s] send %s on channel %u\n",
186		    ether_sprintf(wh->i_addr1),
187		    ieee80211_mgt_subtype_name[
188			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
189				IEEE80211_FC0_SUBTYPE_SHIFT],
190		    ieee80211_chan2ieee(ic, ic->ic_curchan));
191	}
192#endif
193	IEEE80211_NODE_STAT(ni, tx_mgmt);
194	IF_ENQUEUE(&ic->ic_mgtq, m);
195	if (timer) {
196		/*
197		 * Set the mgt frame timeout.
198		 */
199		ic->ic_mgt_timer = timer;
200		ifp->if_timer = 1;
201	}
202	if_start(ifp);
203	return 0;
204}
205
206/*
207 * Send a null data frame to the specified node.
208 *
209 * NB: the caller is assumed to have setup a node reference
210 *     for use; this is necessary to deal with a race condition
211 *     when probing for inactive stations.
212 */
213int
214ieee80211_send_nulldata(struct ieee80211_node *ni)
215{
216	struct ieee80211com *ic = ni->ni_ic;
217	struct ifnet *ifp = ic->ic_ifp;
218	struct mbuf *m;
219	struct ieee80211_frame *wh;
220
221	MGETHDR(m, M_NOWAIT, MT_DATA);
222	if (m == NULL) {
223		/* XXX debug msg */
224		ic->ic_stats.is_tx_nobuf++;
225		ieee80211_unref_node(&ni);
226		return ENOMEM;
227	}
228	m->m_pkthdr.rcvif = (void *) ni;
229
230	wh = mtod(m, struct ieee80211_frame *);
231	ieee80211_send_setup(ic, ni, wh,
232		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
233		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
234	/* NB: power management bit is never sent by an AP */
235	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
236	    ic->ic_opmode != IEEE80211_M_HOSTAP)
237		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
238	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
239
240	IEEE80211_NODE_STAT(ni, tx_data);
241
242	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
243	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
244	    ether_sprintf(ni->ni_macaddr),
245	    ieee80211_chan2ieee(ic, ic->ic_curchan),
246	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
247
248	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
249	if_start(ifp);
250
251	return 0;
252}
253
254/*
255 * Assign priority to a frame based on any vlan tag assigned
256 * to the station and/or any Diffserv setting in an IP header.
257 * Finally, if an ACM policy is setup (in station mode) it's
258 * applied.
259 */
260int
261ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
262{
263	int v_wme_ac, d_wme_ac, ac;
264#ifdef INET
265	struct ether_header *eh;
266#endif
267
268	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
269		ac = WME_AC_BE;
270		goto done;
271	}
272
273	/*
274	 * If node has a vlan tag then all traffic
275	 * to it must have a matching tag.
276	 */
277	v_wme_ac = 0;
278	if (ni->ni_vlan != 0) {
279		 struct m_tag *mtag = VLAN_OUTPUT_TAG(ic->ic_ifp, m);
280		 if (mtag == NULL) {
281			IEEE80211_NODE_STAT(ni, tx_novlantag);
282			return 1;
283		}
284		if (EVL_VLANOFTAG(VLAN_TAG_VALUE(mtag)) !=
285		    EVL_VLANOFTAG(ni->ni_vlan)) {
286			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
287			return 1;
288		}
289		/* map vlan priority to AC */
290		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
291		case 1:
292		case 2:
293			v_wme_ac = WME_AC_BK;
294			break;
295		case 0:
296		case 3:
297			v_wme_ac = WME_AC_BE;
298			break;
299		case 4:
300		case 5:
301			v_wme_ac = WME_AC_VI;
302			break;
303		case 6:
304		case 7:
305			v_wme_ac = WME_AC_VO;
306			break;
307		}
308	}
309
310#ifdef INET
311	eh = mtod(m, struct ether_header *);
312	if (eh->ether_type == htons(ETHERTYPE_IP)) {
313		const struct ip *ip = (struct ip *)
314			(mtod(m, u_int8_t *) + sizeof (*eh));
315		/*
316		 * IP frame, map the TOS field.
317		 */
318		switch (ip->ip_tos) {
319		case 0x08:
320		case 0x20:
321			d_wme_ac = WME_AC_BK;	/* background */
322			break;
323		case 0x28:
324		case 0xa0:
325			d_wme_ac = WME_AC_VI;	/* video */
326			break;
327		case 0x30:			/* voice */
328		case 0xe0:
329		case 0x88:			/* XXX UPSD */
330		case 0xb8:
331			d_wme_ac = WME_AC_VO;
332			break;
333		default:
334			d_wme_ac = WME_AC_BE;
335			break;
336		}
337	} else {
338#endif /* INET */
339		d_wme_ac = WME_AC_BE;
340#ifdef INET
341	}
342#endif
343	/*
344	 * Use highest priority AC.
345	 */
346	if (v_wme_ac > d_wme_ac)
347		ac = v_wme_ac;
348	else
349		ac = d_wme_ac;
350
351	/*
352	 * Apply ACM policy.
353	 */
354	if (ic->ic_opmode == IEEE80211_M_STA) {
355		static const int acmap[4] = {
356			WME_AC_BK,	/* WME_AC_BE */
357			WME_AC_BK,	/* WME_AC_BK */
358			WME_AC_BE,	/* WME_AC_VI */
359			WME_AC_VI,	/* WME_AC_VO */
360		};
361		while (ac != WME_AC_BK &&
362		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
363			ac = acmap[ac];
364	}
365done:
366	M_WME_SETAC(m, ac);
367	return 0;
368}
369
370/*
371 * Insure there is sufficient contiguous space to encapsulate the
372 * 802.11 data frame.  If room isn't already there, arrange for it.
373 * Drivers and cipher modules assume we have done the necessary work
374 * and fail rudely if they don't find the space they need.
375 */
376static struct mbuf *
377ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
378	struct ieee80211_key *key, struct mbuf *m)
379{
380#define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
381	int needed_space = hdrsize;
382
383	if (key != NULL) {
384		/* XXX belongs in crypto code? */
385		needed_space += key->wk_cipher->ic_header;
386		/* XXX frags */
387	}
388	/*
389	 * We know we are called just before stripping an Ethernet
390	 * header and prepending an LLC header.  This means we know
391	 * there will be
392	 *	sizeof(struct ether_header) - sizeof(struct llc)
393	 * bytes recovered to which we need additional space for the
394	 * 802.11 header and any crypto header.
395	 */
396	/* XXX check trailing space and copy instead? */
397	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
398		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
399		if (n == NULL) {
400			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
401			    "%s: cannot expand storage\n", __func__);
402			ic->ic_stats.is_tx_nobuf++;
403			m_freem(m);
404			return NULL;
405		}
406		KASSERT(needed_space <= MHLEN,
407		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
408		/*
409		 * Setup new mbuf to have leading space to prepend the
410		 * 802.11 header and any crypto header bits that are
411		 * required (the latter are added when the driver calls
412		 * back to ieee80211_crypto_encap to do crypto encapsulation).
413		 */
414		/* NB: must be first 'cuz it clobbers m_data */
415		m_move_pkthdr(n, m);
416		n->m_len = 0;			/* NB: m_gethdr does not set */
417		n->m_data += needed_space;
418		/*
419		 * Pull up Ethernet header to create the expected layout.
420		 * We could use m_pullup but that's overkill (i.e. we don't
421		 * need the actual data) and it cannot fail so do it inline
422		 * for speed.
423		 */
424		/* NB: struct ether_header is known to be contiguous */
425		n->m_len += sizeof(struct ether_header);
426		m->m_len -= sizeof(struct ether_header);
427		m->m_data += sizeof(struct ether_header);
428		/*
429		 * Replace the head of the chain.
430		 */
431		n->m_next = m;
432		m = n;
433	}
434	return m;
435#undef TO_BE_RECLAIMED
436}
437
438#define	KEY_UNDEFINED(k)	((k).wk_cipher == &ieee80211_cipher_none)
439/*
440 * Return the transmit key to use in sending a unicast frame.
441 * If a unicast key is set we use that.  When no unicast key is set
442 * we fall back to the default transmit key.
443 */
444static __inline struct ieee80211_key *
445ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
446{
447	if (KEY_UNDEFINED(ni->ni_ucastkey)) {
448		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
449		    KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
450			return NULL;
451		return &ic->ic_nw_keys[ic->ic_def_txkey];
452	} else {
453		return &ni->ni_ucastkey;
454	}
455}
456
457/*
458 * Return the transmit key to use in sending a multicast frame.
459 * Multicast traffic always uses the group key which is installed as
460 * the default tx key.
461 */
462static __inline struct ieee80211_key *
463ieee80211_crypto_getmcastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
464{
465	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
466	    KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
467		return NULL;
468	return &ic->ic_nw_keys[ic->ic_def_txkey];
469}
470
471/*
472 * Encapsulate an outbound data frame.  The mbuf chain is updated.
473 * If an error is encountered NULL is returned.  The caller is required
474 * to provide a node reference and pullup the ethernet header in the
475 * first mbuf.
476 */
477struct mbuf *
478ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
479	struct ieee80211_node *ni)
480{
481	struct ether_header eh;
482	struct ieee80211_frame *wh;
483	struct ieee80211_key *key;
484	struct llc *llc;
485	int hdrsize, datalen, addqos;
486
487	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
488	memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
489
490	/*
491	 * Insure space for additional headers.  First identify
492	 * transmit key to use in calculating any buffer adjustments
493	 * required.  This is also used below to do privacy
494	 * encapsulation work.  Then calculate the 802.11 header
495	 * size and any padding required by the driver.
496	 *
497	 * Note key may be NULL if we fall back to the default
498	 * transmit key and that is not set.  In that case the
499	 * buffer may not be expanded as needed by the cipher
500	 * routines, but they will/should discard it.
501	 */
502	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
503		if (ic->ic_opmode == IEEE80211_M_STA ||
504		    !IEEE80211_IS_MULTICAST(eh.ether_dhost))
505			key = ieee80211_crypto_getucastkey(ic, ni);
506		else
507			key = ieee80211_crypto_getmcastkey(ic, ni);
508		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
509			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
510			    "[%s] no default transmit key (%s) deftxkey %u\n",
511			    ether_sprintf(eh.ether_dhost), __func__,
512			    ic->ic_def_txkey);
513			ic->ic_stats.is_tx_nodefkey++;
514		}
515	} else
516		key = NULL;
517	/* XXX 4-address format */
518	/*
519	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
520	 * frames so suppress use.  This may be an issue if other
521	 * ap's require all data frames to be QoS-encapsulated
522	 * once negotiated in which case we'll need to make this
523	 * configurable.
524	 */
525	addqos = (ni->ni_flags & IEEE80211_NODE_QOS) &&
526		 eh.ether_type != htons(ETHERTYPE_PAE);
527	if (addqos)
528		hdrsize = sizeof(struct ieee80211_qosframe);
529	else
530		hdrsize = sizeof(struct ieee80211_frame);
531	if (ic->ic_flags & IEEE80211_F_DATAPAD)
532		hdrsize = roundup(hdrsize, sizeof(u_int32_t));
533	m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
534	if (m == NULL) {
535		/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
536		goto bad;
537	}
538
539	/* NB: this could be optimized because of ieee80211_mbuf_adjust */
540	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
541	llc = mtod(m, struct llc *);
542	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
543	llc->llc_control = LLC_UI;
544	llc->llc_snap.org_code[0] = 0;
545	llc->llc_snap.org_code[1] = 0;
546	llc->llc_snap.org_code[2] = 0;
547	llc->llc_snap.ether_type = eh.ether_type;
548	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
549
550	M_PREPEND(m, hdrsize, M_DONTWAIT);
551	if (m == NULL) {
552		ic->ic_stats.is_tx_nobuf++;
553		goto bad;
554	}
555	wh = mtod(m, struct ieee80211_frame *);
556	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
557	*(u_int16_t *)wh->i_dur = 0;
558	switch (ic->ic_opmode) {
559	case IEEE80211_M_STA:
560		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
561		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
562		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
563		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
564		break;
565	case IEEE80211_M_IBSS:
566	case IEEE80211_M_AHDEMO:
567		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
568		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
569		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
570		/*
571		 * NB: always use the bssid from ic_bss as the
572		 *     neighbor's may be stale after an ibss merge
573		 */
574		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
575		break;
576	case IEEE80211_M_HOSTAP:
577		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
578		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
579		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
580		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
581		break;
582	case IEEE80211_M_MONITOR:
583		goto bad;
584	}
585	if (m->m_flags & M_MORE_DATA)
586		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
587	if (addqos) {
588		struct ieee80211_qosframe *qwh =
589			(struct ieee80211_qosframe *) wh;
590		int ac, tid;
591
592		ac = M_WME_GETAC(m);
593		/* map from access class/queue to 11e header priorty value */
594		tid = WME_AC_TO_TID(ac);
595		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
596		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
597			qwh->i_qos[0] |= 1 << IEEE80211_QOS_ACKPOLICY_S;
598		qwh->i_qos[1] = 0;
599		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
600
601		*(u_int16_t *)wh->i_seq =
602		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
603		ni->ni_txseqs[tid]++;
604	} else {
605		*(u_int16_t *)wh->i_seq =
606		    htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
607		ni->ni_txseqs[0]++;
608	}
609	if (key != NULL) {
610		/*
611		 * IEEE 802.1X: send EAPOL frames always in the clear.
612		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
613		 */
614		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
615		    ((ic->ic_flags & IEEE80211_F_WPA) &&
616		     (ic->ic_opmode == IEEE80211_M_STA ?
617		      !KEY_UNDEFINED(*key) : !KEY_UNDEFINED(ni->ni_ucastkey)))) {
618			wh->i_fc[1] |= IEEE80211_FC1_WEP;
619			/* XXX do fragmentation */
620			if (!ieee80211_crypto_enmic(ic, key, m, 0)) {
621				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
622				    "[%s] enmic failed, discard frame\n",
623				    ether_sprintf(eh.ether_dhost));
624				ic->ic_stats.is_crypto_enmicfail++;
625				goto bad;
626			}
627		}
628	}
629
630	IEEE80211_NODE_STAT(ni, tx_data);
631	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
632
633	return m;
634bad:
635	if (m != NULL)
636		m_freem(m);
637	return NULL;
638}
639
640/*
641 * Add a supported rates element id to a frame.
642 */
643static u_int8_t *
644ieee80211_add_rates(u_int8_t *frm, const struct ieee80211_rateset *rs)
645{
646	int nrates;
647
648	*frm++ = IEEE80211_ELEMID_RATES;
649	nrates = rs->rs_nrates;
650	if (nrates > IEEE80211_RATE_SIZE)
651		nrates = IEEE80211_RATE_SIZE;
652	*frm++ = nrates;
653	memcpy(frm, rs->rs_rates, nrates);
654	return frm + nrates;
655}
656
657/*
658 * Add an extended supported rates element id to a frame.
659 */
660static u_int8_t *
661ieee80211_add_xrates(u_int8_t *frm, const struct ieee80211_rateset *rs)
662{
663	/*
664	 * Add an extended supported rates element if operating in 11g mode.
665	 */
666	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
667		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
668		*frm++ = IEEE80211_ELEMID_XRATES;
669		*frm++ = nrates;
670		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
671		frm += nrates;
672	}
673	return frm;
674}
675
676/*
677 * Add an ssid elemet to a frame.
678 */
679static u_int8_t *
680ieee80211_add_ssid(u_int8_t *frm, const u_int8_t *ssid, u_int len)
681{
682	*frm++ = IEEE80211_ELEMID_SSID;
683	*frm++ = len;
684	memcpy(frm, ssid, len);
685	return frm + len;
686}
687
688/*
689 * Add an erp element to a frame.
690 */
691static u_int8_t *
692ieee80211_add_erp(u_int8_t *frm, struct ieee80211com *ic)
693{
694	u_int8_t erp;
695
696	*frm++ = IEEE80211_ELEMID_ERP;
697	*frm++ = 1;
698	erp = 0;
699	if (ic->ic_nonerpsta != 0)
700		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
701	if (ic->ic_flags & IEEE80211_F_USEPROT)
702		erp |= IEEE80211_ERP_USE_PROTECTION;
703	if (ic->ic_flags & IEEE80211_F_USEBARKER)
704		erp |= IEEE80211_ERP_LONG_PREAMBLE;
705	*frm++ = erp;
706	return frm;
707}
708
709static u_int8_t *
710ieee80211_setup_wpa_ie(struct ieee80211com *ic, u_int8_t *ie)
711{
712#define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
713#define	ADDSHORT(frm, v) do {			\
714	frm[0] = (v) & 0xff;			\
715	frm[1] = (v) >> 8;			\
716	frm += 2;				\
717} while (0)
718#define	ADDSELECTOR(frm, sel) do {		\
719	memcpy(frm, sel, 4);			\
720	frm += 4;				\
721} while (0)
722	static const u_int8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
723	static const u_int8_t cipher_suite[][4] = {
724		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
725		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
726		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
727		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
728		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
729		{ WPA_OUI_BYTES, WPA_CSE_NULL },
730	};
731	static const u_int8_t wep104_suite[4] =
732		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
733	static const u_int8_t key_mgt_unspec[4] =
734		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
735	static const u_int8_t key_mgt_psk[4] =
736		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
737	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
738	u_int8_t *frm = ie;
739	u_int8_t *selcnt;
740
741	*frm++ = IEEE80211_ELEMID_VENDOR;
742	*frm++ = 0;				/* length filled in below */
743	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
744	frm += sizeof(oui);
745	ADDSHORT(frm, WPA_VERSION);
746
747	/* XXX filter out CKIP */
748
749	/* multicast cipher */
750	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
751	    rsn->rsn_mcastkeylen >= 13)
752		ADDSELECTOR(frm, wep104_suite);
753	else
754		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
755
756	/* unicast cipher list */
757	selcnt = frm;
758	ADDSHORT(frm, 0);			/* selector count */
759	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
760		selcnt[0]++;
761		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
762	}
763	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
764		selcnt[0]++;
765		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
766	}
767
768	/* authenticator selector list */
769	selcnt = frm;
770	ADDSHORT(frm, 0);			/* selector count */
771	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
772		selcnt[0]++;
773		ADDSELECTOR(frm, key_mgt_unspec);
774	}
775	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
776		selcnt[0]++;
777		ADDSELECTOR(frm, key_mgt_psk);
778	}
779
780	/* optional capabilities */
781	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
782		ADDSHORT(frm, rsn->rsn_caps);
783
784	/* calculate element length */
785	ie[1] = frm - ie - 2;
786	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
787		("WPA IE too big, %u > %zu",
788		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
789	return frm;
790#undef ADDSHORT
791#undef ADDSELECTOR
792#undef WPA_OUI_BYTES
793}
794
795static u_int8_t *
796ieee80211_setup_rsn_ie(struct ieee80211com *ic, u_int8_t *ie)
797{
798#define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
799#define	ADDSHORT(frm, v) do {			\
800	frm[0] = (v) & 0xff;			\
801	frm[1] = (v) >> 8;			\
802	frm += 2;				\
803} while (0)
804#define	ADDSELECTOR(frm, sel) do {		\
805	memcpy(frm, sel, 4);			\
806	frm += 4;				\
807} while (0)
808	static const u_int8_t cipher_suite[][4] = {
809		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
810		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
811		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
812		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
813		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
814		{ RSN_OUI_BYTES, RSN_CSE_NULL },
815	};
816	static const u_int8_t wep104_suite[4] =
817		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
818	static const u_int8_t key_mgt_unspec[4] =
819		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
820	static const u_int8_t key_mgt_psk[4] =
821		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
822	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
823	u_int8_t *frm = ie;
824	u_int8_t *selcnt;
825
826	*frm++ = IEEE80211_ELEMID_RSN;
827	*frm++ = 0;				/* length filled in below */
828	ADDSHORT(frm, RSN_VERSION);
829
830	/* XXX filter out CKIP */
831
832	/* multicast cipher */
833	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
834	    rsn->rsn_mcastkeylen >= 13)
835		ADDSELECTOR(frm, wep104_suite);
836	else
837		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
838
839	/* unicast cipher list */
840	selcnt = frm;
841	ADDSHORT(frm, 0);			/* selector count */
842	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
843		selcnt[0]++;
844		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
845	}
846	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
847		selcnt[0]++;
848		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
849	}
850
851	/* authenticator selector list */
852	selcnt = frm;
853	ADDSHORT(frm, 0);			/* selector count */
854	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
855		selcnt[0]++;
856		ADDSELECTOR(frm, key_mgt_unspec);
857	}
858	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
859		selcnt[0]++;
860		ADDSELECTOR(frm, key_mgt_psk);
861	}
862
863	/* optional capabilities */
864	ADDSHORT(frm, rsn->rsn_caps);
865	/* XXX PMKID */
866
867	/* calculate element length */
868	ie[1] = frm - ie - 2;
869	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
870		("RSN IE too big, %u > %zu",
871		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
872	return frm;
873#undef ADDSELECTOR
874#undef ADDSHORT
875#undef RSN_OUI_BYTES
876}
877
878/*
879 * Add a WPA/RSN element to a frame.
880 */
881static u_int8_t *
882ieee80211_add_wpa(u_int8_t *frm, struct ieee80211com *ic)
883{
884
885	KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
886	if (ic->ic_flags & IEEE80211_F_WPA2)
887		frm = ieee80211_setup_rsn_ie(ic, frm);
888	if (ic->ic_flags & IEEE80211_F_WPA1)
889		frm = ieee80211_setup_wpa_ie(ic, frm);
890	return frm;
891}
892
893#define	WME_OUI_BYTES		0x00, 0x50, 0xf2
894/*
895 * Add a WME information element to a frame.
896 */
897static u_int8_t *
898ieee80211_add_wme_info(u_int8_t *frm, struct ieee80211_wme_state *wme)
899{
900	static const struct ieee80211_wme_info info = {
901		.wme_id		= IEEE80211_ELEMID_VENDOR,
902		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
903		.wme_oui	= { WME_OUI_BYTES },
904		.wme_type	= WME_OUI_TYPE,
905		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
906		.wme_version	= WME_VERSION,
907		.wme_info	= 0,
908	};
909	memcpy(frm, &info, sizeof(info));
910	return frm + sizeof(info);
911}
912
913/*
914 * Add a WME parameters element to a frame.
915 */
916static u_int8_t *
917ieee80211_add_wme_param(u_int8_t *frm, struct ieee80211_wme_state *wme)
918{
919#define	SM(_v, _f)	(((_v) << _f##_S) & _f)
920#define	ADDSHORT(frm, v) do {			\
921	frm[0] = (v) & 0xff;			\
922	frm[1] = (v) >> 8;			\
923	frm += 2;				\
924} while (0)
925	/* NB: this works 'cuz a param has an info at the front */
926	static const struct ieee80211_wme_info param = {
927		.wme_id		= IEEE80211_ELEMID_VENDOR,
928		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
929		.wme_oui	= { WME_OUI_BYTES },
930		.wme_type	= WME_OUI_TYPE,
931		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
932		.wme_version	= WME_VERSION,
933	};
934	int i;
935
936	memcpy(frm, &param, sizeof(param));
937	frm += __offsetof(struct ieee80211_wme_info, wme_info);
938	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
939	*frm++ = 0;					/* reserved field */
940	for (i = 0; i < WME_NUM_AC; i++) {
941		const struct wmeParams *ac =
942		       &wme->wme_bssChanParams.cap_wmeParams[i];
943		*frm++ = SM(i, WME_PARAM_ACI)
944		       | SM(ac->wmep_acm, WME_PARAM_ACM)
945		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
946		       ;
947		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
948		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
949		       ;
950		ADDSHORT(frm, ac->wmep_txopLimit);
951	}
952	return frm;
953#undef SM
954#undef ADDSHORT
955}
956#undef WME_OUI_BYTES
957
958/*
959 * Send a probe request frame with the specified ssid
960 * and any optional information element data.
961 */
962int
963ieee80211_send_probereq(struct ieee80211_node *ni,
964	const u_int8_t sa[IEEE80211_ADDR_LEN],
965	const u_int8_t da[IEEE80211_ADDR_LEN],
966	const u_int8_t bssid[IEEE80211_ADDR_LEN],
967	const u_int8_t *ssid, size_t ssidlen,
968	const void *optie, size_t optielen)
969{
970	struct ieee80211com *ic = ni->ni_ic;
971	enum ieee80211_phymode mode;
972	struct ieee80211_frame *wh;
973	struct mbuf *m;
974	u_int8_t *frm;
975
976	/*
977	 * Hold a reference on the node so it doesn't go away until after
978	 * the xmit is complete all the way in the driver.  On error we
979	 * will remove our reference.
980	 */
981	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
982		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
983		__func__, __LINE__,
984		ni, ether_sprintf(ni->ni_macaddr),
985		ieee80211_node_refcnt(ni)+1);
986	ieee80211_ref_node(ni);
987
988	/*
989	 * prreq frame format
990	 *	[tlv] ssid
991	 *	[tlv] supported rates
992	 *	[tlv] extended supported rates
993	 *	[tlv] user-specified ie's
994	 */
995	m = ieee80211_getmgtframe(&frm,
996		 2 + IEEE80211_NWID_LEN
997	       + 2 + IEEE80211_RATE_SIZE
998	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
999	       + (optie != NULL ? optielen : 0)
1000	);
1001	if (m == NULL) {
1002		ic->ic_stats.is_tx_nobuf++;
1003		ieee80211_free_node(ni);
1004		return ENOMEM;
1005	}
1006
1007	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1008	mode = ieee80211_chan2mode(ic, ic->ic_curchan);
1009	frm = ieee80211_add_rates(frm, &ic->ic_sup_rates[mode]);
1010	frm = ieee80211_add_xrates(frm, &ic->ic_sup_rates[mode]);
1011
1012	if (optie != NULL) {
1013		memcpy(frm, optie, optielen);
1014		frm += optielen;
1015	}
1016	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1017
1018	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1019	if (m == NULL)
1020		return ENOMEM;
1021	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
1022	m->m_pkthdr.rcvif = (void *)ni;
1023
1024	wh = mtod(m, struct ieee80211_frame *);
1025	ieee80211_send_setup(ic, ni, wh,
1026		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1027		sa, da, bssid);
1028	/* XXX power management? */
1029
1030	IEEE80211_NODE_STAT(ni, tx_probereq);
1031	IEEE80211_NODE_STAT(ni, tx_mgmt);
1032
1033	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1034	    "[%s] send probe req on channel %u\n",
1035	    ether_sprintf(wh->i_addr1),
1036	    ieee80211_chan2ieee(ic, ic->ic_curchan));
1037
1038	IF_ENQUEUE(&ic->ic_mgtq, m);
1039	if_start(ic->ic_ifp);
1040	return 0;
1041}
1042
1043/*
1044 * Calculate capability information for mgt frames.
1045 */
1046static u_int16_t
1047getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
1048{
1049	u_int16_t capinfo;
1050
1051	KASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
1052
1053	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1054		capinfo = IEEE80211_CAPINFO_ESS;
1055	else if (ic->ic_opmode == IEEE80211_M_IBSS)
1056		capinfo = IEEE80211_CAPINFO_IBSS;
1057	else
1058		capinfo = 0;
1059	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1060		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1061	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1062	    IEEE80211_IS_CHAN_2GHZ(chan))
1063		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1064	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1065		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1066	return capinfo;
1067}
1068
1069/*
1070 * Send a management frame.  The node is for the destination (or ic_bss
1071 * when in station mode).  Nodes other than ic_bss have their reference
1072 * count bumped to reflect our use for an indeterminant time.
1073 */
1074int
1075ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1076	int type, int arg)
1077{
1078#define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1079	struct mbuf *m;
1080	u_int8_t *frm;
1081	u_int16_t capinfo;
1082	int has_challenge, is_shared_key, ret, timer, status;
1083
1084	KASSERT(ni != NULL, ("null node"));
1085
1086	/*
1087	 * Hold a reference on the node so it doesn't go away until after
1088	 * the xmit is complete all the way in the driver.  On error we
1089	 * will remove our reference.
1090	 */
1091	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1092		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1093		__func__, __LINE__,
1094		ni, ether_sprintf(ni->ni_macaddr),
1095		ieee80211_node_refcnt(ni)+1);
1096	ieee80211_ref_node(ni);
1097
1098	timer = 0;
1099	switch (type) {
1100	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1101		/*
1102		 * probe response frame format
1103		 *	[8] time stamp
1104		 *	[2] beacon interval
1105		 *	[2] cabability information
1106		 *	[tlv] ssid
1107		 *	[tlv] supported rates
1108		 *	[tlv] parameter set (FH/DS)
1109		 *	[tlv] parameter set (IBSS)
1110		 *	[tlv] extended rate phy (ERP)
1111		 *	[tlv] extended supported rates
1112		 *	[tlv] WPA
1113		 *	[tlv] WME (optional)
1114		 */
1115		m = ieee80211_getmgtframe(&frm,
1116			 8
1117		       + sizeof(u_int16_t)
1118		       + sizeof(u_int16_t)
1119		       + 2 + IEEE80211_NWID_LEN
1120		       + 2 + IEEE80211_RATE_SIZE
1121		       + 7	/* max(7,3) */
1122		       + 6
1123		       + 3
1124		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1125		       /* XXX !WPA1+WPA2 fits w/o a cluster */
1126		       + (ic->ic_flags & IEEE80211_F_WPA ?
1127				2*sizeof(struct ieee80211_ie_wpa) : 0)
1128		       + sizeof(struct ieee80211_wme_param)
1129		);
1130		if (m == NULL)
1131			senderr(ENOMEM, is_tx_nobuf);
1132
1133		memset(frm, 0, 8);	/* timestamp should be filled later */
1134		frm += 8;
1135		*(u_int16_t *)frm = htole16(ic->ic_bss->ni_intval);
1136		frm += 2;
1137		capinfo = getcapinfo(ic, ic->ic_curchan);
1138		*(u_int16_t *)frm = htole16(capinfo);
1139		frm += 2;
1140
1141		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1142				ic->ic_bss->ni_esslen);
1143		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1144
1145		if (ic->ic_phytype == IEEE80211_T_FH) {
1146                        *frm++ = IEEE80211_ELEMID_FHPARMS;
1147                        *frm++ = 5;
1148                        *frm++ = ni->ni_fhdwell & 0x00ff;
1149                        *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1150                        *frm++ = IEEE80211_FH_CHANSET(
1151			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1152                        *frm++ = IEEE80211_FH_CHANPAT(
1153			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1154                        *frm++ = ni->ni_fhindex;
1155		} else {
1156			*frm++ = IEEE80211_ELEMID_DSPARMS;
1157			*frm++ = 1;
1158			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
1159		}
1160
1161		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1162			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1163			*frm++ = 2;
1164			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1165		}
1166		if (ic->ic_flags & IEEE80211_F_WPA)
1167			frm = ieee80211_add_wpa(frm, ic);
1168		if (ic->ic_curmode == IEEE80211_MODE_11G)
1169			frm = ieee80211_add_erp(frm, ic);
1170		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1171		if (ic->ic_flags & IEEE80211_F_WME)
1172			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1173		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1174		break;
1175
1176	case IEEE80211_FC0_SUBTYPE_AUTH:
1177		status = arg >> 16;
1178		arg &= 0xffff;
1179		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1180		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1181		    ni->ni_challenge != NULL);
1182
1183		/*
1184		 * Deduce whether we're doing open authentication or
1185		 * shared key authentication.  We do the latter if
1186		 * we're in the middle of a shared key authentication
1187		 * handshake or if we're initiating an authentication
1188		 * request and configured to use shared key.
1189		 */
1190		is_shared_key = has_challenge ||
1191		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1192		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1193		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1194
1195		m = ieee80211_getmgtframe(&frm,
1196			  3 * sizeof(u_int16_t)
1197			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1198				sizeof(u_int16_t)+IEEE80211_CHALLENGE_LEN : 0)
1199		);
1200		if (m == NULL)
1201			senderr(ENOMEM, is_tx_nobuf);
1202
1203		((u_int16_t *)frm)[0] =
1204		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1205		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1206		((u_int16_t *)frm)[1] = htole16(arg);	/* sequence number */
1207		((u_int16_t *)frm)[2] = htole16(status);/* status */
1208
1209		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1210			((u_int16_t *)frm)[3] =
1211			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1212			    IEEE80211_ELEMID_CHALLENGE);
1213			memcpy(&((u_int16_t *)frm)[4], ni->ni_challenge,
1214			    IEEE80211_CHALLENGE_LEN);
1215			m->m_pkthdr.len = m->m_len =
1216				4 * sizeof(u_int16_t) + IEEE80211_CHALLENGE_LEN;
1217			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1218				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1219				    "[%s] request encrypt frame (%s)\n",
1220				    ether_sprintf(ni->ni_macaddr), __func__);
1221				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1222			}
1223		} else
1224			m->m_pkthdr.len = m->m_len = 3 * sizeof(u_int16_t);
1225
1226		/* XXX not right for shared key */
1227		if (status == IEEE80211_STATUS_SUCCESS)
1228			IEEE80211_NODE_STAT(ni, tx_auth);
1229		else
1230			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1231
1232		if (ic->ic_opmode == IEEE80211_M_STA)
1233			timer = IEEE80211_TRANS_WAIT;
1234		break;
1235
1236	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1237		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1238			"[%s] send station deauthenticate (reason %d)\n",
1239			ether_sprintf(ni->ni_macaddr), arg);
1240		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1241		if (m == NULL)
1242			senderr(ENOMEM, is_tx_nobuf);
1243		*(u_int16_t *)frm = htole16(arg);	/* reason */
1244		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1245
1246		IEEE80211_NODE_STAT(ni, tx_deauth);
1247		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1248
1249		ieee80211_node_unauthorize(ni);		/* port closed */
1250		break;
1251
1252	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1253	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1254		/*
1255		 * asreq frame format
1256		 *	[2] capability information
1257		 *	[2] listen interval
1258		 *	[6*] current AP address (reassoc only)
1259		 *	[tlv] ssid
1260		 *	[tlv] supported rates
1261		 *	[tlv] extended supported rates
1262		 *	[tlv] WME
1263		 *	[tlv] user-specified ie's
1264		 */
1265		m = ieee80211_getmgtframe(&frm,
1266			 sizeof(u_int16_t)
1267		       + sizeof(u_int16_t)
1268		       + IEEE80211_ADDR_LEN
1269		       + 2 + IEEE80211_NWID_LEN
1270		       + 2 + IEEE80211_RATE_SIZE
1271		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1272		       + sizeof(struct ieee80211_wme_info)
1273		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1274		);
1275		if (m == NULL)
1276			senderr(ENOMEM, is_tx_nobuf);
1277
1278		KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1279		    ("wrong mode %u", ic->ic_opmode));
1280		capinfo = IEEE80211_CAPINFO_ESS;
1281		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1282			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1283		/*
1284		 * NB: Some 11a AP's reject the request when
1285		 *     short premable is set.
1286		 */
1287		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1288		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1289			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1290		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) &&
1291		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1292			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1293		*(u_int16_t *)frm = htole16(capinfo);
1294		frm += 2;
1295
1296		*(u_int16_t *)frm = htole16(ic->ic_lintval);
1297		frm += 2;
1298
1299		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1300			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1301			frm += IEEE80211_ADDR_LEN;
1302		}
1303
1304		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1305		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1306		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1307		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1308			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1309		if (ic->ic_opt_ie != NULL) {
1310			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1311			frm += ic->ic_opt_ie_len;
1312		}
1313		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1314
1315		timer = IEEE80211_TRANS_WAIT;
1316		break;
1317
1318	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1319	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1320		/*
1321		 * asreq frame format
1322		 *	[2] capability information
1323		 *	[2] status
1324		 *	[2] association ID
1325		 *	[tlv] supported rates
1326		 *	[tlv] extended supported rates
1327		 *	[tlv] WME (if enabled and STA enabled)
1328		 */
1329		m = ieee80211_getmgtframe(&frm,
1330			 sizeof(u_int16_t)
1331		       + sizeof(u_int16_t)
1332		       + sizeof(u_int16_t)
1333		       + 2 + IEEE80211_RATE_SIZE
1334		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1335		       + sizeof(struct ieee80211_wme_param)
1336		);
1337		if (m == NULL)
1338			senderr(ENOMEM, is_tx_nobuf);
1339
1340		capinfo = getcapinfo(ic, ic->ic_curchan);
1341		*(u_int16_t *)frm = htole16(capinfo);
1342		frm += 2;
1343
1344		*(u_int16_t *)frm = htole16(arg);	/* status */
1345		frm += 2;
1346
1347		if (arg == IEEE80211_STATUS_SUCCESS) {
1348			*(u_int16_t *)frm = htole16(ni->ni_associd);
1349			IEEE80211_NODE_STAT(ni, tx_assoc);
1350		} else
1351			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1352		frm += 2;
1353
1354		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1355		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1356		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1357			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1358		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1359		break;
1360
1361	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1362		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1363			"[%s] send station disassociate (reason %d)\n",
1364			ether_sprintf(ni->ni_macaddr), arg);
1365		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1366		if (m == NULL)
1367			senderr(ENOMEM, is_tx_nobuf);
1368		*(u_int16_t *)frm = htole16(arg);	/* reason */
1369		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1370
1371		IEEE80211_NODE_STAT(ni, tx_disassoc);
1372		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1373		break;
1374
1375	default:
1376		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1377			"[%s] invalid mgmt frame type %u\n",
1378			ether_sprintf(ni->ni_macaddr), type);
1379		senderr(EINVAL, is_tx_unknownmgt);
1380		/* NOTREACHED */
1381	}
1382	ret = ieee80211_mgmt_output(ic, ni, m, type, timer);
1383	if (ret != 0) {
1384bad:
1385		ieee80211_free_node(ni);
1386	}
1387	return ret;
1388#undef senderr
1389}
1390
1391/*
1392 * Allocate a beacon frame and fillin the appropriate bits.
1393 */
1394struct mbuf *
1395ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
1396	struct ieee80211_beacon_offsets *bo)
1397{
1398	struct ifnet *ifp = ic->ic_ifp;
1399	struct ieee80211_frame *wh;
1400	struct mbuf *m;
1401	int pktlen;
1402	u_int8_t *frm, *efrm;
1403	u_int16_t capinfo;
1404	struct ieee80211_rateset *rs;
1405
1406	/*
1407	 * beacon frame format
1408	 *	[8] time stamp
1409	 *	[2] beacon interval
1410	 *	[2] cabability information
1411	 *	[tlv] ssid
1412	 *	[tlv] supported rates
1413	 *	[3] parameter set (DS)
1414	 *	[tlv] parameter set (IBSS/TIM)
1415	 *	[tlv] extended rate phy (ERP)
1416	 *	[tlv] extended supported rates
1417	 *	[tlv] WME parameters
1418	 *	[tlv] WPA/RSN parameters
1419	 * XXX Vendor-specific OIDs (e.g. Atheros)
1420	 * NB: we allocate the max space required for the TIM bitmap.
1421	 */
1422	rs = &ni->ni_rates;
1423	pktlen =   8					/* time stamp */
1424		 + sizeof(u_int16_t)			/* beacon interval */
1425		 + sizeof(u_int16_t)			/* capabilities */
1426		 + 2 + ni->ni_esslen			/* ssid */
1427	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
1428	         + 2 + 1				/* DS parameters */
1429		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
1430		 + 2 + 1				/* ERP */
1431	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1432		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
1433			sizeof(struct ieee80211_wme_param) : 0)
1434		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
1435			2*sizeof(struct ieee80211_ie_wpa) : 0)
1436		 ;
1437	m = ieee80211_getmgtframe(&frm, pktlen);
1438	if (m == NULL) {
1439		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1440			"%s: cannot get buf; size %u\n", __func__, pktlen);
1441		ic->ic_stats.is_tx_nobuf++;
1442		return NULL;
1443	}
1444
1445	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
1446	frm += 8;
1447	*(u_int16_t *)frm = htole16(ni->ni_intval);
1448	frm += 2;
1449	capinfo = getcapinfo(ic, ni->ni_chan);
1450	bo->bo_caps = (u_int16_t *)frm;
1451	*(u_int16_t *)frm = htole16(capinfo);
1452	frm += 2;
1453	*frm++ = IEEE80211_ELEMID_SSID;
1454	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
1455		*frm++ = ni->ni_esslen;
1456		memcpy(frm, ni->ni_essid, ni->ni_esslen);
1457		frm += ni->ni_esslen;
1458	} else
1459		*frm++ = 0;
1460	frm = ieee80211_add_rates(frm, rs);
1461	if (ic->ic_curmode != IEEE80211_MODE_FH) {
1462		*frm++ = IEEE80211_ELEMID_DSPARMS;
1463		*frm++ = 1;
1464		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1465	}
1466	bo->bo_tim = frm;
1467	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1468		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1469		*frm++ = 2;
1470		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1471		bo->bo_tim_len = 0;
1472	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1473		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
1474
1475		tie->tim_ie = IEEE80211_ELEMID_TIM;
1476		tie->tim_len = 4;	/* length */
1477		tie->tim_count = 0;	/* DTIM count */
1478		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
1479		tie->tim_bitctl = 0;	/* bitmap control */
1480		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
1481		frm += sizeof(struct ieee80211_tim_ie);
1482		bo->bo_tim_len = 1;
1483	}
1484	bo->bo_trailer = frm;
1485	if (ic->ic_flags & IEEE80211_F_WME) {
1486		bo->bo_wme = frm;
1487		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1488		ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1489	}
1490	if (ic->ic_flags & IEEE80211_F_WPA)
1491		frm = ieee80211_add_wpa(frm, ic);
1492	if (ic->ic_curmode == IEEE80211_MODE_11G) {
1493		bo->bo_erp = frm;
1494		frm = ieee80211_add_erp(frm, ic);
1495	}
1496	efrm = ieee80211_add_xrates(frm, rs);
1497	bo->bo_trailer_len = efrm - bo->bo_trailer;
1498	m->m_pkthdr.len = m->m_len = efrm - mtod(m, u_int8_t *);
1499
1500	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1501	KASSERT(m != NULL, ("no space for 802.11 header?"));
1502	wh = mtod(m, struct ieee80211_frame *);
1503	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1504	    IEEE80211_FC0_SUBTYPE_BEACON;
1505	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1506	*(u_int16_t *)wh->i_dur = 0;
1507	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1508	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1509	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1510	*(u_int16_t *)wh->i_seq = 0;
1511
1512	return m;
1513}
1514
1515/*
1516 * Update the dynamic parts of a beacon frame based on the current state.
1517 */
1518int
1519ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
1520	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
1521{
1522	int len_changed = 0;
1523	u_int16_t capinfo;
1524
1525	IEEE80211_BEACON_LOCK(ic);
1526	/* XXX faster to recalculate entirely or just changes? */
1527	capinfo = getcapinfo(ic, ni->ni_chan);
1528	*bo->bo_caps = htole16(capinfo);
1529
1530	if (ic->ic_flags & IEEE80211_F_WME) {
1531		struct ieee80211_wme_state *wme = &ic->ic_wme;
1532
1533		/*
1534		 * Check for agressive mode change.  When there is
1535		 * significant high priority traffic in the BSS
1536		 * throttle back BE traffic by using conservative
1537		 * parameters.  Otherwise BE uses agressive params
1538		 * to optimize performance of legacy/non-QoS traffic.
1539		 */
1540		if (wme->wme_flags & WME_F_AGGRMODE) {
1541			if (wme->wme_hipri_traffic >
1542			    wme->wme_hipri_switch_thresh) {
1543				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1544				    "%s: traffic %u, disable aggressive mode\n",
1545				    __func__, wme->wme_hipri_traffic);
1546				wme->wme_flags &= ~WME_F_AGGRMODE;
1547				ieee80211_wme_updateparams_locked(ic);
1548				wme->wme_hipri_traffic =
1549					wme->wme_hipri_switch_hysteresis;
1550			} else
1551				wme->wme_hipri_traffic = 0;
1552		} else {
1553			if (wme->wme_hipri_traffic <=
1554			    wme->wme_hipri_switch_thresh) {
1555				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1556				    "%s: traffic %u, enable aggressive mode\n",
1557				    __func__, wme->wme_hipri_traffic);
1558				wme->wme_flags |= WME_F_AGGRMODE;
1559				ieee80211_wme_updateparams_locked(ic);
1560				wme->wme_hipri_traffic = 0;
1561			} else
1562				wme->wme_hipri_traffic =
1563					wme->wme_hipri_switch_hysteresis;
1564		}
1565		if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
1566			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
1567			ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1568		}
1569	}
1570
1571	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
1572		struct ieee80211_tim_ie *tie =
1573			(struct ieee80211_tim_ie *) bo->bo_tim;
1574		if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
1575			u_int timlen, timoff, i;
1576			/*
1577			 * ATIM/DTIM needs updating.  If it fits in the
1578			 * current space allocated then just copy in the
1579			 * new bits.  Otherwise we need to move any trailing
1580			 * data to make room.  Note that we know there is
1581			 * contiguous space because ieee80211_beacon_allocate
1582			 * insures there is space in the mbuf to write a
1583			 * maximal-size virtual bitmap (based on ic_max_aid).
1584			 */
1585			/*
1586			 * Calculate the bitmap size and offset, copy any
1587			 * trailer out of the way, and then copy in the
1588			 * new bitmap and update the information element.
1589			 * Note that the tim bitmap must contain at least
1590			 * one byte and any offset must be even.
1591			 */
1592			if (ic->ic_ps_pending != 0) {
1593				timoff = 128;		/* impossibly large */
1594				for (i = 0; i < ic->ic_tim_len; i++)
1595					if (ic->ic_tim_bitmap[i]) {
1596						timoff = i &~ 1;
1597						break;
1598					}
1599				KASSERT(timoff != 128, ("tim bitmap empty!"));
1600				for (i = ic->ic_tim_len-1; i >= timoff; i--)
1601					if (ic->ic_tim_bitmap[i])
1602						break;
1603				timlen = 1 + (i - timoff);
1604			} else {
1605				timoff = 0;
1606				timlen = 1;
1607			}
1608			if (timlen != bo->bo_tim_len) {
1609				/* copy up/down trailer */
1610				int adjust = tie->tim_bitmap+timlen
1611					   - bo->bo_trailer;
1612				ovbcopy(bo->bo_trailer, bo->bo_trailer+adjust,
1613					bo->bo_trailer_len);
1614				bo->bo_trailer += adjust;
1615				bo->bo_wme += adjust;
1616				bo->bo_erp += adjust;
1617				bo->bo_tim_len = timlen;
1618
1619				/* update information element */
1620				tie->tim_len = 3 + timlen;
1621				tie->tim_bitctl = timoff;
1622				len_changed = 1;
1623			}
1624			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
1625				bo->bo_tim_len);
1626
1627			ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
1628
1629			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1630				"%s: TIM updated, pending %u, off %u, len %u\n",
1631				__func__, ic->ic_ps_pending, timoff, timlen);
1632		}
1633		/* count down DTIM period */
1634		if (tie->tim_count == 0)
1635			tie->tim_count = tie->tim_period - 1;
1636		else
1637			tie->tim_count--;
1638		/* update state for buffered multicast frames on DTIM */
1639		if (mcast && tie->tim_count == 0)
1640			tie->tim_bitctl |= 1;
1641		else
1642			tie->tim_bitctl &= ~1;
1643		if (ic->ic_flags_ext & IEEE80211_FEXT_ERPUPDATE) {
1644			/*
1645			 * ERP element needs updating.
1646			 */
1647			(void) ieee80211_add_erp(bo->bo_erp, ic);
1648			ic->ic_flags_ext &= ~IEEE80211_FEXT_ERPUPDATE;
1649		}
1650	}
1651	IEEE80211_BEACON_UNLOCK(ic);
1652
1653	return len_changed;
1654}
1655
1656/*
1657 * Save an outbound packet for a node in power-save sleep state.
1658 * The new packet is placed on the node's saved queue, and the TIM
1659 * is changed, if necessary.
1660 */
1661void
1662ieee80211_pwrsave(struct ieee80211com *ic, struct ieee80211_node *ni,
1663		  struct mbuf *m)
1664{
1665	int qlen, age;
1666
1667	IEEE80211_NODE_SAVEQ_LOCK(ni);
1668	if (_IF_QFULL(&ni->ni_savedq)) {
1669		_IF_DROP(&ni->ni_savedq);
1670		IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1671		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1672			"[%s] pwr save q overflow, drops %d (size %d)\n",
1673			ether_sprintf(ni->ni_macaddr),
1674			ni->ni_savedq.ifq_drops, IEEE80211_PS_MAX_QUEUE);
1675#ifdef IEEE80211_DEBUG
1676		if (ieee80211_msg_dumppkts(ic))
1677			ieee80211_dump_pkt(mtod(m, caddr_t), m->m_len, -1, -1);
1678#endif
1679		m_freem(m);
1680		return;
1681	}
1682	/*
1683	 * Tag the frame with it's expiry time and insert
1684	 * it in the queue.  The aging interval is 4 times
1685	 * the listen interval specified by the station.
1686	 * Frames that sit around too long are reclaimed
1687	 * using this information.
1688	 */
1689	/* XXX handle overflow? */
1690	age = ((ni->ni_intval * ic->ic_bintval) << 2) / 1024; /* TU -> secs */
1691	_IEEE80211_NODE_SAVEQ_ENQUEUE(ni, m, qlen, age);
1692	IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1693
1694	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1695		"[%s] save frame with age %d, %u now queued\n",
1696		ether_sprintf(ni->ni_macaddr), age, qlen);
1697
1698	if (qlen == 1)
1699		ic->ic_set_tim(ni, 1);
1700}
1701