ieee80211_output.c revision 170360
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2007 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 170360 2007-06-06 04:56:04Z sam $");
29
30#include "opt_inet.h"
31
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/mbuf.h>
35#include <sys/kernel.h>
36#include <sys/endian.h>
37
38#include <sys/socket.h>
39
40#include <net/bpf.h>
41#include <net/ethernet.h>
42#include <net/if.h>
43#include <net/if_llc.h>
44#include <net/if_media.h>
45#include <net/if_vlan_var.h>
46
47#include <net80211/ieee80211_var.h>
48
49#ifdef INET
50#include <netinet/in.h>
51#include <netinet/if_ether.h>
52#include <netinet/in_systm.h>
53#include <netinet/ip.h>
54#endif
55
56#ifdef IEEE80211_DEBUG
57/*
58 * Decide if an outbound management frame should be
59 * printed when debugging is enabled.  This filters some
60 * of the less interesting frames that come frequently
61 * (e.g. beacons).
62 */
63static __inline int
64doprint(struct ieee80211com *ic, int subtype)
65{
66	switch (subtype) {
67	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
68		return (ic->ic_opmode == IEEE80211_M_IBSS);
69	}
70	return 1;
71}
72#endif
73
74/*
75 * Set the direction field and address fields of an outgoing
76 * non-QoS frame.  Note this should be called early on in
77 * constructing a frame as it sets i_fc[1]; other bits can
78 * then be or'd in.
79 */
80static void
81ieee80211_send_setup(struct ieee80211com *ic,
82	struct ieee80211_node *ni,
83	struct ieee80211_frame *wh,
84	int type,
85	const u_int8_t sa[IEEE80211_ADDR_LEN],
86	const u_int8_t da[IEEE80211_ADDR_LEN],
87	const u_int8_t bssid[IEEE80211_ADDR_LEN])
88{
89#define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
90
91	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
92	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
93		switch (ic->ic_opmode) {
94		case IEEE80211_M_STA:
95			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
96			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
97			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
98			IEEE80211_ADDR_COPY(wh->i_addr3, da);
99			break;
100		case IEEE80211_M_IBSS:
101		case IEEE80211_M_AHDEMO:
102			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
103			IEEE80211_ADDR_COPY(wh->i_addr1, da);
104			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
105			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
106			break;
107		case IEEE80211_M_HOSTAP:
108			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
109			IEEE80211_ADDR_COPY(wh->i_addr1, da);
110			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
111			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
112			break;
113		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
114			break;
115		}
116	} else {
117		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
118		IEEE80211_ADDR_COPY(wh->i_addr1, da);
119		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
120		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
121	}
122	*(u_int16_t *)&wh->i_dur[0] = 0;
123	/* NB: use non-QoS tid */
124	*(u_int16_t *)&wh->i_seq[0] =
125	    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
126	ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
127#undef WH4
128}
129
130/*
131 * Send a management frame to the specified node.  The node pointer
132 * must have a reference as the pointer will be passed to the driver
133 * and potentially held for a long time.  If the frame is successfully
134 * dispatched to the driver, then it is responsible for freeing the
135 * reference (and potentially free'ing up any associated storage).
136 */
137static int
138ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
139    struct mbuf *m, int type, int timer)
140{
141	struct ifnet *ifp = ic->ic_ifp;
142	struct ieee80211_frame *wh;
143
144	KASSERT(ni != NULL, ("null node"));
145
146	/*
147	 * Yech, hack alert!  We want to pass the node down to the
148	 * driver's start routine.  If we don't do so then the start
149	 * routine must immediately look it up again and that can
150	 * cause a lock order reversal if, for example, this frame
151	 * is being sent because the station is being timedout and
152	 * the frame being sent is a DEAUTH message.  We could stick
153	 * this in an m_tag and tack that on to the mbuf.  However
154	 * that's rather expensive to do for every frame so instead
155	 * we stuff it in the rcvif field since outbound frames do
156	 * not (presently) use this.
157	 */
158	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
159	if (m == NULL)
160		return ENOMEM;
161	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
162	m->m_pkthdr.rcvif = (void *)ni;
163
164	wh = mtod(m, struct ieee80211_frame *);
165	ieee80211_send_setup(ic, ni, wh,
166		IEEE80211_FC0_TYPE_MGT | type,
167		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
168	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
169		m->m_flags &= ~M_LINK0;
170		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
171			"[%s] encrypting frame (%s)\n",
172			ether_sprintf(wh->i_addr1), __func__);
173		wh->i_fc[1] |= IEEE80211_FC1_WEP;
174	}
175#ifdef IEEE80211_DEBUG
176	/* avoid printing too many frames */
177	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
178	    ieee80211_msg_dumppkts(ic)) {
179		printf("[%s] send %s on channel %u\n",
180		    ether_sprintf(wh->i_addr1),
181		    ieee80211_mgt_subtype_name[
182			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
183				IEEE80211_FC0_SUBTYPE_SHIFT],
184		    ieee80211_chan2ieee(ic, ic->ic_curchan));
185	}
186#endif
187	IEEE80211_NODE_STAT(ni, tx_mgmt);
188	IF_ENQUEUE(&ic->ic_mgtq, m);
189	if (timer) {
190		/*
191		 * Set the mgt frame timeout.
192		 */
193		ic->ic_mgt_timer = timer;
194		ifp->if_timer = 1;
195	}
196	if_start(ifp);
197	return 0;
198}
199
200/*
201 * Raw packet transmit stub for legacy drivers.
202 * Send the packet through the mgt q so we bypass
203 * the normal encapsulation work.
204 */
205int
206ieee80211_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
207	const struct ieee80211_bpf_params *params)
208{
209	struct ieee80211com *ic = ni->ni_ic;
210	struct ifnet *ifp = ic->ic_ifp;
211
212	m->m_pkthdr.rcvif = (void *) ni;
213	IF_ENQUEUE(&ic->ic_mgtq, m);
214	if_start(ifp);
215	ifp->if_opackets++;
216
217	return 0;
218}
219
220/*
221 * 802.11 output routine. This is (currently) used only to
222 * connect bpf write calls to the 802.11 layer for injecting
223 * raw 802.11 frames.  Note we locate the ieee80211com from
224 * the ifnet using a spare field setup at attach time.  This
225 * will go away when the virtual ap support comes in.
226 */
227int
228ieee80211_output(struct ifnet *ifp, struct mbuf *m,
229	struct sockaddr *dst, struct rtentry *rt0)
230{
231#define senderr(e) do { error = (e); goto bad;} while (0)
232	struct ieee80211com *ic = ifp->if_spare2;	/* XXX */
233	struct ieee80211_node *ni = NULL;
234	struct ieee80211_frame *wh;
235	int error;
236
237	/*
238	 * Hand to the 802.3 code if not tagged as
239	 * a raw 802.11 frame.
240	 */
241	if (dst->sa_family != AF_IEEE80211)
242		return ether_output(ifp, m, dst, rt0);
243#ifdef MAC
244	error = mac_check_ifnet_transmit(ifp, m);
245	if (error)
246		senderr(error);
247#endif
248	if (ifp->if_flags & IFF_MONITOR)
249		senderr(ENETDOWN);
250	if ((ifp->if_flags & IFF_UP) == 0)
251		senderr(ENETDOWN);
252
253	/* XXX bypass bridge, pfil, carp, etc. */
254
255	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
256		senderr(EIO);	/* XXX */
257	wh = mtod(m, struct ieee80211_frame *);
258	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
259	    IEEE80211_FC0_VERSION_0)
260		senderr(EIO);	/* XXX */
261
262	/* locate destination node */
263	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
264	case IEEE80211_FC1_DIR_NODS:
265	case IEEE80211_FC1_DIR_FROMDS:
266		ni = ieee80211_find_txnode(ic, wh->i_addr1);
267		break;
268	case IEEE80211_FC1_DIR_TODS:
269	case IEEE80211_FC1_DIR_DSTODS:
270		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
271			senderr(EIO);	/* XXX */
272		ni = ieee80211_find_txnode(ic, wh->i_addr3);
273		break;
274	default:
275		senderr(EIO);	/* XXX */
276	}
277	if (ni == NULL) {
278		/*
279		 * Permit packets w/ bpf params through regardless
280		 * (see below about sa_len).
281		 */
282		if (dst->sa_len == 0)
283			senderr(EHOSTUNREACH);
284		ni = ieee80211_ref_node(ic->ic_bss);
285	}
286
287	/* XXX ctrl frames should go through */
288	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
289	    (m->m_flags & M_PWR_SAV) == 0) {
290		/*
291		 * Station in power save mode; pass the frame
292		 * to the 802.11 layer and continue.  We'll get
293		 * the frame back when the time is right.
294		 */
295		ieee80211_pwrsave(ic, ni, m);
296		error = 0;
297		goto reclaim;
298	}
299
300	/* calculate priority so drivers can find the tx queue */
301	/* XXX assumes an 802.3 frame */
302	if (ieee80211_classify(ic, m, ni))
303		senderr(EIO);		/* XXX */
304
305	BPF_MTAP(ifp, m);
306	/*
307	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
308	 * present by setting the sa_len field of the sockaddr (yes,
309	 * this is a hack).
310	 * NB: we assume sa_data is suitably aligned to cast.
311	 */
312	return ic->ic_raw_xmit(ni, m, (const struct ieee80211_bpf_params *)
313		(dst->sa_len ? dst->sa_data : NULL));
314bad:
315	if (m != NULL)
316		m_freem(m);
317reclaim:
318	if (ni != NULL)
319		ieee80211_free_node(ni);
320	return error;
321#undef senderr
322}
323
324/*
325 * Send a null data frame to the specified node.
326 *
327 * NB: the caller is assumed to have setup a node reference
328 *     for use; this is necessary to deal with a race condition
329 *     when probing for inactive stations.
330 */
331int
332ieee80211_send_nulldata(struct ieee80211_node *ni)
333{
334	struct ieee80211com *ic = ni->ni_ic;
335	struct ifnet *ifp = ic->ic_ifp;
336	struct mbuf *m;
337	struct ieee80211_frame *wh;
338
339	MGETHDR(m, M_NOWAIT, MT_DATA);
340	if (m == NULL) {
341		/* XXX debug msg */
342		ic->ic_stats.is_tx_nobuf++;
343		ieee80211_unref_node(&ni);
344		return ENOMEM;
345	}
346	m->m_pkthdr.rcvif = (void *) ni;
347
348	wh = mtod(m, struct ieee80211_frame *);
349	ieee80211_send_setup(ic, ni, wh,
350		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
351		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
352	/* NB: power management bit is never sent by an AP */
353	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
354	    ic->ic_opmode != IEEE80211_M_HOSTAP)
355		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
356	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
357
358	IEEE80211_NODE_STAT(ni, tx_data);
359
360	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
361	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
362	    ether_sprintf(ni->ni_macaddr),
363	    ieee80211_chan2ieee(ic, ic->ic_curchan),
364	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
365
366	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
367	if_start(ifp);
368
369	return 0;
370}
371
372/*
373 * Assign priority to a frame based on any vlan tag assigned
374 * to the station and/or any Diffserv setting in an IP header.
375 * Finally, if an ACM policy is setup (in station mode) it's
376 * applied.
377 */
378int
379ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
380{
381	int v_wme_ac, d_wme_ac, ac;
382#ifdef INET
383	struct ether_header *eh;
384#endif
385
386	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
387		ac = WME_AC_BE;
388		goto done;
389	}
390
391	/*
392	 * If node has a vlan tag then all traffic
393	 * to it must have a matching tag.
394	 */
395	v_wme_ac = 0;
396	if (ni->ni_vlan != 0) {
397		 if ((m->m_flags & M_VLANTAG) == 0) {
398			IEEE80211_NODE_STAT(ni, tx_novlantag);
399			return 1;
400		}
401		if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
402		    EVL_VLANOFTAG(ni->ni_vlan)) {
403			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
404			return 1;
405		}
406		/* map vlan priority to AC */
407		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
408		case 1:
409		case 2:
410			v_wme_ac = WME_AC_BK;
411			break;
412		case 0:
413		case 3:
414			v_wme_ac = WME_AC_BE;
415			break;
416		case 4:
417		case 5:
418			v_wme_ac = WME_AC_VI;
419			break;
420		case 6:
421		case 7:
422			v_wme_ac = WME_AC_VO;
423			break;
424		}
425	}
426
427#ifdef INET
428	eh = mtod(m, struct ether_header *);
429	if (eh->ether_type == htons(ETHERTYPE_IP)) {
430		const struct ip *ip = (struct ip *)
431			(mtod(m, u_int8_t *) + sizeof (*eh));
432		/*
433		 * IP frame, map the TOS field.
434		 */
435		switch (ip->ip_tos) {
436		case 0x08:
437		case 0x20:
438			d_wme_ac = WME_AC_BK;	/* background */
439			break;
440		case 0x28:
441		case 0xa0:
442			d_wme_ac = WME_AC_VI;	/* video */
443			break;
444		case 0x30:			/* voice */
445		case 0xe0:
446		case 0x88:			/* XXX UPSD */
447		case 0xb8:
448			d_wme_ac = WME_AC_VO;
449			break;
450		default:
451			d_wme_ac = WME_AC_BE;
452			break;
453		}
454	} else {
455#endif /* INET */
456		d_wme_ac = WME_AC_BE;
457#ifdef INET
458	}
459#endif
460	/*
461	 * Use highest priority AC.
462	 */
463	if (v_wme_ac > d_wme_ac)
464		ac = v_wme_ac;
465	else
466		ac = d_wme_ac;
467
468	/*
469	 * Apply ACM policy.
470	 */
471	if (ic->ic_opmode == IEEE80211_M_STA) {
472		static const int acmap[4] = {
473			WME_AC_BK,	/* WME_AC_BE */
474			WME_AC_BK,	/* WME_AC_BK */
475			WME_AC_BE,	/* WME_AC_VI */
476			WME_AC_VI,	/* WME_AC_VO */
477		};
478		while (ac != WME_AC_BK &&
479		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
480			ac = acmap[ac];
481	}
482done:
483	M_WME_SETAC(m, ac);
484	return 0;
485}
486
487/*
488 * Insure there is sufficient contiguous space to encapsulate the
489 * 802.11 data frame.  If room isn't already there, arrange for it.
490 * Drivers and cipher modules assume we have done the necessary work
491 * and fail rudely if they don't find the space they need.
492 */
493static struct mbuf *
494ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
495	struct ieee80211_key *key, struct mbuf *m)
496{
497#define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
498	int needed_space = hdrsize;
499
500	if (key != NULL) {
501		/* XXX belongs in crypto code? */
502		needed_space += key->wk_cipher->ic_header;
503		/* XXX frags */
504		/*
505		 * When crypto is being done in the host we must insure
506		 * the data are writable for the cipher routines; clone
507		 * a writable mbuf chain.
508		 * XXX handle SWMIC specially
509		 */
510		if (key->wk_flags & (IEEE80211_KEY_SWCRYPT|IEEE80211_KEY_SWMIC)) {
511			m = m_unshare(m, M_NOWAIT);
512			if (m == NULL) {
513				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
514				    "%s: cannot get writable mbuf\n", __func__);
515				ic->ic_stats.is_tx_nobuf++; /* XXX new stat */
516				return NULL;
517			}
518		}
519	}
520	/*
521	 * We know we are called just before stripping an Ethernet
522	 * header and prepending an LLC header.  This means we know
523	 * there will be
524	 *	sizeof(struct ether_header) - sizeof(struct llc)
525	 * bytes recovered to which we need additional space for the
526	 * 802.11 header and any crypto header.
527	 */
528	/* XXX check trailing space and copy instead? */
529	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
530		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
531		if (n == NULL) {
532			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
533			    "%s: cannot expand storage\n", __func__);
534			ic->ic_stats.is_tx_nobuf++;
535			m_freem(m);
536			return NULL;
537		}
538		KASSERT(needed_space <= MHLEN,
539		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
540		/*
541		 * Setup new mbuf to have leading space to prepend the
542		 * 802.11 header and any crypto header bits that are
543		 * required (the latter are added when the driver calls
544		 * back to ieee80211_crypto_encap to do crypto encapsulation).
545		 */
546		/* NB: must be first 'cuz it clobbers m_data */
547		m_move_pkthdr(n, m);
548		n->m_len = 0;			/* NB: m_gethdr does not set */
549		n->m_data += needed_space;
550		/*
551		 * Pull up Ethernet header to create the expected layout.
552		 * We could use m_pullup but that's overkill (i.e. we don't
553		 * need the actual data) and it cannot fail so do it inline
554		 * for speed.
555		 */
556		/* NB: struct ether_header is known to be contiguous */
557		n->m_len += sizeof(struct ether_header);
558		m->m_len -= sizeof(struct ether_header);
559		m->m_data += sizeof(struct ether_header);
560		/*
561		 * Replace the head of the chain.
562		 */
563		n->m_next = m;
564		m = n;
565	}
566	return m;
567#undef TO_BE_RECLAIMED
568}
569
570/*
571 * Return the transmit key to use in sending a unicast frame.
572 * If a unicast key is set we use that.  When no unicast key is set
573 * we fall back to the default transmit key.
574 */
575static __inline struct ieee80211_key *
576ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
577{
578	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
579		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
580		    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
581			return NULL;
582		return &ic->ic_nw_keys[ic->ic_def_txkey];
583	} else {
584		return &ni->ni_ucastkey;
585	}
586}
587
588/*
589 * Return the transmit key to use in sending a multicast frame.
590 * Multicast traffic always uses the group key which is installed as
591 * the default tx key.
592 */
593static __inline struct ieee80211_key *
594ieee80211_crypto_getmcastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
595{
596	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
597	    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
598		return NULL;
599	return &ic->ic_nw_keys[ic->ic_def_txkey];
600}
601
602/*
603 * Encapsulate an outbound data frame.  The mbuf chain is updated.
604 * If an error is encountered NULL is returned.  The caller is required
605 * to provide a node reference and pullup the ethernet header in the
606 * first mbuf.
607 */
608struct mbuf *
609ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
610	struct ieee80211_node *ni)
611{
612	struct ether_header eh;
613	struct ieee80211_frame *wh;
614	struct ieee80211_key *key;
615	struct llc *llc;
616	int hdrsize, datalen, addqos;
617
618	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
619	memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
620
621	/*
622	 * Insure space for additional headers.  First identify
623	 * transmit key to use in calculating any buffer adjustments
624	 * required.  This is also used below to do privacy
625	 * encapsulation work.  Then calculate the 802.11 header
626	 * size and any padding required by the driver.
627	 *
628	 * Note key may be NULL if we fall back to the default
629	 * transmit key and that is not set.  In that case the
630	 * buffer may not be expanded as needed by the cipher
631	 * routines, but they will/should discard it.
632	 */
633	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
634		if (ic->ic_opmode == IEEE80211_M_STA ||
635		    !IEEE80211_IS_MULTICAST(eh.ether_dhost))
636			key = ieee80211_crypto_getucastkey(ic, ni);
637		else
638			key = ieee80211_crypto_getmcastkey(ic, ni);
639		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
640			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
641			    "[%s] no default transmit key (%s) deftxkey %u\n",
642			    ether_sprintf(eh.ether_dhost), __func__,
643			    ic->ic_def_txkey);
644			ic->ic_stats.is_tx_nodefkey++;
645		}
646	} else
647		key = NULL;
648	/* XXX 4-address format */
649	/*
650	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
651	 * frames so suppress use.  This may be an issue if other
652	 * ap's require all data frames to be QoS-encapsulated
653	 * once negotiated in which case we'll need to make this
654	 * configurable.
655	 */
656	addqos = (ni->ni_flags & IEEE80211_NODE_QOS) &&
657		 eh.ether_type != htons(ETHERTYPE_PAE);
658	if (addqos)
659		hdrsize = sizeof(struct ieee80211_qosframe);
660	else
661		hdrsize = sizeof(struct ieee80211_frame);
662	if (ic->ic_flags & IEEE80211_F_DATAPAD)
663		hdrsize = roundup(hdrsize, sizeof(u_int32_t));
664	m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
665	if (m == NULL) {
666		/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
667		goto bad;
668	}
669
670	/* NB: this could be optimized because of ieee80211_mbuf_adjust */
671	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
672	llc = mtod(m, struct llc *);
673	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
674	llc->llc_control = LLC_UI;
675	llc->llc_snap.org_code[0] = 0;
676	llc->llc_snap.org_code[1] = 0;
677	llc->llc_snap.org_code[2] = 0;
678	llc->llc_snap.ether_type = eh.ether_type;
679	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
680
681	M_PREPEND(m, hdrsize, M_DONTWAIT);
682	if (m == NULL) {
683		ic->ic_stats.is_tx_nobuf++;
684		goto bad;
685	}
686	wh = mtod(m, struct ieee80211_frame *);
687	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
688	*(u_int16_t *)wh->i_dur = 0;
689	switch (ic->ic_opmode) {
690	case IEEE80211_M_STA:
691		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
692		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
693		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
694		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
695		break;
696	case IEEE80211_M_IBSS:
697	case IEEE80211_M_AHDEMO:
698		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
699		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
700		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
701		/*
702		 * NB: always use the bssid from ic_bss as the
703		 *     neighbor's may be stale after an ibss merge
704		 */
705		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
706		break;
707	case IEEE80211_M_HOSTAP:
708		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
709		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
710		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
711		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
712		break;
713	case IEEE80211_M_MONITOR:
714		goto bad;
715	}
716	if (m->m_flags & M_MORE_DATA)
717		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
718	if (addqos) {
719		struct ieee80211_qosframe *qwh =
720			(struct ieee80211_qosframe *) wh;
721		int ac, tid;
722
723		ac = M_WME_GETAC(m);
724		/* map from access class/queue to 11e header priorty value */
725		tid = WME_AC_TO_TID(ac);
726		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
727		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
728			qwh->i_qos[0] |= 1 << IEEE80211_QOS_ACKPOLICY_S;
729		qwh->i_qos[1] = 0;
730		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
731
732		*(u_int16_t *)wh->i_seq =
733		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
734		ni->ni_txseqs[tid]++;
735	} else {
736		*(u_int16_t *)wh->i_seq =
737		    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
738		ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
739	}
740	if (key != NULL) {
741		/*
742		 * IEEE 802.1X: send EAPOL frames always in the clear.
743		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
744		 */
745		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
746		    ((ic->ic_flags & IEEE80211_F_WPA) &&
747		     (ic->ic_opmode == IEEE80211_M_STA ?
748		      !IEEE80211_KEY_UNDEFINED(key) :
749		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
750			wh->i_fc[1] |= IEEE80211_FC1_WEP;
751			/* XXX do fragmentation */
752			if (!ieee80211_crypto_enmic(ic, key, m, 0)) {
753				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
754				    "[%s] enmic failed, discard frame\n",
755				    ether_sprintf(eh.ether_dhost));
756				ic->ic_stats.is_crypto_enmicfail++;
757				goto bad;
758			}
759		}
760	}
761
762	IEEE80211_NODE_STAT(ni, tx_data);
763	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
764		IEEE80211_NODE_STAT(ni, tx_mcast);
765	else
766		IEEE80211_NODE_STAT(ni, tx_ucast);
767	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
768
769	return m;
770bad:
771	if (m != NULL)
772		m_freem(m);
773	return NULL;
774}
775
776/*
777 * Add a supported rates element id to a frame.
778 */
779static u_int8_t *
780ieee80211_add_rates(u_int8_t *frm, const struct ieee80211_rateset *rs)
781{
782	int nrates;
783
784	*frm++ = IEEE80211_ELEMID_RATES;
785	nrates = rs->rs_nrates;
786	if (nrates > IEEE80211_RATE_SIZE)
787		nrates = IEEE80211_RATE_SIZE;
788	*frm++ = nrates;
789	memcpy(frm, rs->rs_rates, nrates);
790	return frm + nrates;
791}
792
793/*
794 * Add an extended supported rates element id to a frame.
795 */
796static u_int8_t *
797ieee80211_add_xrates(u_int8_t *frm, const struct ieee80211_rateset *rs)
798{
799	/*
800	 * Add an extended supported rates element if operating in 11g mode.
801	 */
802	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
803		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
804		*frm++ = IEEE80211_ELEMID_XRATES;
805		*frm++ = nrates;
806		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
807		frm += nrates;
808	}
809	return frm;
810}
811
812/*
813 * Add an ssid elemet to a frame.
814 */
815static u_int8_t *
816ieee80211_add_ssid(u_int8_t *frm, const u_int8_t *ssid, u_int len)
817{
818	*frm++ = IEEE80211_ELEMID_SSID;
819	*frm++ = len;
820	memcpy(frm, ssid, len);
821	return frm + len;
822}
823
824/*
825 * Add an erp element to a frame.
826 */
827static u_int8_t *
828ieee80211_add_erp(u_int8_t *frm, struct ieee80211com *ic)
829{
830	u_int8_t erp;
831
832	*frm++ = IEEE80211_ELEMID_ERP;
833	*frm++ = 1;
834	erp = 0;
835	if (ic->ic_nonerpsta != 0)
836		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
837	if (ic->ic_flags & IEEE80211_F_USEPROT)
838		erp |= IEEE80211_ERP_USE_PROTECTION;
839	if (ic->ic_flags & IEEE80211_F_USEBARKER)
840		erp |= IEEE80211_ERP_LONG_PREAMBLE;
841	*frm++ = erp;
842	return frm;
843}
844
845static u_int8_t *
846ieee80211_setup_wpa_ie(struct ieee80211com *ic, u_int8_t *ie)
847{
848#define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
849#define	ADDSHORT(frm, v) do {			\
850	frm[0] = (v) & 0xff;			\
851	frm[1] = (v) >> 8;			\
852	frm += 2;				\
853} while (0)
854#define	ADDSELECTOR(frm, sel) do {		\
855	memcpy(frm, sel, 4);			\
856	frm += 4;				\
857} while (0)
858	static const u_int8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
859	static const u_int8_t cipher_suite[][4] = {
860		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
861		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
862		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
863		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
864		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
865		{ WPA_OUI_BYTES, WPA_CSE_NULL },
866	};
867	static const u_int8_t wep104_suite[4] =
868		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
869	static const u_int8_t key_mgt_unspec[4] =
870		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
871	static const u_int8_t key_mgt_psk[4] =
872		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
873	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
874	u_int8_t *frm = ie;
875	u_int8_t *selcnt;
876
877	*frm++ = IEEE80211_ELEMID_VENDOR;
878	*frm++ = 0;				/* length filled in below */
879	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
880	frm += sizeof(oui);
881	ADDSHORT(frm, WPA_VERSION);
882
883	/* XXX filter out CKIP */
884
885	/* multicast cipher */
886	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
887	    rsn->rsn_mcastkeylen >= 13)
888		ADDSELECTOR(frm, wep104_suite);
889	else
890		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
891
892	/* unicast cipher list */
893	selcnt = frm;
894	ADDSHORT(frm, 0);			/* selector count */
895	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
896		selcnt[0]++;
897		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
898	}
899	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
900		selcnt[0]++;
901		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
902	}
903
904	/* authenticator selector list */
905	selcnt = frm;
906	ADDSHORT(frm, 0);			/* selector count */
907	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
908		selcnt[0]++;
909		ADDSELECTOR(frm, key_mgt_unspec);
910	}
911	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
912		selcnt[0]++;
913		ADDSELECTOR(frm, key_mgt_psk);
914	}
915
916	/* optional capabilities */
917	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
918		ADDSHORT(frm, rsn->rsn_caps);
919
920	/* calculate element length */
921	ie[1] = frm - ie - 2;
922	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
923		("WPA IE too big, %u > %zu",
924		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
925	return frm;
926#undef ADDSHORT
927#undef ADDSELECTOR
928#undef WPA_OUI_BYTES
929}
930
931static u_int8_t *
932ieee80211_setup_rsn_ie(struct ieee80211com *ic, u_int8_t *ie)
933{
934#define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
935#define	ADDSHORT(frm, v) do {			\
936	frm[0] = (v) & 0xff;			\
937	frm[1] = (v) >> 8;			\
938	frm += 2;				\
939} while (0)
940#define	ADDSELECTOR(frm, sel) do {		\
941	memcpy(frm, sel, 4);			\
942	frm += 4;				\
943} while (0)
944	static const u_int8_t cipher_suite[][4] = {
945		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
946		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
947		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
948		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
949		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
950		{ RSN_OUI_BYTES, RSN_CSE_NULL },
951	};
952	static const u_int8_t wep104_suite[4] =
953		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
954	static const u_int8_t key_mgt_unspec[4] =
955		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
956	static const u_int8_t key_mgt_psk[4] =
957		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
958	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
959	u_int8_t *frm = ie;
960	u_int8_t *selcnt;
961
962	*frm++ = IEEE80211_ELEMID_RSN;
963	*frm++ = 0;				/* length filled in below */
964	ADDSHORT(frm, RSN_VERSION);
965
966	/* XXX filter out CKIP */
967
968	/* multicast cipher */
969	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
970	    rsn->rsn_mcastkeylen >= 13)
971		ADDSELECTOR(frm, wep104_suite);
972	else
973		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
974
975	/* unicast cipher list */
976	selcnt = frm;
977	ADDSHORT(frm, 0);			/* selector count */
978	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
979		selcnt[0]++;
980		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
981	}
982	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
983		selcnt[0]++;
984		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
985	}
986
987	/* authenticator selector list */
988	selcnt = frm;
989	ADDSHORT(frm, 0);			/* selector count */
990	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
991		selcnt[0]++;
992		ADDSELECTOR(frm, key_mgt_unspec);
993	}
994	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
995		selcnt[0]++;
996		ADDSELECTOR(frm, key_mgt_psk);
997	}
998
999	/* optional capabilities */
1000	ADDSHORT(frm, rsn->rsn_caps);
1001	/* XXX PMKID */
1002
1003	/* calculate element length */
1004	ie[1] = frm - ie - 2;
1005	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1006		("RSN IE too big, %u > %zu",
1007		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1008	return frm;
1009#undef ADDSELECTOR
1010#undef ADDSHORT
1011#undef RSN_OUI_BYTES
1012}
1013
1014/*
1015 * Add a WPA/RSN element to a frame.
1016 */
1017static u_int8_t *
1018ieee80211_add_wpa(u_int8_t *frm, struct ieee80211com *ic)
1019{
1020
1021	KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
1022	if (ic->ic_flags & IEEE80211_F_WPA2)
1023		frm = ieee80211_setup_rsn_ie(ic, frm);
1024	if (ic->ic_flags & IEEE80211_F_WPA1)
1025		frm = ieee80211_setup_wpa_ie(ic, frm);
1026	return frm;
1027}
1028
1029#define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1030/*
1031 * Add a WME information element to a frame.
1032 */
1033static u_int8_t *
1034ieee80211_add_wme_info(u_int8_t *frm, struct ieee80211_wme_state *wme)
1035{
1036	static const struct ieee80211_wme_info info = {
1037		.wme_id		= IEEE80211_ELEMID_VENDOR,
1038		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1039		.wme_oui	= { WME_OUI_BYTES },
1040		.wme_type	= WME_OUI_TYPE,
1041		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1042		.wme_version	= WME_VERSION,
1043		.wme_info	= 0,
1044	};
1045	memcpy(frm, &info, sizeof(info));
1046	return frm + sizeof(info);
1047}
1048
1049/*
1050 * Add a WME parameters element to a frame.
1051 */
1052static u_int8_t *
1053ieee80211_add_wme_param(u_int8_t *frm, struct ieee80211_wme_state *wme)
1054{
1055#define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1056#define	ADDSHORT(frm, v) do {			\
1057	frm[0] = (v) & 0xff;			\
1058	frm[1] = (v) >> 8;			\
1059	frm += 2;				\
1060} while (0)
1061	/* NB: this works 'cuz a param has an info at the front */
1062	static const struct ieee80211_wme_info param = {
1063		.wme_id		= IEEE80211_ELEMID_VENDOR,
1064		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1065		.wme_oui	= { WME_OUI_BYTES },
1066		.wme_type	= WME_OUI_TYPE,
1067		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1068		.wme_version	= WME_VERSION,
1069	};
1070	int i;
1071
1072	memcpy(frm, &param, sizeof(param));
1073	frm += __offsetof(struct ieee80211_wme_info, wme_info);
1074	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1075	*frm++ = 0;					/* reserved field */
1076	for (i = 0; i < WME_NUM_AC; i++) {
1077		const struct wmeParams *ac =
1078		       &wme->wme_bssChanParams.cap_wmeParams[i];
1079		*frm++ = SM(i, WME_PARAM_ACI)
1080		       | SM(ac->wmep_acm, WME_PARAM_ACM)
1081		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1082		       ;
1083		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1084		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1085		       ;
1086		ADDSHORT(frm, ac->wmep_txopLimit);
1087	}
1088	return frm;
1089#undef SM
1090#undef ADDSHORT
1091}
1092#undef WME_OUI_BYTES
1093
1094/*
1095 * Send a probe request frame with the specified ssid
1096 * and any optional information element data.
1097 */
1098int
1099ieee80211_send_probereq(struct ieee80211_node *ni,
1100	const u_int8_t sa[IEEE80211_ADDR_LEN],
1101	const u_int8_t da[IEEE80211_ADDR_LEN],
1102	const u_int8_t bssid[IEEE80211_ADDR_LEN],
1103	const u_int8_t *ssid, size_t ssidlen,
1104	const void *optie, size_t optielen)
1105{
1106	struct ieee80211com *ic = ni->ni_ic;
1107	struct ieee80211_frame *wh;
1108	const struct ieee80211_rateset *rs;
1109	struct mbuf *m;
1110	u_int8_t *frm;
1111
1112	/*
1113	 * Hold a reference on the node so it doesn't go away until after
1114	 * the xmit is complete all the way in the driver.  On error we
1115	 * will remove our reference.
1116	 */
1117	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1118		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1119		__func__, __LINE__,
1120		ni, ether_sprintf(ni->ni_macaddr),
1121		ieee80211_node_refcnt(ni)+1);
1122	ieee80211_ref_node(ni);
1123
1124	/*
1125	 * prreq frame format
1126	 *	[tlv] ssid
1127	 *	[tlv] supported rates
1128	 *	[tlv] extended supported rates
1129	 *	[tlv] user-specified ie's
1130	 */
1131	m = ieee80211_getmgtframe(&frm,
1132		 2 + IEEE80211_NWID_LEN
1133	       + 2 + IEEE80211_RATE_SIZE
1134	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1135	       + (optie != NULL ? optielen : 0)
1136	);
1137	if (m == NULL) {
1138		ic->ic_stats.is_tx_nobuf++;
1139		ieee80211_free_node(ni);
1140		return ENOMEM;
1141	}
1142
1143	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1144	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1145	frm = ieee80211_add_rates(frm, rs);
1146	frm = ieee80211_add_xrates(frm, rs);
1147
1148	if (optie != NULL) {
1149		memcpy(frm, optie, optielen);
1150		frm += optielen;
1151	}
1152	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1153
1154	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1155	if (m == NULL)
1156		return ENOMEM;
1157	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
1158	m->m_pkthdr.rcvif = (void *)ni;
1159
1160	wh = mtod(m, struct ieee80211_frame *);
1161	ieee80211_send_setup(ic, ni, wh,
1162		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1163		sa, da, bssid);
1164	/* XXX power management? */
1165
1166	IEEE80211_NODE_STAT(ni, tx_probereq);
1167	IEEE80211_NODE_STAT(ni, tx_mgmt);
1168
1169	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1170	    "[%s] send probe req on channel %u\n",
1171	    ether_sprintf(wh->i_addr1),
1172	    ieee80211_chan2ieee(ic, ic->ic_curchan));
1173
1174	IF_ENQUEUE(&ic->ic_mgtq, m);
1175	if_start(ic->ic_ifp);
1176	return 0;
1177}
1178
1179/*
1180 * Calculate capability information for mgt frames.
1181 */
1182static u_int16_t
1183getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
1184{
1185	u_int16_t capinfo;
1186
1187	KASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
1188
1189	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1190		capinfo = IEEE80211_CAPINFO_ESS;
1191	else if (ic->ic_opmode == IEEE80211_M_IBSS)
1192		capinfo = IEEE80211_CAPINFO_IBSS;
1193	else
1194		capinfo = 0;
1195	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1196		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1197	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1198	    IEEE80211_IS_CHAN_2GHZ(chan))
1199		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1200	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1201		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1202	return capinfo;
1203}
1204
1205/*
1206 * Send a management frame.  The node is for the destination (or ic_bss
1207 * when in station mode).  Nodes other than ic_bss have their reference
1208 * count bumped to reflect our use for an indeterminant time.
1209 */
1210int
1211ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1212	int type, int arg)
1213{
1214#define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1215	struct mbuf *m;
1216	u_int8_t *frm;
1217	u_int16_t capinfo;
1218	int has_challenge, is_shared_key, ret, timer, status;
1219
1220	KASSERT(ni != NULL, ("null node"));
1221
1222	/*
1223	 * Hold a reference on the node so it doesn't go away until after
1224	 * the xmit is complete all the way in the driver.  On error we
1225	 * will remove our reference.
1226	 */
1227	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1228		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1229		__func__, __LINE__,
1230		ni, ether_sprintf(ni->ni_macaddr),
1231		ieee80211_node_refcnt(ni)+1);
1232	ieee80211_ref_node(ni);
1233
1234	timer = 0;
1235	switch (type) {
1236	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1237		/*
1238		 * probe response frame format
1239		 *	[8] time stamp
1240		 *	[2] beacon interval
1241		 *	[2] cabability information
1242		 *	[tlv] ssid
1243		 *	[tlv] supported rates
1244		 *	[tlv] parameter set (FH/DS)
1245		 *	[tlv] parameter set (IBSS)
1246		 *	[tlv] extended rate phy (ERP)
1247		 *	[tlv] extended supported rates
1248		 *	[tlv] WPA
1249		 *	[tlv] WME (optional)
1250		 */
1251		m = ieee80211_getmgtframe(&frm,
1252			 8
1253		       + sizeof(u_int16_t)
1254		       + sizeof(u_int16_t)
1255		       + 2 + IEEE80211_NWID_LEN
1256		       + 2 + IEEE80211_RATE_SIZE
1257		       + 7	/* max(7,3) */
1258		       + 6
1259		       + 3
1260		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1261		       /* XXX !WPA1+WPA2 fits w/o a cluster */
1262		       + (ic->ic_flags & IEEE80211_F_WPA ?
1263				2*sizeof(struct ieee80211_ie_wpa) : 0)
1264		       + sizeof(struct ieee80211_wme_param)
1265		);
1266		if (m == NULL)
1267			senderr(ENOMEM, is_tx_nobuf);
1268
1269		memset(frm, 0, 8);	/* timestamp should be filled later */
1270		frm += 8;
1271		*(u_int16_t *)frm = htole16(ic->ic_bss->ni_intval);
1272		frm += 2;
1273		capinfo = getcapinfo(ic, ic->ic_curchan);
1274		*(u_int16_t *)frm = htole16(capinfo);
1275		frm += 2;
1276
1277		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1278				ic->ic_bss->ni_esslen);
1279		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1280
1281		if (ic->ic_phytype == IEEE80211_T_FH) {
1282                        *frm++ = IEEE80211_ELEMID_FHPARMS;
1283                        *frm++ = 5;
1284                        *frm++ = ni->ni_fhdwell & 0x00ff;
1285                        *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1286                        *frm++ = IEEE80211_FH_CHANSET(
1287			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1288                        *frm++ = IEEE80211_FH_CHANPAT(
1289			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1290                        *frm++ = ni->ni_fhindex;
1291		} else {
1292			*frm++ = IEEE80211_ELEMID_DSPARMS;
1293			*frm++ = 1;
1294			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
1295		}
1296
1297		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1298			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1299			*frm++ = 2;
1300			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1301		}
1302		if (ic->ic_flags & IEEE80211_F_WPA)
1303			frm = ieee80211_add_wpa(frm, ic);
1304		if (ic->ic_curmode == IEEE80211_MODE_11G)
1305			frm = ieee80211_add_erp(frm, ic);
1306		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1307		if (ic->ic_flags & IEEE80211_F_WME)
1308			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1309		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1310		break;
1311
1312	case IEEE80211_FC0_SUBTYPE_AUTH:
1313		status = arg >> 16;
1314		arg &= 0xffff;
1315		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1316		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1317		    ni->ni_challenge != NULL);
1318
1319		/*
1320		 * Deduce whether we're doing open authentication or
1321		 * shared key authentication.  We do the latter if
1322		 * we're in the middle of a shared key authentication
1323		 * handshake or if we're initiating an authentication
1324		 * request and configured to use shared key.
1325		 */
1326		is_shared_key = has_challenge ||
1327		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1328		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1329		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1330
1331		m = ieee80211_getmgtframe(&frm,
1332			  3 * sizeof(u_int16_t)
1333			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1334				sizeof(u_int16_t)+IEEE80211_CHALLENGE_LEN : 0)
1335		);
1336		if (m == NULL)
1337			senderr(ENOMEM, is_tx_nobuf);
1338
1339		((u_int16_t *)frm)[0] =
1340		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1341		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1342		((u_int16_t *)frm)[1] = htole16(arg);	/* sequence number */
1343		((u_int16_t *)frm)[2] = htole16(status);/* status */
1344
1345		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1346			((u_int16_t *)frm)[3] =
1347			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1348			    IEEE80211_ELEMID_CHALLENGE);
1349			memcpy(&((u_int16_t *)frm)[4], ni->ni_challenge,
1350			    IEEE80211_CHALLENGE_LEN);
1351			m->m_pkthdr.len = m->m_len =
1352				4 * sizeof(u_int16_t) + IEEE80211_CHALLENGE_LEN;
1353			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1354				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1355				    "[%s] request encrypt frame (%s)\n",
1356				    ether_sprintf(ni->ni_macaddr), __func__);
1357				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1358			}
1359		} else
1360			m->m_pkthdr.len = m->m_len = 3 * sizeof(u_int16_t);
1361
1362		/* XXX not right for shared key */
1363		if (status == IEEE80211_STATUS_SUCCESS)
1364			IEEE80211_NODE_STAT(ni, tx_auth);
1365		else
1366			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1367
1368		if (ic->ic_opmode == IEEE80211_M_STA)
1369			timer = IEEE80211_TRANS_WAIT;
1370		break;
1371
1372	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1373		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1374			"[%s] send station deauthenticate (reason %d)\n",
1375			ether_sprintf(ni->ni_macaddr), arg);
1376		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1377		if (m == NULL)
1378			senderr(ENOMEM, is_tx_nobuf);
1379		*(u_int16_t *)frm = htole16(arg);	/* reason */
1380		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1381
1382		IEEE80211_NODE_STAT(ni, tx_deauth);
1383		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1384
1385		ieee80211_node_unauthorize(ni);		/* port closed */
1386		break;
1387
1388	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1389	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1390		/*
1391		 * asreq frame format
1392		 *	[2] capability information
1393		 *	[2] listen interval
1394		 *	[6*] current AP address (reassoc only)
1395		 *	[tlv] ssid
1396		 *	[tlv] supported rates
1397		 *	[tlv] extended supported rates
1398		 *	[tlv] WME
1399		 *	[tlv] user-specified ie's
1400		 */
1401		m = ieee80211_getmgtframe(&frm,
1402			 sizeof(u_int16_t)
1403		       + sizeof(u_int16_t)
1404		       + IEEE80211_ADDR_LEN
1405		       + 2 + IEEE80211_NWID_LEN
1406		       + 2 + IEEE80211_RATE_SIZE
1407		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1408		       + sizeof(struct ieee80211_wme_info)
1409		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1410		);
1411		if (m == NULL)
1412			senderr(ENOMEM, is_tx_nobuf);
1413
1414		KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1415		    ("wrong mode %u", ic->ic_opmode));
1416		capinfo = IEEE80211_CAPINFO_ESS;
1417		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1418			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1419		/*
1420		 * NB: Some 11a AP's reject the request when
1421		 *     short premable is set.
1422		 */
1423		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1424		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1425			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1426		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) &&
1427		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1428			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1429		*(u_int16_t *)frm = htole16(capinfo);
1430		frm += 2;
1431
1432		*(u_int16_t *)frm = htole16(ic->ic_lintval);
1433		frm += 2;
1434
1435		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1436			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1437			frm += IEEE80211_ADDR_LEN;
1438		}
1439
1440		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1441		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1442		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1443		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1444			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1445		if (ic->ic_opt_ie != NULL) {
1446			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1447			frm += ic->ic_opt_ie_len;
1448		}
1449		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1450
1451		timer = IEEE80211_TRANS_WAIT;
1452		break;
1453
1454	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1455	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1456		/*
1457		 * asreq frame format
1458		 *	[2] capability information
1459		 *	[2] status
1460		 *	[2] association ID
1461		 *	[tlv] supported rates
1462		 *	[tlv] extended supported rates
1463		 *	[tlv] WME (if enabled and STA enabled)
1464		 */
1465		m = ieee80211_getmgtframe(&frm,
1466			 sizeof(u_int16_t)
1467		       + sizeof(u_int16_t)
1468		       + sizeof(u_int16_t)
1469		       + 2 + IEEE80211_RATE_SIZE
1470		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1471		       + sizeof(struct ieee80211_wme_param)
1472		);
1473		if (m == NULL)
1474			senderr(ENOMEM, is_tx_nobuf);
1475
1476		capinfo = getcapinfo(ic, ic->ic_curchan);
1477		*(u_int16_t *)frm = htole16(capinfo);
1478		frm += 2;
1479
1480		*(u_int16_t *)frm = htole16(arg);	/* status */
1481		frm += 2;
1482
1483		if (arg == IEEE80211_STATUS_SUCCESS) {
1484			*(u_int16_t *)frm = htole16(ni->ni_associd);
1485			IEEE80211_NODE_STAT(ni, tx_assoc);
1486		} else
1487			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1488		frm += 2;
1489
1490		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1491		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1492		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1493			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1494		m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1495		break;
1496
1497	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1498		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1499			"[%s] send station disassociate (reason %d)\n",
1500			ether_sprintf(ni->ni_macaddr), arg);
1501		m = ieee80211_getmgtframe(&frm, sizeof(u_int16_t));
1502		if (m == NULL)
1503			senderr(ENOMEM, is_tx_nobuf);
1504		*(u_int16_t *)frm = htole16(arg);	/* reason */
1505		m->m_pkthdr.len = m->m_len = sizeof(u_int16_t);
1506
1507		IEEE80211_NODE_STAT(ni, tx_disassoc);
1508		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1509		break;
1510
1511	default:
1512		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1513			"[%s] invalid mgmt frame type %u\n",
1514			ether_sprintf(ni->ni_macaddr), type);
1515		senderr(EINVAL, is_tx_unknownmgt);
1516		/* NOTREACHED */
1517	}
1518	ret = ieee80211_mgmt_output(ic, ni, m, type, timer);
1519	if (ret != 0) {
1520bad:
1521		ieee80211_free_node(ni);
1522	}
1523	return ret;
1524#undef senderr
1525}
1526
1527/*
1528 * Allocate a beacon frame and fillin the appropriate bits.
1529 */
1530struct mbuf *
1531ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
1532	struct ieee80211_beacon_offsets *bo)
1533{
1534	struct ifnet *ifp = ic->ic_ifp;
1535	struct ieee80211_frame *wh;
1536	struct mbuf *m;
1537	int pktlen;
1538	u_int8_t *frm, *efrm;
1539	u_int16_t capinfo;
1540	struct ieee80211_rateset *rs;
1541
1542	/*
1543	 * beacon frame format
1544	 *	[8] time stamp
1545	 *	[2] beacon interval
1546	 *	[2] cabability information
1547	 *	[tlv] ssid
1548	 *	[tlv] supported rates
1549	 *	[3] parameter set (DS)
1550	 *	[tlv] parameter set (IBSS/TIM)
1551	 *	[tlv] extended rate phy (ERP)
1552	 *	[tlv] extended supported rates
1553	 *	[tlv] WME parameters
1554	 *	[tlv] WPA/RSN parameters
1555	 * XXX Vendor-specific OIDs (e.g. Atheros)
1556	 * NB: we allocate the max space required for the TIM bitmap.
1557	 */
1558	rs = &ni->ni_rates;
1559	pktlen =   8					/* time stamp */
1560		 + sizeof(u_int16_t)			/* beacon interval */
1561		 + sizeof(u_int16_t)			/* capabilities */
1562		 + 2 + ni->ni_esslen			/* ssid */
1563	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
1564	         + 2 + 1				/* DS parameters */
1565		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
1566		 + 2 + 1				/* ERP */
1567	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1568		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
1569			sizeof(struct ieee80211_wme_param) : 0)
1570		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
1571			2*sizeof(struct ieee80211_ie_wpa) : 0)
1572		 ;
1573	m = ieee80211_getmgtframe(&frm, pktlen);
1574	if (m == NULL) {
1575		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1576			"%s: cannot get buf; size %u\n", __func__, pktlen);
1577		ic->ic_stats.is_tx_nobuf++;
1578		return NULL;
1579	}
1580
1581	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
1582	frm += 8;
1583	*(u_int16_t *)frm = htole16(ni->ni_intval);
1584	frm += 2;
1585	capinfo = getcapinfo(ic, ni->ni_chan);
1586	bo->bo_caps = (u_int16_t *)frm;
1587	*(u_int16_t *)frm = htole16(capinfo);
1588	frm += 2;
1589	*frm++ = IEEE80211_ELEMID_SSID;
1590	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
1591		*frm++ = ni->ni_esslen;
1592		memcpy(frm, ni->ni_essid, ni->ni_esslen);
1593		frm += ni->ni_esslen;
1594	} else
1595		*frm++ = 0;
1596	frm = ieee80211_add_rates(frm, rs);
1597	if (ic->ic_curmode != IEEE80211_MODE_FH) {
1598		*frm++ = IEEE80211_ELEMID_DSPARMS;
1599		*frm++ = 1;
1600		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1601	}
1602	bo->bo_tim = frm;
1603	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1604		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1605		*frm++ = 2;
1606		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1607		bo->bo_tim_len = 0;
1608	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1609		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
1610
1611		tie->tim_ie = IEEE80211_ELEMID_TIM;
1612		tie->tim_len = 4;	/* length */
1613		tie->tim_count = 0;	/* DTIM count */
1614		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
1615		tie->tim_bitctl = 0;	/* bitmap control */
1616		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
1617		frm += sizeof(struct ieee80211_tim_ie);
1618		bo->bo_tim_len = 1;
1619	}
1620	bo->bo_trailer = frm;
1621	if (ic->ic_flags & IEEE80211_F_WME) {
1622		bo->bo_wme = frm;
1623		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1624		ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1625	}
1626	if (ic->ic_flags & IEEE80211_F_WPA)
1627		frm = ieee80211_add_wpa(frm, ic);
1628	if (ic->ic_curmode == IEEE80211_MODE_11G) {
1629		bo->bo_erp = frm;
1630		frm = ieee80211_add_erp(frm, ic);
1631	}
1632	efrm = ieee80211_add_xrates(frm, rs);
1633	bo->bo_trailer_len = efrm - bo->bo_trailer;
1634	m->m_pkthdr.len = m->m_len = efrm - mtod(m, u_int8_t *);
1635
1636	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1637	KASSERT(m != NULL, ("no space for 802.11 header?"));
1638	wh = mtod(m, struct ieee80211_frame *);
1639	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1640	    IEEE80211_FC0_SUBTYPE_BEACON;
1641	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1642	*(u_int16_t *)wh->i_dur = 0;
1643	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1644	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1645	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1646	*(u_int16_t *)wh->i_seq = 0;
1647
1648	return m;
1649}
1650
1651/*
1652 * Update the dynamic parts of a beacon frame based on the current state.
1653 */
1654int
1655ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
1656	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
1657{
1658	int len_changed = 0;
1659	u_int16_t capinfo;
1660
1661	IEEE80211_BEACON_LOCK(ic);
1662	/* XXX faster to recalculate entirely or just changes? */
1663	capinfo = getcapinfo(ic, ni->ni_chan);
1664	*bo->bo_caps = htole16(capinfo);
1665
1666	if (ic->ic_flags & IEEE80211_F_WME) {
1667		struct ieee80211_wme_state *wme = &ic->ic_wme;
1668
1669		/*
1670		 * Check for agressive mode change.  When there is
1671		 * significant high priority traffic in the BSS
1672		 * throttle back BE traffic by using conservative
1673		 * parameters.  Otherwise BE uses agressive params
1674		 * to optimize performance of legacy/non-QoS traffic.
1675		 */
1676		if (wme->wme_flags & WME_F_AGGRMODE) {
1677			if (wme->wme_hipri_traffic >
1678			    wme->wme_hipri_switch_thresh) {
1679				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1680				    "%s: traffic %u, disable aggressive mode\n",
1681				    __func__, wme->wme_hipri_traffic);
1682				wme->wme_flags &= ~WME_F_AGGRMODE;
1683				ieee80211_wme_updateparams_locked(ic);
1684				wme->wme_hipri_traffic =
1685					wme->wme_hipri_switch_hysteresis;
1686			} else
1687				wme->wme_hipri_traffic = 0;
1688		} else {
1689			if (wme->wme_hipri_traffic <=
1690			    wme->wme_hipri_switch_thresh) {
1691				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1692				    "%s: traffic %u, enable aggressive mode\n",
1693				    __func__, wme->wme_hipri_traffic);
1694				wme->wme_flags |= WME_F_AGGRMODE;
1695				ieee80211_wme_updateparams_locked(ic);
1696				wme->wme_hipri_traffic = 0;
1697			} else
1698				wme->wme_hipri_traffic =
1699					wme->wme_hipri_switch_hysteresis;
1700		}
1701		if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
1702			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
1703			ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1704		}
1705	}
1706
1707	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
1708		struct ieee80211_tim_ie *tie =
1709			(struct ieee80211_tim_ie *) bo->bo_tim;
1710		if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
1711			u_int timlen, timoff, i;
1712			/*
1713			 * ATIM/DTIM needs updating.  If it fits in the
1714			 * current space allocated then just copy in the
1715			 * new bits.  Otherwise we need to move any trailing
1716			 * data to make room.  Note that we know there is
1717			 * contiguous space because ieee80211_beacon_allocate
1718			 * insures there is space in the mbuf to write a
1719			 * maximal-size virtual bitmap (based on ic_max_aid).
1720			 */
1721			/*
1722			 * Calculate the bitmap size and offset, copy any
1723			 * trailer out of the way, and then copy in the
1724			 * new bitmap and update the information element.
1725			 * Note that the tim bitmap must contain at least
1726			 * one byte and any offset must be even.
1727			 */
1728			if (ic->ic_ps_pending != 0) {
1729				timoff = 128;		/* impossibly large */
1730				for (i = 0; i < ic->ic_tim_len; i++)
1731					if (ic->ic_tim_bitmap[i]) {
1732						timoff = i &~ 1;
1733						break;
1734					}
1735				KASSERT(timoff != 128, ("tim bitmap empty!"));
1736				for (i = ic->ic_tim_len-1; i >= timoff; i--)
1737					if (ic->ic_tim_bitmap[i])
1738						break;
1739				timlen = 1 + (i - timoff);
1740			} else {
1741				timoff = 0;
1742				timlen = 1;
1743			}
1744			if (timlen != bo->bo_tim_len) {
1745				/* copy up/down trailer */
1746				int adjust = tie->tim_bitmap+timlen
1747					   - bo->bo_trailer;
1748				ovbcopy(bo->bo_trailer, bo->bo_trailer+adjust,
1749					bo->bo_trailer_len);
1750				bo->bo_trailer += adjust;
1751				bo->bo_wme += adjust;
1752				bo->bo_erp += adjust;
1753				bo->bo_tim_len = timlen;
1754
1755				/* update information element */
1756				tie->tim_len = 3 + timlen;
1757				tie->tim_bitctl = timoff;
1758				len_changed = 1;
1759			}
1760			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
1761				bo->bo_tim_len);
1762
1763			ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
1764
1765			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1766				"%s: TIM updated, pending %u, off %u, len %u\n",
1767				__func__, ic->ic_ps_pending, timoff, timlen);
1768		}
1769		/* count down DTIM period */
1770		if (tie->tim_count == 0)
1771			tie->tim_count = tie->tim_period - 1;
1772		else
1773			tie->tim_count--;
1774		/* update state for buffered multicast frames on DTIM */
1775		if (mcast && tie->tim_count == 0)
1776			tie->tim_bitctl |= 1;
1777		else
1778			tie->tim_bitctl &= ~1;
1779		if (ic->ic_flags_ext & IEEE80211_FEXT_ERPUPDATE) {
1780			/*
1781			 * ERP element needs updating.
1782			 */
1783			(void) ieee80211_add_erp(bo->bo_erp, ic);
1784			ic->ic_flags_ext &= ~IEEE80211_FEXT_ERPUPDATE;
1785		}
1786	}
1787	IEEE80211_BEACON_UNLOCK(ic);
1788
1789	return len_changed;
1790}
1791
1792/*
1793 * Save an outbound packet for a node in power-save sleep state.
1794 * The new packet is placed on the node's saved queue, and the TIM
1795 * is changed, if necessary.
1796 */
1797void
1798ieee80211_pwrsave(struct ieee80211com *ic, struct ieee80211_node *ni,
1799		  struct mbuf *m)
1800{
1801	int qlen, age;
1802
1803	IEEE80211_NODE_SAVEQ_LOCK(ni);
1804	if (_IF_QFULL(&ni->ni_savedq)) {
1805		_IF_DROP(&ni->ni_savedq);
1806		IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1807		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1808			"[%s] pwr save q overflow, drops %d (size %d)\n",
1809			ether_sprintf(ni->ni_macaddr),
1810			ni->ni_savedq.ifq_drops, IEEE80211_PS_MAX_QUEUE);
1811#ifdef IEEE80211_DEBUG
1812		if (ieee80211_msg_dumppkts(ic))
1813			ieee80211_dump_pkt(mtod(m, caddr_t), m->m_len, -1, -1);
1814#endif
1815		m_freem(m);
1816		return;
1817	}
1818	/*
1819	 * Tag the frame with it's expiry time and insert
1820	 * it in the queue.  The aging interval is 4 times
1821	 * the listen interval specified by the station.
1822	 * Frames that sit around too long are reclaimed
1823	 * using this information.
1824	 */
1825	/* XXX handle overflow? */
1826	age = ((ni->ni_intval * ic->ic_bintval) << 2) / 1024; /* TU -> secs */
1827	_IEEE80211_NODE_SAVEQ_ENQUEUE(ni, m, qlen, age);
1828	IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1829
1830	IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1831		"[%s] save frame with age %d, %u now queued\n",
1832		ether_sprintf(ni->ni_macaddr), age, qlen);
1833
1834	if (qlen == 1)
1835		ic->ic_set_tim(ni, 1);
1836}
1837