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