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