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