xref: /freebsd-src/sys/net80211/ieee80211_output.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2008 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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_inet.h"
31 #include "opt_wlan.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/mbuf.h>
36 #include <sys/kernel.h>
37 #include <sys/endian.h>
38 
39 #include <sys/socket.h>
40 
41 #include <net/bpf.h>
42 #include <net/ethernet.h>
43 #include <net/if.h>
44 #include <net/if_llc.h>
45 #include <net/if_media.h>
46 #include <net/if_vlan_var.h>
47 
48 #include <net80211/ieee80211_var.h>
49 #include <net80211/ieee80211_regdomain.h>
50 #include <net80211/ieee80211_wds.h>
51 
52 #ifdef INET
53 #include <netinet/in.h>
54 #include <netinet/if_ether.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #endif
58 
59 #define	ETHER_HEADER_COPY(dst, src) \
60 	memcpy(dst, src, sizeof(struct ether_header))
61 
62 static struct mbuf *ieee80211_encap_fastframe(struct ieee80211vap *,
63 	struct mbuf *m1, const struct ether_header *eh1,
64 	struct mbuf *m2, const struct ether_header *eh2);
65 static int ieee80211_fragment(struct ieee80211vap *, struct mbuf *,
66 	u_int hdrsize, u_int ciphdrsize, u_int mtu);
67 static	void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
68 
69 #ifdef IEEE80211_DEBUG
70 /*
71  * Decide if an outbound management frame should be
72  * printed when debugging is enabled.  This filters some
73  * of the less interesting frames that come frequently
74  * (e.g. beacons).
75  */
76 static __inline int
77 doprint(struct ieee80211vap *vap, int subtype)
78 {
79 	switch (subtype) {
80 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
81 		return (vap->iv_opmode == IEEE80211_M_IBSS);
82 	}
83 	return 1;
84 }
85 #endif
86 
87 /*
88  * Start method for vap's.  All packets from the stack come
89  * through here.  We handle common processing of the packets
90  * before dispatching them to the underlying device.
91  */
92 void
93 ieee80211_start(struct ifnet *ifp)
94 {
95 #define	IS_DWDS(vap) \
96 	(vap->iv_opmode == IEEE80211_M_WDS && \
97 	 (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) == 0)
98 	struct ieee80211vap *vap = ifp->if_softc;
99 	struct ieee80211com *ic = vap->iv_ic;
100 	struct ifnet *parent = ic->ic_ifp;
101 	struct ieee80211_node *ni;
102 	struct mbuf *m;
103 	struct ether_header *eh;
104 	int error;
105 
106 	/* NB: parent must be up and running */
107 	if (!IFNET_IS_UP_RUNNING(parent)) {
108 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
109 		    "%s: ignore queue, parent %s not up+running\n",
110 		    __func__, parent->if_xname);
111 		/* XXX stat */
112 		return;
113 	}
114 	if (vap->iv_state == IEEE80211_S_SLEEP) {
115 		/*
116 		 * In power save, wakeup device for transmit.
117 		 */
118 		ieee80211_new_state(vap, IEEE80211_S_RUN, 0);
119 		return;
120 	}
121 	/*
122 	 * No data frames go out unless we're running.
123 	 * Note in particular this covers CAC and CSA
124 	 * states (though maybe we should check muting
125 	 * for CSA).
126 	 */
127 	if (vap->iv_state != IEEE80211_S_RUN) {
128 		IEEE80211_LOCK(ic);
129 		/* re-check under the com lock to avoid races */
130 		if (vap->iv_state != IEEE80211_S_RUN) {
131 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
132 			    "%s: ignore queue, in %s state\n",
133 			    __func__, ieee80211_state_name[vap->iv_state]);
134 			vap->iv_stats.is_tx_badstate++;
135 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
136 			IEEE80211_UNLOCK(ic);
137 			return;
138 		}
139 		IEEE80211_UNLOCK(ic);
140 	}
141 	for (;;) {
142 		IFQ_DEQUEUE(&ifp->if_snd, m);
143 		if (m == NULL)
144 			break;
145 		/*
146 		 * Sanitize mbuf flags for net80211 use.  We cannot
147 		 * clear M_PWR_SAV because this may be set for frames
148 		 * that are re-submitted from the power save queue.
149 		 *
150 		 * NB: This must be done before ieee80211_classify as
151 		 *     it marks EAPOL in frames with M_EAPOL.
152 		 */
153 		m->m_flags &= ~(M_80211_TX - M_PWR_SAV);
154 		/*
155 		 * Cancel any background scan.
156 		 */
157 		if (ic->ic_flags & IEEE80211_F_SCAN)
158 			ieee80211_cancel_anyscan(vap);
159 		/*
160 		 * Find the node for the destination so we can do
161 		 * things like power save and fast frames aggregation.
162 		 *
163 		 * NB: past this point various code assumes the first
164 		 *     mbuf has the 802.3 header present (and contiguous).
165 		 */
166 		ni = NULL;
167 		if (m->m_len < sizeof(struct ether_header) &&
168 		   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
169 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
170 			    "discard frame, %s\n", "m_pullup failed");
171 			vap->iv_stats.is_tx_nobuf++;	/* XXX */
172 			ifp->if_oerrors++;
173 			continue;
174 		}
175 		eh = mtod(m, struct ether_header *);
176 		if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
177 			if (IS_DWDS(vap)) {
178 				/*
179 				 * Only unicast frames from the above go out
180 				 * DWDS vaps; multicast frames are handled by
181 				 * dispatching the frame as it comes through
182 				 * the AP vap (see below).
183 				 */
184 				IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_WDS,
185 				    eh->ether_dhost, "mcast", "%s", "on DWDS");
186 				vap->iv_stats.is_dwds_mcast++;
187 				m_freem(m);
188 				continue;
189 			}
190 			if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
191 				/*
192 				 * Spam DWDS vap's w/ multicast traffic.
193 				 */
194 				/* XXX only if dwds in use? */
195 				ieee80211_dwds_mcast(vap, m);
196 			}
197 		}
198 		ni = ieee80211_find_txnode(vap, eh->ether_dhost);
199 		if (ni == NULL) {
200 			/* NB: ieee80211_find_txnode does stat+msg */
201 			ifp->if_oerrors++;
202 			m_freem(m);
203 			continue;
204 		}
205 		/* XXX AUTH'd */
206 		if (ni->ni_associd == 0) {
207 			/*
208 			 * Destination is not associated; must special
209 			 * case DWDS where we point iv_bss at the node
210 			 * for the associated station.
211 			 * XXX adhoc mode?
212 			 */
213 			if (ni != vap->iv_bss || IS_DWDS(vap)) {
214 				IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
215 				    eh->ether_dhost, NULL,
216 				    "sta not associated (type 0x%04x)",
217 				    htons(eh->ether_type));
218 				vap->iv_stats.is_tx_notassoc++;
219 				ifp->if_oerrors++;
220 				m_freem(m);
221 				ieee80211_free_node(ni);
222 				continue;
223 			}
224 		}
225 		if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
226 		    (m->m_flags & M_PWR_SAV) == 0) {
227 			/*
228 			 * Station in power save mode; pass the frame
229 			 * to the 802.11 layer and continue.  We'll get
230 			 * the frame back when the time is right.
231 			 * XXX lose WDS vap linkage?
232 			 */
233 			ieee80211_pwrsave(ni, m);
234 			ieee80211_free_node(ni);
235 			continue;
236 		}
237 		/* calculate priority so drivers can find the tx queue */
238 		if (ieee80211_classify(ni, m)) {
239 			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
240 			    eh->ether_dhost, NULL,
241 			    "%s", "classification failure");
242 			vap->iv_stats.is_tx_classify++;
243 			ifp->if_oerrors++;
244 			m_freem(m);
245 			ieee80211_free_node(ni);
246 			continue;
247 		}
248 
249 		BPF_MTAP(ifp, m);		/* 802.11 tx path */
250 
251 		/*
252 		 * XXX When ni is associated with a WDS link then
253 		 * the vap will be the WDS vap but ni_vap will point
254 		 * to the ap vap the station associated to.  Once
255 		 * we handoff the packet to the driver the callback
256 		 * to ieee80211_encap won't be able to tell if the
257 		 * packet should be encapsulated for WDS or not (e.g.
258 		 * multicast frames will not be handled correctly).
259 		 * We hack this by marking the mbuf so ieee80211_encap
260 		 * can do the right thing.
261 		 */
262 		if (vap->iv_opmode == IEEE80211_M_WDS)
263 			m->m_flags |= M_WDS;
264 		else
265 			m->m_flags &= ~M_WDS;
266 
267 		/*
268 		 * Stash the node pointer and hand the frame off to
269 		 * the underlying device.  Note that we do this after
270 		 * any call to ieee80211_dwds_mcast because that code
271 		 * uses any existing value for rcvif.
272 		 */
273 		m->m_pkthdr.rcvif = (void *)ni;
274 
275 		/* XXX defer if_start calls? */
276 		IFQ_HANDOFF(parent, m, error);
277 		if (error != 0) {
278 			/* NB: IFQ_HANDOFF reclaims mbuf */
279 			ieee80211_free_node(ni);
280 		} else {
281 			ifp->if_opackets++;
282 		}
283 		ic->ic_lastdata = ticks;
284 	}
285 #undef IS_DWDS
286 }
287 
288 /*
289  * 802.11 output routine. This is (currently) used only to
290  * connect bpf write calls to the 802.11 layer for injecting
291  * raw 802.11 frames.  Note we locate the ieee80211com from
292  * the ifnet using a spare field setup at attach time.  This
293  * will go away when the virtual ap support comes in.
294  */
295 int
296 ieee80211_output(struct ifnet *ifp, struct mbuf *m,
297 	struct sockaddr *dst, struct rtentry *rt0)
298 {
299 #define senderr(e) do { error = (e); goto bad;} while (0)
300 	struct ieee80211_node *ni = NULL;
301 	struct ieee80211vap *vap;
302 	struct ieee80211_frame *wh;
303 	int error;
304 
305 	if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
306 		/*
307 		 * Short-circuit requests if the vap is marked OACTIVE
308 		 * as this is used when tearing down state to indicate
309 		 * the vap may be gone.  This can also happen because a
310 		 * packet came down through ieee80211_start before the
311 		 * vap entered RUN state in which case it's also ok to
312 		 * just drop the frame.  This should not be necessary
313 		 * but callers of if_output don't check OACTIVE.
314 		 */
315 		senderr(ENETDOWN);
316 	}
317 	vap = ifp->if_softc;
318 	/*
319 	 * Hand to the 802.3 code if not tagged as
320 	 * a raw 802.11 frame.
321 	 */
322 	if (dst->sa_family != AF_IEEE80211)
323 		return vap->iv_output(ifp, m, dst, rt0);
324 #ifdef MAC
325 	error = mac_check_ifnet_transmit(ifp, m);
326 	if (error)
327 		senderr(error);
328 #endif
329 	if (ifp->if_flags & IFF_MONITOR)
330 		senderr(ENETDOWN);
331 	if (!IFNET_IS_UP_RUNNING(ifp))
332 		senderr(ENETDOWN);
333 	if (vap->iv_state == IEEE80211_S_CAC) {
334 		IEEE80211_DPRINTF(vap,
335 		    IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
336 		    "block %s frame in CAC state\n", "raw data");
337 		vap->iv_stats.is_tx_badstate++;
338 		senderr(EIO);		/* XXX */
339 	}
340 	/* XXX bypass bridge, pfil, carp, etc. */
341 
342 	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
343 		senderr(EIO);	/* XXX */
344 	wh = mtod(m, struct ieee80211_frame *);
345 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
346 	    IEEE80211_FC0_VERSION_0)
347 		senderr(EIO);	/* XXX */
348 
349 	/* locate destination node */
350 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
351 	case IEEE80211_FC1_DIR_NODS:
352 	case IEEE80211_FC1_DIR_FROMDS:
353 		ni = ieee80211_find_txnode(vap, wh->i_addr1);
354 		break;
355 	case IEEE80211_FC1_DIR_TODS:
356 	case IEEE80211_FC1_DIR_DSTODS:
357 		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
358 			senderr(EIO);	/* XXX */
359 		ni = ieee80211_find_txnode(vap, wh->i_addr3);
360 		break;
361 	default:
362 		senderr(EIO);	/* XXX */
363 	}
364 	if (ni == NULL) {
365 		/*
366 		 * Permit packets w/ bpf params through regardless
367 		 * (see below about sa_len).
368 		 */
369 		if (dst->sa_len == 0)
370 			senderr(EHOSTUNREACH);
371 		ni = ieee80211_ref_node(vap->iv_bss);
372 	}
373 
374 	/*
375 	 * Sanitize mbuf for net80211 flags leaked from above.
376 	 *
377 	 * NB: This must be done before ieee80211_classify as
378 	 *     it marks EAPOL in frames with M_EAPOL.
379 	 */
380 	m->m_flags &= ~M_80211_TX;
381 
382 	/* calculate priority so drivers can find the tx queue */
383 	/* XXX assumes an 802.3 frame */
384 	if (ieee80211_classify(ni, m))
385 		senderr(EIO);		/* XXX */
386 
387 	BPF_MTAP(ifp, m);
388 
389 	/*
390 	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
391 	 * present by setting the sa_len field of the sockaddr (yes,
392 	 * this is a hack).
393 	 * NB: we assume sa_data is suitably aligned to cast.
394 	 */
395 	return vap->iv_ic->ic_raw_xmit(ni, m,
396 	    (const struct ieee80211_bpf_params *)(dst->sa_len ?
397 		dst->sa_data : NULL));
398 bad:
399 	if (m != NULL)
400 		m_freem(m);
401 	if (ni != NULL)
402 		ieee80211_free_node(ni);
403 	return error;
404 #undef senderr
405 }
406 
407 /*
408  * Set the direction field and address fields of an outgoing
409  * non-QoS frame.  Note this should be called early on in
410  * constructing a frame as it sets i_fc[1]; other bits can
411  * then be or'd in.
412  */
413 static void
414 ieee80211_send_setup(
415 	struct ieee80211_node *ni,
416 	struct ieee80211_frame *wh,
417 	int type,
418 	const uint8_t sa[IEEE80211_ADDR_LEN],
419 	const uint8_t da[IEEE80211_ADDR_LEN],
420 	const uint8_t bssid[IEEE80211_ADDR_LEN])
421 {
422 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
423 
424 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
425 	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
426 		struct ieee80211vap *vap = ni->ni_vap;
427 
428 		switch (vap->iv_opmode) {
429 		case IEEE80211_M_STA:
430 			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
431 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
432 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
433 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
434 			break;
435 		case IEEE80211_M_IBSS:
436 		case IEEE80211_M_AHDEMO:
437 			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
438 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
439 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
440 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
441 			break;
442 		case IEEE80211_M_HOSTAP:
443 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
444 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
445 			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
446 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
447 			break;
448 		case IEEE80211_M_WDS:
449 			wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
450 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
451 			IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
452 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
453 			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
454 			break;
455 		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
456 			break;
457 		}
458 	} else {
459 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
460 		IEEE80211_ADDR_COPY(wh->i_addr1, da);
461 		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
462 		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
463 	}
464 	*(uint16_t *)&wh->i_dur[0] = 0;
465 	/* XXX probe response use per-vap seq#? */
466 	/* NB: use non-QoS tid */
467 	*(uint16_t *)&wh->i_seq[0] =
468 	    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
469 	ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
470 #undef WH4
471 }
472 
473 /*
474  * Send a management frame to the specified node.  The node pointer
475  * must have a reference as the pointer will be passed to the driver
476  * and potentially held for a long time.  If the frame is successfully
477  * dispatched to the driver, then it is responsible for freeing the
478  * reference (and potentially free'ing up any associated storage);
479  * otherwise deal with reclaiming any reference (on error).
480  */
481 int
482 ieee80211_mgmt_output(struct ieee80211_node *ni, struct mbuf *m, int type)
483 {
484 	struct ieee80211vap *vap = ni->ni_vap;
485 	struct ieee80211com *ic = ni->ni_ic;
486 	struct ieee80211_frame *wh;
487 
488 	KASSERT(ni != NULL, ("null node"));
489 
490 	if (vap->iv_state == IEEE80211_S_CAC) {
491 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
492 		    ni, "block %s frame in CAC state",
493 			ieee80211_mgt_subtype_name[
494 			    (type & IEEE80211_FC0_SUBTYPE_MASK) >>
495 				IEEE80211_FC0_SUBTYPE_SHIFT]);
496 		vap->iv_stats.is_tx_badstate++;
497 		ieee80211_free_node(ni);
498 		m_freem(m);
499 		return EIO;		/* XXX */
500 	}
501 
502 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
503 	if (m == NULL) {
504 		ieee80211_free_node(ni);
505 		return ENOMEM;
506 	}
507 
508 	wh = mtod(m, struct ieee80211_frame *);
509 	ieee80211_send_setup(ni, wh,
510 		IEEE80211_FC0_TYPE_MGT | type,
511 		vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
512 	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
513 		m->m_flags &= ~M_LINK0;
514 		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_AUTH, wh->i_addr1,
515 		    "encrypting frame (%s)", __func__);
516 		wh->i_fc[1] |= IEEE80211_FC1_WEP;
517 	}
518 	if (type != IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
519 		/* NB: force non-ProbeResp frames to the highest queue */
520 		M_WME_SETAC(m, WME_AC_VO);
521 	} else
522 		M_WME_SETAC(m, WME_AC_BE);
523 #ifdef IEEE80211_DEBUG
524 	/* avoid printing too many frames */
525 	if ((ieee80211_msg_debug(vap) && doprint(vap, type)) ||
526 	    ieee80211_msg_dumppkts(vap)) {
527 		printf("[%s] send %s on channel %u\n",
528 		    ether_sprintf(wh->i_addr1),
529 		    ieee80211_mgt_subtype_name[
530 			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
531 				IEEE80211_FC0_SUBTYPE_SHIFT],
532 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
533 	}
534 #endif
535 	IEEE80211_NODE_STAT(ni, tx_mgmt);
536 
537 	return ic->ic_raw_xmit(ni, m, NULL);
538 }
539 
540 /*
541  * Send a null data frame to the specified node.
542  *
543  * NB: the caller is assumed to have setup a node reference
544  *     for use; this is necessary to deal with a race condition
545  *     when probing for inactive stations.  Like ieee80211_mgmt_output
546  *     we must cleanup any node reference on error;  however we
547  *     can safely just unref it as we know it will never be the
548  *     last reference to the node.
549  */
550 int
551 ieee80211_send_nulldata(struct ieee80211_node *ni)
552 {
553 	struct ieee80211vap *vap = ni->ni_vap;
554 	struct ieee80211com *ic = ni->ni_ic;
555 	struct mbuf *m;
556 	struct ieee80211_frame *wh;
557 
558 	if (vap->iv_state == IEEE80211_S_CAC) {
559 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
560 		    ni, "block %s frame in CAC state", "null data");
561 		ieee80211_unref_node(&ni);
562 		vap->iv_stats.is_tx_badstate++;
563 		return EIO;		/* XXX */
564 	}
565 
566 	m = m_gethdr(M_NOWAIT, MT_HEADER);
567 	if (m == NULL) {
568 		/* XXX debug msg */
569 		ieee80211_unref_node(&ni);
570 		vap->iv_stats.is_tx_nobuf++;
571 		return ENOMEM;
572 	}
573 	MH_ALIGN(m, sizeof(struct ieee80211_frame));
574 
575 	wh = mtod(m, struct ieee80211_frame *);
576 	ieee80211_send_setup(ni, wh,
577 		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
578 		vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
579 	if (vap->iv_opmode != IEEE80211_M_WDS) {
580 		/* NB: power management bit is never sent by an AP */
581 		if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
582 		    vap->iv_opmode != IEEE80211_M_HOSTAP)
583 			wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
584 		m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
585 	} else {
586 		/* NB: 4-address frame */
587 		m->m_len = m->m_pkthdr.len =
588 		    sizeof(struct ieee80211_frame_addr4);
589 	}
590 	M_WME_SETAC(m, WME_AC_BE);
591 
592 	IEEE80211_NODE_STAT(ni, tx_data);
593 
594 	IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, ni,
595 	    "send null data frame on channel %u, pwr mgt %s",
596 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
597 	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
598 
599 	return ic->ic_raw_xmit(ni, m, NULL);
600 }
601 
602 /*
603  * Assign priority to a frame based on any vlan tag assigned
604  * to the station and/or any Diffserv setting in an IP header.
605  * Finally, if an ACM policy is setup (in station mode) it's
606  * applied.
607  */
608 int
609 ieee80211_classify(struct ieee80211_node *ni, struct mbuf *m)
610 {
611 	const struct ether_header *eh = mtod(m, struct ether_header *);
612 	int v_wme_ac, d_wme_ac, ac;
613 
614 	/*
615 	 * Always promote PAE/EAPOL frames to high priority.
616 	 */
617 	if (eh->ether_type == htons(ETHERTYPE_PAE)) {
618 		/* NB: mark so others don't need to check header */
619 		m->m_flags |= M_EAPOL;
620 		ac = WME_AC_VO;
621 		goto done;
622 	}
623 	/*
624 	 * Non-qos traffic goes to BE.
625 	 */
626 	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
627 		ac = WME_AC_BE;
628 		goto done;
629 	}
630 
631 	/*
632 	 * If node has a vlan tag then all traffic
633 	 * to it must have a matching tag.
634 	 */
635 	v_wme_ac = 0;
636 	if (ni->ni_vlan != 0) {
637 		 if ((m->m_flags & M_VLANTAG) == 0) {
638 			IEEE80211_NODE_STAT(ni, tx_novlantag);
639 			return 1;
640 		}
641 		if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
642 		    EVL_VLANOFTAG(ni->ni_vlan)) {
643 			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
644 			return 1;
645 		}
646 		/* map vlan priority to AC */
647 		v_wme_ac = TID_TO_WME_AC(EVL_PRIOFTAG(ni->ni_vlan));
648 	}
649 
650 #ifdef INET
651 	if (eh->ether_type == htons(ETHERTYPE_IP)) {
652 		uint8_t tos;
653 		/*
654 		 * IP frame, map the DSCP bits from the TOS field.
655 		 */
656 		/* XXX m_copydata may be too slow for fast path */
657 		/* NB: ip header may not be in first mbuf */
658 		m_copydata(m, sizeof(struct ether_header) +
659 		    offsetof(struct ip, ip_tos), sizeof(tos), &tos);
660 		tos >>= 5;		/* NB: ECN + low 3 bits of DSCP */
661 		d_wme_ac = TID_TO_WME_AC(tos);
662 	} else {
663 #endif /* INET */
664 		d_wme_ac = WME_AC_BE;
665 #ifdef INET
666 	}
667 #endif
668 	/*
669 	 * Use highest priority AC.
670 	 */
671 	if (v_wme_ac > d_wme_ac)
672 		ac = v_wme_ac;
673 	else
674 		ac = d_wme_ac;
675 
676 	/*
677 	 * Apply ACM policy.
678 	 */
679 	if (ni->ni_vap->iv_opmode == IEEE80211_M_STA) {
680 		static const int acmap[4] = {
681 			WME_AC_BK,	/* WME_AC_BE */
682 			WME_AC_BK,	/* WME_AC_BK */
683 			WME_AC_BE,	/* WME_AC_VI */
684 			WME_AC_VI,	/* WME_AC_VO */
685 		};
686 		struct ieee80211com *ic = ni->ni_ic;
687 
688 		while (ac != WME_AC_BK &&
689 		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
690 			ac = acmap[ac];
691 	}
692 done:
693 	M_WME_SETAC(m, ac);
694 	return 0;
695 }
696 
697 /*
698  * Insure there is sufficient contiguous space to encapsulate the
699  * 802.11 data frame.  If room isn't already there, arrange for it.
700  * Drivers and cipher modules assume we have done the necessary work
701  * and fail rudely if they don't find the space they need.
702  */
703 static struct mbuf *
704 ieee80211_mbuf_adjust(struct ieee80211vap *vap, int hdrsize,
705 	struct ieee80211_key *key, struct mbuf *m)
706 {
707 #define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
708 	int needed_space = vap->iv_ic->ic_headroom + hdrsize;
709 
710 	if (key != NULL) {
711 		/* XXX belongs in crypto code? */
712 		needed_space += key->wk_cipher->ic_header;
713 		/* XXX frags */
714 		/*
715 		 * When crypto is being done in the host we must insure
716 		 * the data are writable for the cipher routines; clone
717 		 * a writable mbuf chain.
718 		 * XXX handle SWMIC specially
719 		 */
720 		if (key->wk_flags & (IEEE80211_KEY_SWCRYPT|IEEE80211_KEY_SWMIC)) {
721 			m = m_unshare(m, M_NOWAIT);
722 			if (m == NULL) {
723 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
724 				    "%s: cannot get writable mbuf\n", __func__);
725 				vap->iv_stats.is_tx_nobuf++; /* XXX new stat */
726 				return NULL;
727 			}
728 		}
729 	}
730 	/*
731 	 * We know we are called just before stripping an Ethernet
732 	 * header and prepending an LLC header.  This means we know
733 	 * there will be
734 	 *	sizeof(struct ether_header) - sizeof(struct llc)
735 	 * bytes recovered to which we need additional space for the
736 	 * 802.11 header and any crypto header.
737 	 */
738 	/* XXX check trailing space and copy instead? */
739 	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
740 		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
741 		if (n == NULL) {
742 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
743 			    "%s: cannot expand storage\n", __func__);
744 			vap->iv_stats.is_tx_nobuf++;
745 			m_freem(m);
746 			return NULL;
747 		}
748 		KASSERT(needed_space <= MHLEN,
749 		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
750 		/*
751 		 * Setup new mbuf to have leading space to prepend the
752 		 * 802.11 header and any crypto header bits that are
753 		 * required (the latter are added when the driver calls
754 		 * back to ieee80211_crypto_encap to do crypto encapsulation).
755 		 */
756 		/* NB: must be first 'cuz it clobbers m_data */
757 		m_move_pkthdr(n, m);
758 		n->m_len = 0;			/* NB: m_gethdr does not set */
759 		n->m_data += needed_space;
760 		/*
761 		 * Pull up Ethernet header to create the expected layout.
762 		 * We could use m_pullup but that's overkill (i.e. we don't
763 		 * need the actual data) and it cannot fail so do it inline
764 		 * for speed.
765 		 */
766 		/* NB: struct ether_header is known to be contiguous */
767 		n->m_len += sizeof(struct ether_header);
768 		m->m_len -= sizeof(struct ether_header);
769 		m->m_data += sizeof(struct ether_header);
770 		/*
771 		 * Replace the head of the chain.
772 		 */
773 		n->m_next = m;
774 		m = n;
775 	}
776 	return m;
777 #undef TO_BE_RECLAIMED
778 }
779 
780 /*
781  * Return the transmit key to use in sending a unicast frame.
782  * If a unicast key is set we use that.  When no unicast key is set
783  * we fall back to the default transmit key.
784  */
785 static __inline struct ieee80211_key *
786 ieee80211_crypto_getucastkey(struct ieee80211vap *vap,
787 	struct ieee80211_node *ni)
788 {
789 	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
790 		if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
791 		    IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
792 			return NULL;
793 		return &vap->iv_nw_keys[vap->iv_def_txkey];
794 	} else {
795 		return &ni->ni_ucastkey;
796 	}
797 }
798 
799 /*
800  * Return the transmit key to use in sending a multicast frame.
801  * Multicast traffic always uses the group key which is installed as
802  * the default tx key.
803  */
804 static __inline struct ieee80211_key *
805 ieee80211_crypto_getmcastkey(struct ieee80211vap *vap,
806 	struct ieee80211_node *ni)
807 {
808 	if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
809 	    IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
810 		return NULL;
811 	return &vap->iv_nw_keys[vap->iv_def_txkey];
812 }
813 
814 /*
815  * Encapsulate an outbound data frame.  The mbuf chain is updated.
816  * If an error is encountered NULL is returned.  The caller is required
817  * to provide a node reference and pullup the ethernet header in the
818  * first mbuf.
819  *
820  * NB: Packet is assumed to be processed by ieee80211_classify which
821  *     marked EAPOL frames w/ M_EAPOL.
822  */
823 struct mbuf *
824 ieee80211_encap(struct ieee80211_node *ni, struct mbuf *m)
825 {
826 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)(wh))
827 	struct ieee80211vap *vap = ni->ni_vap;
828 	struct ieee80211com *ic = ni->ni_ic;
829 	struct ether_header eh;
830 	struct ieee80211_frame *wh;
831 	struct ieee80211_key *key;
832 	struct llc *llc;
833 	int hdrsize, hdrspace, datalen, addqos, txfrag, isff, is4addr;
834 
835 	/*
836 	 * Copy existing Ethernet header to a safe place.  The
837 	 * rest of the code assumes it's ok to strip it when
838 	 * reorganizing state for the final encapsulation.
839 	 */
840 	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
841 	ETHER_HEADER_COPY(&eh, mtod(m, caddr_t));
842 
843 	/*
844 	 * Insure space for additional headers.  First identify
845 	 * transmit key to use in calculating any buffer adjustments
846 	 * required.  This is also used below to do privacy
847 	 * encapsulation work.  Then calculate the 802.11 header
848 	 * size and any padding required by the driver.
849 	 *
850 	 * Note key may be NULL if we fall back to the default
851 	 * transmit key and that is not set.  In that case the
852 	 * buffer may not be expanded as needed by the cipher
853 	 * routines, but they will/should discard it.
854 	 */
855 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
856 		if (vap->iv_opmode == IEEE80211_M_STA ||
857 		    !IEEE80211_IS_MULTICAST(eh.ether_dhost) ||
858 		    (vap->iv_opmode == IEEE80211_M_WDS &&
859 		     (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY)))
860 			key = ieee80211_crypto_getucastkey(vap, ni);
861 		else
862 			key = ieee80211_crypto_getmcastkey(vap, ni);
863 		if (key == NULL && (m->m_flags & M_EAPOL) == 0) {
864 			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO,
865 			    eh.ether_dhost,
866 			    "no default transmit key (%s) deftxkey %u",
867 			    __func__, vap->iv_def_txkey);
868 			vap->iv_stats.is_tx_nodefkey++;
869 			goto bad;
870 		}
871 	} else
872 		key = NULL;
873 	/*
874 	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
875 	 * frames so suppress use.  This may be an issue if other
876 	 * ap's require all data frames to be QoS-encapsulated
877 	 * once negotiated in which case we'll need to make this
878 	 * configurable.
879 	 */
880 	addqos = (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) &&
881 		 (m->m_flags & M_EAPOL) == 0;
882 	if (addqos)
883 		hdrsize = sizeof(struct ieee80211_qosframe);
884 	else
885 		hdrsize = sizeof(struct ieee80211_frame);
886 	/*
887 	 * 4-address frames need to be generated for:
888 	 * o packets sent through a WDS vap (M_WDS || IEEE80211_M_WDS)
889 	 * o packets relayed by a station operating with dynamic WDS
890 	 *   (IEEE80211_M_STA+IEEE80211_F_DWDS and src address)
891 	 */
892 	is4addr = (m->m_flags & M_WDS) ||
893 	    vap->iv_opmode == IEEE80211_M_WDS ||	/* XXX redundant? */
894 	    (vap->iv_opmode == IEEE80211_M_STA &&
895 	     (vap->iv_flags & IEEE80211_F_DWDS) &&
896 	     !IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr));
897 	if (is4addr)
898 		hdrsize += IEEE80211_ADDR_LEN;
899 	/*
900 	 * Honor driver DATAPAD requirement.
901 	 */
902 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
903 		hdrspace = roundup(hdrsize, sizeof(uint32_t));
904 	else
905 		hdrspace = hdrsize;
906 
907 	if ((isff = m->m_flags & M_FF) != 0) {
908 		struct mbuf *m2;
909 		struct ether_header eh2;
910 
911 		/*
912 		 * Fast frame encapsulation.  There must be two packets
913 		 * chained with m_nextpkt.  We do header adjustment for
914 		 * each, add the tunnel encapsulation, and then concatenate
915 		 * the mbuf chains to form a single frame for transmission.
916 		 */
917 		m2 = m->m_nextpkt;
918 		if (m2 == NULL) {
919 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
920 				"%s: only one frame\n", __func__);
921 			goto bad;
922 		}
923 		m->m_nextpkt = NULL;
924 		/*
925 		 * Include fast frame headers in adjusting header
926 		 * layout; this allocates space according to what
927 		 * ieee80211_encap_fastframe will do.
928 		 */
929 		m = ieee80211_mbuf_adjust(vap,
930 			hdrspace + sizeof(struct llc) + sizeof(uint32_t) + 2 +
931 			    sizeof(struct ether_header),
932 			key, m);
933 		if (m == NULL) {
934 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
935 			m_freem(m2);
936 			goto bad;
937 		}
938 		/*
939 		 * Copy second frame's Ethernet header out of line
940 		 * and adjust for encapsulation headers.  Note that
941 		 * we make room for padding in case there isn't room
942 		 * at the end of first frame.
943 		 */
944 		KASSERT(m2->m_len >= sizeof(eh2), ("no ethernet header!"));
945 		ETHER_HEADER_COPY(&eh2, mtod(m2, caddr_t));
946 		m2 = ieee80211_mbuf_adjust(vap,
947 			ATH_FF_MAX_HDR_PAD + sizeof(struct ether_header),
948 			NULL, m2);
949 		if (m2 == NULL) {
950 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
951 			goto bad;
952 		}
953 		m = ieee80211_encap_fastframe(vap, m, &eh, m2, &eh2);
954 		if (m == NULL)
955 			goto bad;
956 	} else {
957 		/*
958 		 * Normal frame.
959 		 */
960 		m = ieee80211_mbuf_adjust(vap, hdrspace, key, m);
961 		if (m == NULL) {
962 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
963 			goto bad;
964 		}
965 		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
966 		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
967 		llc = mtod(m, struct llc *);
968 		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
969 		llc->llc_control = LLC_UI;
970 		llc->llc_snap.org_code[0] = 0;
971 		llc->llc_snap.org_code[1] = 0;
972 		llc->llc_snap.org_code[2] = 0;
973 		llc->llc_snap.ether_type = eh.ether_type;
974 	}
975 	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
976 
977 	M_PREPEND(m, hdrspace, M_DONTWAIT);
978 	if (m == NULL) {
979 		vap->iv_stats.is_tx_nobuf++;
980 		goto bad;
981 	}
982 	wh = mtod(m, struct ieee80211_frame *);
983 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
984 	*(uint16_t *)wh->i_dur = 0;
985 	if (is4addr) {
986 		wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
987 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
988 		IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
989 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
990 		IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost);
991 	} else switch (vap->iv_opmode) {
992 	case IEEE80211_M_STA:
993 		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
994 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
995 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
996 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
997 		break;
998 	case IEEE80211_M_IBSS:
999 	case IEEE80211_M_AHDEMO:
1000 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1001 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1002 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1003 		/*
1004 		 * NB: always use the bssid from iv_bss as the
1005 		 *     neighbor's may be stale after an ibss merge
1006 		 */
1007 		IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_bssid);
1008 		break;
1009 	case IEEE80211_M_HOSTAP:
1010 		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1011 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1012 		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
1013 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
1014 		break;
1015 	case IEEE80211_M_MONITOR:
1016 	case IEEE80211_M_WDS:		/* NB: is4addr should always be true */
1017 		goto bad;
1018 	}
1019 	if (m->m_flags & M_MORE_DATA)
1020 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
1021 	if (addqos) {
1022 		uint8_t *qos;
1023 		int ac, tid;
1024 
1025 		if (is4addr) {
1026 			qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1027 		} else
1028 			qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1029 		ac = M_WME_GETAC(m);
1030 		/* map from access class/queue to 11e header priorty value */
1031 		tid = WME_AC_TO_TID(ac);
1032 		qos[0] = tid & IEEE80211_QOS_TID;
1033 		/*
1034 		 * Check if A-MPDU tx aggregation is setup or if we
1035 		 * should try to enable it.  The sta must be associated
1036 		 * with HT and A-MPDU enabled for use.  When the policy
1037 		 * routine decides we should enable A-MPDU we issue an
1038 		 * ADDBA request and wait for a reply.  The frame being
1039 		 * encapsulated will go out w/o using A-MPDU, or possibly
1040 		 * it might be collected by the driver and held/retransmit.
1041 		 * The default ic_ampdu_enable routine handles staggering
1042 		 * ADDBA requests in case the receiver NAK's us or we are
1043 		 * otherwise unable to establish a BA stream.
1044 		 */
1045 		if ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) &&
1046 		    (vap->iv_flags_ext & IEEE80211_FEXT_AMPDU_TX)) {
1047 			struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
1048 
1049 			ieee80211_txampdu_count_packet(tap);
1050 			if (IEEE80211_AMPDU_RUNNING(tap)) {
1051 				/*
1052 				 * Operational, mark frame for aggregation.
1053 				 */
1054 				qos[0] |= IEEE80211_QOS_ACKPOLICY_BA;
1055 			} else if (!IEEE80211_AMPDU_REQUESTED(tap) &&
1056 			    ic->ic_ampdu_enable(ni, tap)) {
1057 				/*
1058 				 * Not negotiated yet, request service.
1059 				 */
1060 				ieee80211_ampdu_request(ni, tap);
1061 			}
1062 		}
1063 		/* XXX works even when BA marked above */
1064 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
1065 			qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
1066 		qos[1] = 0;
1067 		wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
1068 
1069 		*(uint16_t *)wh->i_seq =
1070 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
1071 		ni->ni_txseqs[tid]++;
1072 	} else {
1073 		*(uint16_t *)wh->i_seq =
1074 		    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
1075 		ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
1076 	}
1077 	/* check if xmit fragmentation is required */
1078 	txfrag = (m->m_pkthdr.len > vap->iv_fragthreshold &&
1079 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1080 	    (vap->iv_caps & IEEE80211_C_TXFRAG) &&
1081 	    !isff);		/* NB: don't fragment ff's */
1082 	if (key != NULL) {
1083 		/*
1084 		 * IEEE 802.1X: send EAPOL frames always in the clear.
1085 		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
1086 		 */
1087 		if ((m->m_flags & M_EAPOL) == 0 ||
1088 		    ((vap->iv_flags & IEEE80211_F_WPA) &&
1089 		     (vap->iv_opmode == IEEE80211_M_STA ?
1090 		      !IEEE80211_KEY_UNDEFINED(key) :
1091 		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
1092 			wh->i_fc[1] |= IEEE80211_FC1_WEP;
1093 			if (!ieee80211_crypto_enmic(vap, key, m, txfrag)) {
1094 				IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT,
1095 				    eh.ether_dhost,
1096 				    "%s", "enmic failed, discard frame");
1097 				vap->iv_stats.is_crypto_enmicfail++;
1098 				goto bad;
1099 			}
1100 		}
1101 	}
1102 	if (txfrag && !ieee80211_fragment(vap, m, hdrsize,
1103 	    key != NULL ? key->wk_cipher->ic_header : 0, vap->iv_fragthreshold))
1104 		goto bad;
1105 
1106 	IEEE80211_NODE_STAT(ni, tx_data);
1107 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1108 		IEEE80211_NODE_STAT(ni, tx_mcast);
1109 	else
1110 		IEEE80211_NODE_STAT(ni, tx_ucast);
1111 	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
1112 
1113 	/* XXX fragmented frames not handled */
1114 	if (bpf_peers_present(vap->iv_rawbpf))
1115 		bpf_mtap(vap->iv_rawbpf, m);
1116 
1117 	return m;
1118 bad:
1119 	if (m != NULL)
1120 		m_freem(m);
1121 	return NULL;
1122 #undef WH4
1123 }
1124 
1125 /*
1126  * Do Ethernet-LLC encapsulation for each payload in a fast frame
1127  * tunnel encapsulation.  The frame is assumed to have an Ethernet
1128  * header at the front that must be stripped before prepending the
1129  * LLC followed by the Ethernet header passed in (with an Ethernet
1130  * type that specifies the payload size).
1131  */
1132 static struct mbuf *
1133 ieee80211_encap1(struct ieee80211vap *vap, struct mbuf *m,
1134 	const struct ether_header *eh)
1135 {
1136 	struct llc *llc;
1137 	uint16_t payload;
1138 
1139 	/* XXX optimize by combining m_adj+M_PREPEND */
1140 	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
1141 	llc = mtod(m, struct llc *);
1142 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1143 	llc->llc_control = LLC_UI;
1144 	llc->llc_snap.org_code[0] = 0;
1145 	llc->llc_snap.org_code[1] = 0;
1146 	llc->llc_snap.org_code[2] = 0;
1147 	llc->llc_snap.ether_type = eh->ether_type;
1148 	payload = m->m_pkthdr.len;		/* NB: w/o Ethernet header */
1149 
1150 	M_PREPEND(m, sizeof(struct ether_header), M_DONTWAIT);
1151 	if (m == NULL) {		/* XXX cannot happen */
1152 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
1153 			"%s: no space for ether_header\n", __func__);
1154 		vap->iv_stats.is_tx_nobuf++;
1155 		return NULL;
1156 	}
1157 	ETHER_HEADER_COPY(mtod(m, void *), eh);
1158 	mtod(m, struct ether_header *)->ether_type = htons(payload);
1159 	return m;
1160 }
1161 
1162 /*
1163  * Do fast frame tunnel encapsulation.  The two frames and
1164  * Ethernet headers are supplied.  The caller is assumed to
1165  * have arrange for space in the mbuf chains for encapsulating
1166  * headers (to avoid major mbuf fragmentation).
1167  *
1168  * The encapsulated frame is returned or NULL if there is a
1169  * problem (should not happen).
1170  */
1171 static struct mbuf *
1172 ieee80211_encap_fastframe(struct ieee80211vap *vap,
1173 	struct mbuf *m1, const struct ether_header *eh1,
1174 	struct mbuf *m2, const struct ether_header *eh2)
1175 {
1176 	struct llc *llc;
1177 	struct mbuf *m;
1178 	int pad;
1179 
1180 	/*
1181 	 * First, each frame gets a standard encapsulation.
1182 	 */
1183 	m1 = ieee80211_encap1(vap, m1, eh1);
1184 	if (m1 == NULL) {
1185 		m_freem(m2);
1186 		return NULL;
1187 	}
1188 	m2 = ieee80211_encap1(vap, m2, eh2);
1189 	if (m2 == NULL) {
1190 		m_freem(m1);
1191 		return NULL;
1192 	}
1193 
1194 	/*
1195 	 * Pad leading frame to a 4-byte boundary.  If there
1196 	 * is space at the end of the first frame, put it
1197 	 * there; otherwise prepend to the front of the second
1198 	 * frame.  We know doing the second will always work
1199 	 * because we reserve space above.  We prefer appending
1200 	 * as this typically has better DMA alignment properties.
1201 	 */
1202 	for (m = m1; m->m_next != NULL; m = m->m_next)
1203 		;
1204 	pad = roundup2(m1->m_pkthdr.len, 4) - m1->m_pkthdr.len;
1205 	if (pad) {
1206 		if (M_TRAILINGSPACE(m) < pad) {		/* prepend to second */
1207 			m2->m_data -= pad;
1208 			m2->m_len += pad;
1209 			m2->m_pkthdr.len += pad;
1210 		} else {				/* append to first */
1211 			m->m_len += pad;
1212 			m1->m_pkthdr.len += pad;
1213 		}
1214 	}
1215 
1216 	/*
1217 	 * Now, stick 'em together and prepend the tunnel headers;
1218 	 * first the Atheros tunnel header (all zero for now) and
1219 	 * then a special fast frame LLC.
1220 	 *
1221 	 * XXX optimize by prepending together
1222 	 */
1223 	m->m_next = m2;			/* NB: last mbuf from above */
1224 	m1->m_pkthdr.len += m2->m_pkthdr.len;
1225 	M_PREPEND(m1, sizeof(uint32_t)+2, M_DONTWAIT);
1226 	if (m1 == NULL) {		/* XXX cannot happen */
1227 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
1228 			"%s: no space for tunnel header\n", __func__);
1229 		vap->iv_stats.is_tx_nobuf++;
1230 		return NULL;
1231 	}
1232 	memset(mtod(m1, void *), 0, sizeof(uint32_t)+2);
1233 
1234 	M_PREPEND(m1, sizeof(struct llc), M_DONTWAIT);
1235 	if (m1 == NULL) {		/* XXX cannot happen */
1236 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
1237 			"%s: no space for llc header\n", __func__);
1238 		vap->iv_stats.is_tx_nobuf++;
1239 		return NULL;
1240 	}
1241 	llc = mtod(m1, struct llc *);
1242 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1243 	llc->llc_control = LLC_UI;
1244 	llc->llc_snap.org_code[0] = ATH_FF_SNAP_ORGCODE_0;
1245 	llc->llc_snap.org_code[1] = ATH_FF_SNAP_ORGCODE_1;
1246 	llc->llc_snap.org_code[2] = ATH_FF_SNAP_ORGCODE_2;
1247 	llc->llc_snap.ether_type = htons(ATH_FF_ETH_TYPE);
1248 
1249 	vap->iv_stats.is_ff_encap++;
1250 
1251 	return m1;
1252 }
1253 
1254 /*
1255  * Fragment the frame according to the specified mtu.
1256  * The size of the 802.11 header (w/o padding) is provided
1257  * so we don't need to recalculate it.  We create a new
1258  * mbuf for each fragment and chain it through m_nextpkt;
1259  * we might be able to optimize this by reusing the original
1260  * packet's mbufs but that is significantly more complicated.
1261  */
1262 static int
1263 ieee80211_fragment(struct ieee80211vap *vap, struct mbuf *m0,
1264 	u_int hdrsize, u_int ciphdrsize, u_int mtu)
1265 {
1266 	struct ieee80211_frame *wh, *whf;
1267 	struct mbuf *m, *prev, *next;
1268 	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1269 
1270 	KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1271 	KASSERT(m0->m_pkthdr.len > mtu,
1272 		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1273 
1274 	wh = mtod(m0, struct ieee80211_frame *);
1275 	/* NB: mark the first frag; it will be propagated below */
1276 	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1277 	totalhdrsize = hdrsize + ciphdrsize;
1278 	fragno = 1;
1279 	off = mtu - ciphdrsize;
1280 	remainder = m0->m_pkthdr.len - off;
1281 	prev = m0;
1282 	do {
1283 		fragsize = totalhdrsize + remainder;
1284 		if (fragsize > mtu)
1285 			fragsize = mtu;
1286 		/* XXX fragsize can be >2048! */
1287 		KASSERT(fragsize < MCLBYTES,
1288 			("fragment size %u too big!", fragsize));
1289 		if (fragsize > MHLEN)
1290 			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1291 		else
1292 			m = m_gethdr(M_DONTWAIT, MT_DATA);
1293 		if (m == NULL)
1294 			goto bad;
1295 		/* leave room to prepend any cipher header */
1296 		m_align(m, fragsize - ciphdrsize);
1297 
1298 		/*
1299 		 * Form the header in the fragment.  Note that since
1300 		 * we mark the first fragment with the MORE_FRAG bit
1301 		 * it automatically is propagated to each fragment; we
1302 		 * need only clear it on the last fragment (done below).
1303 		 */
1304 		whf = mtod(m, struct ieee80211_frame *);
1305 		memcpy(whf, wh, hdrsize);
1306 		*(uint16_t *)&whf->i_seq[0] |= htole16(
1307 			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
1308 				IEEE80211_SEQ_FRAG_SHIFT);
1309 		fragno++;
1310 
1311 		payload = fragsize - totalhdrsize;
1312 		/* NB: destination is known to be contiguous */
1313 		m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize);
1314 		m->m_len = hdrsize + payload;
1315 		m->m_pkthdr.len = hdrsize + payload;
1316 		m->m_flags |= M_FRAG;
1317 
1318 		/* chain up the fragment */
1319 		prev->m_nextpkt = m;
1320 		prev = m;
1321 
1322 		/* deduct fragment just formed */
1323 		remainder -= payload;
1324 		off += payload;
1325 	} while (remainder != 0);
1326 	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
1327 
1328 	/* strip first mbuf now that everything has been copied */
1329 	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
1330 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1331 
1332 	vap->iv_stats.is_tx_fragframes++;
1333 	vap->iv_stats.is_tx_frags += fragno-1;
1334 
1335 	return 1;
1336 bad:
1337 	/* reclaim fragments but leave original frame for caller to free */
1338 	for (m = m0->m_nextpkt; m != NULL; m = next) {
1339 		next = m->m_nextpkt;
1340 		m->m_nextpkt = NULL;		/* XXX paranoid */
1341 		m_freem(m);
1342 	}
1343 	m0->m_nextpkt = NULL;
1344 	return 0;
1345 }
1346 
1347 /*
1348  * Add a supported rates element id to a frame.
1349  */
1350 static uint8_t *
1351 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
1352 {
1353 	int nrates;
1354 
1355 	*frm++ = IEEE80211_ELEMID_RATES;
1356 	nrates = rs->rs_nrates;
1357 	if (nrates > IEEE80211_RATE_SIZE)
1358 		nrates = IEEE80211_RATE_SIZE;
1359 	*frm++ = nrates;
1360 	memcpy(frm, rs->rs_rates, nrates);
1361 	return frm + nrates;
1362 }
1363 
1364 /*
1365  * Add an extended supported rates element id to a frame.
1366  */
1367 static uint8_t *
1368 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
1369 {
1370 	/*
1371 	 * Add an extended supported rates element if operating in 11g mode.
1372 	 */
1373 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1374 		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1375 		*frm++ = IEEE80211_ELEMID_XRATES;
1376 		*frm++ = nrates;
1377 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1378 		frm += nrates;
1379 	}
1380 	return frm;
1381 }
1382 
1383 /*
1384  * Add an ssid element to a frame.
1385  */
1386 static uint8_t *
1387 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
1388 {
1389 	*frm++ = IEEE80211_ELEMID_SSID;
1390 	*frm++ = len;
1391 	memcpy(frm, ssid, len);
1392 	return frm + len;
1393 }
1394 
1395 /*
1396  * Add an erp element to a frame.
1397  */
1398 static uint8_t *
1399 ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
1400 {
1401 	uint8_t erp;
1402 
1403 	*frm++ = IEEE80211_ELEMID_ERP;
1404 	*frm++ = 1;
1405 	erp = 0;
1406 	if (ic->ic_nonerpsta != 0)
1407 		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1408 	if (ic->ic_flags & IEEE80211_F_USEPROT)
1409 		erp |= IEEE80211_ERP_USE_PROTECTION;
1410 	if (ic->ic_flags & IEEE80211_F_USEBARKER)
1411 		erp |= IEEE80211_ERP_LONG_PREAMBLE;
1412 	*frm++ = erp;
1413 	return frm;
1414 }
1415 
1416 /*
1417  * Add a CFParams element to a frame.
1418  */
1419 static uint8_t *
1420 ieee80211_add_cfparms(uint8_t *frm, struct ieee80211com *ic)
1421 {
1422 #define	ADDSHORT(frm, v) do {			\
1423 	frm[0] = (v) & 0xff;			\
1424 	frm[1] = (v) >> 8;			\
1425 	frm += 2;				\
1426 } while (0)
1427 	*frm++ = IEEE80211_ELEMID_CFPARMS;
1428 	*frm++ = 6;
1429 	*frm++ = 0;		/* CFP count */
1430 	*frm++ = 2;		/* CFP period */
1431 	ADDSHORT(frm, 0);	/* CFP MaxDuration (TU) */
1432 	ADDSHORT(frm, 0);	/* CFP CurRemaining (TU) */
1433 	return frm;
1434 #undef ADDSHORT
1435 }
1436 
1437 static __inline uint8_t *
1438 add_appie(uint8_t *frm, const struct ieee80211_appie *ie)
1439 {
1440 	memcpy(frm, ie->ie_data, ie->ie_len);
1441 	return frm + ie->ie_len;
1442 }
1443 
1444 static __inline uint8_t *
1445 add_ie(uint8_t *frm, const uint8_t *ie)
1446 {
1447 	memcpy(frm, ie, 2 + ie[1]);
1448 	return frm + 2 + ie[1];
1449 }
1450 
1451 #define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1452 /*
1453  * Add a WME information element to a frame.
1454  */
1455 static uint8_t *
1456 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
1457 {
1458 	static const struct ieee80211_wme_info info = {
1459 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1460 		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1461 		.wme_oui	= { WME_OUI_BYTES },
1462 		.wme_type	= WME_OUI_TYPE,
1463 		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1464 		.wme_version	= WME_VERSION,
1465 		.wme_info	= 0,
1466 	};
1467 	memcpy(frm, &info, sizeof(info));
1468 	return frm + sizeof(info);
1469 }
1470 
1471 /*
1472  * Add a WME parameters element to a frame.
1473  */
1474 static uint8_t *
1475 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
1476 {
1477 #define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1478 #define	ADDSHORT(frm, v) do {			\
1479 	frm[0] = (v) & 0xff;			\
1480 	frm[1] = (v) >> 8;			\
1481 	frm += 2;				\
1482 } while (0)
1483 	/* NB: this works 'cuz a param has an info at the front */
1484 	static const struct ieee80211_wme_info param = {
1485 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1486 		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1487 		.wme_oui	= { WME_OUI_BYTES },
1488 		.wme_type	= WME_OUI_TYPE,
1489 		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1490 		.wme_version	= WME_VERSION,
1491 	};
1492 	int i;
1493 
1494 	memcpy(frm, &param, sizeof(param));
1495 	frm += __offsetof(struct ieee80211_wme_info, wme_info);
1496 	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1497 	*frm++ = 0;					/* reserved field */
1498 	for (i = 0; i < WME_NUM_AC; i++) {
1499 		const struct wmeParams *ac =
1500 		       &wme->wme_bssChanParams.cap_wmeParams[i];
1501 		*frm++ = SM(i, WME_PARAM_ACI)
1502 		       | SM(ac->wmep_acm, WME_PARAM_ACM)
1503 		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1504 		       ;
1505 		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1506 		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1507 		       ;
1508 		ADDSHORT(frm, ac->wmep_txopLimit);
1509 	}
1510 	return frm;
1511 #undef SM
1512 #undef ADDSHORT
1513 }
1514 #undef WME_OUI_BYTES
1515 
1516 #define	ATH_OUI_BYTES		0x00, 0x03, 0x7f
1517 /*
1518  * Add a WME information element to a frame.
1519  */
1520 static uint8_t *
1521 ieee80211_add_ath(uint8_t *frm, uint8_t caps, uint16_t defkeyix)
1522 {
1523 	static const struct ieee80211_ath_ie info = {
1524 		.ath_id		= IEEE80211_ELEMID_VENDOR,
1525 		.ath_len	= sizeof(struct ieee80211_ath_ie) - 2,
1526 		.ath_oui	= { ATH_OUI_BYTES },
1527 		.ath_oui_type	= ATH_OUI_TYPE,
1528 		.ath_oui_subtype= ATH_OUI_SUBTYPE,
1529 		.ath_version	= ATH_OUI_VERSION,
1530 	};
1531 	struct ieee80211_ath_ie *ath = (struct ieee80211_ath_ie *) frm;
1532 
1533 	memcpy(frm, &info, sizeof(info));
1534 	ath->ath_capability = caps;
1535 	ath->ath_defkeyix[0] = (defkeyix & 0xff);
1536 	ath->ath_defkeyix[1] = ((defkeyix >> 8) & 0xff);
1537 	return frm + sizeof(info);
1538 }
1539 #undef ATH_OUI_BYTES
1540 
1541 /*
1542  * Add an 11h Power Constraint element to a frame.
1543  */
1544 static uint8_t *
1545 ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap)
1546 {
1547 	const struct ieee80211_channel *c = vap->iv_bss->ni_chan;
1548 	/* XXX per-vap tx power limit? */
1549 	int8_t limit = vap->iv_ic->ic_txpowlimit / 2;
1550 
1551 	frm[0] = IEEE80211_ELEMID_PWRCNSTR;
1552 	frm[1] = 1;
1553 	frm[2] = c->ic_maxregpower > limit ?  c->ic_maxregpower - limit : 0;
1554 	return frm + 3;
1555 }
1556 
1557 /*
1558  * Add an 11h Power Capability element to a frame.
1559  */
1560 static uint8_t *
1561 ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c)
1562 {
1563 	frm[0] = IEEE80211_ELEMID_PWRCAP;
1564 	frm[1] = 2;
1565 	frm[2] = c->ic_minpower;
1566 	frm[3] = c->ic_maxpower;
1567 	return frm + 4;
1568 }
1569 
1570 /*
1571  * Add an 11h Supported Channels element to a frame.
1572  */
1573 static uint8_t *
1574 ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic)
1575 {
1576 	static const int ielen = 26;
1577 
1578 	frm[0] = IEEE80211_ELEMID_SUPPCHAN;
1579 	frm[1] = ielen;
1580 	/* XXX not correct */
1581 	memcpy(frm+2, ic->ic_chan_avail, ielen);
1582 	return frm + 2 + ielen;
1583 }
1584 
1585 /*
1586  * Add an 11h Channel Switch Announcement element to a frame.
1587  * Note that we use the per-vap CSA count to adjust the global
1588  * counter so we can use this routine to form probe response
1589  * frames and get the current count.
1590  */
1591 static uint8_t *
1592 ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap)
1593 {
1594 	struct ieee80211com *ic = vap->iv_ic;
1595 	struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm;
1596 
1597 	csa->csa_ie = IEEE80211_ELEMID_CHANSWITCHANN;
1598 	csa->csa_len = 3;
1599 	csa->csa_mode = 1;		/* XXX force quiet on channel */
1600 	csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan);
1601 	csa->csa_count = ic->ic_csa_count - vap->iv_csa_count;
1602 	return frm + sizeof(*csa);
1603 }
1604 
1605 /*
1606  * Add an 11h country information element to a frame.
1607  */
1608 static uint8_t *
1609 ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic)
1610 {
1611 
1612 	if (ic->ic_countryie == NULL ||
1613 	    ic->ic_countryie_chan != ic->ic_bsschan) {
1614 		/*
1615 		 * Handle lazy construction of ie.  This is done on
1616 		 * first use and after a channel change that requires
1617 		 * re-calculation.
1618 		 */
1619 		if (ic->ic_countryie != NULL)
1620 			free(ic->ic_countryie, M_80211_NODE_IE);
1621 		ic->ic_countryie = ieee80211_alloc_countryie(ic);
1622 		if (ic->ic_countryie == NULL)
1623 			return frm;
1624 		ic->ic_countryie_chan = ic->ic_bsschan;
1625 	}
1626 	return add_appie(frm, ic->ic_countryie);
1627 }
1628 
1629 /*
1630  * Send a probe request frame with the specified ssid
1631  * and any optional information element data.
1632  */
1633 int
1634 ieee80211_send_probereq(struct ieee80211_node *ni,
1635 	const uint8_t sa[IEEE80211_ADDR_LEN],
1636 	const uint8_t da[IEEE80211_ADDR_LEN],
1637 	const uint8_t bssid[IEEE80211_ADDR_LEN],
1638 	const uint8_t *ssid, size_t ssidlen)
1639 {
1640 	struct ieee80211vap *vap = ni->ni_vap;
1641 	struct ieee80211com *ic = ni->ni_ic;
1642 	struct ieee80211_frame *wh;
1643 	const struct ieee80211_rateset *rs;
1644 	struct mbuf *m;
1645 	uint8_t *frm;
1646 
1647 	if (vap->iv_state == IEEE80211_S_CAC) {
1648 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
1649 		    "block %s frame in CAC state", "probe request");
1650 		vap->iv_stats.is_tx_badstate++;
1651 		return EIO;		/* XXX */
1652 	}
1653 
1654 	/*
1655 	 * Hold a reference on the node so it doesn't go away until after
1656 	 * the xmit is complete all the way in the driver.  On error we
1657 	 * will remove our reference.
1658 	 */
1659 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1660 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1661 		__func__, __LINE__,
1662 		ni, ether_sprintf(ni->ni_macaddr),
1663 		ieee80211_node_refcnt(ni)+1);
1664 	ieee80211_ref_node(ni);
1665 
1666 	/*
1667 	 * prreq frame format
1668 	 *	[tlv] ssid
1669 	 *	[tlv] supported rates
1670 	 *	[tlv] RSN (optional)
1671 	 *	[tlv] extended supported rates
1672 	 *	[tlv] WPA (optional)
1673 	 *	[tlv] user-specified ie's
1674 	 */
1675 	m = ieee80211_getmgtframe(&frm,
1676 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
1677 	       	 2 + IEEE80211_NWID_LEN
1678 	       + 2 + IEEE80211_RATE_SIZE
1679 	       + sizeof(struct ieee80211_ie_wpa)
1680 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1681 	       + sizeof(struct ieee80211_ie_wpa)
1682 	       + (vap->iv_appie_probereq != NULL ?
1683 		   vap->iv_appie_probereq->ie_len : 0)
1684 	);
1685 	if (m == NULL) {
1686 		vap->iv_stats.is_tx_nobuf++;
1687 		ieee80211_free_node(ni);
1688 		return ENOMEM;
1689 	}
1690 
1691 	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1692 	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1693 	frm = ieee80211_add_rates(frm, rs);
1694 	if (vap->iv_flags & IEEE80211_F_WPA2) {
1695 		if (vap->iv_rsn_ie != NULL)
1696 			frm = add_ie(frm, vap->iv_rsn_ie);
1697 		/* XXX else complain? */
1698 	}
1699 	frm = ieee80211_add_xrates(frm, rs);
1700 	if (vap->iv_flags & IEEE80211_F_WPA1) {
1701 		if (vap->iv_wpa_ie != NULL)
1702 			frm = add_ie(frm, vap->iv_wpa_ie);
1703 		/* XXX else complain? */
1704 	}
1705 	if (vap->iv_appie_probereq != NULL)
1706 		frm = add_appie(frm, vap->iv_appie_probereq);
1707 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1708 
1709 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1710 	if (m == NULL)
1711 		return ENOMEM;
1712 
1713 	wh = mtod(m, struct ieee80211_frame *);
1714 	ieee80211_send_setup(ni, wh,
1715 		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1716 		sa, da, bssid);
1717 	/* XXX power management? */
1718 
1719 	M_WME_SETAC(m, WME_AC_BE);
1720 
1721 	IEEE80211_NODE_STAT(ni, tx_probereq);
1722 	IEEE80211_NODE_STAT(ni, tx_mgmt);
1723 
1724 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1725 	    "send probe req on channel %u bssid %s ssid \"%.*s\"\n",
1726 	    ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(bssid),
1727 	    ssidlen, ssid);
1728 
1729 	return ic->ic_raw_xmit(ni, m, NULL);
1730 }
1731 
1732 /*
1733  * Calculate capability information for mgt frames.
1734  */
1735 static uint16_t
1736 getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan)
1737 {
1738 	struct ieee80211com *ic = vap->iv_ic;
1739 	uint16_t capinfo;
1740 
1741 	KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode"));
1742 
1743 	if (vap->iv_opmode == IEEE80211_M_HOSTAP)
1744 		capinfo = IEEE80211_CAPINFO_ESS;
1745 	else if (vap->iv_opmode == IEEE80211_M_IBSS)
1746 		capinfo = IEEE80211_CAPINFO_IBSS;
1747 	else
1748 		capinfo = 0;
1749 	if (vap->iv_flags & IEEE80211_F_PRIVACY)
1750 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1751 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1752 	    IEEE80211_IS_CHAN_2GHZ(chan))
1753 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1754 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1755 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1756 	if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH))
1757 		capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
1758 	return capinfo;
1759 }
1760 
1761 /*
1762  * Send a management frame.  The node is for the destination (or ic_bss
1763  * when in station mode).  Nodes other than ic_bss have their reference
1764  * count bumped to reflect our use for an indeterminant time.
1765  */
1766 int
1767 ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg)
1768 {
1769 #define	HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
1770 #define	senderr(_x, _v)	do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
1771 	struct ieee80211vap *vap = ni->ni_vap;
1772 	struct ieee80211com *ic = ni->ni_ic;
1773 	struct ieee80211_node *bss = vap->iv_bss;
1774 	struct mbuf *m;
1775 	uint8_t *frm;
1776 	uint16_t capinfo;
1777 	int has_challenge, is_shared_key, ret, status;
1778 
1779 	KASSERT(ni != NULL, ("null node"));
1780 
1781 	/*
1782 	 * Hold a reference on the node so it doesn't go away until after
1783 	 * the xmit is complete all the way in the driver.  On error we
1784 	 * will remove our reference.
1785 	 */
1786 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1787 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1788 		__func__, __LINE__,
1789 		ni, ether_sprintf(ni->ni_macaddr),
1790 		ieee80211_node_refcnt(ni)+1);
1791 	ieee80211_ref_node(ni);
1792 
1793 	switch (type) {
1794 
1795 	case IEEE80211_FC0_SUBTYPE_AUTH:
1796 		status = arg >> 16;
1797 		arg &= 0xffff;
1798 		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1799 		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1800 		    ni->ni_challenge != NULL);
1801 
1802 		/*
1803 		 * Deduce whether we're doing open authentication or
1804 		 * shared key authentication.  We do the latter if
1805 		 * we're in the middle of a shared key authentication
1806 		 * handshake or if we're initiating an authentication
1807 		 * request and configured to use shared key.
1808 		 */
1809 		is_shared_key = has_challenge ||
1810 		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1811 		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1812 		      bss->ni_authmode == IEEE80211_AUTH_SHARED);
1813 
1814 		m = ieee80211_getmgtframe(&frm,
1815 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1816 			  3 * sizeof(uint16_t)
1817 			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1818 				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
1819 		);
1820 		if (m == NULL)
1821 			senderr(ENOMEM, is_tx_nobuf);
1822 
1823 		((uint16_t *)frm)[0] =
1824 		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1825 		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1826 		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
1827 		((uint16_t *)frm)[2] = htole16(status);/* status */
1828 
1829 		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1830 			((uint16_t *)frm)[3] =
1831 			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1832 			    IEEE80211_ELEMID_CHALLENGE);
1833 			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
1834 			    IEEE80211_CHALLENGE_LEN);
1835 			m->m_pkthdr.len = m->m_len =
1836 				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
1837 			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1838 				IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
1839 				    "request encrypt frame (%s)", __func__);
1840 				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1841 			}
1842 		} else
1843 			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
1844 
1845 		/* XXX not right for shared key */
1846 		if (status == IEEE80211_STATUS_SUCCESS)
1847 			IEEE80211_NODE_STAT(ni, tx_auth);
1848 		else
1849 			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1850 
1851 		if (vap->iv_opmode == IEEE80211_M_STA)
1852 			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1853 				(void *) vap->iv_state);
1854 		break;
1855 
1856 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1857 		IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
1858 		    "send station deauthenticate (reason %d)", arg);
1859 		m = ieee80211_getmgtframe(&frm,
1860 			ic->ic_headroom + sizeof(struct ieee80211_frame),
1861 			sizeof(uint16_t));
1862 		if (m == NULL)
1863 			senderr(ENOMEM, is_tx_nobuf);
1864 		*(uint16_t *)frm = htole16(arg);	/* reason */
1865 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1866 
1867 		IEEE80211_NODE_STAT(ni, tx_deauth);
1868 		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1869 
1870 		ieee80211_node_unauthorize(ni);		/* port closed */
1871 		break;
1872 
1873 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1874 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1875 		/*
1876 		 * asreq frame format
1877 		 *	[2] capability information
1878 		 *	[2] listen interval
1879 		 *	[6*] current AP address (reassoc only)
1880 		 *	[tlv] ssid
1881 		 *	[tlv] supported rates
1882 		 *	[tlv] extended supported rates
1883 		 *	[4] power capability (optional)
1884 		 *	[28] supported channels (optional)
1885 		 *	[tlv] HT capabilities
1886 		 *	[tlv] WME (optional)
1887 		 *	[tlv] Vendor OUI HT capabilities (optional)
1888 		 *	[tlv] Atheros capabilities (if negotiated)
1889 		 *	[tlv] AppIE's (optional)
1890 		 */
1891 		m = ieee80211_getmgtframe(&frm,
1892 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1893 			 sizeof(uint16_t)
1894 		       + sizeof(uint16_t)
1895 		       + IEEE80211_ADDR_LEN
1896 		       + 2 + IEEE80211_NWID_LEN
1897 		       + 2 + IEEE80211_RATE_SIZE
1898 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1899 		       + 4
1900 		       + 2 + 26
1901 		       + sizeof(struct ieee80211_wme_info)
1902 		       + sizeof(struct ieee80211_ie_htcap)
1903 		       + 4 + sizeof(struct ieee80211_ie_htcap)
1904 		       + sizeof(struct ieee80211_ath_ie)
1905 		       + (vap->iv_appie_wpa != NULL ?
1906 				vap->iv_appie_wpa->ie_len : 0)
1907 		       + (vap->iv_appie_assocreq != NULL ?
1908 				vap->iv_appie_assocreq->ie_len : 0)
1909 		);
1910 		if (m == NULL)
1911 			senderr(ENOMEM, is_tx_nobuf);
1912 
1913 		KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1914 		    ("wrong mode %u", vap->iv_opmode));
1915 		capinfo = IEEE80211_CAPINFO_ESS;
1916 		if (vap->iv_flags & IEEE80211_F_PRIVACY)
1917 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1918 		/*
1919 		 * NB: Some 11a AP's reject the request when
1920 		 *     short premable is set.
1921 		 */
1922 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1923 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1924 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1925 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
1926 		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1927 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1928 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
1929 		    (vap->iv_flags & IEEE80211_F_DOTH))
1930 			capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
1931 		*(uint16_t *)frm = htole16(capinfo);
1932 		frm += 2;
1933 
1934 		KASSERT(bss->ni_intval != 0, ("beacon interval is zero!"));
1935 		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
1936 						    bss->ni_intval));
1937 		frm += 2;
1938 
1939 		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1940 			IEEE80211_ADDR_COPY(frm, bss->ni_bssid);
1941 			frm += IEEE80211_ADDR_LEN;
1942 		}
1943 
1944 		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1945 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1946 		if (vap->iv_flags & IEEE80211_F_WPA2) {
1947 			if (vap->iv_rsn_ie != NULL)
1948 				frm = add_ie(frm, vap->iv_rsn_ie);
1949 			/* XXX else complain? */
1950 		}
1951 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1952 		if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) {
1953 			frm = ieee80211_add_powercapability(frm,
1954 			    ic->ic_curchan);
1955 			frm = ieee80211_add_supportedchannels(frm, ic);
1956 		}
1957 		if ((vap->iv_flags_ext & IEEE80211_FEXT_HT) &&
1958 		    ni->ni_ies.htcap_ie != NULL &&
1959 		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP)
1960 			frm = ieee80211_add_htcap(frm, ni);
1961 		if (vap->iv_flags & IEEE80211_F_WPA1) {
1962 			if (vap->iv_wpa_ie != NULL)
1963 				frm = add_ie(frm, vap->iv_wpa_ie);
1964 			/* XXX else complain */
1965 		}
1966 		if ((ic->ic_flags & IEEE80211_F_WME) &&
1967 		    ni->ni_ies.wme_ie != NULL)
1968 			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1969 		if ((vap->iv_flags_ext & IEEE80211_FEXT_HT) &&
1970 		    ni->ni_ies.htcap_ie != NULL &&
1971 		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR)
1972 			frm = ieee80211_add_htcap_vendor(frm, ni);
1973 		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
1974 			frm = ieee80211_add_ath(frm,
1975 				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
1976 				(vap->iv_flags & IEEE80211_F_WPA) == 0 &&
1977 				ni->ni_authmode != IEEE80211_AUTH_8021X &&
1978 				vap->iv_def_txkey != IEEE80211_KEYIX_NONE ?
1979 				vap->iv_def_txkey : 0x7fff);
1980 		if (vap->iv_appie_assocreq != NULL)
1981 			frm = add_appie(frm, vap->iv_appie_assocreq);
1982 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1983 
1984 		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1985 			(void *) vap->iv_state);
1986 		break;
1987 
1988 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1989 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1990 		/*
1991 		 * asresp frame format
1992 		 *	[2] capability information
1993 		 *	[2] status
1994 		 *	[2] association ID
1995 		 *	[tlv] supported rates
1996 		 *	[tlv] extended supported rates
1997 		 *	[tlv] HT capabilities (standard, if STA enabled)
1998 		 *	[tlv] HT information (standard, if STA enabled)
1999 		 *	[tlv] WME (if configured and STA enabled)
2000 		 *	[tlv] HT capabilities (vendor OUI, if STA enabled)
2001 		 *	[tlv] HT information (vendor OUI, if STA enabled)
2002 		 *	[tlv] Atheros capabilities (if STA enabled)
2003 		 *	[tlv] AppIE's (optional)
2004 		 */
2005 		m = ieee80211_getmgtframe(&frm,
2006 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
2007 			 sizeof(uint16_t)
2008 		       + sizeof(uint16_t)
2009 		       + sizeof(uint16_t)
2010 		       + 2 + IEEE80211_RATE_SIZE
2011 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2012 		       + sizeof(struct ieee80211_ie_htcap) + 4
2013 		       + sizeof(struct ieee80211_ie_htinfo) + 4
2014 		       + sizeof(struct ieee80211_wme_param)
2015 		       + sizeof(struct ieee80211_ath_ie)
2016 		       + (vap->iv_appie_assocresp != NULL ?
2017 				vap->iv_appie_assocresp->ie_len : 0)
2018 		);
2019 		if (m == NULL)
2020 			senderr(ENOMEM, is_tx_nobuf);
2021 
2022 		capinfo = getcapinfo(vap, bss->ni_chan);
2023 		*(uint16_t *)frm = htole16(capinfo);
2024 		frm += 2;
2025 
2026 		*(uint16_t *)frm = htole16(arg);	/* status */
2027 		frm += 2;
2028 
2029 		if (arg == IEEE80211_STATUS_SUCCESS) {
2030 			*(uint16_t *)frm = htole16(ni->ni_associd);
2031 			IEEE80211_NODE_STAT(ni, tx_assoc);
2032 		} else
2033 			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
2034 		frm += 2;
2035 
2036 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
2037 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2038 		/* NB: respond according to what we received */
2039 		if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
2040 			frm = ieee80211_add_htcap(frm, ni);
2041 			frm = ieee80211_add_htinfo(frm, ni);
2042 		}
2043 		if ((vap->iv_flags & IEEE80211_F_WME) &&
2044 		    ni->ni_ies.wme_ie != NULL)
2045 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2046 		if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
2047 			frm = ieee80211_add_htcap_vendor(frm, ni);
2048 			frm = ieee80211_add_htinfo_vendor(frm, ni);
2049 		}
2050 		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
2051 			frm = ieee80211_add_ath(frm,
2052 				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2053 				ni->ni_ath_defkeyix);
2054 		if (vap->iv_appie_assocresp != NULL)
2055 			frm = add_appie(frm, vap->iv_appie_assocresp);
2056 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2057 		break;
2058 
2059 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
2060 		IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2061 		    "send station disassociate (reason %d)", arg);
2062 		m = ieee80211_getmgtframe(&frm,
2063 			ic->ic_headroom + sizeof(struct ieee80211_frame),
2064 			sizeof(uint16_t));
2065 		if (m == NULL)
2066 			senderr(ENOMEM, is_tx_nobuf);
2067 		*(uint16_t *)frm = htole16(arg);	/* reason */
2068 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2069 
2070 		IEEE80211_NODE_STAT(ni, tx_disassoc);
2071 		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
2072 		break;
2073 
2074 	default:
2075 		IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni,
2076 		    "invalid mgmt frame type %u", type);
2077 		senderr(EINVAL, is_tx_unknownmgt);
2078 		/* NOTREACHED */
2079 	}
2080 
2081 	return ieee80211_mgmt_output(ni, m, type);
2082 bad:
2083 	ieee80211_free_node(ni);
2084 	return ret;
2085 #undef senderr
2086 #undef HTFLAGS
2087 }
2088 
2089 /*
2090  * Return an mbuf with a probe response frame in it.
2091  * Space is left to prepend and 802.11 header at the
2092  * front but it's left to the caller to fill in.
2093  */
2094 struct mbuf *
2095 ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy)
2096 {
2097 	struct ieee80211vap *vap = bss->ni_vap;
2098 	struct ieee80211com *ic = bss->ni_ic;
2099 	const struct ieee80211_rateset *rs;
2100 	struct mbuf *m;
2101 	uint16_t capinfo;
2102 	uint8_t *frm;
2103 
2104 	/*
2105 	 * probe response frame format
2106 	 *	[8] time stamp
2107 	 *	[2] beacon interval
2108 	 *	[2] cabability information
2109 	 *	[tlv] ssid
2110 	 *	[tlv] supported rates
2111 	 *	[tlv] parameter set (FH/DS)
2112 	 *	[tlv] parameter set (IBSS)
2113 	 *	[tlv] country (optional)
2114 	 *	[tlv] RSN (optional)
2115 	 *	[3] power control (optional)
2116 	 *	[5] channel switch announcement (CSA) (optional)
2117 	 *	[tlv] extended rate phy (ERP)
2118 	 *	[tlv] extended supported rates
2119 	 *	[tlv] HT capabilities
2120 	 *	[tlv] HT information
2121 	 *	[tlv] WPA (optional)
2122 	 *	[tlv] WME (optional)
2123 	 *	[tlv] Vendor OUI HT capabilities (optional)
2124 	 *	[tlv] Vendor OUI HT information (optional)
2125 	 *	[tlv] Atheros capabilities
2126 	 *	[tlv] AppIE's (optional)
2127 	 */
2128 	m = ieee80211_getmgtframe(&frm,
2129 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
2130 		 8
2131 	       + sizeof(uint16_t)
2132 	       + sizeof(uint16_t)
2133 	       + 2 + IEEE80211_NWID_LEN
2134 	       + 2 + IEEE80211_RATE_SIZE
2135 	       + 7	/* max(7,3) */
2136 	       + IEEE80211_COUNTRY_MAX_SIZE
2137 	       + sizeof(struct ieee80211_ie_wpa)
2138 	       + 3
2139 	       + sizeof(struct ieee80211_csa_ie)
2140 	       + 3
2141 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2142 	       + sizeof(struct ieee80211_ie_htcap)
2143 	       + sizeof(struct ieee80211_ie_htinfo)
2144 	       + sizeof(struct ieee80211_ie_wpa)
2145 	       + sizeof(struct ieee80211_wme_param)
2146 	       + 4 + sizeof(struct ieee80211_ie_htcap)
2147 	       + 4 + sizeof(struct ieee80211_ie_htinfo)
2148 	       + sizeof(struct ieee80211_ath_ie)
2149 	       + (vap->iv_appie_proberesp != NULL ?
2150 			vap->iv_appie_proberesp->ie_len : 0)
2151 	);
2152 	if (m == NULL) {
2153 		vap->iv_stats.is_tx_nobuf++;
2154 		return NULL;
2155 	}
2156 
2157 	memset(frm, 0, 8);	/* timestamp should be filled later */
2158 	frm += 8;
2159 	*(uint16_t *)frm = htole16(bss->ni_intval);
2160 	frm += 2;
2161 	capinfo = getcapinfo(vap, bss->ni_chan);
2162 	*(uint16_t *)frm = htole16(capinfo);
2163 	frm += 2;
2164 
2165 	frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen);
2166 	rs = ieee80211_get_suprates(ic, bss->ni_chan);
2167 	frm = ieee80211_add_rates(frm, rs);
2168 
2169 	if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) {
2170 		*frm++ = IEEE80211_ELEMID_FHPARMS;
2171 		*frm++ = 5;
2172 		*frm++ = bss->ni_fhdwell & 0x00ff;
2173 		*frm++ = (bss->ni_fhdwell >> 8) & 0x00ff;
2174 		*frm++ = IEEE80211_FH_CHANSET(
2175 		    ieee80211_chan2ieee(ic, bss->ni_chan));
2176 		*frm++ = IEEE80211_FH_CHANPAT(
2177 		    ieee80211_chan2ieee(ic, bss->ni_chan));
2178 		*frm++ = bss->ni_fhindex;
2179 	} else {
2180 		*frm++ = IEEE80211_ELEMID_DSPARMS;
2181 		*frm++ = 1;
2182 		*frm++ = ieee80211_chan2ieee(ic, bss->ni_chan);
2183 	}
2184 
2185 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
2186 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2187 		*frm++ = 2;
2188 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2189 	}
2190 	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2191 	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2192 		frm = ieee80211_add_countryie(frm, ic);
2193 	if (vap->iv_flags & IEEE80211_F_WPA2) {
2194 		if (vap->iv_rsn_ie != NULL)
2195 			frm = add_ie(frm, vap->iv_rsn_ie);
2196 		/* XXX else complain? */
2197 	}
2198 	if (vap->iv_flags & IEEE80211_F_DOTH) {
2199 		if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan))
2200 			frm = ieee80211_add_powerconstraint(frm, vap);
2201 		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2202 			frm = ieee80211_add_csa(frm, vap);
2203 	}
2204 	if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan))
2205 		frm = ieee80211_add_erp(frm, ic);
2206 	frm = ieee80211_add_xrates(frm, rs);
2207 	/*
2208 	 * NB: legacy 11b clients do not get certain ie's.
2209 	 *     The caller identifies such clients by passing
2210 	 *     a token in legacy to us.  Could expand this to be
2211 	 *     any legacy client for stuff like HT ie's.
2212 	 */
2213 	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2214 	    legacy != IEEE80211_SEND_LEGACY_11B) {
2215 		frm = ieee80211_add_htcap(frm, bss);
2216 		frm = ieee80211_add_htinfo(frm, bss);
2217 	}
2218 	if (vap->iv_flags & IEEE80211_F_WPA1) {
2219 		if (vap->iv_wpa_ie != NULL)
2220 			frm = add_ie(frm, vap->iv_wpa_ie);
2221 		/* XXX else complain? */
2222 	}
2223 	if (vap->iv_flags & IEEE80211_F_WME)
2224 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2225 	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2226 	    (vap->iv_flags_ext & IEEE80211_FEXT_HTCOMPAT) &&
2227 	    legacy != IEEE80211_SEND_LEGACY_11B) {
2228 		frm = ieee80211_add_htcap_vendor(frm, bss);
2229 		frm = ieee80211_add_htinfo_vendor(frm, bss);
2230 	}
2231 	if (bss->ni_ies.ath_ie != NULL && legacy != IEEE80211_SEND_LEGACY_11B)
2232 		frm = ieee80211_add_ath(frm, bss->ni_ath_flags,
2233 			bss->ni_ath_defkeyix);
2234 	if (vap->iv_appie_proberesp != NULL)
2235 		frm = add_appie(frm, vap->iv_appie_proberesp);
2236 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2237 
2238 	return m;
2239 }
2240 
2241 /*
2242  * Send a probe response frame to the specified mac address.
2243  * This does not go through the normal mgt frame api so we
2244  * can specify the destination address and re-use the bss node
2245  * for the sta reference.
2246  */
2247 int
2248 ieee80211_send_proberesp(struct ieee80211vap *vap,
2249 	const uint8_t da[IEEE80211_ADDR_LEN], int legacy)
2250 {
2251 	struct ieee80211_node *bss = vap->iv_bss;
2252 	struct ieee80211com *ic = vap->iv_ic;
2253 	struct ieee80211_frame *wh;
2254 	struct mbuf *m;
2255 
2256 	if (vap->iv_state == IEEE80211_S_CAC) {
2257 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss,
2258 		    "block %s frame in CAC state", "probe response");
2259 		vap->iv_stats.is_tx_badstate++;
2260 		return EIO;		/* XXX */
2261 	}
2262 
2263 	/*
2264 	 * Hold a reference on the node so it doesn't go away until after
2265 	 * the xmit is complete all the way in the driver.  On error we
2266 	 * will remove our reference.
2267 	 */
2268 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2269 	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2270 	    __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr),
2271 	    ieee80211_node_refcnt(bss)+1);
2272 	ieee80211_ref_node(bss);
2273 
2274 	m = ieee80211_alloc_proberesp(bss, legacy);
2275 	if (m == NULL) {
2276 		ieee80211_free_node(bss);
2277 		return ENOMEM;
2278 	}
2279 
2280 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2281 	KASSERT(m != NULL, ("no room for header"));
2282 
2283 	wh = mtod(m, struct ieee80211_frame *);
2284 	ieee80211_send_setup(bss, wh,
2285 		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP,
2286 		vap->iv_myaddr, da, bss->ni_bssid);
2287 	/* XXX power management? */
2288 
2289 	M_WME_SETAC(m, WME_AC_BE);
2290 
2291 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
2292 	    "send probe resp on channel %u to %s%s\n",
2293 	    ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da),
2294 	    legacy ? " <legacy>" : "");
2295 	IEEE80211_NODE_STAT(bss, tx_mgmt);
2296 
2297 	return ic->ic_raw_xmit(bss, m, NULL);
2298 }
2299 
2300 /*
2301  * Allocate and build a RTS (Request To Send) control frame.
2302  */
2303 struct mbuf *
2304 ieee80211_alloc_rts(struct ieee80211com *ic,
2305 	const uint8_t ra[IEEE80211_ADDR_LEN],
2306 	const uint8_t ta[IEEE80211_ADDR_LEN],
2307 	uint16_t dur)
2308 {
2309 	struct ieee80211_frame_rts *rts;
2310 	struct mbuf *m;
2311 
2312 	/* XXX honor ic_headroom */
2313 	m = m_gethdr(M_DONTWAIT, MT_DATA);
2314 	if (m != NULL) {
2315 		rts = mtod(m, struct ieee80211_frame_rts *);
2316 		rts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2317 			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS;
2318 		rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2319 		*(u_int16_t *)rts->i_dur = htole16(dur);
2320 		IEEE80211_ADDR_COPY(rts->i_ra, ra);
2321 		IEEE80211_ADDR_COPY(rts->i_ta, ta);
2322 
2323 		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
2324 	}
2325 	return m;
2326 }
2327 
2328 /*
2329  * Allocate and build a CTS (Clear To Send) control frame.
2330  */
2331 struct mbuf *
2332 ieee80211_alloc_cts(struct ieee80211com *ic,
2333 	const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur)
2334 {
2335 	struct ieee80211_frame_cts *cts;
2336 	struct mbuf *m;
2337 
2338 	/* XXX honor ic_headroom */
2339 	m = m_gethdr(M_DONTWAIT, MT_DATA);
2340 	if (m != NULL) {
2341 		cts = mtod(m, struct ieee80211_frame_cts *);
2342 		cts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2343 			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS;
2344 		cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2345 		*(u_int16_t *)cts->i_dur = htole16(dur);
2346 		IEEE80211_ADDR_COPY(cts->i_ra, ra);
2347 
2348 		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
2349 	}
2350 	return m;
2351 }
2352 
2353 static void
2354 ieee80211_tx_mgt_timeout(void *arg)
2355 {
2356 	struct ieee80211_node *ni = arg;
2357 	struct ieee80211vap *vap = ni->ni_vap;
2358 
2359 	if (vap->iv_state != IEEE80211_S_INIT &&
2360 	    (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2361 		/*
2362 		 * NB: it's safe to specify a timeout as the reason here;
2363 		 *     it'll only be used in the right state.
2364 		 */
2365 		ieee80211_new_state(vap, IEEE80211_S_SCAN,
2366 			IEEE80211_SCAN_FAIL_TIMEOUT);
2367 	}
2368 }
2369 
2370 static void
2371 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
2372 {
2373 	struct ieee80211vap *vap = ni->ni_vap;
2374 	enum ieee80211_state ostate = (enum ieee80211_state) arg;
2375 
2376 	/*
2377 	 * Frame transmit completed; arrange timer callback.  If
2378 	 * transmit was successfuly we wait for response.  Otherwise
2379 	 * we arrange an immediate callback instead of doing the
2380 	 * callback directly since we don't know what state the driver
2381 	 * is in (e.g. what locks it is holding).  This work should
2382 	 * not be too time-critical and not happen too often so the
2383 	 * added overhead is acceptable.
2384 	 *
2385 	 * XXX what happens if !acked but response shows up before callback?
2386 	 */
2387 	if (vap->iv_state == ostate)
2388 		callout_reset(&vap->iv_mgtsend,
2389 			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
2390 			ieee80211_tx_mgt_timeout, ni);
2391 }
2392 
2393 static void
2394 ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm,
2395 	struct ieee80211_beacon_offsets *bo, struct ieee80211_node *ni)
2396 {
2397 	struct ieee80211vap *vap = ni->ni_vap;
2398 	struct ieee80211com *ic = ni->ni_ic;
2399 	struct ieee80211_rateset *rs = &ni->ni_rates;
2400 	uint16_t capinfo;
2401 
2402 	/*
2403 	 * beacon frame format
2404 	 *	[8] time stamp
2405 	 *	[2] beacon interval
2406 	 *	[2] cabability information
2407 	 *	[tlv] ssid
2408 	 *	[tlv] supported rates
2409 	 *	[3] parameter set (DS)
2410 	 *	[8] CF parameter set (optional)
2411 	 *	[tlv] parameter set (IBSS/TIM)
2412 	 *	[tlv] country (optional)
2413 	 *	[tlv] RSN parameters
2414 	 *	[3] power control (optional)
2415 	 *	[5] channel switch announcement (CSA) (optional)
2416 	 *	[tlv] extended rate phy (ERP)
2417 	 *	[tlv] extended supported rates
2418 	 *	[tlv] HT capabilities
2419 	 *	[tlv] HT information
2420 	 * XXX Vendor-specific OIDs (e.g. Atheros)
2421 	 *	[tlv] WPA parameters
2422 	 *	[tlv] WME parameters
2423 	 *	[tlv] Vendor OUI HT capabilities (optional)
2424 	 *	[tlv] Vendor OUI HT information (optional)
2425 	 *	[tlv] application data (optional)
2426 	 */
2427 
2428 	memset(bo, 0, sizeof(*bo));
2429 
2430 	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
2431 	frm += 8;
2432 	*(uint16_t *)frm = htole16(ni->ni_intval);
2433 	frm += 2;
2434 	capinfo = getcapinfo(vap, ni->ni_chan);
2435 	bo->bo_caps = (uint16_t *)frm;
2436 	*(uint16_t *)frm = htole16(capinfo);
2437 	frm += 2;
2438 	*frm++ = IEEE80211_ELEMID_SSID;
2439 	if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) {
2440 		*frm++ = ni->ni_esslen;
2441 		memcpy(frm, ni->ni_essid, ni->ni_esslen);
2442 		frm += ni->ni_esslen;
2443 	} else
2444 		*frm++ = 0;
2445 	frm = ieee80211_add_rates(frm, rs);
2446 	if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) {
2447 		*frm++ = IEEE80211_ELEMID_DSPARMS;
2448 		*frm++ = 1;
2449 		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
2450 	}
2451 	if (ic->ic_flags & IEEE80211_F_PCF) {
2452 		bo->bo_cfp = frm;
2453 		frm = ieee80211_add_cfparms(frm, ic);
2454 	}
2455 	bo->bo_tim = frm;
2456 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
2457 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2458 		*frm++ = 2;
2459 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2460 		bo->bo_tim_len = 0;
2461 	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
2462 		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
2463 
2464 		tie->tim_ie = IEEE80211_ELEMID_TIM;
2465 		tie->tim_len = 4;	/* length */
2466 		tie->tim_count = 0;	/* DTIM count */
2467 		tie->tim_period = vap->iv_dtim_period;	/* DTIM period */
2468 		tie->tim_bitctl = 0;	/* bitmap control */
2469 		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
2470 		frm += sizeof(struct ieee80211_tim_ie);
2471 		bo->bo_tim_len = 1;
2472 	}
2473 	bo->bo_tim_trailer = frm;
2474 	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2475 	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2476 		frm = ieee80211_add_countryie(frm, ic);
2477 	if (vap->iv_flags & IEEE80211_F_WPA2) {
2478 		if (vap->iv_rsn_ie != NULL)
2479 			frm = add_ie(frm, vap->iv_rsn_ie);
2480 		/* XXX else complain */
2481 	}
2482 	if (vap->iv_flags & IEEE80211_F_DOTH) {
2483 		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
2484 			frm = ieee80211_add_powerconstraint(frm, vap);
2485 		bo->bo_csa = frm;
2486 		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2487 			frm = ieee80211_add_csa(frm, vap);
2488 	} else
2489 		bo->bo_csa = frm;
2490 	if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) {
2491 		bo->bo_erp = frm;
2492 		frm = ieee80211_add_erp(frm, ic);
2493 	}
2494 	frm = ieee80211_add_xrates(frm, rs);
2495 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
2496 		frm = ieee80211_add_htcap(frm, ni);
2497 		bo->bo_htinfo = frm;
2498 		frm = ieee80211_add_htinfo(frm, ni);
2499 	}
2500 	if (vap->iv_flags & IEEE80211_F_WPA1) {
2501 		if (vap->iv_wpa_ie != NULL)
2502 			frm = add_ie(frm, vap->iv_wpa_ie);
2503 		/* XXX else complain */
2504 	}
2505 	if (vap->iv_flags & IEEE80211_F_WME) {
2506 		bo->bo_wme = frm;
2507 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2508 	}
2509 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2510 	    (vap->iv_flags_ext & IEEE80211_FEXT_HTCOMPAT)) {
2511 		frm = ieee80211_add_htcap_vendor(frm, ni);
2512 		frm = ieee80211_add_htinfo_vendor(frm, ni);
2513 	}
2514 	if (vap->iv_appie_beacon != NULL) {
2515 		bo->bo_appie = frm;
2516 		bo->bo_appie_len = vap->iv_appie_beacon->ie_len;
2517 		frm = add_appie(frm, vap->iv_appie_beacon);
2518 	}
2519 	bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
2520 	bo->bo_csa_trailer_len = frm - bo->bo_csa;
2521 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2522 }
2523 
2524 /*
2525  * Allocate a beacon frame and fillin the appropriate bits.
2526  */
2527 struct mbuf *
2528 ieee80211_beacon_alloc(struct ieee80211_node *ni,
2529 	struct ieee80211_beacon_offsets *bo)
2530 {
2531 	struct ieee80211vap *vap = ni->ni_vap;
2532 	struct ieee80211com *ic = ni->ni_ic;
2533 	struct ifnet *ifp = vap->iv_ifp;
2534 	struct ieee80211_frame *wh;
2535 	struct mbuf *m;
2536 	int pktlen;
2537 	uint8_t *frm;
2538 
2539 	/*
2540 	 * beacon frame format
2541 	 *	[8] time stamp
2542 	 *	[2] beacon interval
2543 	 *	[2] cabability information
2544 	 *	[tlv] ssid
2545 	 *	[tlv] supported rates
2546 	 *	[3] parameter set (DS)
2547 	 *	[8] CF parameter set (optional)
2548 	 *	[tlv] parameter set (IBSS/TIM)
2549 	 *	[tlv] country (optional)
2550 	 *	[3] power control (optional)
2551 	 *	[5] channel switch announcement (CSA) (optional)
2552 	 *	[tlv] extended rate phy (ERP)
2553 	 *	[tlv] extended supported rates
2554 	 *	[tlv] RSN parameters
2555 	 *	[tlv] HT capabilities
2556 	 *	[tlv] HT information
2557 	 *	[tlv] Vendor OUI HT capabilities (optional)
2558 	 *	[tlv] Vendor OUI HT information (optional)
2559 	 * XXX Vendor-specific OIDs (e.g. Atheros)
2560 	 *	[tlv] WPA parameters
2561 	 *	[tlv] WME parameters
2562 	 *	[tlv] application data (optional)
2563 	 * NB: we allocate the max space required for the TIM bitmap.
2564 	 * XXX how big is this?
2565 	 */
2566 	pktlen =   8					/* time stamp */
2567 		 + sizeof(uint16_t)			/* beacon interval */
2568 		 + sizeof(uint16_t)			/* capabilities */
2569 		 + 2 + ni->ni_esslen			/* ssid */
2570 	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
2571 	         + 2 + 1				/* DS parameters */
2572 		 + 2 + 6				/* CF parameters */
2573 		 + 2 + 4 + vap->iv_tim_len		/* DTIM/IBSSPARMS */
2574 		 + IEEE80211_COUNTRY_MAX_SIZE		/* country */
2575 		 + 2 + 1				/* power control */
2576 	         + sizeof(struct ieee80211_csa_ie)	/* CSA */
2577 		 + 2 + 1				/* ERP */
2578 	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2579 		 + (vap->iv_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
2580 			2*sizeof(struct ieee80211_ie_wpa) : 0)
2581 		 /* XXX conditional? */
2582 		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
2583 		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
2584 		 + (vap->iv_caps & IEEE80211_C_WME ?	/* WME */
2585 			sizeof(struct ieee80211_wme_param) : 0)
2586 		 + IEEE80211_MAX_APPIE
2587 		 ;
2588 	m = ieee80211_getmgtframe(&frm,
2589 		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
2590 	if (m == NULL) {
2591 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
2592 			"%s: cannot get buf; size %u\n", __func__, pktlen);
2593 		vap->iv_stats.is_tx_nobuf++;
2594 		return NULL;
2595 	}
2596 	ieee80211_beacon_construct(m, frm, bo, ni);
2597 
2598 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2599 	KASSERT(m != NULL, ("no space for 802.11 header?"));
2600 	wh = mtod(m, struct ieee80211_frame *);
2601 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2602 	    IEEE80211_FC0_SUBTYPE_BEACON;
2603 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2604 	*(uint16_t *)wh->i_dur = 0;
2605 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2606 	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
2607 	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
2608 	*(uint16_t *)wh->i_seq = 0;
2609 
2610 	return m;
2611 }
2612 
2613 /*
2614  * Update the dynamic parts of a beacon frame based on the current state.
2615  */
2616 int
2617 ieee80211_beacon_update(struct ieee80211_node *ni,
2618 	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
2619 {
2620 	struct ieee80211vap *vap = ni->ni_vap;
2621 	struct ieee80211com *ic = ni->ni_ic;
2622 	int len_changed = 0;
2623 	uint16_t capinfo;
2624 
2625 	IEEE80211_LOCK(ic);
2626 	/*
2627 	 * Handle 11h channel change when we've reached the count.
2628 	 * We must recalculate the beacon frame contents to account
2629 	 * for the new channel.  Note we do this only for the first
2630 	 * vap that reaches this point; subsequent vaps just update
2631 	 * their beacon state to reflect the recalculated channel.
2632 	 */
2633 	if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) &&
2634 	    vap->iv_csa_count == ic->ic_csa_count) {
2635 		vap->iv_csa_count = 0;
2636 		/*
2637 		 * Effect channel change before reconstructing the beacon
2638 		 * frame contents as many places reference ni_chan.
2639 		 */
2640 		if (ic->ic_csa_newchan != NULL)
2641 			ieee80211_csa_completeswitch(ic);
2642 		/*
2643 		 * NB: ieee80211_beacon_construct clears all pending
2644 		 * updates in bo_flags so we don't need to explicitly
2645 		 * clear IEEE80211_BEACON_CSA.
2646 		 */
2647 		ieee80211_beacon_construct(m,
2648 		    mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), bo, ni);
2649 
2650 		/* XXX do WME aggressive mode processing? */
2651 		IEEE80211_UNLOCK(ic);
2652 		return 1;		/* just assume length changed */
2653 	}
2654 
2655 	/* XXX faster to recalculate entirely or just changes? */
2656 	capinfo = getcapinfo(vap, ni->ni_chan);
2657 	*bo->bo_caps = htole16(capinfo);
2658 
2659 	if (vap->iv_flags & IEEE80211_F_WME) {
2660 		struct ieee80211_wme_state *wme = &ic->ic_wme;
2661 
2662 		/*
2663 		 * Check for agressive mode change.  When there is
2664 		 * significant high priority traffic in the BSS
2665 		 * throttle back BE traffic by using conservative
2666 		 * parameters.  Otherwise BE uses agressive params
2667 		 * to optimize performance of legacy/non-QoS traffic.
2668 		 */
2669 		if (wme->wme_flags & WME_F_AGGRMODE) {
2670 			if (wme->wme_hipri_traffic >
2671 			    wme->wme_hipri_switch_thresh) {
2672 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2673 				    "%s: traffic %u, disable aggressive mode\n",
2674 				    __func__, wme->wme_hipri_traffic);
2675 				wme->wme_flags &= ~WME_F_AGGRMODE;
2676 				ieee80211_wme_updateparams_locked(vap);
2677 				wme->wme_hipri_traffic =
2678 					wme->wme_hipri_switch_hysteresis;
2679 			} else
2680 				wme->wme_hipri_traffic = 0;
2681 		} else {
2682 			if (wme->wme_hipri_traffic <=
2683 			    wme->wme_hipri_switch_thresh) {
2684 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2685 				    "%s: traffic %u, enable aggressive mode\n",
2686 				    __func__, wme->wme_hipri_traffic);
2687 				wme->wme_flags |= WME_F_AGGRMODE;
2688 				ieee80211_wme_updateparams_locked(vap);
2689 				wme->wme_hipri_traffic = 0;
2690 			} else
2691 				wme->wme_hipri_traffic =
2692 					wme->wme_hipri_switch_hysteresis;
2693 		}
2694 		if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
2695 			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
2696 			clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
2697 		}
2698 	}
2699 
2700 	if (isset(bo->bo_flags,  IEEE80211_BEACON_HTINFO)) {
2701 		ieee80211_ht_update_beacon(vap, bo);
2702 		clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
2703 	}
2704 
2705 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
2706 		struct ieee80211_tim_ie *tie =
2707 			(struct ieee80211_tim_ie *) bo->bo_tim;
2708 		if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
2709 			u_int timlen, timoff, i;
2710 			/*
2711 			 * ATIM/DTIM needs updating.  If it fits in the
2712 			 * current space allocated then just copy in the
2713 			 * new bits.  Otherwise we need to move any trailing
2714 			 * data to make room.  Note that we know there is
2715 			 * contiguous space because ieee80211_beacon_allocate
2716 			 * insures there is space in the mbuf to write a
2717 			 * maximal-size virtual bitmap (based on iv_max_aid).
2718 			 */
2719 			/*
2720 			 * Calculate the bitmap size and offset, copy any
2721 			 * trailer out of the way, and then copy in the
2722 			 * new bitmap and update the information element.
2723 			 * Note that the tim bitmap must contain at least
2724 			 * one byte and any offset must be even.
2725 			 */
2726 			if (vap->iv_ps_pending != 0) {
2727 				timoff = 128;		/* impossibly large */
2728 				for (i = 0; i < vap->iv_tim_len; i++)
2729 					if (vap->iv_tim_bitmap[i]) {
2730 						timoff = i &~ 1;
2731 						break;
2732 					}
2733 				KASSERT(timoff != 128, ("tim bitmap empty!"));
2734 				for (i = vap->iv_tim_len-1; i >= timoff; i--)
2735 					if (vap->iv_tim_bitmap[i])
2736 						break;
2737 				timlen = 1 + (i - timoff);
2738 			} else {
2739 				timoff = 0;
2740 				timlen = 1;
2741 			}
2742 			if (timlen != bo->bo_tim_len) {
2743 				/* copy up/down trailer */
2744 				int adjust = tie->tim_bitmap+timlen
2745 					   - bo->bo_tim_trailer;
2746 				ovbcopy(bo->bo_tim_trailer,
2747 				    bo->bo_tim_trailer+adjust,
2748 				    bo->bo_tim_trailer_len);
2749 				bo->bo_tim_trailer += adjust;
2750 				bo->bo_erp += adjust;
2751 				bo->bo_htinfo += adjust;
2752 				bo->bo_appie += adjust;
2753 				bo->bo_wme += adjust;
2754 				bo->bo_csa += adjust;
2755 				bo->bo_tim_len = timlen;
2756 
2757 				/* update information element */
2758 				tie->tim_len = 3 + timlen;
2759 				tie->tim_bitctl = timoff;
2760 				len_changed = 1;
2761 			}
2762 			memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff,
2763 				bo->bo_tim_len);
2764 
2765 			clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
2766 
2767 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER,
2768 				"%s: TIM updated, pending %u, off %u, len %u\n",
2769 				__func__, vap->iv_ps_pending, timoff, timlen);
2770 		}
2771 		/* count down DTIM period */
2772 		if (tie->tim_count == 0)
2773 			tie->tim_count = tie->tim_period - 1;
2774 		else
2775 			tie->tim_count--;
2776 		/* update state for buffered multicast frames on DTIM */
2777 		if (mcast && tie->tim_count == 0)
2778 			tie->tim_bitctl |= 1;
2779 		else
2780 			tie->tim_bitctl &= ~1;
2781 		if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) {
2782 			struct ieee80211_csa_ie *csa =
2783 			    (struct ieee80211_csa_ie *) bo->bo_csa;
2784 
2785 			/*
2786 			 * Insert or update CSA ie.  If we're just starting
2787 			 * to count down to the channel switch then we need
2788 			 * to insert the CSA ie.  Otherwise we just need to
2789 			 * drop the count.  The actual change happens above
2790 			 * when the vap's count reaches the target count.
2791 			 */
2792 			if (vap->iv_csa_count == 0) {
2793 				memmove(&csa[1], csa, bo->bo_csa_trailer_len);
2794 				bo->bo_erp += sizeof(*csa);
2795 				bo->bo_wme += sizeof(*csa);
2796 				bo->bo_appie += sizeof(*csa);
2797 				bo->bo_csa_trailer_len += sizeof(*csa);
2798 				bo->bo_tim_trailer_len += sizeof(*csa);
2799 				m->m_len += sizeof(*csa);
2800 				m->m_pkthdr.len += sizeof(*csa);
2801 
2802 				ieee80211_add_csa(bo->bo_csa, vap);
2803 			} else
2804 				csa->csa_count--;
2805 			vap->iv_csa_count++;
2806 			/* NB: don't clear IEEE80211_BEACON_CSA */
2807 		}
2808 		if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
2809 			/*
2810 			 * ERP element needs updating.
2811 			 */
2812 			(void) ieee80211_add_erp(bo->bo_erp, ic);
2813 			clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
2814 		}
2815 	}
2816 	if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) {
2817 		const struct ieee80211_appie *aie = vap->iv_appie_beacon;
2818 		int aielen;
2819 		uint8_t *frm;
2820 
2821 		aielen = 0;
2822 		if (aie != NULL)
2823 			aielen += aie->ie_len;
2824 		if (aielen != bo->bo_appie_len) {
2825 			/* copy up/down trailer */
2826 			int adjust = aielen - bo->bo_appie_len;
2827 			ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust,
2828 				bo->bo_tim_trailer_len);
2829 			bo->bo_tim_trailer += adjust;
2830 			bo->bo_appie += adjust;
2831 			bo->bo_appie_len = aielen;
2832 
2833 			len_changed = 1;
2834 		}
2835 		frm = bo->bo_appie;
2836 		if (aie != NULL)
2837 			frm  = add_appie(frm, aie);
2838 		clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE);
2839 	}
2840 	IEEE80211_UNLOCK(ic);
2841 
2842 	return len_changed;
2843 }
2844