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