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