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