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