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