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