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