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