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