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