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