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