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