xref: /freebsd/sys/net80211/ieee80211_output.c (revision b28624fde638caadd4a89f50c9b7e7da0f98c4d2)
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$");
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 #include <net80211/ieee80211_regdomain.h>
49 
50 #ifdef INET
51 #include <netinet/in.h>
52 #include <netinet/if_ether.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55 #endif
56 
57 #define	ETHER_HEADER_COPY(dst, src) \
58 	memcpy(dst, src, sizeof(struct ether_header))
59 
60 static struct mbuf *ieee80211_encap_fastframe(struct ieee80211com *ic,
61 	struct mbuf *m1, const struct ether_header *eh1,
62 	struct mbuf *m2, const struct ether_header *eh2);
63 static int ieee80211_fragment(struct ieee80211com *, struct mbuf *,
64 	u_int hdrsize, u_int ciphdrsize, u_int mtu);
65 static	void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
66 
67 #ifdef IEEE80211_DEBUG
68 /*
69  * Decide if an outbound management frame should be
70  * printed when debugging is enabled.  This filters some
71  * of the less interesting frames that come frequently
72  * (e.g. beacons).
73  */
74 static __inline int
75 doprint(struct ieee80211com *ic, int subtype)
76 {
77 	switch (subtype) {
78 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
79 		return (ic->ic_opmode == IEEE80211_M_IBSS);
80 	}
81 	return 1;
82 }
83 #endif
84 
85 /*
86  * Set the direction field and address fields of an outgoing
87  * non-QoS frame.  Note this should be called early on in
88  * constructing a frame as it sets i_fc[1]; other bits can
89  * then be or'd in.
90  */
91 static void
92 ieee80211_send_setup(struct ieee80211com *ic,
93 	struct ieee80211_node *ni,
94 	struct ieee80211_frame *wh,
95 	int type,
96 	const uint8_t sa[IEEE80211_ADDR_LEN],
97 	const uint8_t da[IEEE80211_ADDR_LEN],
98 	const uint8_t bssid[IEEE80211_ADDR_LEN])
99 {
100 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
101 
102 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
103 	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
104 		switch (ic->ic_opmode) {
105 		case IEEE80211_M_STA:
106 			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
107 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
108 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
109 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
110 			break;
111 		case IEEE80211_M_IBSS:
112 		case IEEE80211_M_AHDEMO:
113 			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
114 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
115 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
116 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
117 			break;
118 		case IEEE80211_M_HOSTAP:
119 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
120 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
121 			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
122 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
123 			break;
124 		case IEEE80211_M_WDS:
125 			wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
126 			/* XXX cheat, bssid holds RA */
127 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
128 			IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
129 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
130 			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
131 			break;
132 		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
133 			break;
134 		}
135 	} else {
136 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
137 		IEEE80211_ADDR_COPY(wh->i_addr1, da);
138 		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
139 		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
140 	}
141 	*(uint16_t *)&wh->i_dur[0] = 0;
142 	/* NB: use non-QoS tid */
143 	*(uint16_t *)&wh->i_seq[0] =
144 	    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
145 	ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
146 #undef WH4
147 }
148 
149 /*
150  * Send a management frame to the specified node.  The node pointer
151  * must have a reference as the pointer will be passed to the driver
152  * and potentially held for a long time.  If the frame is successfully
153  * dispatched to the driver, then it is responsible for freeing the
154  * reference (and potentially free'ing up any associated storage).
155  */
156 int
157 ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
158     struct mbuf *m, int type)
159 {
160 	struct ifnet *ifp = ic->ic_ifp;
161 	struct ieee80211_frame *wh;
162 
163 	KASSERT(ni != NULL, ("null node"));
164 
165 	/*
166 	 * Yech, hack alert!  We want to pass the node down to the
167 	 * driver's start routine.  If we don't do so then the start
168 	 * routine must immediately look it up again and that can
169 	 * cause a lock order reversal if, for example, this frame
170 	 * is being sent because the station is being timedout and
171 	 * the frame being sent is a DEAUTH message.  We could stick
172 	 * this in an m_tag and tack that on to the mbuf.  However
173 	 * that's rather expensive to do for every frame so instead
174 	 * we stuff it in the rcvif field since outbound frames do
175 	 * not (presently) use this.
176 	 */
177 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
178 	if (m == NULL)
179 		return ENOMEM;
180 	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
181 	m->m_pkthdr.rcvif = (void *)ni;
182 
183 	wh = mtod(m, struct ieee80211_frame *);
184 	ieee80211_send_setup(ic, ni, wh,
185 		IEEE80211_FC0_TYPE_MGT | type,
186 		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
187 	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
188 		m->m_flags &= ~M_LINK0;
189 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
190 			"[%s] encrypting frame (%s)\n",
191 			ether_sprintf(wh->i_addr1), __func__);
192 		wh->i_fc[1] |= IEEE80211_FC1_WEP;
193 	}
194 #ifdef IEEE80211_DEBUG
195 	/* avoid printing too many frames */
196 	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
197 	    ieee80211_msg_dumppkts(ic)) {
198 		printf("[%s] send %s on channel %u\n",
199 		    ether_sprintf(wh->i_addr1),
200 		    ieee80211_mgt_subtype_name[
201 			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
202 				IEEE80211_FC0_SUBTYPE_SHIFT],
203 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
204 	}
205 #endif
206 	IEEE80211_NODE_STAT(ni, tx_mgmt);
207 	IF_ENQUEUE(&ic->ic_mgtq, m);
208 	if_start(ifp);
209 	ifp->if_opackets++;
210 
211 	return 0;
212 }
213 
214 /*
215  * Raw packet transmit stub for legacy drivers.
216  * Send the packet through the mgt q so we bypass
217  * the normal encapsulation work.
218  */
219 int
220 ieee80211_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
221 	const struct ieee80211_bpf_params *params)
222 {
223 	struct ieee80211com *ic = ni->ni_ic;
224 	struct ifnet *ifp = ic->ic_ifp;
225 
226 	m->m_pkthdr.rcvif = (void *) ni;
227 	IF_ENQUEUE(&ic->ic_mgtq, m);
228 	if_start(ifp);
229 	ifp->if_opackets++;
230 
231 	return 0;
232 }
233 
234 /*
235  * 802.11 output routine. This is (currently) used only to
236  * connect bpf write calls to the 802.11 layer for injecting
237  * raw 802.11 frames.  Note we locate the ieee80211com from
238  * the ifnet using a spare field setup at attach time.  This
239  * will go away when the virtual ap support comes in.
240  */
241 int
242 ieee80211_output(struct ifnet *ifp, struct mbuf *m,
243 	struct sockaddr *dst, struct rtentry *rt0)
244 {
245 #define senderr(e) do { error = (e); goto bad;} while (0)
246 	struct ieee80211com *ic = ifp->if_spare2;	/* XXX */
247 	struct ieee80211_node *ni = NULL;
248 	struct ieee80211_frame *wh;
249 	int error;
250 
251 	/*
252 	 * Hand to the 802.3 code if not tagged as
253 	 * a raw 802.11 frame.
254 	 */
255 	if (dst->sa_family != AF_IEEE80211)
256 		return ether_output(ifp, m, dst, rt0);
257 #ifdef MAC
258 	error = mac_check_ifnet_transmit(ifp, m);
259 	if (error)
260 		senderr(error);
261 #endif
262 	if (ifp->if_flags & IFF_MONITOR)
263 		senderr(ENETDOWN);
264 	if ((ifp->if_flags & IFF_UP) == 0)
265 		senderr(ENETDOWN);
266 
267 	/* XXX bypass bridge, pfil, carp, etc. */
268 
269 	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
270 		senderr(EIO);	/* XXX */
271 	wh = mtod(m, struct ieee80211_frame *);
272 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
273 	    IEEE80211_FC0_VERSION_0)
274 		senderr(EIO);	/* XXX */
275 
276 	/* locate destination node */
277 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
278 	case IEEE80211_FC1_DIR_NODS:
279 	case IEEE80211_FC1_DIR_FROMDS:
280 		ni = ieee80211_find_txnode(ic, wh->i_addr1);
281 		break;
282 	case IEEE80211_FC1_DIR_TODS:
283 	case IEEE80211_FC1_DIR_DSTODS:
284 		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
285 			senderr(EIO);	/* XXX */
286 		ni = ieee80211_find_txnode(ic, wh->i_addr3);
287 		break;
288 	default:
289 		senderr(EIO);	/* XXX */
290 	}
291 	if (ni == NULL) {
292 		/*
293 		 * Permit packets w/ bpf params through regardless
294 		 * (see below about sa_len).
295 		 */
296 		if (dst->sa_len == 0)
297 			senderr(EHOSTUNREACH);
298 		ni = ieee80211_ref_node(ic->ic_bss);
299 	}
300 
301 	/* XXX ctrl frames should go through */
302 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
303 	    (m->m_flags & M_PWR_SAV) == 0) {
304 		/*
305 		 * Station in power save mode; pass the frame
306 		 * to the 802.11 layer and continue.  We'll get
307 		 * the frame back when the time is right.
308 		 */
309 		ieee80211_pwrsave(ni, m);
310 		error = 0;
311 		goto reclaim;
312 	}
313 
314 	/* calculate priority so drivers can find the tx queue */
315 	/* XXX assumes an 802.3 frame */
316 	if (ieee80211_classify(ic, m, ni))
317 		senderr(EIO);		/* XXX */
318 
319 	BPF_MTAP(ifp, m);
320 	/*
321 	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
322 	 * present by setting the sa_len field of the sockaddr (yes,
323 	 * this is a hack).
324 	 * NB: we assume sa_data is suitably aligned to cast.
325 	 */
326 	return ic->ic_raw_xmit(ni, m, (const struct ieee80211_bpf_params *)
327 		(dst->sa_len ? dst->sa_data : NULL));
328 bad:
329 	if (m != NULL)
330 		m_freem(m);
331 reclaim:
332 	if (ni != NULL)
333 		ieee80211_free_node(ni);
334 	return error;
335 #undef senderr
336 }
337 
338 /*
339  * Send a null data frame to the specified node.
340  *
341  * NB: the caller is assumed to have setup a node reference
342  *     for use; this is necessary to deal with a race condition
343  *     when probing for inactive stations.
344  */
345 int
346 ieee80211_send_nulldata(struct ieee80211_node *ni)
347 {
348 	struct ieee80211com *ic = ni->ni_ic;
349 	struct ifnet *ifp = ic->ic_ifp;
350 	struct mbuf *m;
351 	struct ieee80211_frame *wh;
352 
353 	MGETHDR(m, M_NOWAIT, MT_DATA);
354 	if (m == NULL) {
355 		/* XXX debug msg */
356 		ieee80211_unref_node(&ni);
357 		ic->ic_stats.is_tx_nobuf++;
358 		return ENOMEM;
359 	}
360 	MH_ALIGN(m, sizeof(struct ieee80211_frame));
361 	m->m_pkthdr.rcvif = (void *) ni;
362 
363 	wh = mtod(m, struct ieee80211_frame *);
364 	ieee80211_send_setup(ic, ni, wh,
365 		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
366 		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
367 	/* NB: power management bit is never sent by an AP */
368 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
369 	    ic->ic_opmode != IEEE80211_M_HOSTAP &&
370 	    ic->ic_opmode != IEEE80211_M_WDS)
371 		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
372 	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
373 
374 	IEEE80211_NODE_STAT(ni, tx_data);
375 
376 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
377 	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
378 	    ether_sprintf(ni->ni_macaddr),
379 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
380 	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
381 
382 	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
383 	if_start(ifp);
384 
385 	return 0;
386 }
387 
388 /*
389  * Assign priority to a frame based on any vlan tag assigned
390  * to the station and/or any Diffserv setting in an IP header.
391  * Finally, if an ACM policy is setup (in station mode) it's
392  * applied.
393  */
394 int
395 ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
396 {
397 	int v_wme_ac, d_wme_ac, ac;
398 #ifdef INET
399 	struct ether_header *eh;
400 #endif
401 
402 	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
403 		ac = WME_AC_BE;
404 		goto done;
405 	}
406 
407 	/*
408 	 * If node has a vlan tag then all traffic
409 	 * to it must have a matching tag.
410 	 */
411 	v_wme_ac = 0;
412 	if (ni->ni_vlan != 0) {
413 		 if ((m->m_flags & M_VLANTAG) == 0) {
414 			IEEE80211_NODE_STAT(ni, tx_novlantag);
415 			return 1;
416 		}
417 		if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
418 		    EVL_VLANOFTAG(ni->ni_vlan)) {
419 			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
420 			return 1;
421 		}
422 		/* map vlan priority to AC */
423 		switch (EVL_PRIOFTAG(ni->ni_vlan)) {
424 		case 1:
425 		case 2:
426 			v_wme_ac = WME_AC_BK;
427 			break;
428 		case 0:
429 		case 3:
430 			v_wme_ac = WME_AC_BE;
431 			break;
432 		case 4:
433 		case 5:
434 			v_wme_ac = WME_AC_VI;
435 			break;
436 		case 6:
437 		case 7:
438 			v_wme_ac = WME_AC_VO;
439 			break;
440 		}
441 	}
442 
443 #ifdef INET
444 	eh = mtod(m, struct ether_header *);
445 	if (eh->ether_type == htons(ETHERTYPE_IP)) {
446 		const struct ip *ip = (struct ip *)
447 			(mtod(m, uint8_t *) + sizeof (*eh));
448 		/*
449 		 * IP frame, map the TOS field.
450 		 */
451 		switch (ip->ip_tos) {
452 		case 0x08:
453 		case 0x20:
454 			d_wme_ac = WME_AC_BK;	/* background */
455 			break;
456 		case 0x28:
457 		case 0xa0:
458 			d_wme_ac = WME_AC_VI;	/* video */
459 			break;
460 		case 0x30:			/* voice */
461 		case 0xe0:
462 		case 0x88:			/* XXX UPSD */
463 		case 0xb8:
464 			d_wme_ac = WME_AC_VO;
465 			break;
466 		default:
467 			d_wme_ac = WME_AC_BE;
468 			break;
469 		}
470 	} else {
471 #endif /* INET */
472 		d_wme_ac = WME_AC_BE;
473 #ifdef INET
474 	}
475 #endif
476 	/*
477 	 * Use highest priority AC.
478 	 */
479 	if (v_wme_ac > d_wme_ac)
480 		ac = v_wme_ac;
481 	else
482 		ac = d_wme_ac;
483 
484 	/*
485 	 * Apply ACM policy.
486 	 */
487 	if (ic->ic_opmode == IEEE80211_M_STA) {
488 		static const int acmap[4] = {
489 			WME_AC_BK,	/* WME_AC_BE */
490 			WME_AC_BK,	/* WME_AC_BK */
491 			WME_AC_BE,	/* WME_AC_VI */
492 			WME_AC_VI,	/* WME_AC_VO */
493 		};
494 		while (ac != WME_AC_BK &&
495 		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
496 			ac = acmap[ac];
497 	}
498 done:
499 	M_WME_SETAC(m, ac);
500 	return 0;
501 }
502 
503 /*
504  * Insure there is sufficient contiguous space to encapsulate the
505  * 802.11 data frame.  If room isn't already there, arrange for it.
506  * Drivers and cipher modules assume we have done the necessary work
507  * and fail rudely if they don't find the space they need.
508  */
509 static struct mbuf *
510 ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
511 	struct ieee80211_key *key, struct mbuf *m)
512 {
513 #define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
514 	int needed_space = ic->ic_headroom + hdrsize;
515 
516 	if (key != NULL) {
517 		/* XXX belongs in crypto code? */
518 		needed_space += key->wk_cipher->ic_header;
519 		/* XXX frags */
520 		/*
521 		 * When crypto is being done in the host we must insure
522 		 * the data are writable for the cipher routines; clone
523 		 * a writable mbuf chain.
524 		 * XXX handle SWMIC specially
525 		 */
526 		if (key->wk_flags & (IEEE80211_KEY_SWCRYPT|IEEE80211_KEY_SWMIC)) {
527 			m = m_unshare(m, M_NOWAIT);
528 			if (m == NULL) {
529 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
530 				    "%s: cannot get writable mbuf\n", __func__);
531 				ic->ic_stats.is_tx_nobuf++; /* XXX new stat */
532 				return NULL;
533 			}
534 		}
535 	}
536 	/*
537 	 * We know we are called just before stripping an Ethernet
538 	 * header and prepending an LLC header.  This means we know
539 	 * there will be
540 	 *	sizeof(struct ether_header) - sizeof(struct llc)
541 	 * bytes recovered to which we need additional space for the
542 	 * 802.11 header and any crypto header.
543 	 */
544 	/* XXX check trailing space and copy instead? */
545 	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
546 		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
547 		if (n == NULL) {
548 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
549 			    "%s: cannot expand storage\n", __func__);
550 			ic->ic_stats.is_tx_nobuf++;
551 			m_freem(m);
552 			return NULL;
553 		}
554 		KASSERT(needed_space <= MHLEN,
555 		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
556 		/*
557 		 * Setup new mbuf to have leading space to prepend the
558 		 * 802.11 header and any crypto header bits that are
559 		 * required (the latter are added when the driver calls
560 		 * back to ieee80211_crypto_encap to do crypto encapsulation).
561 		 */
562 		/* NB: must be first 'cuz it clobbers m_data */
563 		m_move_pkthdr(n, m);
564 		n->m_len = 0;			/* NB: m_gethdr does not set */
565 		n->m_data += needed_space;
566 		/*
567 		 * Pull up Ethernet header to create the expected layout.
568 		 * We could use m_pullup but that's overkill (i.e. we don't
569 		 * need the actual data) and it cannot fail so do it inline
570 		 * for speed.
571 		 */
572 		/* NB: struct ether_header is known to be contiguous */
573 		n->m_len += sizeof(struct ether_header);
574 		m->m_len -= sizeof(struct ether_header);
575 		m->m_data += sizeof(struct ether_header);
576 		/*
577 		 * Replace the head of the chain.
578 		 */
579 		n->m_next = m;
580 		m = n;
581 	}
582 	return m;
583 #undef TO_BE_RECLAIMED
584 }
585 
586 /*
587  * Return the transmit key to use in sending a unicast frame.
588  * If a unicast key is set we use that.  When no unicast key is set
589  * we fall back to the default transmit key.
590  */
591 static __inline struct ieee80211_key *
592 ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
593 {
594 	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
595 		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
596 		    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
597 			return NULL;
598 		return &ic->ic_nw_keys[ic->ic_def_txkey];
599 	} else {
600 		return &ni->ni_ucastkey;
601 	}
602 }
603 
604 /*
605  * Return the transmit key to use in sending a multicast frame.
606  * Multicast traffic always uses the group key which is installed as
607  * the default tx key.
608  */
609 static __inline struct ieee80211_key *
610 ieee80211_crypto_getmcastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
611 {
612 	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
613 	    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
614 		return NULL;
615 	return &ic->ic_nw_keys[ic->ic_def_txkey];
616 }
617 
618 /*
619  * Encapsulate an outbound data frame.  The mbuf chain is updated.
620  * If an error is encountered NULL is returned.  The caller is required
621  * to provide a node reference and pullup the ethernet header in the
622  * first mbuf.
623  */
624 struct mbuf *
625 ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
626 	struct ieee80211_node *ni)
627 {
628 	struct ether_header eh;
629 	struct ieee80211_frame *wh;
630 	struct ieee80211_key *key;
631 	struct llc *llc;
632 	int hdrsize, datalen, addqos, txfrag, isff;
633 
634 	/*
635 	 * Copy existing Ethernet header to a safe place.  The
636 	 * rest of the code assumes it's ok to strip it when
637 	 * reorganizing state for the final encapsulation.
638 	 */
639 	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
640 	memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
641 
642 	/*
643 	 * Insure space for additional headers.  First identify
644 	 * transmit key to use in calculating any buffer adjustments
645 	 * required.  This is also used below to do privacy
646 	 * encapsulation work.  Then calculate the 802.11 header
647 	 * size and any padding required by the driver.
648 	 *
649 	 * Note key may be NULL if we fall back to the default
650 	 * transmit key and that is not set.  In that case the
651 	 * buffer may not be expanded as needed by the cipher
652 	 * routines, but they will/should discard it.
653 	 */
654 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
655 		if (ic->ic_opmode == IEEE80211_M_STA ||
656 		    !IEEE80211_IS_MULTICAST(eh.ether_dhost))
657 			key = ieee80211_crypto_getucastkey(ic, ni);
658 		else
659 			key = ieee80211_crypto_getmcastkey(ic, ni);
660 		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
661 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
662 			    "[%s] no default transmit key (%s) deftxkey %u\n",
663 			    ether_sprintf(eh.ether_dhost), __func__,
664 			    ic->ic_def_txkey);
665 			ic->ic_stats.is_tx_nodefkey++;
666 			goto bad;
667 		}
668 	} else
669 		key = NULL;
670 	/* XXX 4-address format */
671 	/*
672 	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
673 	 * frames so suppress use.  This may be an issue if other
674 	 * ap's require all data frames to be QoS-encapsulated
675 	 * once negotiated in which case we'll need to make this
676 	 * configurable.
677 	 */
678 	addqos = (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) &&
679 		 eh.ether_type != htons(ETHERTYPE_PAE);
680 	if (addqos)
681 		hdrsize = sizeof(struct ieee80211_qosframe);
682 	else
683 		hdrsize = sizeof(struct ieee80211_frame);
684 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
685 		hdrsize = roundup(hdrsize, sizeof(uint32_t));
686 
687 	if ((isff = m->m_flags & M_FF) != 0) {
688 		struct mbuf *m2;
689 		struct ether_header eh2;
690 
691 		/*
692 		 * Fast frame encapsulation.  There must be two packets
693 		 * chained with m_nextpkt.  We do header adjustment for
694 		 * each, add the tunnel encapsulation, and then concatenate
695 		 * the mbuf chains to form a single frame for transmission.
696 		 */
697 		m2 = m->m_nextpkt;
698 		if (m2 == NULL) {
699 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
700 				"%s: only one frame\n", __func__);
701 			goto bad;
702 		}
703 		m->m_nextpkt = NULL;
704 		/*
705 		 * Include fast frame headers in adjusting header
706 		 * layout; this allocates space according to what
707 		 * ieee80211_encap_fastframe will do.
708 		 */
709 		m = ieee80211_mbuf_adjust(ic,
710 			hdrsize + sizeof(struct llc) + sizeof(uint32_t) + 2 +
711 			    sizeof(struct ether_header),
712 			key, m);
713 		if (m == NULL) {
714 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
715 			m_freem(m2);
716 			goto bad;
717 		}
718 		/*
719 		 * Copy second frame's Ethernet header out of line
720 		 * and adjust for encapsulation headers.  Note that
721 		 * we make room for padding in case there isn't room
722 		 * at the end of first frame.
723 		 */
724 		KASSERT(m2->m_len >= sizeof(eh2), ("no ethernet header!"));
725 		memcpy(&eh2, mtod(m2, caddr_t), sizeof(struct ether_header));
726 		m2 = ieee80211_mbuf_adjust(ic,
727 			ATH_FF_MAX_HDR_PAD + sizeof(struct ether_header),
728 			NULL, m2);
729 		if (m2 == NULL) {
730 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
731 			goto bad;
732 		}
733 		m = ieee80211_encap_fastframe(ic, m, &eh, m2, &eh2);
734 		if (m == NULL)
735 			goto bad;
736 	} else {
737 		/*
738 		 * Normal frame.
739 		 */
740 		m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
741 		if (m == NULL) {
742 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
743 			goto bad;
744 		}
745 		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
746 		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
747 		llc = mtod(m, struct llc *);
748 		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
749 		llc->llc_control = LLC_UI;
750 		llc->llc_snap.org_code[0] = 0;
751 		llc->llc_snap.org_code[1] = 0;
752 		llc->llc_snap.org_code[2] = 0;
753 		llc->llc_snap.ether_type = eh.ether_type;
754 	}
755 	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
756 
757 	M_PREPEND(m, hdrsize, M_DONTWAIT);
758 	if (m == NULL) {
759 		ic->ic_stats.is_tx_nobuf++;
760 		goto bad;
761 	}
762 	wh = mtod(m, struct ieee80211_frame *);
763 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
764 	*(uint16_t *)wh->i_dur = 0;
765 	switch (ic->ic_opmode) {
766 	case IEEE80211_M_STA:
767 		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
768 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
769 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
770 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
771 		break;
772 	case IEEE80211_M_IBSS:
773 	case IEEE80211_M_AHDEMO:
774 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
775 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
776 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
777 		/*
778 		 * NB: always use the bssid from ic_bss as the
779 		 *     neighbor's may be stale after an ibss merge
780 		 */
781 		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
782 		break;
783 	case IEEE80211_M_HOSTAP:
784 		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
785 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
786 		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
787 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
788 		break;
789 	case IEEE80211_M_MONITOR:
790 	case IEEE80211_M_WDS:
791 		goto bad;
792 	}
793 	if (m->m_flags & M_MORE_DATA)
794 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
795 	if (addqos) {
796 		struct ieee80211_qosframe *qwh =
797 			(struct ieee80211_qosframe *) wh;
798 		int ac, tid;
799 
800 		ac = M_WME_GETAC(m);
801 		/* map from access class/queue to 11e header priorty value */
802 		tid = WME_AC_TO_TID(ac);
803 		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
804 		/*
805 		 * Check if A-MPDU tx aggregation is setup or if we
806 		 * should try to enable it.  The sta must be associated
807 		 * with HT and A-MPDU enabled for use.  On the first
808 		 * frame that goes out We issue an ADDBA request and
809 		 * wait for a reply.  The frame being encapsulated
810 		 * will go out w/o using A-MPDU, or possibly it might
811 		 * be collected by the driver and held/retransmit.
812 		 * ieee80211_ampdu_request handles staggering requests
813 		 * in case the receiver NAK's us or we are otherwise
814 		 * unable to establish a BA stream.
815 		 */
816 		if ((ni->ni_flags & IEEE80211_NODE_HT) &&
817 		    (ic->ic_flags_ext & IEEE80211_FEXT_AMPDU_TX)) {
818 			struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
819 
820 			if (IEEE80211_AMPDU_RUNNING(tap)) {
821 				/*
822 				 * Operational, mark frame for aggregation.
823 				 */
824 				qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_BA;
825 			} else if (!IEEE80211_AMPDU_REQUESTED(tap)) {
826 				/*
827 				 * Not negotiated yet, request service.
828 				 */
829 				ieee80211_ampdu_request(ni, tap);
830 			}
831 		}
832 		/* XXX works even when BA marked above */
833 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
834 			qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
835 		qwh->i_qos[1] = 0;
836 		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
837 
838 		*(uint16_t *)wh->i_seq =
839 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
840 		ni->ni_txseqs[tid]++;
841 	} else {
842 		*(uint16_t *)wh->i_seq =
843 		    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
844 		ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
845 	}
846 	/* check if xmit fragmentation is required */
847 	txfrag = (m->m_pkthdr.len > ic->ic_fragthreshold &&
848 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
849 	    !isff);		/* NB: don't fragment ff's */
850 	if (key != NULL) {
851 		/*
852 		 * IEEE 802.1X: send EAPOL frames always in the clear.
853 		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
854 		 */
855 		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
856 		    ((ic->ic_flags & IEEE80211_F_WPA) &&
857 		     (ic->ic_opmode == IEEE80211_M_STA ?
858 		      !IEEE80211_KEY_UNDEFINED(key) :
859 		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
860 			wh->i_fc[1] |= IEEE80211_FC1_WEP;
861 			if (!ieee80211_crypto_enmic(ic, key, m, txfrag)) {
862 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
863 				    "[%s] enmic failed, discard frame\n",
864 				    ether_sprintf(eh.ether_dhost));
865 				ic->ic_stats.is_crypto_enmicfail++;
866 				goto bad;
867 			}
868 		}
869 	}
870 	/*
871 	 * NB: frag flags may leak from above; they should only
872 	 *     be set on return to the caller if we fragment at
873 	 *     the 802.11 layer.
874 	 */
875 	m->m_flags &= ~(M_FRAG | M_FIRSTFRAG);
876 	if (txfrag && !ieee80211_fragment(ic, m, hdrsize,
877 	    key != NULL ? key->wk_cipher->ic_header : 0, ic->ic_fragthreshold))
878 		goto bad;
879 
880 	IEEE80211_NODE_STAT(ni, tx_data);
881 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
882 		IEEE80211_NODE_STAT(ni, tx_mcast);
883 	else
884 		IEEE80211_NODE_STAT(ni, tx_ucast);
885 	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
886 
887 	return m;
888 bad:
889 	if (m != NULL)
890 		m_freem(m);
891 	return NULL;
892 }
893 
894 /*
895  * Do Ethernet-LLC encapsulation for each payload in a fast frame
896  * tunnel encapsulation.  The frame is assumed to have an Ethernet
897  * header at the front that must be stripped before prepending the
898  * LLC followed by the Ethernet header passed in (with an Ethernet
899  * type that specifies the payload size).
900  */
901 static struct mbuf *
902 ieee80211_encap1(struct ieee80211com *ic, struct mbuf *m,
903 	const struct ether_header *eh)
904 {
905 	struct llc *llc;
906 	uint16_t payload;
907 
908 	/* XXX optimize by combining m_adj+M_PREPEND */
909 	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
910 	llc = mtod(m, struct llc *);
911 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
912 	llc->llc_control = LLC_UI;
913 	llc->llc_snap.org_code[0] = 0;
914 	llc->llc_snap.org_code[1] = 0;
915 	llc->llc_snap.org_code[2] = 0;
916 	llc->llc_snap.ether_type = eh->ether_type;
917 	payload = m->m_pkthdr.len;		/* NB: w/o Ethernet header */
918 
919 	M_PREPEND(m, sizeof(struct ether_header), M_DONTWAIT);
920 	if (m == NULL) {		/* XXX cannot happen */
921 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
922 			"%s: no space for ether_header\n", __func__);
923 		ic->ic_stats.is_tx_nobuf++;
924 		return NULL;
925 	}
926 	ETHER_HEADER_COPY(mtod(m, void *), eh);
927 	mtod(m, struct ether_header *)->ether_type = htons(payload);
928 	return m;
929 }
930 
931 /*
932  * Do fast frame tunnel encapsulation.  The two frames and
933  * Ethernet headers are supplied.  The caller is assumed to
934  * have arrange for space in the mbuf chains for encapsulating
935  * headers (to avoid major mbuf fragmentation).
936  *
937  * The encapsulated frame is returned or NULL if there is a
938  * problem (should not happen).
939  */
940 static struct mbuf *
941 ieee80211_encap_fastframe(struct ieee80211com *ic,
942 	struct mbuf *m1, const struct ether_header *eh1,
943 	struct mbuf *m2, const struct ether_header *eh2)
944 {
945 	struct llc *llc;
946 	struct mbuf *m;
947 	int pad;
948 
949 	/*
950 	 * First, each frame gets a standard encapsulation.
951 	 */
952 	m1 = ieee80211_encap1(ic, m1, eh1);
953 	if (m1 == NULL) {
954 		m_freem(m2);
955 		return NULL;
956 	}
957 	m2 = ieee80211_encap1(ic, m2, eh2);
958 	if (m2 == NULL) {
959 		m_freem(m1);
960 		return NULL;
961 	}
962 
963 	/*
964 	 * Pad leading frame to a 4-byte boundary.  If there
965 	 * is space at the end of the first frame, put it
966 	 * there; otherwise prepend to the front of the second
967 	 * frame.  We know doing the second will always work
968 	 * because we reserve space above.  We prefer appending
969 	 * as this typically has better DMA alignment properties.
970 	 */
971 	for (m = m1; m->m_next != NULL; m = m->m_next)
972 		;
973 	pad = roundup2(m1->m_pkthdr.len, 4) - m1->m_pkthdr.len;
974 	if (pad) {
975 		if (M_TRAILINGSPACE(m) < pad) {		/* prepend to second */
976 			m2->m_data -= pad;
977 			m2->m_len += pad;
978 			m2->m_pkthdr.len += pad;
979 		} else {				/* append to first */
980 			m->m_len += pad;
981 			m1->m_pkthdr.len += pad;
982 		}
983 	}
984 
985 	/*
986 	 * Now, stick 'em together and prepend the tunnel headers;
987 	 * first the Atheros tunnel header (all zero for now) and
988 	 * then a special fast frame LLC.
989 	 *
990 	 * XXX optimize by prepending together
991 	 */
992 	m->m_next = m2;			/* NB: last mbuf from above */
993 	m1->m_pkthdr.len += m2->m_pkthdr.len;
994 	M_PREPEND(m1, sizeof(uint32_t)+2, M_DONTWAIT);
995 	if (m1 == NULL) {		/* XXX cannot happen */
996 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
997 			"%s: no space for tunnel header\n", __func__);
998 		ic->ic_stats.is_tx_nobuf++;
999 		return NULL;
1000 	}
1001 	memset(mtod(m1, void *), 0, sizeof(uint32_t)+2);
1002 
1003 	M_PREPEND(m1, sizeof(struct llc), M_DONTWAIT);
1004 	if (m1 == NULL) {		/* XXX cannot happen */
1005 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
1006 			"%s: no space for llc header\n", __func__);
1007 		ic->ic_stats.is_tx_nobuf++;
1008 		return NULL;
1009 	}
1010 	llc = mtod(m1, struct llc *);
1011 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1012 	llc->llc_control = LLC_UI;
1013 	llc->llc_snap.org_code[0] = ATH_FF_SNAP_ORGCODE_0;
1014 	llc->llc_snap.org_code[1] = ATH_FF_SNAP_ORGCODE_1;
1015 	llc->llc_snap.org_code[2] = ATH_FF_SNAP_ORGCODE_2;
1016 	llc->llc_snap.ether_type = htons(ATH_FF_ETH_TYPE);
1017 
1018 	ic->ic_stats.is_ff_encap++;
1019 
1020 	return m1;
1021 }
1022 
1023 /*
1024  * Fragment the frame according to the specified mtu.
1025  * The size of the 802.11 header (w/o padding) is provided
1026  * so we don't need to recalculate it.  We create a new
1027  * mbuf for each fragment and chain it through m_nextpkt;
1028  * we might be able to optimize this by reusing the original
1029  * packet's mbufs but that is significantly more complicated.
1030  */
1031 static int
1032 ieee80211_fragment(struct ieee80211com *ic, struct mbuf *m0,
1033 	u_int hdrsize, u_int ciphdrsize, u_int mtu)
1034 {
1035 	struct ieee80211_frame *wh, *whf;
1036 	struct mbuf *m, *prev, *next;
1037 	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1038 
1039 	KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1040 	KASSERT(m0->m_pkthdr.len > mtu,
1041 		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1042 
1043 	wh = mtod(m0, struct ieee80211_frame *);
1044 	/* NB: mark the first frag; it will be propagated below */
1045 	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1046 	totalhdrsize = hdrsize + ciphdrsize;
1047 	fragno = 1;
1048 	off = mtu - ciphdrsize;
1049 	remainder = m0->m_pkthdr.len - off;
1050 	prev = m0;
1051 	do {
1052 		fragsize = totalhdrsize + remainder;
1053 		if (fragsize > mtu)
1054 			fragsize = mtu;
1055 		KASSERT(fragsize < MCLBYTES,
1056 			("fragment size %u too big!", fragsize));
1057 		if (fragsize > MHLEN)
1058 			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1059 		else
1060 			m = m_gethdr(M_DONTWAIT, MT_DATA);
1061 		if (m == NULL)
1062 			goto bad;
1063 		/* leave room to prepend any cipher header */
1064 		m_align(m, fragsize - ciphdrsize);
1065 
1066 		/*
1067 		 * Form the header in the fragment.  Note that since
1068 		 * we mark the first fragment with the MORE_FRAG bit
1069 		 * it automatically is propagated to each fragment; we
1070 		 * need only clear it on the last fragment (done below).
1071 		 */
1072 		whf = mtod(m, struct ieee80211_frame *);
1073 		memcpy(whf, wh, hdrsize);
1074 		*(uint16_t *)&whf->i_seq[0] |= htole16(
1075 			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
1076 				IEEE80211_SEQ_FRAG_SHIFT);
1077 		fragno++;
1078 
1079 		payload = fragsize - totalhdrsize;
1080 		/* NB: destination is known to be contiguous */
1081 		m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize);
1082 		m->m_len = hdrsize + payload;
1083 		m->m_pkthdr.len = hdrsize + payload;
1084 		m->m_flags |= M_FRAG;
1085 
1086 		/* chain up the fragment */
1087 		prev->m_nextpkt = m;
1088 		prev = m;
1089 
1090 		/* deduct fragment just formed */
1091 		remainder -= payload;
1092 		off += payload;
1093 	} while (remainder != 0);
1094 	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
1095 
1096 	/* strip first mbuf now that everything has been copied */
1097 	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
1098 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1099 
1100 	ic->ic_stats.is_tx_fragframes++;
1101 	ic->ic_stats.is_tx_frags += fragno-1;
1102 
1103 	return 1;
1104 bad:
1105 	/* reclaim fragments but leave original frame for caller to free */
1106 	for (m = m0->m_nextpkt; m != NULL; m = next) {
1107 		next = m->m_nextpkt;
1108 		m->m_nextpkt = NULL;		/* XXX paranoid */
1109 		m_freem(m);
1110 	}
1111 	m0->m_nextpkt = NULL;
1112 	return 0;
1113 }
1114 
1115 /*
1116  * Add a supported rates element id to a frame.
1117  */
1118 static uint8_t *
1119 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
1120 {
1121 	int nrates;
1122 
1123 	*frm++ = IEEE80211_ELEMID_RATES;
1124 	nrates = rs->rs_nrates;
1125 	if (nrates > IEEE80211_RATE_SIZE)
1126 		nrates = IEEE80211_RATE_SIZE;
1127 	*frm++ = nrates;
1128 	memcpy(frm, rs->rs_rates, nrates);
1129 	return frm + nrates;
1130 }
1131 
1132 /*
1133  * Add an extended supported rates element id to a frame.
1134  */
1135 static uint8_t *
1136 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
1137 {
1138 	/*
1139 	 * Add an extended supported rates element if operating in 11g mode.
1140 	 */
1141 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
1142 		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
1143 		*frm++ = IEEE80211_ELEMID_XRATES;
1144 		*frm++ = nrates;
1145 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
1146 		frm += nrates;
1147 	}
1148 	return frm;
1149 }
1150 
1151 /*
1152  * Add an ssid elemet to a frame.
1153  */
1154 static uint8_t *
1155 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
1156 {
1157 	*frm++ = IEEE80211_ELEMID_SSID;
1158 	*frm++ = len;
1159 	memcpy(frm, ssid, len);
1160 	return frm + len;
1161 }
1162 
1163 /*
1164  * Add an erp element to a frame.
1165  */
1166 static uint8_t *
1167 ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
1168 {
1169 	uint8_t erp;
1170 
1171 	*frm++ = IEEE80211_ELEMID_ERP;
1172 	*frm++ = 1;
1173 	erp = 0;
1174 	if (ic->ic_nonerpsta != 0)
1175 		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
1176 	if (ic->ic_flags & IEEE80211_F_USEPROT)
1177 		erp |= IEEE80211_ERP_USE_PROTECTION;
1178 	if (ic->ic_flags & IEEE80211_F_USEBARKER)
1179 		erp |= IEEE80211_ERP_LONG_PREAMBLE;
1180 	*frm++ = erp;
1181 	return frm;
1182 }
1183 
1184 static uint8_t *
1185 ieee80211_setup_wpa_ie(struct ieee80211com *ic, uint8_t *ie)
1186 {
1187 #define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
1188 #define	ADDSHORT(frm, v) do {			\
1189 	frm[0] = (v) & 0xff;			\
1190 	frm[1] = (v) >> 8;			\
1191 	frm += 2;				\
1192 } while (0)
1193 #define	ADDSELECTOR(frm, sel) do {		\
1194 	memcpy(frm, sel, 4);			\
1195 	frm += 4;				\
1196 } while (0)
1197 	static const uint8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
1198 	static const uint8_t cipher_suite[][4] = {
1199 		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
1200 		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
1201 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
1202 		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
1203 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1204 		{ WPA_OUI_BYTES, WPA_CSE_NULL },
1205 	};
1206 	static const uint8_t wep104_suite[4] =
1207 		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
1208 	static const uint8_t key_mgt_unspec[4] =
1209 		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
1210 	static const uint8_t key_mgt_psk[4] =
1211 		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
1212 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1213 	uint8_t *frm = ie;
1214 	uint8_t *selcnt;
1215 
1216 	*frm++ = IEEE80211_ELEMID_VENDOR;
1217 	*frm++ = 0;				/* length filled in below */
1218 	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
1219 	frm += sizeof(oui);
1220 	ADDSHORT(frm, WPA_VERSION);
1221 
1222 	/* XXX filter out CKIP */
1223 
1224 	/* multicast cipher */
1225 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1226 	    rsn->rsn_mcastkeylen >= 13)
1227 		ADDSELECTOR(frm, wep104_suite);
1228 	else
1229 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1230 
1231 	/* unicast cipher list */
1232 	selcnt = frm;
1233 	ADDSHORT(frm, 0);			/* selector count */
1234 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
1235 		selcnt[0]++;
1236 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1237 	}
1238 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
1239 		selcnt[0]++;
1240 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1241 	}
1242 
1243 	/* authenticator selector list */
1244 	selcnt = frm;
1245 	ADDSHORT(frm, 0);			/* selector count */
1246 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1247 		selcnt[0]++;
1248 		ADDSELECTOR(frm, key_mgt_unspec);
1249 	}
1250 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1251 		selcnt[0]++;
1252 		ADDSELECTOR(frm, key_mgt_psk);
1253 	}
1254 
1255 	/* optional capabilities */
1256 	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
1257 		ADDSHORT(frm, rsn->rsn_caps);
1258 
1259 	/* calculate element length */
1260 	ie[1] = frm - ie - 2;
1261 	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1262 		("WPA IE too big, %u > %zu",
1263 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1264 	return frm;
1265 #undef ADDSHORT
1266 #undef ADDSELECTOR
1267 #undef WPA_OUI_BYTES
1268 }
1269 
1270 static uint8_t *
1271 ieee80211_setup_rsn_ie(struct ieee80211com *ic, uint8_t *ie)
1272 {
1273 #define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
1274 #define	ADDSHORT(frm, v) do {			\
1275 	frm[0] = (v) & 0xff;			\
1276 	frm[1] = (v) >> 8;			\
1277 	frm += 2;				\
1278 } while (0)
1279 #define	ADDSELECTOR(frm, sel) do {		\
1280 	memcpy(frm, sel, 4);			\
1281 	frm += 4;				\
1282 } while (0)
1283 	static const uint8_t cipher_suite[][4] = {
1284 		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
1285 		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
1286 		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
1287 		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
1288 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
1289 		{ RSN_OUI_BYTES, RSN_CSE_NULL },
1290 	};
1291 	static const uint8_t wep104_suite[4] =
1292 		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
1293 	static const uint8_t key_mgt_unspec[4] =
1294 		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
1295 	static const uint8_t key_mgt_psk[4] =
1296 		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
1297 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
1298 	uint8_t *frm = ie;
1299 	uint8_t *selcnt;
1300 
1301 	*frm++ = IEEE80211_ELEMID_RSN;
1302 	*frm++ = 0;				/* length filled in below */
1303 	ADDSHORT(frm, RSN_VERSION);
1304 
1305 	/* XXX filter out CKIP */
1306 
1307 	/* multicast cipher */
1308 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
1309 	    rsn->rsn_mcastkeylen >= 13)
1310 		ADDSELECTOR(frm, wep104_suite);
1311 	else
1312 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
1313 
1314 	/* unicast cipher list */
1315 	selcnt = frm;
1316 	ADDSHORT(frm, 0);			/* selector count */
1317 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
1318 		selcnt[0]++;
1319 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
1320 	}
1321 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
1322 		selcnt[0]++;
1323 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
1324 	}
1325 
1326 	/* authenticator selector list */
1327 	selcnt = frm;
1328 	ADDSHORT(frm, 0);			/* selector count */
1329 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
1330 		selcnt[0]++;
1331 		ADDSELECTOR(frm, key_mgt_unspec);
1332 	}
1333 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
1334 		selcnt[0]++;
1335 		ADDSELECTOR(frm, key_mgt_psk);
1336 	}
1337 
1338 	/* optional capabilities */
1339 	ADDSHORT(frm, rsn->rsn_caps);
1340 	/* XXX PMKID */
1341 
1342 	/* calculate element length */
1343 	ie[1] = frm - ie - 2;
1344 	KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
1345 		("RSN IE too big, %u > %zu",
1346 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
1347 	return frm;
1348 #undef ADDSELECTOR
1349 #undef ADDSHORT
1350 #undef RSN_OUI_BYTES
1351 }
1352 
1353 /*
1354  * Add a WPA/RSN element to a frame.
1355  */
1356 static uint8_t *
1357 ieee80211_add_wpa(uint8_t *frm, struct ieee80211com *ic)
1358 {
1359 
1360 	KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
1361 	if (ic->ic_flags & IEEE80211_F_WPA2)
1362 		frm = ieee80211_setup_rsn_ie(ic, frm);
1363 	if (ic->ic_flags & IEEE80211_F_WPA1)
1364 		frm = ieee80211_setup_wpa_ie(ic, frm);
1365 	return frm;
1366 }
1367 
1368 #define	WME_OUI_BYTES		0x00, 0x50, 0xf2
1369 /*
1370  * Add a WME information element to a frame.
1371  */
1372 static uint8_t *
1373 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
1374 {
1375 	static const struct ieee80211_wme_info info = {
1376 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1377 		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
1378 		.wme_oui	= { WME_OUI_BYTES },
1379 		.wme_type	= WME_OUI_TYPE,
1380 		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
1381 		.wme_version	= WME_VERSION,
1382 		.wme_info	= 0,
1383 	};
1384 	memcpy(frm, &info, sizeof(info));
1385 	return frm + sizeof(info);
1386 }
1387 
1388 /*
1389  * Add a WME parameters element to a frame.
1390  */
1391 static uint8_t *
1392 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
1393 {
1394 #define	SM(_v, _f)	(((_v) << _f##_S) & _f)
1395 #define	ADDSHORT(frm, v) do {			\
1396 	frm[0] = (v) & 0xff;			\
1397 	frm[1] = (v) >> 8;			\
1398 	frm += 2;				\
1399 } while (0)
1400 	/* NB: this works 'cuz a param has an info at the front */
1401 	static const struct ieee80211_wme_info param = {
1402 		.wme_id		= IEEE80211_ELEMID_VENDOR,
1403 		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
1404 		.wme_oui	= { WME_OUI_BYTES },
1405 		.wme_type	= WME_OUI_TYPE,
1406 		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
1407 		.wme_version	= WME_VERSION,
1408 	};
1409 	int i;
1410 
1411 	memcpy(frm, &param, sizeof(param));
1412 	frm += __offsetof(struct ieee80211_wme_info, wme_info);
1413 	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
1414 	*frm++ = 0;					/* reserved field */
1415 	for (i = 0; i < WME_NUM_AC; i++) {
1416 		const struct wmeParams *ac =
1417 		       &wme->wme_bssChanParams.cap_wmeParams[i];
1418 		*frm++ = SM(i, WME_PARAM_ACI)
1419 		       | SM(ac->wmep_acm, WME_PARAM_ACM)
1420 		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
1421 		       ;
1422 		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
1423 		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
1424 		       ;
1425 		ADDSHORT(frm, ac->wmep_txopLimit);
1426 	}
1427 	return frm;
1428 #undef SM
1429 #undef ADDSHORT
1430 }
1431 #undef WME_OUI_BYTES
1432 
1433 #define	ATH_OUI_BYTES		0x00, 0x03, 0x7f
1434 /*
1435  * Add a WME information element to a frame.
1436  */
1437 static uint8_t *
1438 ieee80211_add_ath(uint8_t *frm, uint8_t caps, uint16_t defkeyix)
1439 {
1440 	static const struct ieee80211_ath_ie info = {
1441 		.ath_id		= IEEE80211_ELEMID_VENDOR,
1442 		.ath_len	= sizeof(struct ieee80211_ath_ie) - 2,
1443 		.ath_oui	= { ATH_OUI_BYTES },
1444 		.ath_oui_type	= ATH_OUI_TYPE,
1445 		.ath_oui_subtype= ATH_OUI_SUBTYPE,
1446 		.ath_version	= ATH_OUI_VERSION,
1447 	};
1448 	struct ieee80211_ath_ie *ath = (struct ieee80211_ath_ie *) frm;
1449 
1450 	memcpy(frm, &info, sizeof(info));
1451 	ath->ath_capability = caps;
1452 	ath->ath_defkeyix[0] = (defkeyix & 0xff);
1453 	ath->ath_defkeyix[1] = ((defkeyix >> 8) & 0xff);
1454 	return frm + sizeof(info);
1455 }
1456 #undef ATH_OUI_BYTES
1457 
1458 /*
1459  * Send a probe request frame with the specified ssid
1460  * and any optional information element data.
1461  */
1462 int
1463 ieee80211_send_probereq(struct ieee80211_node *ni,
1464 	const uint8_t sa[IEEE80211_ADDR_LEN],
1465 	const uint8_t da[IEEE80211_ADDR_LEN],
1466 	const uint8_t bssid[IEEE80211_ADDR_LEN],
1467 	const uint8_t *ssid, size_t ssidlen,
1468 	const void *optie, size_t optielen)
1469 {
1470 	struct ieee80211com *ic = ni->ni_ic;
1471 	struct ieee80211_frame *wh;
1472 	const struct ieee80211_rateset *rs;
1473 	struct mbuf *m;
1474 	uint8_t *frm;
1475 
1476 	/*
1477 	 * Hold a reference on the node so it doesn't go away until after
1478 	 * the xmit is complete all the way in the driver.  On error we
1479 	 * will remove our reference.
1480 	 */
1481 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1482 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1483 		__func__, __LINE__,
1484 		ni, ether_sprintf(ni->ni_macaddr),
1485 		ieee80211_node_refcnt(ni)+1);
1486 	ieee80211_ref_node(ni);
1487 
1488 	/*
1489 	 * prreq frame format
1490 	 *	[tlv] ssid
1491 	 *	[tlv] supported rates
1492 	 *	[tlv] extended supported rates
1493 	 *	[tlv] user-specified ie's
1494 	 */
1495 	m = ieee80211_getmgtframe(&frm,
1496 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
1497 		 2 + IEEE80211_NWID_LEN
1498 	       + 2 + IEEE80211_RATE_SIZE
1499 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1500 	       + (optie != NULL ? optielen : 0)
1501 	);
1502 	if (m == NULL) {
1503 		ic->ic_stats.is_tx_nobuf++;
1504 		ieee80211_free_node(ni);
1505 		return ENOMEM;
1506 	}
1507 
1508 	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1509 	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1510 	frm = ieee80211_add_rates(frm, rs);
1511 	frm = ieee80211_add_xrates(frm, rs);
1512 
1513 	if (optie != NULL) {
1514 		memcpy(frm, optie, optielen);
1515 		frm += optielen;
1516 	}
1517 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1518 
1519 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
1520 	if (m == NULL)
1521 		return ENOMEM;
1522 	KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
1523 	m->m_pkthdr.rcvif = (void *)ni;
1524 
1525 	wh = mtod(m, struct ieee80211_frame *);
1526 	ieee80211_send_setup(ic, ni, wh,
1527 		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1528 		sa, da, bssid);
1529 	/* XXX power management? */
1530 
1531 	IEEE80211_NODE_STAT(ni, tx_probereq);
1532 	IEEE80211_NODE_STAT(ni, tx_mgmt);
1533 
1534 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1535 	    "[%s] send probe req on channel %u\n",
1536 	    ether_sprintf(wh->i_addr1),
1537 	    ieee80211_chan2ieee(ic, ic->ic_curchan));
1538 
1539 	IF_ENQUEUE(&ic->ic_mgtq, m);
1540 	if_start(ic->ic_ifp);
1541 	return 0;
1542 }
1543 
1544 /*
1545  * Calculate capability information for mgt frames.
1546  */
1547 static uint16_t
1548 getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
1549 {
1550 	uint16_t capinfo;
1551 
1552 	KASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
1553 
1554 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1555 		capinfo = IEEE80211_CAPINFO_ESS;
1556 	else if (ic->ic_opmode == IEEE80211_M_IBSS)
1557 		capinfo = IEEE80211_CAPINFO_IBSS;
1558 	else
1559 		capinfo = 0;
1560 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1561 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1562 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1563 	    IEEE80211_IS_CHAN_2GHZ(chan))
1564 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1565 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1566 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1567 	return capinfo;
1568 }
1569 
1570 /*
1571  * Send a management frame.  The node is for the destination (or ic_bss
1572  * when in station mode).  Nodes other than ic_bss have their reference
1573  * count bumped to reflect our use for an indeterminant time.
1574  */
1575 int
1576 ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1577 	int type, int arg)
1578 {
1579 #define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1580 	struct mbuf *m;
1581 	uint8_t *frm;
1582 	uint16_t capinfo;
1583 	int has_challenge, is_shared_key, ret, status;
1584 
1585 	KASSERT(ni != NULL, ("null node"));
1586 
1587 	/*
1588 	 * Hold a reference on the node so it doesn't go away until after
1589 	 * the xmit is complete all the way in the driver.  On error we
1590 	 * will remove our reference.
1591 	 */
1592 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1593 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
1594 		__func__, __LINE__,
1595 		ni, ether_sprintf(ni->ni_macaddr),
1596 		ieee80211_node_refcnt(ni)+1);
1597 	ieee80211_ref_node(ni);
1598 
1599 	switch (type) {
1600 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1601 		/*
1602 		 * probe response frame format
1603 		 *	[8] time stamp
1604 		 *	[2] beacon interval
1605 		 *	[2] cabability information
1606 		 *	[tlv] ssid
1607 		 *	[tlv] supported rates
1608 		 *	[tlv] parameter set (FH/DS)
1609 		 *	[tlv] parameter set (IBSS)
1610 		 *	[tlv] extended rate phy (ERP)
1611 		 *	[tlv] extended supported rates
1612 		 *	[tlv] WPA
1613 		 *	[tlv] WME (optional)
1614 		 *	[tlv] HT capabilities
1615 		 *	[tlv] HT information
1616 		 *	[tlv] Vendor OUI HT capabilities (optional)
1617 		 *	[tlv] Vendor OUI HT information (optional)
1618 		 *	[tlv] Atheros capabilities
1619 		 */
1620 		m = ieee80211_getmgtframe(&frm,
1621 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1622 			 8
1623 		       + sizeof(uint16_t)
1624 		       + sizeof(uint16_t)
1625 		       + 2 + IEEE80211_NWID_LEN
1626 		       + 2 + IEEE80211_RATE_SIZE
1627 		       + 7	/* max(7,3) */
1628 		       + 6
1629 		       + 3
1630 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1631 		       /* XXX !WPA1+WPA2 fits w/o a cluster */
1632 		       + (ic->ic_flags & IEEE80211_F_WPA ?
1633 				2*sizeof(struct ieee80211_ie_wpa) : 0)
1634 		       + sizeof(struct ieee80211_wme_param)
1635 		       /* XXX check for cluster requirement */
1636 		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
1637 		       + 2*sizeof(struct ieee80211_ie_htinfo) + 4
1638 		       + sizeof(struct ieee80211_ath_ie)
1639 		);
1640 		if (m == NULL)
1641 			senderr(ENOMEM, is_tx_nobuf);
1642 
1643 		memset(frm, 0, 8);	/* timestamp should be filled later */
1644 		frm += 8;
1645 		*(uint16_t *)frm = htole16(ic->ic_bss->ni_intval);
1646 		frm += 2;
1647 		capinfo = getcapinfo(ic, ic->ic_curchan);
1648 		*(uint16_t *)frm = htole16(capinfo);
1649 		frm += 2;
1650 
1651 		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
1652 				ic->ic_bss->ni_esslen);
1653 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1654 
1655 		if (IEEE80211_IS_CHAN_FHSS(ic->ic_curchan)) {
1656                         *frm++ = IEEE80211_ELEMID_FHPARMS;
1657                         *frm++ = 5;
1658                         *frm++ = ni->ni_fhdwell & 0x00ff;
1659                         *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1660                         *frm++ = IEEE80211_FH_CHANSET(
1661 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1662                         *frm++ = IEEE80211_FH_CHANPAT(
1663 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
1664                         *frm++ = ni->ni_fhindex;
1665 		} else {
1666 			*frm++ = IEEE80211_ELEMID_DSPARMS;
1667 			*frm++ = 1;
1668 			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
1669 		}
1670 
1671 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
1672 			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1673 			*frm++ = 2;
1674 			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1675 		}
1676 		if (ic->ic_flags & IEEE80211_F_WPA)
1677 			frm = ieee80211_add_wpa(frm, ic);
1678 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
1679 			frm = ieee80211_add_erp(frm, ic);
1680 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1681 		if (ic->ic_flags & IEEE80211_F_WME)
1682 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1683 		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1684 			frm = ieee80211_add_htcap(frm, ni);
1685 			frm = ieee80211_add_htinfo(frm, ni);
1686 			if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT) {
1687 				frm = ieee80211_add_htcap_vendor(frm, ni);
1688 				frm = ieee80211_add_htinfo_vendor(frm, ni);
1689 			}
1690 		}
1691 		if (ni->ni_ath_ie != NULL)
1692 			frm = ieee80211_add_ath(frm, ni->ni_ath_flags,
1693 				ni->ni_ath_defkeyix);
1694 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1695 		break;
1696 
1697 	case IEEE80211_FC0_SUBTYPE_AUTH:
1698 		status = arg >> 16;
1699 		arg &= 0xffff;
1700 		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1701 		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1702 		    ni->ni_challenge != NULL);
1703 
1704 		/*
1705 		 * Deduce whether we're doing open authentication or
1706 		 * shared key authentication.  We do the latter if
1707 		 * we're in the middle of a shared key authentication
1708 		 * handshake or if we're initiating an authentication
1709 		 * request and configured to use shared key.
1710 		 */
1711 		is_shared_key = has_challenge ||
1712 		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1713 		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1714 		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1715 
1716 		m = ieee80211_getmgtframe(&frm,
1717 			  ic->ic_headroom + sizeof(struct ieee80211_frame),
1718 			  3 * sizeof(uint16_t)
1719 			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1720 				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
1721 		);
1722 		if (m == NULL)
1723 			senderr(ENOMEM, is_tx_nobuf);
1724 
1725 		((uint16_t *)frm)[0] =
1726 		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1727 		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
1728 		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
1729 		((uint16_t *)frm)[2] = htole16(status);/* status */
1730 
1731 		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1732 			((uint16_t *)frm)[3] =
1733 			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
1734 			    IEEE80211_ELEMID_CHALLENGE);
1735 			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
1736 			    IEEE80211_CHALLENGE_LEN);
1737 			m->m_pkthdr.len = m->m_len =
1738 				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
1739 			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1740 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1741 				    "[%s] request encrypt frame (%s)\n",
1742 				    ether_sprintf(ni->ni_macaddr), __func__);
1743 				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
1744 			}
1745 		} else
1746 			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
1747 
1748 		/* XXX not right for shared key */
1749 		if (status == IEEE80211_STATUS_SUCCESS)
1750 			IEEE80211_NODE_STAT(ni, tx_auth);
1751 		else
1752 			IEEE80211_NODE_STAT(ni, tx_auth_fail);
1753 
1754 		if (ic->ic_opmode == IEEE80211_M_STA)
1755 			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1756 				(void *) ic->ic_state);
1757 		break;
1758 
1759 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
1760 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1761 			"[%s] send station deauthenticate (reason %d)\n",
1762 			ether_sprintf(ni->ni_macaddr), arg);
1763 		m = ieee80211_getmgtframe(&frm,
1764 			ic->ic_headroom + sizeof(struct ieee80211_frame),
1765 			sizeof(uint16_t));
1766 		if (m == NULL)
1767 			senderr(ENOMEM, is_tx_nobuf);
1768 		*(uint16_t *)frm = htole16(arg);	/* reason */
1769 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1770 
1771 		IEEE80211_NODE_STAT(ni, tx_deauth);
1772 		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1773 
1774 		ieee80211_node_unauthorize(ni);		/* port closed */
1775 		break;
1776 
1777 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1778 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1779 		/*
1780 		 * asreq frame format
1781 		 *	[2] capability information
1782 		 *	[2] listen interval
1783 		 *	[6*] current AP address (reassoc only)
1784 		 *	[tlv] ssid
1785 		 *	[tlv] supported rates
1786 		 *	[tlv] extended supported rates
1787 		 *	[tlv] WME
1788 		 *	[tlv] HT capabilities
1789 		 *	[tlv] Vendor OUI HT capabilities (optional)
1790 		 *	[tlv] Atheros capabilities (if negotiated)
1791 		 *	[tlv] user-specified ie's
1792 		 */
1793 		m = ieee80211_getmgtframe(&frm,
1794 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1795 			 sizeof(uint16_t)
1796 		       + sizeof(uint16_t)
1797 		       + IEEE80211_ADDR_LEN
1798 		       + 2 + IEEE80211_NWID_LEN
1799 		       + 2 + IEEE80211_RATE_SIZE
1800 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1801 		       + sizeof(struct ieee80211_wme_info)
1802 		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
1803 		       + sizeof(struct ieee80211_ath_ie)
1804 		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1805 		);
1806 		if (m == NULL)
1807 			senderr(ENOMEM, is_tx_nobuf);
1808 
1809 		KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1810 		    ("wrong mode %u", ic->ic_opmode));
1811 		capinfo = IEEE80211_CAPINFO_ESS;
1812 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
1813 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
1814 		/*
1815 		 * NB: Some 11a AP's reject the request when
1816 		 *     short premable is set.
1817 		 */
1818 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1819 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
1820 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1821 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
1822 		    (ic->ic_caps & IEEE80211_C_SHSLOT))
1823 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1824 		*(uint16_t *)frm = htole16(capinfo);
1825 		frm += 2;
1826 
1827 		KASSERT(ic->ic_bss->ni_intval != 0,
1828 			("beacon interval is zero!"));
1829 		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
1830 						   ic->ic_bss->ni_intval));
1831 		frm += 2;
1832 
1833 		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1834 			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1835 			frm += IEEE80211_ADDR_LEN;
1836 		}
1837 
1838 		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1839 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1840 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1841 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1842 			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1843 		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1844 			frm = ieee80211_add_htcap(frm, ni);
1845 			if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT)
1846 				frm = ieee80211_add_htcap_vendor(frm, ni);
1847 		}
1848 		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
1849 			frm = ieee80211_add_ath(frm,
1850 				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
1851 				(ic->ic_flags & IEEE80211_F_WPA) == 0 &&
1852 				ni->ni_authmode != IEEE80211_AUTH_8021X &&
1853 				ic->ic_def_txkey != IEEE80211_KEYIX_NONE ?
1854 				ic->ic_def_txkey : 0x7fff);
1855 		if (ic->ic_opt_ie != NULL) {
1856 			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1857 			frm += ic->ic_opt_ie_len;
1858 		}
1859 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1860 
1861 		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
1862 			(void *) ic->ic_state);
1863 		break;
1864 
1865 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1866 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1867 		/*
1868 		 * asresp frame format
1869 		 *	[2] capability information
1870 		 *	[2] status
1871 		 *	[2] association ID
1872 		 *	[tlv] supported rates
1873 		 *	[tlv] extended supported rates
1874 		 *	[tlv] WME (if enabled and STA enabled)
1875 		 *	[tlv] HT capabilities (standard or vendor OUI)
1876 		 *	[tlv] HT information (standard or vendor OUI)
1877 		 *	[tlv] Atheros capabilities (if enabled and STA enabled)
1878 		 */
1879 		m = ieee80211_getmgtframe(&frm,
1880 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
1881 			 sizeof(uint16_t)
1882 		       + sizeof(uint16_t)
1883 		       + sizeof(uint16_t)
1884 		       + 2 + IEEE80211_RATE_SIZE
1885 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1886 		       + sizeof(struct ieee80211_wme_param)
1887 		       + sizeof(struct ieee80211_ie_htcap) + 4
1888 		       + sizeof(struct ieee80211_ie_htinfo) + 4
1889 		       + sizeof(struct ieee80211_ath_ie)
1890 		);
1891 		if (m == NULL)
1892 			senderr(ENOMEM, is_tx_nobuf);
1893 
1894 		capinfo = getcapinfo(ic, ic->ic_curchan);
1895 		*(uint16_t *)frm = htole16(capinfo);
1896 		frm += 2;
1897 
1898 		*(uint16_t *)frm = htole16(arg);	/* status */
1899 		frm += 2;
1900 
1901 		if (arg == IEEE80211_STATUS_SUCCESS) {
1902 			*(uint16_t *)frm = htole16(ni->ni_associd);
1903 			IEEE80211_NODE_STAT(ni, tx_assoc);
1904 		} else
1905 			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1906 		frm += 2;
1907 
1908 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
1909 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
1910 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1911 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1912 		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan)) {
1913 			/* NB: respond according to what we received */
1914 			if (ni->ni_flags & IEEE80211_NODE_HTCOMPAT) {
1915 				frm = ieee80211_add_htcap_vendor(frm, ni);
1916 				frm = ieee80211_add_htinfo_vendor(frm, ni);
1917 			} else {
1918 				frm = ieee80211_add_htcap(frm, ni);
1919 				frm = ieee80211_add_htinfo(frm, ni);
1920 			}
1921 		}
1922 		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
1923 			frm = ieee80211_add_ath(frm,
1924 				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
1925 				ni->ni_ath_defkeyix);
1926 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1927 		break;
1928 
1929 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
1930 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1931 			"[%s] send station disassociate (reason %d)\n",
1932 			ether_sprintf(ni->ni_macaddr), arg);
1933 		m = ieee80211_getmgtframe(&frm,
1934 			ic->ic_headroom + sizeof(struct ieee80211_frame),
1935 			sizeof(uint16_t));
1936 		if (m == NULL)
1937 			senderr(ENOMEM, is_tx_nobuf);
1938 		*(uint16_t *)frm = htole16(arg);	/* reason */
1939 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1940 
1941 		IEEE80211_NODE_STAT(ni, tx_disassoc);
1942 		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1943 		break;
1944 
1945 	default:
1946 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1947 			"[%s] invalid mgmt frame type %u\n",
1948 			ether_sprintf(ni->ni_macaddr), type);
1949 		senderr(EINVAL, is_tx_unknownmgt);
1950 		/* NOTREACHED */
1951 	}
1952 
1953 	ret = ieee80211_mgmt_output(ic, ni, m, type);
1954 	if (ret != 0)
1955 		goto bad;
1956 	return 0;
1957 bad:
1958 	ieee80211_free_node(ni);
1959 	return ret;
1960 #undef senderr
1961 }
1962 
1963 static void
1964 ieee80211_tx_mgt_timeout(void *arg)
1965 {
1966 	struct ieee80211_node *ni = arg;
1967 	struct ieee80211com *ic	= ni->ni_ic;
1968 
1969 	if (ic->ic_state != IEEE80211_S_INIT &&
1970 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1971 		/*
1972 		 * NB: it's safe to specify a timeout as the reason here;
1973 		 *     it'll only be used in the right state.
1974 		 */
1975 		ieee80211_new_state(ic, IEEE80211_S_SCAN,
1976 			IEEE80211_SCAN_FAIL_TIMEOUT);
1977 	}
1978 }
1979 
1980 static void
1981 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
1982 {
1983 	struct ieee80211com *ic = ni->ni_ic;
1984 	enum ieee80211_state ostate = (enum ieee80211_state) arg;
1985 
1986 	/*
1987 	 * Frame transmit completed; arrange timer callback.  If
1988 	 * transmit was successfuly we wait for response.  Otherwise
1989 	 * we arrange an immediate callback instead of doing the
1990 	 * callback directly since we don't know what state the driver
1991 	 * is in (e.g. what locks it is holding).  This work should
1992 	 * not be too time-critical and not happen too often so the
1993 	 * added overhead is acceptable.
1994 	 *
1995 	 * XXX what happens if !acked but response shows up before callback?
1996 	 */
1997 	if (ic->ic_state == ostate)
1998 		callout_reset(&ic->ic_mgtsend,
1999 			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
2000 			ieee80211_tx_mgt_timeout, ni);
2001 }
2002 
2003 /*
2004  * Allocate a beacon frame and fillin the appropriate bits.
2005  */
2006 struct mbuf *
2007 ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
2008 	struct ieee80211_beacon_offsets *bo)
2009 {
2010 	struct ifnet *ifp = ic->ic_ifp;
2011 	struct ieee80211_frame *wh;
2012 	struct mbuf *m;
2013 	int pktlen;
2014 	uint8_t *frm;
2015 	uint16_t capinfo;
2016 	struct ieee80211_rateset *rs;
2017 
2018 	/*
2019 	 * beacon frame format
2020 	 *	[8] time stamp
2021 	 *	[2] beacon interval
2022 	 *	[2] cabability information
2023 	 *	[tlv] ssid
2024 	 *	[tlv] supported rates
2025 	 *	[3] parameter set (DS)
2026 	 *	[tlv] parameter set (IBSS/TIM)
2027 	 *	[tlv] country code
2028 	 *	[tlv] extended rate phy (ERP)
2029 	 *	[tlv] extended supported rates
2030 	 *	[tlv] WME parameters
2031 	 *	[tlv] WPA/RSN parameters
2032 	 *	[tlv] HT capabilities
2033 	 *	[tlv] HT information
2034 	 *	[tlv] Vendor OUI HT capabilities (optional)
2035 	 *	[tlv] Vendor OUI HT information (optional)
2036 	 * XXX Vendor-specific OIDs (e.g. Atheros)
2037 	 * NB: we allocate the max space required for the TIM bitmap.
2038 	 */
2039 	rs = &ni->ni_rates;
2040 	pktlen =   8					/* time stamp */
2041 		 + sizeof(uint16_t)			/* beacon interval */
2042 		 + sizeof(uint16_t)			/* capabilities */
2043 		 + 2 + ni->ni_esslen			/* ssid */
2044 	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
2045 	         + 2 + 1				/* DS parameters */
2046 		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
2047 		 + sizeof(struct ieee80211_country_ie)	/* country code */
2048 		 + 2 + 1				/* ERP */
2049 	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2050 		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
2051 			sizeof(struct ieee80211_wme_param) : 0)
2052 		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
2053 			2*sizeof(struct ieee80211_ie_wpa) : 0)
2054 		 /* XXX conditional? */
2055 		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
2056 		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
2057 		 ;
2058 	m = ieee80211_getmgtframe(&frm,
2059 		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
2060 	if (m == NULL) {
2061 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
2062 			"%s: cannot get buf; size %u\n", __func__, pktlen);
2063 		ic->ic_stats.is_tx_nobuf++;
2064 		return NULL;
2065 	}
2066 
2067 	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
2068 	frm += 8;
2069 	*(uint16_t *)frm = htole16(ni->ni_intval);
2070 	frm += 2;
2071 	capinfo = getcapinfo(ic, ni->ni_chan);
2072 	bo->bo_caps = (uint16_t *)frm;
2073 	*(uint16_t *)frm = htole16(capinfo);
2074 	frm += 2;
2075 	*frm++ = IEEE80211_ELEMID_SSID;
2076 	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
2077 		*frm++ = ni->ni_esslen;
2078 		memcpy(frm, ni->ni_essid, ni->ni_esslen);
2079 		frm += ni->ni_esslen;
2080 	} else
2081 		*frm++ = 0;
2082 	frm = ieee80211_add_rates(frm, rs);
2083 	if (!IEEE80211_IS_CHAN_FHSS(ic->ic_bsschan)) {
2084 		*frm++ = IEEE80211_ELEMID_DSPARMS;
2085 		*frm++ = 1;
2086 		*frm++ = ieee80211_chan2ieee(ic, ic->ic_bsschan);
2087 	}
2088 	bo->bo_tim = frm;
2089 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2090 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
2091 		*frm++ = 2;
2092 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
2093 		bo->bo_tim_len = 0;
2094 	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2095 		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
2096 
2097 		tie->tim_ie = IEEE80211_ELEMID_TIM;
2098 		tie->tim_len = 4;	/* length */
2099 		tie->tim_count = 0;	/* DTIM count */
2100 		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
2101 		tie->tim_bitctl = 0;	/* bitmap control */
2102 		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
2103 		frm += sizeof(struct ieee80211_tim_ie);
2104 		bo->bo_tim_len = 1;
2105 	}
2106 	bo->bo_trailer = frm;
2107 	if (ic->ic_flags & IEEE80211_F_DOTH)
2108 		frm = ieee80211_add_countryie(frm, ic,
2109 			ic->ic_countrycode, ic->ic_location);
2110 	if (ic->ic_flags & IEEE80211_F_WME) {
2111 		bo->bo_wme = frm;
2112 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
2113 		ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
2114 	} else
2115 		bo->bo_wme = NULL;
2116 	if (ic->ic_flags & IEEE80211_F_WPA)
2117 		frm = ieee80211_add_wpa(frm, ic);
2118 	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan)) {
2119 		bo->bo_erp = frm;
2120 		frm = ieee80211_add_erp(frm, ic);
2121 	} else
2122 		bo->bo_erp = NULL;
2123 	frm = ieee80211_add_xrates(frm, rs);
2124 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan)) {
2125 		frm = ieee80211_add_htcap(frm, ni);
2126 		bo->bo_htinfo = frm;
2127 		frm = ieee80211_add_htinfo(frm, ni);
2128 		if (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT) {
2129 			frm = ieee80211_add_htcap_vendor(frm, ni);
2130 			frm = ieee80211_add_htinfo_vendor(frm, ni);
2131 		}
2132 	} else
2133 		bo->bo_htinfo = NULL;
2134 	bo->bo_trailer_len = frm - bo->bo_trailer;
2135 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2136 
2137 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
2138 	KASSERT(m != NULL, ("no space for 802.11 header?"));
2139 	wh = mtod(m, struct ieee80211_frame *);
2140 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
2141 	    IEEE80211_FC0_SUBTYPE_BEACON;
2142 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
2143 	*(uint16_t *)wh->i_dur = 0;
2144 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
2145 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
2146 	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
2147 	*(uint16_t *)wh->i_seq = 0;
2148 
2149 	return m;
2150 }
2151 
2152 /*
2153  * Update the dynamic parts of a beacon frame based on the current state.
2154  */
2155 int
2156 ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
2157 	struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
2158 {
2159 	int len_changed = 0;
2160 	uint16_t capinfo;
2161 
2162 	IEEE80211_BEACON_LOCK(ic);
2163 	/* XXX faster to recalculate entirely or just changes? */
2164 	capinfo = getcapinfo(ic, ni->ni_chan);
2165 	*bo->bo_caps = htole16(capinfo);
2166 
2167 	if (ic->ic_flags & IEEE80211_F_WME) {
2168 		struct ieee80211_wme_state *wme = &ic->ic_wme;
2169 
2170 		/*
2171 		 * Check for agressive mode change.  When there is
2172 		 * significant high priority traffic in the BSS
2173 		 * throttle back BE traffic by using conservative
2174 		 * parameters.  Otherwise BE uses agressive params
2175 		 * to optimize performance of legacy/non-QoS traffic.
2176 		 */
2177 		if (wme->wme_flags & WME_F_AGGRMODE) {
2178 			if (wme->wme_hipri_traffic >
2179 			    wme->wme_hipri_switch_thresh) {
2180 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2181 				    "%s: traffic %u, disable aggressive mode\n",
2182 				    __func__, wme->wme_hipri_traffic);
2183 				wme->wme_flags &= ~WME_F_AGGRMODE;
2184 				ieee80211_wme_updateparams_locked(ic);
2185 				wme->wme_hipri_traffic =
2186 					wme->wme_hipri_switch_hysteresis;
2187 			} else
2188 				wme->wme_hipri_traffic = 0;
2189 		} else {
2190 			if (wme->wme_hipri_traffic <=
2191 			    wme->wme_hipri_switch_thresh) {
2192 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
2193 				    "%s: traffic %u, enable aggressive mode\n",
2194 				    __func__, wme->wme_hipri_traffic);
2195 				wme->wme_flags |= WME_F_AGGRMODE;
2196 				ieee80211_wme_updateparams_locked(ic);
2197 				wme->wme_hipri_traffic = 0;
2198 			} else
2199 				wme->wme_hipri_traffic =
2200 					wme->wme_hipri_switch_hysteresis;
2201 		}
2202 		if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
2203 			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
2204 			ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
2205 		}
2206 	}
2207 
2208 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan)) {
2209 		struct ieee80211_ie_htinfo *ht =
2210 		   (struct ieee80211_ie_htinfo *) bo->bo_htinfo;
2211 		if (IEEE80211_IS_CHAN_HT40(ic->ic_bsschan))
2212 			ht->hi_byte1 |= IEEE80211_HTINFO_TXWIDTH_2040;
2213 		else
2214 			ht->hi_byte1 &= ~IEEE80211_HTINFO_TXWIDTH_2040;
2215 	}
2216 
2217 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
2218 		struct ieee80211_tim_ie *tie =
2219 			(struct ieee80211_tim_ie *) bo->bo_tim;
2220 		if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
2221 			u_int timlen, timoff, i;
2222 			/*
2223 			 * ATIM/DTIM needs updating.  If it fits in the
2224 			 * current space allocated then just copy in the
2225 			 * new bits.  Otherwise we need to move any trailing
2226 			 * data to make room.  Note that we know there is
2227 			 * contiguous space because ieee80211_beacon_allocate
2228 			 * insures there is space in the mbuf to write a
2229 			 * maximal-size virtual bitmap (based on ic_max_aid).
2230 			 */
2231 			/*
2232 			 * Calculate the bitmap size and offset, copy any
2233 			 * trailer out of the way, and then copy in the
2234 			 * new bitmap and update the information element.
2235 			 * Note that the tim bitmap must contain at least
2236 			 * one byte and any offset must be even.
2237 			 */
2238 			if (ic->ic_ps_pending != 0) {
2239 				timoff = 128;		/* impossibly large */
2240 				for (i = 0; i < ic->ic_tim_len; i++)
2241 					if (ic->ic_tim_bitmap[i]) {
2242 						timoff = i &~ 1;
2243 						break;
2244 					}
2245 				KASSERT(timoff != 128, ("tim bitmap empty!"));
2246 				for (i = ic->ic_tim_len-1; i >= timoff; i--)
2247 					if (ic->ic_tim_bitmap[i])
2248 						break;
2249 				timlen = 1 + (i - timoff);
2250 			} else {
2251 				timoff = 0;
2252 				timlen = 1;
2253 			}
2254 			if (timlen != bo->bo_tim_len) {
2255 				/* copy up/down trailer */
2256 				int adjust = tie->tim_bitmap+timlen
2257 					   - bo->bo_trailer;
2258 				ovbcopy(bo->bo_trailer, bo->bo_trailer+adjust,
2259 					bo->bo_trailer_len);
2260 				bo->bo_trailer += adjust;
2261 				bo->bo_wme += adjust;
2262 				bo->bo_erp += adjust;
2263 				bo->bo_htinfo += adjust;
2264 				bo->bo_tim_len = timlen;
2265 
2266 				/* update information element */
2267 				tie->tim_len = 3 + timlen;
2268 				tie->tim_bitctl = timoff;
2269 				len_changed = 1;
2270 			}
2271 			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
2272 				bo->bo_tim_len);
2273 
2274 			ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
2275 
2276 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
2277 				"%s: TIM updated, pending %u, off %u, len %u\n",
2278 				__func__, ic->ic_ps_pending, timoff, timlen);
2279 		}
2280 		/* count down DTIM period */
2281 		if (tie->tim_count == 0)
2282 			tie->tim_count = tie->tim_period - 1;
2283 		else
2284 			tie->tim_count--;
2285 		/* update state for buffered multicast frames on DTIM */
2286 		if (mcast && tie->tim_count == 0)
2287 			tie->tim_bitctl |= 1;
2288 		else
2289 			tie->tim_bitctl &= ~1;
2290 		if (ic->ic_flags_ext & IEEE80211_FEXT_ERPUPDATE) {
2291 			/*
2292 			 * ERP element needs updating.
2293 			 */
2294 			(void) ieee80211_add_erp(bo->bo_erp, ic);
2295 			ic->ic_flags_ext &= ~IEEE80211_FEXT_ERPUPDATE;
2296 		}
2297 	}
2298 	IEEE80211_BEACON_UNLOCK(ic);
2299 
2300 	return len_changed;
2301 }
2302