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