ieee80211_output.c revision 191555
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 191555 2009-04-26 23:11:22Z 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 sent through a vap marked for relaying
978	 *   (e.g. a station operating with dynamic WDS)
979	 */
980	is4addr = vap->iv_opmode == IEEE80211_M_WDS ||
981	    ((vap->iv_flags_ext & IEEE80211_FEXT_4ADDR) &&
982	     !IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr));
983	if (is4addr)
984		hdrsize += IEEE80211_ADDR_LEN;
985	/*
986	 * Honor driver DATAPAD requirement.
987	 */
988	if (ic->ic_flags & IEEE80211_F_DATAPAD)
989		hdrspace = roundup(hdrsize, sizeof(uint32_t));
990	else
991		hdrspace = hdrsize;
992
993	if (__predict_true((m->m_flags & M_FF) == 0)) {
994		/*
995		 * Normal frame.
996		 */
997		m = ieee80211_mbuf_adjust(vap, hdrspace, key, m);
998		if (m == NULL) {
999			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
1000			goto bad;
1001		}
1002		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
1003		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
1004		llc = mtod(m, struct llc *);
1005		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1006		llc->llc_control = LLC_UI;
1007		llc->llc_snap.org_code[0] = 0;
1008		llc->llc_snap.org_code[1] = 0;
1009		llc->llc_snap.org_code[2] = 0;
1010		llc->llc_snap.ether_type = eh.ether_type;
1011	} else {
1012#ifdef IEEE80211_SUPPORT_SUPERG
1013		/*
1014		 * Aggregated frame.
1015		 */
1016		m = ieee80211_ff_encap(vap, m, hdrspace, key);
1017		if (m == NULL)
1018#endif
1019			goto bad;
1020	}
1021	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
1022
1023	M_PREPEND(m, hdrspace, M_DONTWAIT);
1024	if (m == NULL) {
1025		vap->iv_stats.is_tx_nobuf++;
1026		goto bad;
1027	}
1028	wh = mtod(m, struct ieee80211_frame *);
1029	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
1030	*(uint16_t *)wh->i_dur = 0;
1031	if (is4addr) {
1032		wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
1033		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
1034		IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1035		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1036		IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost);
1037	} else switch (vap->iv_opmode) {
1038	case IEEE80211_M_STA:
1039		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
1040		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
1041		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1042		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1043		break;
1044	case IEEE80211_M_IBSS:
1045	case IEEE80211_M_AHDEMO:
1046		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1047		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1048		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1049		/*
1050		 * NB: always use the bssid from iv_bss as the
1051		 *     neighbor's may be stale after an ibss merge
1052		 */
1053		IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_bssid);
1054		break;
1055	case IEEE80211_M_HOSTAP:
1056		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1057		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1058		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
1059		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
1060		break;
1061	case IEEE80211_M_MONITOR:
1062	case IEEE80211_M_WDS:		/* NB: is4addr should always be true */
1063		goto bad;
1064	}
1065	if (m->m_flags & M_MORE_DATA)
1066		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
1067	if (addqos) {
1068		uint8_t *qos;
1069		int ac, tid;
1070
1071		if (is4addr) {
1072			qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1073		} else
1074			qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1075		ac = M_WME_GETAC(m);
1076		/* map from access class/queue to 11e header priorty value */
1077		tid = WME_AC_TO_TID(ac);
1078		qos[0] = tid & IEEE80211_QOS_TID;
1079		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
1080			qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
1081		qos[1] = 0;
1082		wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
1083
1084		if ((m->m_flags & M_AMPDU_MPDU) == 0) {
1085			/*
1086			 * NB: don't assign a sequence # to potential
1087			 * aggregates; we expect this happens at the
1088			 * point the frame comes off any aggregation q
1089			 * as otherwise we may introduce holes in the
1090			 * BA sequence space and/or make window accouting
1091			 * more difficult.
1092			 *
1093			 * XXX may want to control this with a driver
1094			 * capability; this may also change when we pull
1095			 * aggregation up into net80211
1096			 */
1097			seqno = ni->ni_txseqs[tid]++;
1098			*(uint16_t *)wh->i_seq =
1099			    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1100		}
1101	} else {
1102		seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
1103		*(uint16_t *)wh->i_seq =
1104		    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1105	}
1106	/* check if xmit fragmentation is required */
1107	txfrag = (m->m_pkthdr.len > vap->iv_fragthreshold &&
1108	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1109	    (vap->iv_caps & IEEE80211_C_TXFRAG) &&
1110	    (m->m_flags & (M_FF | M_AMPDU_MPDU)) == 0);
1111	if (key != NULL) {
1112		/*
1113		 * IEEE 802.1X: send EAPOL frames always in the clear.
1114		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
1115		 */
1116		if ((m->m_flags & M_EAPOL) == 0 ||
1117		    ((vap->iv_flags & IEEE80211_F_WPA) &&
1118		     (vap->iv_opmode == IEEE80211_M_STA ?
1119		      !IEEE80211_KEY_UNDEFINED(key) :
1120		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
1121			wh->i_fc[1] |= IEEE80211_FC1_WEP;
1122			if (!ieee80211_crypto_enmic(vap, key, m, txfrag)) {
1123				IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT,
1124				    eh.ether_dhost,
1125				    "%s", "enmic failed, discard frame");
1126				vap->iv_stats.is_crypto_enmicfail++;
1127				goto bad;
1128			}
1129		}
1130	}
1131	if (txfrag && !ieee80211_fragment(vap, m, hdrsize,
1132	    key != NULL ? key->wk_cipher->ic_header : 0, vap->iv_fragthreshold))
1133		goto bad;
1134
1135	m->m_flags |= M_ENCAP;		/* mark encapsulated */
1136
1137	IEEE80211_NODE_STAT(ni, tx_data);
1138	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1139		IEEE80211_NODE_STAT(ni, tx_mcast);
1140		m->m_flags |= M_MCAST;
1141	} else
1142		IEEE80211_NODE_STAT(ni, tx_ucast);
1143	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
1144
1145	return m;
1146bad:
1147	if (m != NULL)
1148		m_freem(m);
1149	return NULL;
1150#undef WH4
1151}
1152
1153/*
1154 * Fragment the frame according to the specified mtu.
1155 * The size of the 802.11 header (w/o padding) is provided
1156 * so we don't need to recalculate it.  We create a new
1157 * mbuf for each fragment and chain it through m_nextpkt;
1158 * we might be able to optimize this by reusing the original
1159 * packet's mbufs but that is significantly more complicated.
1160 */
1161static int
1162ieee80211_fragment(struct ieee80211vap *vap, struct mbuf *m0,
1163	u_int hdrsize, u_int ciphdrsize, u_int mtu)
1164{
1165	struct ieee80211_frame *wh, *whf;
1166	struct mbuf *m, *prev, *next;
1167	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1168
1169	KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1170	KASSERT(m0->m_pkthdr.len > mtu,
1171		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1172
1173	wh = mtod(m0, struct ieee80211_frame *);
1174	/* NB: mark the first frag; it will be propagated below */
1175	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1176	totalhdrsize = hdrsize + ciphdrsize;
1177	fragno = 1;
1178	off = mtu - ciphdrsize;
1179	remainder = m0->m_pkthdr.len - off;
1180	prev = m0;
1181	do {
1182		fragsize = totalhdrsize + remainder;
1183		if (fragsize > mtu)
1184			fragsize = mtu;
1185		/* XXX fragsize can be >2048! */
1186		KASSERT(fragsize < MCLBYTES,
1187			("fragment size %u too big!", fragsize));
1188		if (fragsize > MHLEN)
1189			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1190		else
1191			m = m_gethdr(M_DONTWAIT, MT_DATA);
1192		if (m == NULL)
1193			goto bad;
1194		/* leave room to prepend any cipher header */
1195		m_align(m, fragsize - ciphdrsize);
1196
1197		/*
1198		 * Form the header in the fragment.  Note that since
1199		 * we mark the first fragment with the MORE_FRAG bit
1200		 * it automatically is propagated to each fragment; we
1201		 * need only clear it on the last fragment (done below).
1202		 */
1203		whf = mtod(m, struct ieee80211_frame *);
1204		memcpy(whf, wh, hdrsize);
1205		*(uint16_t *)&whf->i_seq[0] |= htole16(
1206			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
1207				IEEE80211_SEQ_FRAG_SHIFT);
1208		fragno++;
1209
1210		payload = fragsize - totalhdrsize;
1211		/* NB: destination is known to be contiguous */
1212		m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize);
1213		m->m_len = hdrsize + payload;
1214		m->m_pkthdr.len = hdrsize + payload;
1215		m->m_flags |= M_FRAG;
1216
1217		/* chain up the fragment */
1218		prev->m_nextpkt = m;
1219		prev = m;
1220
1221		/* deduct fragment just formed */
1222		remainder -= payload;
1223		off += payload;
1224	} while (remainder != 0);
1225
1226	/* set the last fragment */
1227	m->m_flags |= M_LASTFRAG;
1228	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
1229
1230	/* strip first mbuf now that everything has been copied */
1231	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
1232	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1233
1234	vap->iv_stats.is_tx_fragframes++;
1235	vap->iv_stats.is_tx_frags += fragno-1;
1236
1237	return 1;
1238bad:
1239	/* reclaim fragments but leave original frame for caller to free */
1240	for (m = m0->m_nextpkt; m != NULL; m = next) {
1241		next = m->m_nextpkt;
1242		m->m_nextpkt = NULL;		/* XXX paranoid */
1243		m_freem(m);
1244	}
1245	m0->m_nextpkt = NULL;
1246	return 0;
1247}
1248
1249/*
1250 * Add a supported rates element id to a frame.
1251 */
1252static uint8_t *
1253ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
1254{
1255	int nrates;
1256
1257	*frm++ = IEEE80211_ELEMID_RATES;
1258	nrates = rs->rs_nrates;
1259	if (nrates > IEEE80211_RATE_SIZE)
1260		nrates = IEEE80211_RATE_SIZE;
1261	*frm++ = nrates;
1262	memcpy(frm, rs->rs_rates, nrates);
1263	return frm + nrates;
1264}
1265
1266/*
1267 * Add an extended supported rates element id to a frame.
1268 */
1269static uint8_t *
1270ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
1271{
1272	/*
1273	 * Add an extended supported rates element if operating in 11g mode.
1274	 */
1275	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1276		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1277		*frm++ = IEEE80211_ELEMID_XRATES;
1278		*frm++ = nrates;
1279		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1280		frm += nrates;
1281	}
1282	return frm;
1283}
1284
1285/*
1286 * Add an ssid element to a frame.
1287 */
1288static uint8_t *
1289ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
1290{
1291	*frm++ = IEEE80211_ELEMID_SSID;
1292	*frm++ = len;
1293	memcpy(frm, ssid, len);
1294	return frm + len;
1295}
1296
1297/*
1298 * Add an erp element to a frame.
1299 */
1300static uint8_t *
1301ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
1302{
1303	uint8_t erp;
1304
1305	*frm++ = IEEE80211_ELEMID_ERP;
1306	*frm++ = 1;
1307	erp = 0;
1308	if (ic->ic_nonerpsta != 0)
1309		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1310	if (ic->ic_flags & IEEE80211_F_USEPROT)
1311		erp |= IEEE80211_ERP_USE_PROTECTION;
1312	if (ic->ic_flags & IEEE80211_F_USEBARKER)
1313		erp |= IEEE80211_ERP_LONG_PREAMBLE;
1314	*frm++ = erp;
1315	return frm;
1316}
1317
1318/*
1319 * Add a CFParams element to a frame.
1320 */
1321static uint8_t *
1322ieee80211_add_cfparms(uint8_t *frm, struct ieee80211com *ic)
1323{
1324#define	ADDSHORT(frm, v) do {			\
1325	frm[0] = (v) & 0xff;			\
1326	frm[1] = (v) >> 8;			\
1327	frm += 2;				\
1328} while (0)
1329	*frm++ = IEEE80211_ELEMID_CFPARMS;
1330	*frm++ = 6;
1331	*frm++ = 0;		/* CFP count */
1332	*frm++ = 2;		/* CFP period */
1333	ADDSHORT(frm, 0);	/* CFP MaxDuration (TU) */
1334	ADDSHORT(frm, 0);	/* CFP CurRemaining (TU) */
1335	return frm;
1336#undef ADDSHORT
1337}
1338
1339static __inline uint8_t *
1340add_appie(uint8_t *frm, const struct ieee80211_appie *ie)
1341{
1342	memcpy(frm, ie->ie_data, ie->ie_len);
1343	return frm + ie->ie_len;
1344}
1345
1346static __inline uint8_t *
1347add_ie(uint8_t *frm, const uint8_t *ie)
1348{
1349	memcpy(frm, ie, 2 + ie[1]);
1350	return frm + 2 + ie[1];
1351}
1352
1353#define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1354/*
1355 * Add a WME information element to a frame.
1356 */
1357static uint8_t *
1358ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
1359{
1360	static const struct ieee80211_wme_info info = {
1361		.wme_id		= IEEE80211_ELEMID_VENDOR,
1362		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1363		.wme_oui	= { WME_OUI_BYTES },
1364		.wme_type	= WME_OUI_TYPE,
1365		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1366		.wme_version	= WME_VERSION,
1367		.wme_info	= 0,
1368	};
1369	memcpy(frm, &info, sizeof(info));
1370	return frm + sizeof(info);
1371}
1372
1373/*
1374 * Add a WME parameters element to a frame.
1375 */
1376static uint8_t *
1377ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
1378{
1379#define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1380#define	ADDSHORT(frm, v) do {			\
1381	frm[0] = (v) & 0xff;			\
1382	frm[1] = (v) >> 8;			\
1383	frm += 2;				\
1384} while (0)
1385	/* NB: this works 'cuz a param has an info at the front */
1386	static const struct ieee80211_wme_info param = {
1387		.wme_id		= IEEE80211_ELEMID_VENDOR,
1388		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1389		.wme_oui	= { WME_OUI_BYTES },
1390		.wme_type	= WME_OUI_TYPE,
1391		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1392		.wme_version	= WME_VERSION,
1393	};
1394	int i;
1395
1396	memcpy(frm, &param, sizeof(param));
1397	frm += __offsetof(struct ieee80211_wme_info, wme_info);
1398	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1399	*frm++ = 0;					/* reserved field */
1400	for (i = 0; i < WME_NUM_AC; i++) {
1401		const struct wmeParams *ac =
1402		       &wme->wme_bssChanParams.cap_wmeParams[i];
1403		*frm++ = SM(i, WME_PARAM_ACI)
1404		       | SM(ac->wmep_acm, WME_PARAM_ACM)
1405		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1406		       ;
1407		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1408		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1409		       ;
1410		ADDSHORT(frm, ac->wmep_txopLimit);
1411	}
1412	return frm;
1413#undef SM
1414#undef ADDSHORT
1415}
1416#undef WME_OUI_BYTES
1417
1418/*
1419 * Add an 11h Power Constraint element to a frame.
1420 */
1421static uint8_t *
1422ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap)
1423{
1424	const struct ieee80211_channel *c = vap->iv_bss->ni_chan;
1425	/* XXX per-vap tx power limit? */
1426	int8_t limit = vap->iv_ic->ic_txpowlimit / 2;
1427
1428	frm[0] = IEEE80211_ELEMID_PWRCNSTR;
1429	frm[1] = 1;
1430	frm[2] = c->ic_maxregpower > limit ?  c->ic_maxregpower - limit : 0;
1431	return frm + 3;
1432}
1433
1434/*
1435 * Add an 11h Power Capability element to a frame.
1436 */
1437static uint8_t *
1438ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c)
1439{
1440	frm[0] = IEEE80211_ELEMID_PWRCAP;
1441	frm[1] = 2;
1442	frm[2] = c->ic_minpower;
1443	frm[3] = c->ic_maxpower;
1444	return frm + 4;
1445}
1446
1447/*
1448 * Add an 11h Supported Channels element to a frame.
1449 */
1450static uint8_t *
1451ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic)
1452{
1453	static const int ielen = 26;
1454
1455	frm[0] = IEEE80211_ELEMID_SUPPCHAN;
1456	frm[1] = ielen;
1457	/* XXX not correct */
1458	memcpy(frm+2, ic->ic_chan_avail, ielen);
1459	return frm + 2 + ielen;
1460}
1461
1462/*
1463 * Add an 11h Channel Switch Announcement element to a frame.
1464 * Note that we use the per-vap CSA count to adjust the global
1465 * counter so we can use this routine to form probe response
1466 * frames and get the current count.
1467 */
1468static uint8_t *
1469ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap)
1470{
1471	struct ieee80211com *ic = vap->iv_ic;
1472	struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm;
1473
1474	csa->csa_ie = IEEE80211_ELEMID_CHANSWITCHANN;
1475	csa->csa_len = 3;
1476	csa->csa_mode = 1;		/* XXX force quiet on channel */
1477	csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan);
1478	csa->csa_count = ic->ic_csa_count - vap->iv_csa_count;
1479	return frm + sizeof(*csa);
1480}
1481
1482/*
1483 * Add an 11h country information element to a frame.
1484 */
1485static uint8_t *
1486ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic)
1487{
1488
1489	if (ic->ic_countryie == NULL ||
1490	    ic->ic_countryie_chan != ic->ic_bsschan) {
1491		/*
1492		 * Handle lazy construction of ie.  This is done on
1493		 * first use and after a channel change that requires
1494		 * re-calculation.
1495		 */
1496		if (ic->ic_countryie != NULL)
1497			free(ic->ic_countryie, M_80211_NODE_IE);
1498		ic->ic_countryie = ieee80211_alloc_countryie(ic);
1499		if (ic->ic_countryie == NULL)
1500			return frm;
1501		ic->ic_countryie_chan = ic->ic_bsschan;
1502	}
1503	return add_appie(frm, ic->ic_countryie);
1504}
1505
1506/*
1507 * Send a probe request frame with the specified ssid
1508 * and any optional information element data.
1509 */
1510int
1511ieee80211_send_probereq(struct ieee80211_node *ni,
1512	const uint8_t sa[IEEE80211_ADDR_LEN],
1513	const uint8_t da[IEEE80211_ADDR_LEN],
1514	const uint8_t bssid[IEEE80211_ADDR_LEN],
1515	const uint8_t *ssid, size_t ssidlen)
1516{
1517	struct ieee80211vap *vap = ni->ni_vap;
1518	struct ieee80211com *ic = ni->ni_ic;
1519	const struct ieee80211_txparam *tp;
1520	struct ieee80211_bpf_params params;
1521	struct ieee80211_frame *wh;
1522	const struct ieee80211_rateset *rs;
1523	struct mbuf *m;
1524	uint8_t *frm;
1525
1526	if (vap->iv_state == IEEE80211_S_CAC) {
1527		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
1528		    "block %s frame in CAC state", "probe request");
1529		vap->iv_stats.is_tx_badstate++;
1530		return EIO;		/* XXX */
1531	}
1532
1533	/*
1534	 * Hold a reference on the node so it doesn't go away until after
1535	 * the xmit is complete all the way in the driver.  On error we
1536	 * will remove our reference.
1537	 */
1538	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1539		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1540		__func__, __LINE__,
1541		ni, ether_sprintf(ni->ni_macaddr),
1542		ieee80211_node_refcnt(ni)+1);
1543	ieee80211_ref_node(ni);
1544
1545	/*
1546	 * prreq frame format
1547	 *	[tlv] ssid
1548	 *	[tlv] supported rates
1549	 *	[tlv] RSN (optional)
1550	 *	[tlv] extended supported rates
1551	 *	[tlv] WPA (optional)
1552	 *	[tlv] user-specified ie's
1553	 */
1554	m = ieee80211_getmgtframe(&frm,
1555		 ic->ic_headroom + sizeof(struct ieee80211_frame),
1556	       	 2 + IEEE80211_NWID_LEN
1557	       + 2 + IEEE80211_RATE_SIZE
1558	       + sizeof(struct ieee80211_ie_wpa)
1559	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1560	       + sizeof(struct ieee80211_ie_wpa)
1561	       + (vap->iv_appie_probereq != NULL ?
1562		   vap->iv_appie_probereq->ie_len : 0)
1563	);
1564	if (m == NULL) {
1565		vap->iv_stats.is_tx_nobuf++;
1566		ieee80211_free_node(ni);
1567		return ENOMEM;
1568	}
1569
1570	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1571	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1572	frm = ieee80211_add_rates(frm, rs);
1573	if (vap->iv_flags & IEEE80211_F_WPA2) {
1574		if (vap->iv_rsn_ie != NULL)
1575			frm = add_ie(frm, vap->iv_rsn_ie);
1576		/* XXX else complain? */
1577	}
1578	frm = ieee80211_add_xrates(frm, rs);
1579	if (vap->iv_flags & IEEE80211_F_WPA1) {
1580		if (vap->iv_wpa_ie != NULL)
1581			frm = add_ie(frm, vap->iv_wpa_ie);
1582		/* XXX else complain? */
1583	}
1584	if (vap->iv_appie_probereq != NULL)
1585		frm = add_appie(frm, vap->iv_appie_probereq);
1586	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1587
1588	KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ieee80211_frame),
1589	    ("leading space %zd", M_LEADINGSPACE(m)));
1590	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1591	if (m == NULL) {
1592		/* NB: cannot happen */
1593		ieee80211_free_node(ni);
1594		return ENOMEM;
1595	}
1596
1597	wh = mtod(m, struct ieee80211_frame *);
1598	ieee80211_send_setup(ni, m,
1599	     IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1600	     IEEE80211_NONQOS_TID, sa, da, bssid);
1601	/* XXX power management? */
1602	m->m_flags |= M_ENCAP;		/* mark encapsulated */
1603
1604	M_WME_SETAC(m, WME_AC_BE);
1605
1606	IEEE80211_NODE_STAT(ni, tx_probereq);
1607	IEEE80211_NODE_STAT(ni, tx_mgmt);
1608
1609	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1610	    "send probe req on channel %u bssid %s ssid \"%.*s\"\n",
1611	    ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(bssid),
1612	    ssidlen, ssid);
1613
1614	memset(&params, 0, sizeof(params));
1615	params.ibp_pri = M_WME_GETAC(m);
1616	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1617	params.ibp_rate0 = tp->mgmtrate;
1618	if (IEEE80211_IS_MULTICAST(da)) {
1619		params.ibp_flags |= IEEE80211_BPF_NOACK;
1620		params.ibp_try0 = 1;
1621	} else
1622		params.ibp_try0 = tp->maxretry;
1623	params.ibp_power = ni->ni_txpower;
1624	return ic->ic_raw_xmit(ni, m, &params);
1625}
1626
1627/*
1628 * Calculate capability information for mgt frames.
1629 */
1630static uint16_t
1631getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan)
1632{
1633	struct ieee80211com *ic = vap->iv_ic;
1634	uint16_t capinfo;
1635
1636	KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode"));
1637
1638	if (vap->iv_opmode == IEEE80211_M_HOSTAP)
1639		capinfo = IEEE80211_CAPINFO_ESS;
1640	else if (vap->iv_opmode == IEEE80211_M_IBSS)
1641		capinfo = IEEE80211_CAPINFO_IBSS;
1642	else
1643		capinfo = 0;
1644	if (vap->iv_flags & IEEE80211_F_PRIVACY)
1645		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1646	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1647	    IEEE80211_IS_CHAN_2GHZ(chan))
1648		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1649	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1650		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1651	if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH))
1652		capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
1653	return capinfo;
1654}
1655
1656/*
1657 * Send a management frame.  The node is for the destination (or ic_bss
1658 * when in station mode).  Nodes other than ic_bss have their reference
1659 * count bumped to reflect our use for an indeterminant time.
1660 */
1661int
1662ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg)
1663{
1664#define	HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
1665#define	senderr(_x, _v)	do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
1666	struct ieee80211vap *vap = ni->ni_vap;
1667	struct ieee80211com *ic = ni->ni_ic;
1668	struct ieee80211_node *bss = vap->iv_bss;
1669	struct ieee80211_bpf_params params;
1670	struct mbuf *m;
1671	uint8_t *frm;
1672	uint16_t capinfo;
1673	int has_challenge, is_shared_key, ret, status;
1674
1675	KASSERT(ni != NULL, ("null node"));
1676
1677	/*
1678	 * Hold a reference on the node so it doesn't go away until after
1679	 * the xmit is complete all the way in the driver.  On error we
1680	 * will remove our reference.
1681	 */
1682	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1683		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1684		__func__, __LINE__,
1685		ni, ether_sprintf(ni->ni_macaddr),
1686		ieee80211_node_refcnt(ni)+1);
1687	ieee80211_ref_node(ni);
1688
1689	memset(&params, 0, sizeof(params));
1690	switch (type) {
1691
1692	case IEEE80211_FC0_SUBTYPE_AUTH:
1693		status = arg >> 16;
1694		arg &= 0xffff;
1695		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1696		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1697		    ni->ni_challenge != NULL);
1698
1699		/*
1700		 * Deduce whether we're doing open authentication or
1701		 * shared key authentication.  We do the latter if
1702		 * we're in the middle of a shared key authentication
1703		 * handshake or if we're initiating an authentication
1704		 * request and configured to use shared key.
1705		 */
1706		is_shared_key = has_challenge ||
1707		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1708		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1709		      bss->ni_authmode == IEEE80211_AUTH_SHARED);
1710
1711		m = ieee80211_getmgtframe(&frm,
1712			  ic->ic_headroom + sizeof(struct ieee80211_frame),
1713			  3 * sizeof(uint16_t)
1714			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1715				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
1716		);
1717		if (m == NULL)
1718			senderr(ENOMEM, is_tx_nobuf);
1719
1720		((uint16_t *)frm)[0] =
1721		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1722		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1723		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
1724		((uint16_t *)frm)[2] = htole16(status);/* status */
1725
1726		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1727			((uint16_t *)frm)[3] =
1728			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1729			    IEEE80211_ELEMID_CHALLENGE);
1730			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
1731			    IEEE80211_CHALLENGE_LEN);
1732			m->m_pkthdr.len = m->m_len =
1733				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
1734			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1735				IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
1736				    "request encrypt frame (%s)", __func__);
1737				/* mark frame for encryption */
1738				params.ibp_flags |= IEEE80211_BPF_CRYPTO;
1739			}
1740		} else
1741			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
1742
1743		/* XXX not right for shared key */
1744		if (status == IEEE80211_STATUS_SUCCESS)
1745			IEEE80211_NODE_STAT(ni, tx_auth);
1746		else
1747			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1748
1749		if (vap->iv_opmode == IEEE80211_M_STA)
1750			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1751				(void *) vap->iv_state);
1752		break;
1753
1754	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1755		IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
1756		    "send station deauthenticate (reason %d)", arg);
1757		m = ieee80211_getmgtframe(&frm,
1758			ic->ic_headroom + sizeof(struct ieee80211_frame),
1759			sizeof(uint16_t));
1760		if (m == NULL)
1761			senderr(ENOMEM, is_tx_nobuf);
1762		*(uint16_t *)frm = htole16(arg);	/* reason */
1763		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1764
1765		IEEE80211_NODE_STAT(ni, tx_deauth);
1766		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1767
1768		ieee80211_node_unauthorize(ni);		/* port closed */
1769		break;
1770
1771	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1772	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1773		/*
1774		 * asreq frame format
1775		 *	[2] capability information
1776		 *	[2] listen interval
1777		 *	[6*] current AP address (reassoc only)
1778		 *	[tlv] ssid
1779		 *	[tlv] supported rates
1780		 *	[tlv] extended supported rates
1781		 *	[4] power capability (optional)
1782		 *	[28] supported channels (optional)
1783		 *	[tlv] HT capabilities
1784		 *	[tlv] WME (optional)
1785		 *	[tlv] Vendor OUI HT capabilities (optional)
1786		 *	[tlv] Atheros capabilities (if negotiated)
1787		 *	[tlv] AppIE's (optional)
1788		 */
1789		m = ieee80211_getmgtframe(&frm,
1790			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1791			 sizeof(uint16_t)
1792		       + sizeof(uint16_t)
1793		       + IEEE80211_ADDR_LEN
1794		       + 2 + IEEE80211_NWID_LEN
1795		       + 2 + IEEE80211_RATE_SIZE
1796		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1797		       + 4
1798		       + 2 + 26
1799		       + sizeof(struct ieee80211_wme_info)
1800		       + sizeof(struct ieee80211_ie_htcap)
1801		       + 4 + sizeof(struct ieee80211_ie_htcap)
1802#ifdef IEEE80211_SUPPORT_SUPERG
1803		       + sizeof(struct ieee80211_ath_ie)
1804#endif
1805		       + (vap->iv_appie_wpa != NULL ?
1806				vap->iv_appie_wpa->ie_len : 0)
1807		       + (vap->iv_appie_assocreq != NULL ?
1808				vap->iv_appie_assocreq->ie_len : 0)
1809		);
1810		if (m == NULL)
1811			senderr(ENOMEM, is_tx_nobuf);
1812
1813		KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1814		    ("wrong mode %u", vap->iv_opmode));
1815		capinfo = IEEE80211_CAPINFO_ESS;
1816		if (vap->iv_flags & IEEE80211_F_PRIVACY)
1817			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1818		/*
1819		 * NB: Some 11a AP's reject the request when
1820		 *     short premable is set.
1821		 */
1822		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1823		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1824			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1825		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
1826		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1827			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1828		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
1829		    (vap->iv_flags & IEEE80211_F_DOTH))
1830			capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
1831		*(uint16_t *)frm = htole16(capinfo);
1832		frm += 2;
1833
1834		KASSERT(bss->ni_intval != 0, ("beacon interval is zero!"));
1835		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
1836						    bss->ni_intval));
1837		frm += 2;
1838
1839		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1840			IEEE80211_ADDR_COPY(frm, bss->ni_bssid);
1841			frm += IEEE80211_ADDR_LEN;
1842		}
1843
1844		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1845		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1846		if (vap->iv_flags & IEEE80211_F_WPA2) {
1847			if (vap->iv_rsn_ie != NULL)
1848				frm = add_ie(frm, vap->iv_rsn_ie);
1849			/* XXX else complain? */
1850		}
1851		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1852		if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) {
1853			frm = ieee80211_add_powercapability(frm,
1854			    ic->ic_curchan);
1855			frm = ieee80211_add_supportedchannels(frm, ic);
1856		}
1857		if ((vap->iv_flags_ext & IEEE80211_FEXT_HT) &&
1858		    ni->ni_ies.htcap_ie != NULL &&
1859		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP)
1860			frm = ieee80211_add_htcap(frm, ni);
1861		if (vap->iv_flags & IEEE80211_F_WPA1) {
1862			if (vap->iv_wpa_ie != NULL)
1863				frm = add_ie(frm, vap->iv_wpa_ie);
1864			/* XXX else complain */
1865		}
1866		if ((ic->ic_flags & IEEE80211_F_WME) &&
1867		    ni->ni_ies.wme_ie != NULL)
1868			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1869		if ((vap->iv_flags_ext & IEEE80211_FEXT_HT) &&
1870		    ni->ni_ies.htcap_ie != NULL &&
1871		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR)
1872			frm = ieee80211_add_htcap_vendor(frm, ni);
1873#ifdef IEEE80211_SUPPORT_SUPERG
1874		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) {
1875			frm = ieee80211_add_ath(frm,
1876				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
1877				((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
1878				 ni->ni_authmode != IEEE80211_AUTH_8021X) ?
1879				vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
1880		}
1881#endif /* IEEE80211_SUPPORT_SUPERG */
1882		if (vap->iv_appie_assocreq != NULL)
1883			frm = add_appie(frm, vap->iv_appie_assocreq);
1884		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1885
1886		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1887			(void *) vap->iv_state);
1888		break;
1889
1890	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1891	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1892		/*
1893		 * asresp frame format
1894		 *	[2] capability information
1895		 *	[2] status
1896		 *	[2] association ID
1897		 *	[tlv] supported rates
1898		 *	[tlv] extended supported rates
1899		 *	[tlv] HT capabilities (standard, if STA enabled)
1900		 *	[tlv] HT information (standard, if STA enabled)
1901		 *	[tlv] WME (if configured and STA enabled)
1902		 *	[tlv] HT capabilities (vendor OUI, if STA enabled)
1903		 *	[tlv] HT information (vendor OUI, if STA enabled)
1904		 *	[tlv] Atheros capabilities (if STA enabled)
1905		 *	[tlv] AppIE's (optional)
1906		 */
1907		m = ieee80211_getmgtframe(&frm,
1908			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1909			 sizeof(uint16_t)
1910		       + sizeof(uint16_t)
1911		       + sizeof(uint16_t)
1912		       + 2 + IEEE80211_RATE_SIZE
1913		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1914		       + sizeof(struct ieee80211_ie_htcap) + 4
1915		       + sizeof(struct ieee80211_ie_htinfo) + 4
1916		       + sizeof(struct ieee80211_wme_param)
1917#ifdef IEEE80211_SUPPORT_SUPERG
1918		       + sizeof(struct ieee80211_ath_ie)
1919#endif
1920		       + (vap->iv_appie_assocresp != NULL ?
1921				vap->iv_appie_assocresp->ie_len : 0)
1922		);
1923		if (m == NULL)
1924			senderr(ENOMEM, is_tx_nobuf);
1925
1926		capinfo = getcapinfo(vap, bss->ni_chan);
1927		*(uint16_t *)frm = htole16(capinfo);
1928		frm += 2;
1929
1930		*(uint16_t *)frm = htole16(arg);	/* status */
1931		frm += 2;
1932
1933		if (arg == IEEE80211_STATUS_SUCCESS) {
1934			*(uint16_t *)frm = htole16(ni->ni_associd);
1935			IEEE80211_NODE_STAT(ni, tx_assoc);
1936		} else
1937			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1938		frm += 2;
1939
1940		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1941		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1942		/* NB: respond according to what we received */
1943		if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
1944			frm = ieee80211_add_htcap(frm, ni);
1945			frm = ieee80211_add_htinfo(frm, ni);
1946		}
1947		if ((vap->iv_flags & IEEE80211_F_WME) &&
1948		    ni->ni_ies.wme_ie != NULL)
1949			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1950		if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
1951			frm = ieee80211_add_htcap_vendor(frm, ni);
1952			frm = ieee80211_add_htinfo_vendor(frm, ni);
1953		}
1954#ifdef IEEE80211_SUPPORT_SUPERG
1955		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
1956			frm = ieee80211_add_ath(frm,
1957				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
1958				((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
1959				 ni->ni_authmode != IEEE80211_AUTH_8021X) ?
1960				vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
1961#endif /* IEEE80211_SUPPORT_SUPERG */
1962		if (vap->iv_appie_assocresp != NULL)
1963			frm = add_appie(frm, vap->iv_appie_assocresp);
1964		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1965		break;
1966
1967	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1968		IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
1969		    "send station disassociate (reason %d)", arg);
1970		m = ieee80211_getmgtframe(&frm,
1971			ic->ic_headroom + sizeof(struct ieee80211_frame),
1972			sizeof(uint16_t));
1973		if (m == NULL)
1974			senderr(ENOMEM, is_tx_nobuf);
1975		*(uint16_t *)frm = htole16(arg);	/* reason */
1976		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1977
1978		IEEE80211_NODE_STAT(ni, tx_disassoc);
1979		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1980		break;
1981
1982	default:
1983		IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni,
1984		    "invalid mgmt frame type %u", type);
1985		senderr(EINVAL, is_tx_unknownmgt);
1986		/* NOTREACHED */
1987	}
1988
1989	/* NB: force non-ProbeResp frames to the highest queue */
1990	params.ibp_pri = WME_AC_VO;
1991	params.ibp_rate0 = bss->ni_txparms->mgmtrate;
1992	/* NB: we know all frames are unicast */
1993	params.ibp_try0 = bss->ni_txparms->maxretry;
1994	params.ibp_power = bss->ni_txpower;
1995	return ieee80211_mgmt_output(ni, m, type, &params);
1996bad:
1997	ieee80211_free_node(ni);
1998	return ret;
1999#undef senderr
2000#undef HTFLAGS
2001}
2002
2003/*
2004 * Return an mbuf with a probe response frame in it.
2005 * Space is left to prepend and 802.11 header at the
2006 * front but it's left to the caller to fill in.
2007 */
2008struct mbuf *
2009ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy)
2010{
2011	struct ieee80211vap *vap = bss->ni_vap;
2012	struct ieee80211com *ic = bss->ni_ic;
2013	const struct ieee80211_rateset *rs;
2014	struct mbuf *m;
2015	uint16_t capinfo;
2016	uint8_t *frm;
2017
2018	/*
2019	 * probe response frame format
2020	 *	[8] time stamp
2021	 *	[2] beacon interval
2022	 *	[2] cabability information
2023	 *	[tlv] ssid
2024	 *	[tlv] supported rates
2025	 *	[tlv] parameter set (FH/DS)
2026	 *	[tlv] parameter set (IBSS)
2027	 *	[tlv] country (optional)
2028	 *	[3] power control (optional)
2029	 *	[5] channel switch announcement (CSA) (optional)
2030	 *	[tlv] extended rate phy (ERP)
2031	 *	[tlv] extended supported rates
2032	 *	[tlv] RSN (optional)
2033	 *	[tlv] HT capabilities
2034	 *	[tlv] HT information
2035	 *	[tlv] WPA (optional)
2036	 *	[tlv] WME (optional)
2037	 *	[tlv] Vendor OUI HT capabilities (optional)
2038	 *	[tlv] Vendor OUI HT information (optional)
2039	 *	[tlv] Atheros capabilities
2040	 *	[tlv] AppIE's (optional)
2041	 */
2042	m = ieee80211_getmgtframe(&frm,
2043		 ic->ic_headroom + sizeof(struct ieee80211_frame),
2044		 8
2045	       + sizeof(uint16_t)
2046	       + sizeof(uint16_t)
2047	       + 2 + IEEE80211_NWID_LEN
2048	       + 2 + IEEE80211_RATE_SIZE
2049	       + 7	/* max(7,3) */
2050	       + IEEE80211_COUNTRY_MAX_SIZE
2051	       + 3
2052	       + sizeof(struct ieee80211_csa_ie)
2053	       + 3
2054	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2055	       + sizeof(struct ieee80211_ie_wpa)
2056	       + sizeof(struct ieee80211_ie_htcap)
2057	       + sizeof(struct ieee80211_ie_htinfo)
2058	       + sizeof(struct ieee80211_ie_wpa)
2059	       + sizeof(struct ieee80211_wme_param)
2060	       + 4 + sizeof(struct ieee80211_ie_htcap)
2061	       + 4 + sizeof(struct ieee80211_ie_htinfo)
2062#ifdef IEEE80211_SUPPORT_SUPERG
2063	       + sizeof(struct ieee80211_ath_ie)
2064#endif
2065	       + (vap->iv_appie_proberesp != NULL ?
2066			vap->iv_appie_proberesp->ie_len : 0)
2067	);
2068	if (m == NULL) {
2069		vap->iv_stats.is_tx_nobuf++;
2070		return NULL;
2071	}
2072
2073	memset(frm, 0, 8);	/* timestamp should be filled later */
2074	frm += 8;
2075	*(uint16_t *)frm = htole16(bss->ni_intval);
2076	frm += 2;
2077	capinfo = getcapinfo(vap, bss->ni_chan);
2078	*(uint16_t *)frm = htole16(capinfo);
2079	frm += 2;
2080
2081	frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen);
2082	rs = ieee80211_get_suprates(ic, bss->ni_chan);
2083	frm = ieee80211_add_rates(frm, rs);
2084
2085	if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) {
2086		*frm++ = IEEE80211_ELEMID_FHPARMS;
2087		*frm++ = 5;
2088		*frm++ = bss->ni_fhdwell & 0x00ff;
2089		*frm++ = (bss->ni_fhdwell >> 8) & 0x00ff;
2090		*frm++ = IEEE80211_FH_CHANSET(
2091		    ieee80211_chan2ieee(ic, bss->ni_chan));
2092		*frm++ = IEEE80211_FH_CHANPAT(
2093		    ieee80211_chan2ieee(ic, bss->ni_chan));
2094		*frm++ = bss->ni_fhindex;
2095	} else {
2096		*frm++ = IEEE80211_ELEMID_DSPARMS;
2097		*frm++ = 1;
2098		*frm++ = ieee80211_chan2ieee(ic, bss->ni_chan);
2099	}
2100
2101	if (vap->iv_opmode == IEEE80211_M_IBSS) {
2102		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2103		*frm++ = 2;
2104		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2105	}
2106	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2107	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2108		frm = ieee80211_add_countryie(frm, ic);
2109	if (vap->iv_flags & IEEE80211_F_DOTH) {
2110		if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan))
2111			frm = ieee80211_add_powerconstraint(frm, vap);
2112		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2113			frm = ieee80211_add_csa(frm, vap);
2114	}
2115	if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan))
2116		frm = ieee80211_add_erp(frm, ic);
2117	frm = ieee80211_add_xrates(frm, rs);
2118	if (vap->iv_flags & IEEE80211_F_WPA2) {
2119		if (vap->iv_rsn_ie != NULL)
2120			frm = add_ie(frm, vap->iv_rsn_ie);
2121		/* XXX else complain? */
2122	}
2123	/*
2124	 * NB: legacy 11b clients do not get certain ie's.
2125	 *     The caller identifies such clients by passing
2126	 *     a token in legacy to us.  Could expand this to be
2127	 *     any legacy client for stuff like HT ie's.
2128	 */
2129	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2130	    legacy != IEEE80211_SEND_LEGACY_11B) {
2131		frm = ieee80211_add_htcap(frm, bss);
2132		frm = ieee80211_add_htinfo(frm, bss);
2133	}
2134	if (vap->iv_flags & IEEE80211_F_WPA1) {
2135		if (vap->iv_wpa_ie != NULL)
2136			frm = add_ie(frm, vap->iv_wpa_ie);
2137		/* XXX else complain? */
2138	}
2139	if (vap->iv_flags & IEEE80211_F_WME)
2140		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2141	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
2142	    (vap->iv_flags_ext & IEEE80211_FEXT_HTCOMPAT) &&
2143	    legacy != IEEE80211_SEND_LEGACY_11B) {
2144		frm = ieee80211_add_htcap_vendor(frm, bss);
2145		frm = ieee80211_add_htinfo_vendor(frm, bss);
2146	}
2147#ifdef IEEE80211_SUPPORT_SUPERG
2148	if ((vap->iv_flags & IEEE80211_F_ATHEROS) &&
2149	    legacy != IEEE80211_SEND_LEGACY_11B)
2150		frm = ieee80211_add_athcaps(frm, bss);
2151#endif
2152	if (vap->iv_appie_proberesp != NULL)
2153		frm = add_appie(frm, vap->iv_appie_proberesp);
2154	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2155
2156	return m;
2157}
2158
2159/*
2160 * Send a probe response frame to the specified mac address.
2161 * This does not go through the normal mgt frame api so we
2162 * can specify the destination address and re-use the bss node
2163 * for the sta reference.
2164 */
2165int
2166ieee80211_send_proberesp(struct ieee80211vap *vap,
2167	const uint8_t da[IEEE80211_ADDR_LEN], int legacy)
2168{
2169	struct ieee80211_node *bss = vap->iv_bss;
2170	struct ieee80211com *ic = vap->iv_ic;
2171	struct ieee80211_frame *wh;
2172	struct mbuf *m;
2173
2174	if (vap->iv_state == IEEE80211_S_CAC) {
2175		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss,
2176		    "block %s frame in CAC state", "probe response");
2177		vap->iv_stats.is_tx_badstate++;
2178		return EIO;		/* XXX */
2179	}
2180
2181	/*
2182	 * Hold a reference on the node so it doesn't go away until after
2183	 * the xmit is complete all the way in the driver.  On error we
2184	 * will remove our reference.
2185	 */
2186	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2187	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2188	    __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr),
2189	    ieee80211_node_refcnt(bss)+1);
2190	ieee80211_ref_node(bss);
2191
2192	m = ieee80211_alloc_proberesp(bss, legacy);
2193	if (m == NULL) {
2194		ieee80211_free_node(bss);
2195		return ENOMEM;
2196	}
2197
2198	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2199	KASSERT(m != NULL, ("no room for header"));
2200
2201	wh = mtod(m, struct ieee80211_frame *);
2202	ieee80211_send_setup(bss, m,
2203	     IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP,
2204	     IEEE80211_NONQOS_TID, vap->iv_myaddr, da, bss->ni_bssid);
2205	/* XXX power management? */
2206	m->m_flags |= M_ENCAP;		/* mark encapsulated */
2207
2208	M_WME_SETAC(m, WME_AC_BE);
2209
2210	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
2211	    "send probe resp on channel %u to %s%s\n",
2212	    ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da),
2213	    legacy ? " <legacy>" : "");
2214	IEEE80211_NODE_STAT(bss, tx_mgmt);
2215
2216	return ic->ic_raw_xmit(bss, m, NULL);
2217}
2218
2219/*
2220 * Allocate and build a RTS (Request To Send) control frame.
2221 */
2222struct mbuf *
2223ieee80211_alloc_rts(struct ieee80211com *ic,
2224	const uint8_t ra[IEEE80211_ADDR_LEN],
2225	const uint8_t ta[IEEE80211_ADDR_LEN],
2226	uint16_t dur)
2227{
2228	struct ieee80211_frame_rts *rts;
2229	struct mbuf *m;
2230
2231	/* XXX honor ic_headroom */
2232	m = m_gethdr(M_DONTWAIT, MT_DATA);
2233	if (m != NULL) {
2234		rts = mtod(m, struct ieee80211_frame_rts *);
2235		rts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2236			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS;
2237		rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2238		*(u_int16_t *)rts->i_dur = htole16(dur);
2239		IEEE80211_ADDR_COPY(rts->i_ra, ra);
2240		IEEE80211_ADDR_COPY(rts->i_ta, ta);
2241
2242		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
2243	}
2244	return m;
2245}
2246
2247/*
2248 * Allocate and build a CTS (Clear To Send) control frame.
2249 */
2250struct mbuf *
2251ieee80211_alloc_cts(struct ieee80211com *ic,
2252	const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur)
2253{
2254	struct ieee80211_frame_cts *cts;
2255	struct mbuf *m;
2256
2257	/* XXX honor ic_headroom */
2258	m = m_gethdr(M_DONTWAIT, MT_DATA);
2259	if (m != NULL) {
2260		cts = mtod(m, struct ieee80211_frame_cts *);
2261		cts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
2262			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS;
2263		cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2264		*(u_int16_t *)cts->i_dur = htole16(dur);
2265		IEEE80211_ADDR_COPY(cts->i_ra, ra);
2266
2267		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
2268	}
2269	return m;
2270}
2271
2272static void
2273ieee80211_tx_mgt_timeout(void *arg)
2274{
2275	struct ieee80211_node *ni = arg;
2276	struct ieee80211vap *vap = ni->ni_vap;
2277
2278	if (vap->iv_state != IEEE80211_S_INIT &&
2279	    (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2280		/*
2281		 * NB: it's safe to specify a timeout as the reason here;
2282		 *     it'll only be used in the right state.
2283		 */
2284		ieee80211_new_state(vap, IEEE80211_S_SCAN,
2285			IEEE80211_SCAN_FAIL_TIMEOUT);
2286	}
2287}
2288
2289static void
2290ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
2291{
2292	struct ieee80211vap *vap = ni->ni_vap;
2293	enum ieee80211_state ostate = (enum ieee80211_state) arg;
2294
2295	/*
2296	 * Frame transmit completed; arrange timer callback.  If
2297	 * transmit was successfuly we wait for response.  Otherwise
2298	 * we arrange an immediate callback instead of doing the
2299	 * callback directly since we don't know what state the driver
2300	 * is in (e.g. what locks it is holding).  This work should
2301	 * not be too time-critical and not happen too often so the
2302	 * added overhead is acceptable.
2303	 *
2304	 * XXX what happens if !acked but response shows up before callback?
2305	 */
2306	if (vap->iv_state == ostate)
2307		callout_reset(&vap->iv_mgtsend,
2308			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
2309			ieee80211_tx_mgt_timeout, ni);
2310}
2311
2312static void
2313ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm,
2314	struct ieee80211_beacon_offsets *bo, struct ieee80211_node *ni)
2315{
2316	struct ieee80211vap *vap = ni->ni_vap;
2317	struct ieee80211com *ic = ni->ni_ic;
2318	struct ieee80211_rateset *rs = &ni->ni_rates;
2319	uint16_t capinfo;
2320
2321	/*
2322	 * beacon frame format
2323	 *	[8] time stamp
2324	 *	[2] beacon interval
2325	 *	[2] cabability information
2326	 *	[tlv] ssid
2327	 *	[tlv] supported rates
2328	 *	[3] parameter set (DS)
2329	 *	[8] CF parameter set (optional)
2330	 *	[tlv] parameter set (IBSS/TIM)
2331	 *	[tlv] country (optional)
2332	 *	[3] power control (optional)
2333	 *	[5] channel switch announcement (CSA) (optional)
2334	 *	[tlv] extended rate phy (ERP)
2335	 *	[tlv] extended supported rates
2336	 *	[tlv] RSN parameters
2337	 *	[tlv] HT capabilities
2338	 *	[tlv] HT information
2339	 * XXX Vendor-specific OIDs (e.g. Atheros)
2340	 *	[tlv] WPA parameters
2341	 *	[tlv] WME parameters
2342	 *	[tlv] Vendor OUI HT capabilities (optional)
2343	 *	[tlv] Vendor OUI HT information (optional)
2344	 *	[tlv] Atheros capabilities (optional)
2345	 *	[tlv] TDMA parameters (optional)
2346	 *	[tlv] application data (optional)
2347	 */
2348
2349	memset(bo, 0, sizeof(*bo));
2350
2351	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
2352	frm += 8;
2353	*(uint16_t *)frm = htole16(ni->ni_intval);
2354	frm += 2;
2355	capinfo = getcapinfo(vap, ni->ni_chan);
2356	bo->bo_caps = (uint16_t *)frm;
2357	*(uint16_t *)frm = htole16(capinfo);
2358	frm += 2;
2359	*frm++ = IEEE80211_ELEMID_SSID;
2360	if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) {
2361		*frm++ = ni->ni_esslen;
2362		memcpy(frm, ni->ni_essid, ni->ni_esslen);
2363		frm += ni->ni_esslen;
2364	} else
2365		*frm++ = 0;
2366	frm = ieee80211_add_rates(frm, rs);
2367	if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) {
2368		*frm++ = IEEE80211_ELEMID_DSPARMS;
2369		*frm++ = 1;
2370		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
2371	}
2372	if (ic->ic_flags & IEEE80211_F_PCF) {
2373		bo->bo_cfp = frm;
2374		frm = ieee80211_add_cfparms(frm, ic);
2375	}
2376	bo->bo_tim = frm;
2377	if (vap->iv_opmode == IEEE80211_M_IBSS) {
2378		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2379		*frm++ = 2;
2380		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2381		bo->bo_tim_len = 0;
2382	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
2383		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
2384
2385		tie->tim_ie = IEEE80211_ELEMID_TIM;
2386		tie->tim_len = 4;	/* length */
2387		tie->tim_count = 0;	/* DTIM count */
2388		tie->tim_period = vap->iv_dtim_period;	/* DTIM period */
2389		tie->tim_bitctl = 0;	/* bitmap control */
2390		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
2391		frm += sizeof(struct ieee80211_tim_ie);
2392		bo->bo_tim_len = 1;
2393	}
2394	bo->bo_tim_trailer = frm;
2395	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
2396	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
2397		frm = ieee80211_add_countryie(frm, ic);
2398	if (vap->iv_flags & IEEE80211_F_DOTH) {
2399		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
2400			frm = ieee80211_add_powerconstraint(frm, vap);
2401		bo->bo_csa = frm;
2402		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
2403			frm = ieee80211_add_csa(frm, vap);
2404	} else
2405		bo->bo_csa = frm;
2406	if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) {
2407		bo->bo_erp = frm;
2408		frm = ieee80211_add_erp(frm, ic);
2409	}
2410	frm = ieee80211_add_xrates(frm, rs);
2411	if (vap->iv_flags & IEEE80211_F_WPA2) {
2412		if (vap->iv_rsn_ie != NULL)
2413			frm = add_ie(frm, vap->iv_rsn_ie);
2414		/* XXX else complain */
2415	}
2416	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
2417		frm = ieee80211_add_htcap(frm, ni);
2418		bo->bo_htinfo = frm;
2419		frm = ieee80211_add_htinfo(frm, ni);
2420	}
2421	if (vap->iv_flags & IEEE80211_F_WPA1) {
2422		if (vap->iv_wpa_ie != NULL)
2423			frm = add_ie(frm, vap->iv_wpa_ie);
2424		/* XXX else complain */
2425	}
2426	if (vap->iv_flags & IEEE80211_F_WME) {
2427		bo->bo_wme = frm;
2428		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2429	}
2430	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2431	    (vap->iv_flags_ext & IEEE80211_FEXT_HTCOMPAT)) {
2432		frm = ieee80211_add_htcap_vendor(frm, ni);
2433		frm = ieee80211_add_htinfo_vendor(frm, ni);
2434	}
2435#ifdef IEEE80211_SUPPORT_SUPERG
2436	if (vap->iv_flags & IEEE80211_F_ATHEROS) {
2437		bo->bo_ath = frm;
2438		frm = ieee80211_add_athcaps(frm, ni);
2439	}
2440#endif
2441#ifdef IEEE80211_SUPPORT_TDMA
2442	if (vap->iv_caps & IEEE80211_C_TDMA) {
2443		bo->bo_tdma = frm;
2444		frm = ieee80211_add_tdma(frm, vap);
2445	}
2446#endif
2447	if (vap->iv_appie_beacon != NULL) {
2448		bo->bo_appie = frm;
2449		bo->bo_appie_len = vap->iv_appie_beacon->ie_len;
2450		frm = add_appie(frm, vap->iv_appie_beacon);
2451	}
2452	bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
2453	bo->bo_csa_trailer_len = frm - bo->bo_csa;
2454	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2455}
2456
2457/*
2458 * Allocate a beacon frame and fillin the appropriate bits.
2459 */
2460struct mbuf *
2461ieee80211_beacon_alloc(struct ieee80211_node *ni,
2462	struct ieee80211_beacon_offsets *bo)
2463{
2464	struct ieee80211vap *vap = ni->ni_vap;
2465	struct ieee80211com *ic = ni->ni_ic;
2466	struct ifnet *ifp = vap->iv_ifp;
2467	struct ieee80211_frame *wh;
2468	struct mbuf *m;
2469	int pktlen;
2470	uint8_t *frm;
2471
2472	/*
2473	 * beacon frame format
2474	 *	[8] time stamp
2475	 *	[2] beacon interval
2476	 *	[2] cabability information
2477	 *	[tlv] ssid
2478	 *	[tlv] supported rates
2479	 *	[3] parameter set (DS)
2480	 *	[8] CF parameter set (optional)
2481	 *	[tlv] parameter set (IBSS/TIM)
2482	 *	[tlv] country (optional)
2483	 *	[3] power control (optional)
2484	 *	[5] channel switch announcement (CSA) (optional)
2485	 *	[tlv] extended rate phy (ERP)
2486	 *	[tlv] extended supported rates
2487	 *	[tlv] RSN parameters
2488	 *	[tlv] HT capabilities
2489	 *	[tlv] HT information
2490	 *	[tlv] Vendor OUI HT capabilities (optional)
2491	 *	[tlv] Vendor OUI HT information (optional)
2492	 * XXX Vendor-specific OIDs (e.g. Atheros)
2493	 *	[tlv] WPA parameters
2494	 *	[tlv] WME parameters
2495	 *	[tlv] TDMA parameters (optional)
2496	 *	[tlv] application data (optional)
2497	 * NB: we allocate the max space required for the TIM bitmap.
2498	 * XXX how big is this?
2499	 */
2500	pktlen =   8					/* time stamp */
2501		 + sizeof(uint16_t)			/* beacon interval */
2502		 + sizeof(uint16_t)			/* capabilities */
2503		 + 2 + ni->ni_esslen			/* ssid */
2504	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
2505	         + 2 + 1				/* DS parameters */
2506		 + 2 + 6				/* CF parameters */
2507		 + 2 + 4 + vap->iv_tim_len		/* DTIM/IBSSPARMS */
2508		 + IEEE80211_COUNTRY_MAX_SIZE		/* country */
2509		 + 2 + 1				/* power control */
2510	         + sizeof(struct ieee80211_csa_ie)	/* CSA */
2511		 + 2 + 1				/* ERP */
2512	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2513		 + (vap->iv_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
2514			2*sizeof(struct ieee80211_ie_wpa) : 0)
2515		 /* XXX conditional? */
2516		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
2517		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
2518		 + (vap->iv_caps & IEEE80211_C_WME ?	/* WME */
2519			sizeof(struct ieee80211_wme_param) : 0)
2520#ifdef IEEE80211_SUPPORT_SUPERG
2521		 + sizeof(struct ieee80211_ath_ie)	/* ATH */
2522#endif
2523#ifdef IEEE80211_SUPPORT_TDMA
2524		 + (vap->iv_caps & IEEE80211_C_TDMA ?	/* TDMA */
2525			sizeof(struct ieee80211_tdma_param) : 0)
2526#endif
2527		 + IEEE80211_MAX_APPIE
2528		 ;
2529	m = ieee80211_getmgtframe(&frm,
2530		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
2531	if (m == NULL) {
2532		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
2533			"%s: cannot get buf; size %u\n", __func__, pktlen);
2534		vap->iv_stats.is_tx_nobuf++;
2535		return NULL;
2536	}
2537	ieee80211_beacon_construct(m, frm, bo, ni);
2538
2539	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2540	KASSERT(m != NULL, ("no space for 802.11 header?"));
2541	wh = mtod(m, struct ieee80211_frame *);
2542	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2543	    IEEE80211_FC0_SUBTYPE_BEACON;
2544	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2545	*(uint16_t *)wh->i_dur = 0;
2546	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2547	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
2548	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
2549	*(uint16_t *)wh->i_seq = 0;
2550
2551	return m;
2552}
2553
2554/*
2555 * Update the dynamic parts of a beacon frame based on the current state.
2556 */
2557int
2558ieee80211_beacon_update(struct ieee80211_node *ni,
2559	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
2560{
2561	struct ieee80211vap *vap = ni->ni_vap;
2562	struct ieee80211com *ic = ni->ni_ic;
2563	int len_changed = 0;
2564	uint16_t capinfo;
2565
2566	IEEE80211_LOCK(ic);
2567	/*
2568	 * Handle 11h channel change when we've reached the count.
2569	 * We must recalculate the beacon frame contents to account
2570	 * for the new channel.  Note we do this only for the first
2571	 * vap that reaches this point; subsequent vaps just update
2572	 * their beacon state to reflect the recalculated channel.
2573	 */
2574	if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) &&
2575	    vap->iv_csa_count == ic->ic_csa_count) {
2576		vap->iv_csa_count = 0;
2577		/*
2578		 * Effect channel change before reconstructing the beacon
2579		 * frame contents as many places reference ni_chan.
2580		 */
2581		if (ic->ic_csa_newchan != NULL)
2582			ieee80211_csa_completeswitch(ic);
2583		/*
2584		 * NB: ieee80211_beacon_construct clears all pending
2585		 * updates in bo_flags so we don't need to explicitly
2586		 * clear IEEE80211_BEACON_CSA.
2587		 */
2588		ieee80211_beacon_construct(m,
2589		    mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), bo, ni);
2590
2591		/* XXX do WME aggressive mode processing? */
2592		IEEE80211_UNLOCK(ic);
2593		return 1;		/* just assume length changed */
2594	}
2595
2596	/* XXX faster to recalculate entirely or just changes? */
2597	capinfo = getcapinfo(vap, ni->ni_chan);
2598	*bo->bo_caps = htole16(capinfo);
2599
2600	if (vap->iv_flags & IEEE80211_F_WME) {
2601		struct ieee80211_wme_state *wme = &ic->ic_wme;
2602
2603		/*
2604		 * Check for agressive mode change.  When there is
2605		 * significant high priority traffic in the BSS
2606		 * throttle back BE traffic by using conservative
2607		 * parameters.  Otherwise BE uses agressive params
2608		 * to optimize performance of legacy/non-QoS traffic.
2609		 */
2610		if (wme->wme_flags & WME_F_AGGRMODE) {
2611			if (wme->wme_hipri_traffic >
2612			    wme->wme_hipri_switch_thresh) {
2613				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2614				    "%s: traffic %u, disable aggressive mode\n",
2615				    __func__, wme->wme_hipri_traffic);
2616				wme->wme_flags &= ~WME_F_AGGRMODE;
2617				ieee80211_wme_updateparams_locked(vap);
2618				wme->wme_hipri_traffic =
2619					wme->wme_hipri_switch_hysteresis;
2620			} else
2621				wme->wme_hipri_traffic = 0;
2622		} else {
2623			if (wme->wme_hipri_traffic <=
2624			    wme->wme_hipri_switch_thresh) {
2625				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
2626				    "%s: traffic %u, enable aggressive mode\n",
2627				    __func__, wme->wme_hipri_traffic);
2628				wme->wme_flags |= WME_F_AGGRMODE;
2629				ieee80211_wme_updateparams_locked(vap);
2630				wme->wme_hipri_traffic = 0;
2631			} else
2632				wme->wme_hipri_traffic =
2633					wme->wme_hipri_switch_hysteresis;
2634		}
2635		if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
2636			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
2637			clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
2638		}
2639	}
2640
2641	if (isset(bo->bo_flags,  IEEE80211_BEACON_HTINFO)) {
2642		ieee80211_ht_update_beacon(vap, bo);
2643		clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
2644	}
2645#ifdef IEEE80211_SUPPORT_TDMA
2646	if (vap->iv_caps & IEEE80211_C_TDMA) {
2647		/*
2648		 * NB: the beacon is potentially updated every TBTT.
2649		 */
2650		ieee80211_tdma_update_beacon(vap, bo);
2651	}
2652#endif
2653	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
2654		struct ieee80211_tim_ie *tie =
2655			(struct ieee80211_tim_ie *) bo->bo_tim;
2656		if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
2657			u_int timlen, timoff, i;
2658			/*
2659			 * ATIM/DTIM needs updating.  If it fits in the
2660			 * current space allocated then just copy in the
2661			 * new bits.  Otherwise we need to move any trailing
2662			 * data to make room.  Note that we know there is
2663			 * contiguous space because ieee80211_beacon_allocate
2664			 * insures there is space in the mbuf to write a
2665			 * maximal-size virtual bitmap (based on iv_max_aid).
2666			 */
2667			/*
2668			 * Calculate the bitmap size and offset, copy any
2669			 * trailer out of the way, and then copy in the
2670			 * new bitmap and update the information element.
2671			 * Note that the tim bitmap must contain at least
2672			 * one byte and any offset must be even.
2673			 */
2674			if (vap->iv_ps_pending != 0) {
2675				timoff = 128;		/* impossibly large */
2676				for (i = 0; i < vap->iv_tim_len; i++)
2677					if (vap->iv_tim_bitmap[i]) {
2678						timoff = i &~ 1;
2679						break;
2680					}
2681				KASSERT(timoff != 128, ("tim bitmap empty!"));
2682				for (i = vap->iv_tim_len-1; i >= timoff; i--)
2683					if (vap->iv_tim_bitmap[i])
2684						break;
2685				timlen = 1 + (i - timoff);
2686			} else {
2687				timoff = 0;
2688				timlen = 1;
2689			}
2690			if (timlen != bo->bo_tim_len) {
2691				/* copy up/down trailer */
2692				int adjust = tie->tim_bitmap+timlen
2693					   - bo->bo_tim_trailer;
2694				ovbcopy(bo->bo_tim_trailer,
2695				    bo->bo_tim_trailer+adjust,
2696				    bo->bo_tim_trailer_len);
2697				bo->bo_tim_trailer += adjust;
2698				bo->bo_erp += adjust;
2699				bo->bo_htinfo += adjust;
2700#ifdef IEEE80211_SUPERG_SUPPORT
2701				bo->bo_ath += adjust;
2702#endif
2703#ifdef IEEE80211_TDMA_SUPPORT
2704				bo->bo_tdma += adjust;
2705#endif
2706				bo->bo_appie += adjust;
2707				bo->bo_wme += adjust;
2708				bo->bo_csa += adjust;
2709				bo->bo_tim_len = timlen;
2710
2711				/* update information element */
2712				tie->tim_len = 3 + timlen;
2713				tie->tim_bitctl = timoff;
2714				len_changed = 1;
2715			}
2716			memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff,
2717				bo->bo_tim_len);
2718
2719			clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
2720
2721			IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER,
2722				"%s: TIM updated, pending %u, off %u, len %u\n",
2723				__func__, vap->iv_ps_pending, timoff, timlen);
2724		}
2725		/* count down DTIM period */
2726		if (tie->tim_count == 0)
2727			tie->tim_count = tie->tim_period - 1;
2728		else
2729			tie->tim_count--;
2730		/* update state for buffered multicast frames on DTIM */
2731		if (mcast && tie->tim_count == 0)
2732			tie->tim_bitctl |= 1;
2733		else
2734			tie->tim_bitctl &= ~1;
2735		if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) {
2736			struct ieee80211_csa_ie *csa =
2737			    (struct ieee80211_csa_ie *) bo->bo_csa;
2738
2739			/*
2740			 * Insert or update CSA ie.  If we're just starting
2741			 * to count down to the channel switch then we need
2742			 * to insert the CSA ie.  Otherwise we just need to
2743			 * drop the count.  The actual change happens above
2744			 * when the vap's count reaches the target count.
2745			 */
2746			if (vap->iv_csa_count == 0) {
2747				memmove(&csa[1], csa, bo->bo_csa_trailer_len);
2748				bo->bo_erp += sizeof(*csa);
2749				bo->bo_htinfo += sizeof(*csa);
2750				bo->bo_wme += sizeof(*csa);
2751#ifdef IEEE80211_SUPERG_SUPPORT
2752				bo->bo_ath += sizeof(*csa);
2753#endif
2754#ifdef IEEE80211_TDMA_SUPPORT
2755				bo->bo_tdma += sizeof(*csa);
2756#endif
2757				bo->bo_appie += sizeof(*csa);
2758				bo->bo_csa_trailer_len += sizeof(*csa);
2759				bo->bo_tim_trailer_len += sizeof(*csa);
2760				m->m_len += sizeof(*csa);
2761				m->m_pkthdr.len += sizeof(*csa);
2762
2763				ieee80211_add_csa(bo->bo_csa, vap);
2764			} else
2765				csa->csa_count--;
2766			vap->iv_csa_count++;
2767			/* NB: don't clear IEEE80211_BEACON_CSA */
2768		}
2769		if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
2770			/*
2771			 * ERP element needs updating.
2772			 */
2773			(void) ieee80211_add_erp(bo->bo_erp, ic);
2774			clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
2775		}
2776#ifdef IEEE80211_SUPPORT_SUPERG
2777		if (isset(bo->bo_flags,  IEEE80211_BEACON_ATH)) {
2778			ieee80211_add_athcaps(bo->bo_ath, ni);
2779			clrbit(bo->bo_flags, IEEE80211_BEACON_ATH);
2780		}
2781#endif
2782	}
2783	if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) {
2784		const struct ieee80211_appie *aie = vap->iv_appie_beacon;
2785		int aielen;
2786		uint8_t *frm;
2787
2788		aielen = 0;
2789		if (aie != NULL)
2790			aielen += aie->ie_len;
2791		if (aielen != bo->bo_appie_len) {
2792			/* copy up/down trailer */
2793			int adjust = aielen - bo->bo_appie_len;
2794			ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust,
2795				bo->bo_tim_trailer_len);
2796			bo->bo_tim_trailer += adjust;
2797			bo->bo_appie += adjust;
2798			bo->bo_appie_len = aielen;
2799
2800			len_changed = 1;
2801		}
2802		frm = bo->bo_appie;
2803		if (aie != NULL)
2804			frm  = add_appie(frm, aie);
2805		clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE);
2806	}
2807	IEEE80211_UNLOCK(ic);
2808
2809	return len_changed;
2810}
2811