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