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