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