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