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