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