1 /*-
2  * Copyright (c) 2003-2009 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  * $FreeBSD: head/sys/net80211/ieee80211_freebsd.c 202612 2010-01-19 05:00:57Z thompsa $
26  */
27 
28 /*
29  * IEEE 802.11 support (DragonFlyBSD-specific code)
30  */
31 #include "opt_wlan.h"
32 
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/systm.h>
36 #include <sys/linker.h>
37 #include <sys/malloc.h>
38 #include <sys/mbuf.h>
39 #include <sys/module.h>
40 #include <sys/proc.h>
41 #include <sys/sysctl.h>
42 
43 #include <sys/socket.h>
44 
45 #include <net/bpf.h>
46 #include <net/if.h>
47 #include <net/if_dl.h>
48 #include <net/if_clone.h>
49 #include <net/if_media.h>
50 #include <net/if_types.h>
51 #include <net/ethernet.h>
52 #include <net/route.h>
53 #include <net/ifq_var.h>
54 
55 #include <netproto/802_11/ieee80211_var.h>
56 #include <netproto/802_11/ieee80211_input.h>
57 
58 SYSCTL_NODE(_net, OID_AUTO, wlan, CTLFLAG_RD, 0, "IEEE 80211 parameters");
59 
60 #ifdef IEEE80211_DEBUG
61 int	ieee80211_debug = 0;
62 SYSCTL_INT(_net_wlan, OID_AUTO, debug, CTLFLAG_RW, &ieee80211_debug,
63 	    0, "debugging printfs");
64 #endif
65 
66 int	ieee80211_force_swcrypto = 0;
67 SYSCTL_INT(_net_wlan, OID_AUTO, force_swcrypto, CTLFLAG_RW,
68 	    &ieee80211_force_swcrypto, 0, "force software crypto");
69 
70 static int	wlan_clone_destroy(struct ifnet *);
71 static int	wlan_clone_create(struct if_clone *, int, caddr_t);
72 
73 static struct if_clone wlan_cloner =
74 	IF_CLONE_INITIALIZER("wlan", wlan_clone_create, wlan_clone_destroy,
75 	    0, IF_MAXUNIT);
76 
77 struct lwkt_serialize wlan_global_serializer = LWKT_SERIALIZE_INITIALIZER;
78 
79 static int
80 wlan_clone_create(struct if_clone *ifc, int unit, caddr_t params)
81 {
82 	struct ieee80211_clone_params cp;
83 	struct ieee80211vap *vap;
84 	struct ieee80211com *ic;
85 	int error;
86 
87 	error = copyin(params, &cp, sizeof(cp));
88 	if (error)
89 		return error;
90 
91 	ic = ieee80211_find_com(cp.icp_parent);
92 	if (ic == NULL)
93 		return ENXIO;
94 	if (cp.icp_opmode >= IEEE80211_OPMODE_MAX) {
95 		ic_printf(ic, "%s: invalid opmode %d\n", __func__,
96 		    cp.icp_opmode);
97 		return EINVAL;
98 	}
99 	if ((ic->ic_caps & ieee80211_opcap[cp.icp_opmode]) == 0) {
100 		ic_printf(ic, "%s mode not supported\n",
101 		    ieee80211_opmode_name[cp.icp_opmode]);
102 		return EOPNOTSUPP;
103 	}
104 	if ((cp.icp_flags & IEEE80211_CLONE_TDMA) &&
105 #ifdef IEEE80211_SUPPORT_TDMA
106 	    (ic->ic_caps & IEEE80211_C_TDMA) == 0
107 #else
108 	    (1)
109 #endif
110 	) {
111 		ic_printf(ic, "TDMA not supported\n");
112 		return EOPNOTSUPP;
113 	}
114 	vap = ic->ic_vap_create(ic, ifc->ifc_name, unit,
115 			cp.icp_opmode, cp.icp_flags, cp.icp_bssid,
116 			cp.icp_flags & IEEE80211_CLONE_MACADDR ?
117 			    cp.icp_macaddr : ic->ic_macaddr);
118 
119 
120 	return (vap == NULL ? EIO : 0);
121 }
122 
123 static int
124 wlan_clone_destroy(struct ifnet *ifp)
125 {
126 	struct ieee80211vap *vap = ifp->if_softc;
127 	struct ieee80211com *ic = vap->iv_ic;
128 
129 	ic->ic_vap_delete(vap);
130 
131 	return 0;
132 }
133 
134 const char *wlan_last_enter_func;
135 const char *wlan_last_exit_func;
136 
137 /*
138  * These serializer functions are used by wlan and all drivers.
139  * They are not recursive.  The serializer must be held on
140  * any OACTIVE interactions.  Dragonfly automatically holds
141  * the serializer on most ifp->if_*() calls but calls made
142  * from wlan into ath might not.
143  */
144 void
145 _wlan_serialize_enter(const char *funcname)
146 {
147 	lwkt_serialize_enter(&wlan_global_serializer);
148 	wlan_last_enter_func = funcname;
149 }
150 
151 void
152 _wlan_serialize_exit(const char *funcname)
153 {
154 	lwkt_serialize_exit(&wlan_global_serializer);
155 	wlan_last_exit_func = funcname;
156 }
157 
158 int
159 _wlan_is_serialized(void)
160 {
161 	return (IS_SERIALIZED(&wlan_global_serializer));
162 }
163 
164 /*
165  * Push/pop allows the wlan serializer to be entered recursively.
166  */
167 int
168 _wlan_serialize_push(const char *funcname)
169 {
170 	if (IS_SERIALIZED(&wlan_global_serializer)) {
171 		return 0;
172 	} else {
173 		_wlan_serialize_enter(funcname);
174 		return 1;
175 	}
176 }
177 
178 void
179 _wlan_serialize_pop(const char *funcname, int wst)
180 {
181 	if (wst) {
182 		_wlan_serialize_exit(funcname);
183 	}
184 }
185 
186 #if 0
187 
188 int
189 wlan_serialize_sleep(void *ident, int flags, const char *wmesg, int timo)
190 {
191 	return(zsleep(ident, &wlan_global_serializer, flags, wmesg, timo));
192 }
193 
194 /*
195  * condition-var functions which interlock the ic lock (which is now
196  * just wlan_global_serializer)
197  */
198 void
199 wlan_cv_init(struct cv *cv, const char *desc)
200 {
201 	cv->cv_desc = desc;
202 	cv->cv_waiters = 0;
203 }
204 
205 int
206 wlan_cv_timedwait(struct cv *cv, int ticks)
207 {
208 	int error;
209 
210 	++cv->cv_waiters;
211 	error = wlan_serialize_sleep(cv, 0, cv->cv_desc, ticks);
212 	return (error);
213 }
214 
215 void
216 wlan_cv_wait(struct cv *cv)
217 {
218 	++cv->cv_waiters;
219 	wlan_serialize_sleep(cv, 0, cv->cv_desc, 0);
220 }
221 
222 void
223 wlan_cv_signal(struct cv *cv, int broadcast)
224 {
225 	if (cv->cv_waiters) {
226 		if (broadcast) {
227 			cv->cv_waiters = 0;
228 			wakeup(cv);
229 		} else {
230 			--cv->cv_waiters;
231 			wakeup_one(cv);
232 		}
233 	}
234 }
235 
236 #endif
237 
238 /*
239  * Add RX parameters to the given mbuf.
240  *
241  * Returns 1 if OK, 0 on error.
242  */
243 int
244 ieee80211_add_rx_params(struct mbuf *m, const struct ieee80211_rx_stats *rxs)
245 {
246 	struct m_tag *mtag;
247 	struct ieee80211_rx_params *rx;
248 
249 	mtag = m_tag_alloc(MTAG_ABI_NET80211, NET80211_TAG_RECV_PARAMS,
250 		sizeof(struct ieee80211_rx_stats), M_NOWAIT);
251 	if (mtag == NULL)
252 		return (0);
253 
254 	rx = (struct ieee80211_rx_params *)(mtag + 1);
255 	memcpy(&rx->params, rxs, sizeof(*rxs));
256 	m_tag_prepend(m, mtag);
257 	return (1);
258 }
259 
260 int
261 ieee80211_get_rx_params(struct mbuf *m, struct ieee80211_rx_stats *rxs)
262 {
263 	struct m_tag *mtag;
264 	struct ieee80211_rx_params *rx;
265 
266 	mtag = m_tag_locate(m, MTAG_ABI_NET80211, NET80211_TAG_RECV_PARAMS,
267 	    NULL);
268 	if (mtag == NULL)
269 		return (-1);
270 	rx = (struct ieee80211_rx_params *)(mtag + 1);
271 	memcpy(rxs, &rx->params, sizeof(*rxs));
272 	return (0);
273 }
274 
275 /*
276  * Misc
277  */
278 int
279 ieee80211_vap_xmitpkt(struct ieee80211vap *vap, struct mbuf *m)
280 {
281 	struct ifnet *ifp = vap->iv_ifp;
282 	struct ifaltq_subque *ifsq = ifq_get_subq_default(&ifp->if_snd);
283 	int error;
284 	int wst;
285 
286 	/*
287 	 * When transmitting via the VAP, we shouldn't hold
288 	 * any IC TX lock as the VAP TX path will acquire it.
289 	 */
290 	IEEE80211_TX_UNLOCK_ASSERT(vap->iv_ic);
291 
292 	error = ifsq_enqueue(ifsq, m, NULL);
293 	if (error)
294 		IFNET_STAT_INC(ifp, oqdrops, 1);
295 	wst = wlan_serialize_push();
296 	ifp->if_start(ifp, ifsq);
297 	wlan_serialize_pop(wst);
298 
299 	return error;
300 }
301 
302 int
303 ieee80211_parent_xmitpkt(struct ieee80211com *ic, struct mbuf *m)
304 {
305 	int error;
306 
307 	/*
308 	 * Assert the IC TX lock is held - this enforces the
309 	 * processing -> queuing order is maintained
310 	 */
311 	IEEE80211_TX_LOCK_ASSERT(ic);
312 	error = ic->ic_transmit(ic, m);
313 	if (error) {
314 		struct ieee80211_node *ni;
315 
316 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
317 
318 		/* XXX number of fragments */
319 		IFNET_STAT_INC(ni->ni_vap->iv_ifp, oerrors, 1);
320 		ieee80211_free_node(ni);
321 		ieee80211_free_mbuf(m);
322 	}
323 	return (error);
324 }
325 
326 void
327 ieee80211_vap_destroy(struct ieee80211vap *vap)
328 {
329 	/*
330 	 * WLAN serializer must _not_ be held for if_clone_destroy(),
331 	 * since it could dead-lock the domsg to netisrs.
332 	 */
333 	wlan_serialize_exit();
334 	/*
335 	 * Make sure we con't end up in an infinite loop in ieee80211_ifdetach
336 	 * when if_clone_destroy fails.
337 	 */
338 	KKASSERT(if_clone_destroy(vap->iv_ifp->if_xname) == 0);
339 	wlan_serialize_enter();
340 }
341 
342 /*
343  * NOTE: This handler is used generally to convert milliseconds
344  *	 to ticks for various simple sysctl variables and does not
345  *	 need to be serialized.
346  */
347 int
348 ieee80211_sysctl_msecs_ticks(SYSCTL_HANDLER_ARGS)
349 {
350 	int msecs = ticks_to_msecs(*(int *)arg1);
351 	int error, t;
352 
353 	error = sysctl_handle_int(oidp, &msecs, 0, req);
354 	if (error == 0 && req->newptr) {
355 		t = msecs_to_ticks(msecs);
356 		*(int *)arg1 = (t < 1) ? 1 : t;
357 	}
358 
359 	return error;
360 }
361 
362 static int
363 ieee80211_sysctl_inact(SYSCTL_HANDLER_ARGS)
364 {
365 	int inact = (*(int *)arg1) * IEEE80211_INACT_WAIT;
366 	int error;
367 
368 	error = sysctl_handle_int(oidp, &inact, 0, req);
369 	if (error == 0 && req->newptr)
370 		*(int *)arg1 = inact / IEEE80211_INACT_WAIT;
371 
372 	return error;
373 }
374 
375 static int
376 ieee80211_sysctl_parent(SYSCTL_HANDLER_ARGS)
377 {
378 	struct ieee80211com *ic = arg1;
379 	const char *name = ic->ic_name;
380 
381 	return SYSCTL_OUT(req, name, strlen(name));
382 }
383 
384 static int
385 ieee80211_sysctl_radar(SYSCTL_HANDLER_ARGS)
386 {
387 	struct ieee80211com *ic = arg1;
388 	int t = 0, error;
389 
390 	error = sysctl_handle_int(oidp, &t, 0, req);
391 	if (error == 0 && req->newptr)
392 		ieee80211_dfs_notify_radar(ic, ic->ic_curchan);
393 
394 	return error;
395 }
396 
397 void
398 ieee80211_sysctl_attach(struct ieee80211com *ic)
399 {
400 }
401 
402 void
403 ieee80211_sysctl_detach(struct ieee80211com *ic)
404 {
405 }
406 
407 void
408 ieee80211_sysctl_vattach(struct ieee80211vap *vap)
409 {
410 	struct ifnet *ifp = vap->iv_ifp;
411 	struct sysctl_ctx_list *ctx;
412 	struct sysctl_oid *oid;
413 	char num[14];			/* sufficient for 32 bits */
414 
415 	ctx = (struct sysctl_ctx_list *) kmalloc(sizeof(struct sysctl_ctx_list),
416 		M_DEVBUF, M_INTWAIT | M_ZERO);
417 	if (ctx == NULL) {
418 		if_printf(ifp, "%s: cannot allocate sysctl context!\n",
419 			__func__);
420 		return;
421 	}
422 	sysctl_ctx_init(ctx);
423 	ksnprintf(num, sizeof(num), "%u", ifp->if_dunit);
424 	oid = SYSCTL_ADD_NODE(ctx, &SYSCTL_NODE_CHILDREN(_net, wlan),
425 		OID_AUTO, num, CTLFLAG_RD, NULL, "");
426 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
427 		"%parent", CTLFLAG_RD, vap->iv_ic, 0,
428 		ieee80211_sysctl_parent, "A", "parent device");
429 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
430 		"driver_caps", CTLFLAG_RW, &vap->iv_caps, 0,
431 		"driver capabilities");
432 #ifdef IEEE80211_DEBUG
433 	vap->iv_debug = ieee80211_debug;
434 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
435 		"debug", CTLFLAG_RW, &vap->iv_debug, 0,
436 		"control debugging printfs");
437 #endif
438 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
439 		"bmiss_max", CTLFLAG_RW, &vap->iv_bmiss_max, 0,
440 		"consecutive beacon misses before scanning");
441 	/* XXX inherit from tunables */
442 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
443 		"inact_run", CTLTYPE_INT | CTLFLAG_RW, &vap->iv_inact_run, 0,
444 		ieee80211_sysctl_inact, "I",
445 		"station inactivity timeout (sec)");
446 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
447 		"inact_probe", CTLTYPE_INT | CTLFLAG_RW, &vap->iv_inact_probe, 0,
448 		ieee80211_sysctl_inact, "I",
449 		"station inactivity probe timeout (sec)");
450 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
451 		"inact_auth", CTLTYPE_INT | CTLFLAG_RW, &vap->iv_inact_auth, 0,
452 		ieee80211_sysctl_inact, "I",
453 		"station authentication timeout (sec)");
454 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
455 		"inact_init", CTLTYPE_INT | CTLFLAG_RW, &vap->iv_inact_init, 0,
456 		ieee80211_sysctl_inact, "I",
457 		"station initial state timeout (sec)");
458 	if (vap->iv_htcaps & IEEE80211_HTC_HT) {
459 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
460 			"ampdu_mintraffic_bk", CTLFLAG_RW,
461 			&vap->iv_ampdu_mintraffic[WME_AC_BK], 0,
462 			"BK traffic tx aggr threshold (pps)");
463 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
464 			"ampdu_mintraffic_be", CTLFLAG_RW,
465 			&vap->iv_ampdu_mintraffic[WME_AC_BE], 0,
466 			"BE traffic tx aggr threshold (pps)");
467 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
468 			"ampdu_mintraffic_vo", CTLFLAG_RW,
469 			&vap->iv_ampdu_mintraffic[WME_AC_VO], 0,
470 			"VO traffic tx aggr threshold (pps)");
471 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
472 			"ampdu_mintraffic_vi", CTLFLAG_RW,
473 			&vap->iv_ampdu_mintraffic[WME_AC_VI], 0,
474 			"VI traffic tx aggr threshold (pps)");
475 	}
476 	if (vap->iv_caps & IEEE80211_C_DFS) {
477 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
478 			"radar", CTLTYPE_INT | CTLFLAG_RW, vap->iv_ic, 0,
479 			ieee80211_sysctl_radar, "I", "simulate radar event");
480 	}
481 	vap->iv_sysctl = ctx;
482 	vap->iv_oid = oid;
483 }
484 
485 void
486 ieee80211_sysctl_vdetach(struct ieee80211vap *vap)
487 {
488 
489 	if (vap->iv_sysctl != NULL) {
490 		sysctl_ctx_free(vap->iv_sysctl);
491 		kfree(vap->iv_sysctl, M_DEVBUF);
492 		vap->iv_sysctl = NULL;
493 	}
494 }
495 
496 int
497 ieee80211_node_dectestref(struct ieee80211_node *ni)
498 {
499 	/* XXX need equivalent of atomic_dec_and_test */
500 	atomic_subtract_int(&ni->ni_refcnt, 1);
501 	return atomic_cmpset_int(&ni->ni_refcnt, 0, 1);
502 }
503 
504 #if 0
505 /* XXX this breaks ALTQ's packet scheduler */
506 void
507 ieee80211_flush_ifq(struct ifaltq *ifq, struct ieee80211vap *vap)
508 {
509 	struct ieee80211_node *ni;
510 	struct mbuf *m, **mprev;
511 	struct ifaltq_subque *ifsq = ifq_get_subq_default(ifq);
512 
513 	wlan_assert_serialized();
514 
515 	ALTQ_SQ_LOCK(ifsq);
516 
517 	/*
518 	 * Fix normal queue
519 	 */
520 	mprev = &ifsq->ifsq_norm_head;
521 	while ((m = *mprev) != NULL) {
522 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
523 		if (ni != NULL && ni->ni_vap == vap) {
524 			*mprev = m->m_nextpkt;		/* remove from list */
525 			ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
526 
527 			m_freem(m);
528 			ieee80211_free_node(ni);	/* reclaim ref */
529 		} else
530 			mprev = &m->m_nextpkt;
531 	}
532 	/* recalculate tail ptr */
533 	m = ifsq->ifsq_norm_head;
534 	for (; m != NULL && m->m_nextpkt != NULL; m = m->m_nextpkt)
535 		;
536 	ifsq->ifsq_norm_tail = m;
537 
538 	/*
539 	 * Fix priority queue
540 	 */
541 	mprev = &ifsq->ifsq_prio_head;
542 	while ((m = *mprev) != NULL) {
543 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
544 		if (ni != NULL && ni->ni_vap == vap) {
545 			*mprev = m->m_nextpkt;		/* remove from list */
546 			ALTQ_SQ_CNTR_DEC(ifsq, m->m_pkthdr.len);
547 			ALTQ_SQ_PRIO_CNTR_DEC(ifsq, m->m_pkthdr.len);
548 
549 			m_freem(m);
550 			ieee80211_free_node(ni);	/* reclaim ref */
551 		} else
552 			mprev = &m->m_nextpkt;
553 	}
554 	/* recalculate tail ptr */
555 	m = ifsq->ifsq_prio_head;
556 	for (; m != NULL && m->m_nextpkt != NULL; m = m->m_nextpkt)
557 		;
558 	ifsq->ifsq_prio_tail = m;
559 
560 	ALTQ_SQ_UNLOCK(ifsq);
561 }
562 #endif
563 
564 /*
565  * As above, for mbufs allocated with m_gethdr/MGETHDR
566  * or initialized by M_COPY_PKTHDR.
567  */
568 #define	MC_ALIGN(m, len)						\
569 do {									\
570 	(m)->m_data += rounddown2(MCLBYTES - (len), sizeof(long));	\
571 } while (/* CONSTCOND */ 0)
572 
573 /*
574  * Allocate and setup a management frame of the specified
575  * size.  We return the mbuf and a pointer to the start
576  * of the contiguous data area that's been reserved based
577  * on the packet length.  The data area is forced to 32-bit
578  * alignment and the buffer length to a multiple of 4 bytes.
579  * This is done mainly so beacon frames (that require this)
580  * can use this interface too.
581  */
582 struct mbuf *
583 ieee80211_getmgtframe(uint8_t **frm, int headroom, int pktlen)
584 {
585 	struct mbuf *m;
586 	u_int len;
587 
588 	/*
589 	 * NB: we know the mbuf routines will align the data area
590 	 *     so we don't need to do anything special.
591 	 */
592 	len = roundup2(headroom + pktlen, 4);
593 	KASSERT(len <= MCLBYTES, ("802.11 mgt frame too large: %u", len));
594 	if (len < MINCLSIZE) {
595 		m = m_gethdr(M_NOWAIT, MT_DATA);
596 		/*
597 		 * Align the data in case additional headers are added.
598 		 * This should only happen when a WEP header is added
599 		 * which only happens for shared key authentication mgt
600 		 * frames which all fit in MHLEN.
601 		 */
602 		if (m != NULL)
603 			MH_ALIGN(m, len);
604 	} else {
605 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
606 		if (m != NULL)
607 			MC_ALIGN(m, len);
608 	}
609 	if (m != NULL) {
610 		m->m_data += headroom;
611 		*frm = m->m_data;
612 	}
613 	return m;
614 }
615 
616 /*
617  * Re-align the payload in the mbuf.  This is mainly used (right now)
618  * to handle IP header alignment requirements on certain architectures.
619  */
620 struct mbuf *
621 ieee80211_realign(struct ieee80211vap *vap, struct mbuf *m, size_t align)
622 {
623 	int pktlen, space;
624 	struct mbuf *n = NULL;
625 
626 	pktlen = m->m_pkthdr.len;
627 	space = pktlen + align;
628 	if (space < MINCLSIZE) {
629 		n = m_gethdr(M_NOWAIT, MT_DATA);
630 	} else {
631 		if (space <= MCLBYTES)
632 			space = MCLBYTES;
633 		else if (space <= MJUMPAGESIZE)
634 			space = MJUMPAGESIZE;
635 		else if (space <= MJUM9BYTES)
636 			space = MJUM9BYTES;
637 		else
638 			space = MJUM16BYTES;
639 		n = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, space);
640 	}
641 	if (__predict_true(n != NULL)) {
642 		m_move_pkthdr(n, m);
643 		n->m_data = (caddr_t)(ALIGN(n->m_data + align) - align);
644 		m_copydata(m, 0, pktlen, mtod(n, caddr_t));
645 		n->m_len = pktlen;
646 	} else {
647 		IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
648 		    mtod(m, const struct ieee80211_frame *), NULL,
649 		    "%s", "no mbuf to realign");
650 		vap->iv_stats.is_rx_badalign++;
651 	}
652 	m_freem(m);
653 	return n;
654 }
655 
656 int
657 ieee80211_add_callback(struct mbuf *m,
658 	void (*func)(struct ieee80211_node *, void *, int), void *arg)
659 {
660 	struct m_tag *mtag;
661 	struct ieee80211_cb *cb;
662 
663 	mtag = m_tag_alloc(MTAG_ABI_NET80211, NET80211_TAG_CALLBACK,
664 			sizeof(struct ieee80211_cb), M_INTWAIT);
665 	if (mtag == NULL)
666 		return 0;
667 
668 	cb = (struct ieee80211_cb *)(mtag+1);
669 	cb->func = func;
670 	cb->arg = arg;
671 	m_tag_prepend(m, mtag);
672 	m->m_flags |= M_TXCB;
673 	return 1;
674 }
675 
676 int
677 ieee80211_add_xmit_params(struct mbuf *m,
678     const struct ieee80211_bpf_params *params)
679 {
680 	struct m_tag *mtag;
681 	struct ieee80211_tx_params *tx;
682 
683 	mtag = m_tag_alloc(MTAG_ABI_NET80211, NET80211_TAG_XMIT_PARAMS,
684 	    sizeof(struct ieee80211_tx_params), M_NOWAIT);
685 	if (mtag == NULL)
686 		return (0);
687 
688 	tx = (struct ieee80211_tx_params *)(mtag+1);
689 	memcpy(&tx->params, params, sizeof(struct ieee80211_bpf_params));
690 	m_tag_prepend(m, mtag);
691 	return (1);
692 }
693 
694 int
695 ieee80211_get_xmit_params(struct mbuf *m,
696     struct ieee80211_bpf_params *params)
697 {
698 	struct m_tag *mtag;
699 	struct ieee80211_tx_params *tx;
700 
701 	mtag = m_tag_locate(m, MTAG_ABI_NET80211, NET80211_TAG_XMIT_PARAMS,
702 	    NULL);
703 	if (mtag == NULL)
704 		return (-1);
705 	tx = (struct ieee80211_tx_params *)(mtag + 1);
706 	memcpy(params, &tx->params, sizeof(struct ieee80211_bpf_params));
707 	return (0);
708 }
709 
710 void
711 ieee80211_process_callback(struct ieee80211_node *ni,
712 	struct mbuf *m, int status)
713 {
714 	struct m_tag *mtag;
715 
716 	mtag = m_tag_locate(m, MTAG_ABI_NET80211, NET80211_TAG_CALLBACK, NULL);
717 	if (mtag != NULL) {
718 		struct ieee80211_cb *cb = (struct ieee80211_cb *)(mtag+1);
719 		cb->func(ni, cb->arg, status);
720 	}
721 }
722 
723 #include <sys/libkern.h>
724 
725 void
726 get_random_bytes(void *p, size_t n)
727 {
728 	uint8_t *dp = p;
729 
730 	while (n > 0) {
731 		uint32_t v = karc4random();
732 		size_t nb = n > sizeof(uint32_t) ? sizeof(uint32_t) : n;
733 		bcopy(&v, dp, n > sizeof(uint32_t) ? sizeof(uint32_t) : n);
734 		dp += sizeof(uint32_t), n -= nb;
735 	}
736 }
737 
738 /*
739  * Helper function for events that pass just a single mac address.
740  */
741 static void
742 notify_macaddr(struct ifnet *ifp, int op, const uint8_t mac[IEEE80211_ADDR_LEN])
743 {
744 	struct ieee80211_join_event iev;
745 
746 	memset(&iev, 0, sizeof(iev));
747 	IEEE80211_ADDR_COPY(iev.iev_addr, mac);
748 	rt_ieee80211msg(ifp, op, &iev, sizeof(iev));
749 }
750 
751 void
752 ieee80211_notify_node_join(struct ieee80211_node *ni, int newassoc)
753 {
754 	struct ieee80211vap *vap = ni->ni_vap;
755 	struct ifnet *ifp = vap->iv_ifp;
756 
757 	IEEE80211_NOTE(vap, IEEE80211_MSG_NODE, ni, "%snode join",
758 	    (ni == vap->iv_bss) ? "bss " : "");
759 
760 	if (ni == vap->iv_bss) {
761 		ifp->if_link_state = LINK_STATE_UP;
762 		notify_macaddr(ifp, newassoc ?
763 		    RTM_IEEE80211_ASSOC : RTM_IEEE80211_REASSOC, ni->ni_bssid);
764 		if_link_state_change(ifp);
765 	} else {
766 		notify_macaddr(ifp, newassoc ?
767 		    RTM_IEEE80211_JOIN : RTM_IEEE80211_REJOIN, ni->ni_macaddr);
768 	}
769 }
770 
771 void
772 ieee80211_notify_node_leave(struct ieee80211_node *ni)
773 {
774 	struct ieee80211vap *vap = ni->ni_vap;
775 	struct ifnet *ifp = vap->iv_ifp;
776 
777 	IEEE80211_NOTE(vap, IEEE80211_MSG_NODE, ni, "%snode leave",
778 	    (ni == vap->iv_bss) ? "bss " : "");
779 
780 	if (ni == vap->iv_bss) {
781 		ifp->if_link_state = LINK_STATE_DOWN;
782 		rt_ieee80211msg(ifp, RTM_IEEE80211_DISASSOC, NULL, 0);
783 		if_link_state_change(ifp);
784 	} else {
785 		/* fire off wireless event station leaving */
786 		notify_macaddr(ifp, RTM_IEEE80211_LEAVE, ni->ni_macaddr);
787 	}
788 }
789 
790 void
791 ieee80211_notify_scan_done(struct ieee80211vap *vap)
792 {
793 	struct ifnet *ifp = vap->iv_ifp;
794 
795 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s\n", "notify scan done");
796 
797 	/* dispatch wireless event indicating scan completed */
798 	rt_ieee80211msg(ifp, RTM_IEEE80211_SCAN, NULL, 0);
799 }
800 
801 void
802 ieee80211_notify_replay_failure(struct ieee80211vap *vap,
803 	const struct ieee80211_frame *wh, const struct ieee80211_key *k,
804 	u_int64_t rsc, int tid)
805 {
806 	struct ifnet *ifp = vap->iv_ifp;
807 
808 	IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, wh->i_addr2,
809 	    "%s replay detected <rsc %ju, csc %ju, keyix %u rxkeyix %u>",
810 	    k->wk_cipher->ic_name, (intmax_t) rsc,
811 	    (intmax_t) k->wk_keyrsc[tid],
812 	    k->wk_keyix, k->wk_rxkeyix);
813 
814 	if (ifp != NULL) {		/* NB: for cipher test modules */
815 		struct ieee80211_replay_event iev;
816 
817 		IEEE80211_ADDR_COPY(iev.iev_dst, wh->i_addr1);
818 		IEEE80211_ADDR_COPY(iev.iev_src, wh->i_addr2);
819 		iev.iev_cipher = k->wk_cipher->ic_cipher;
820 		if (k->wk_rxkeyix != IEEE80211_KEYIX_NONE)
821 			iev.iev_keyix = k->wk_rxkeyix;
822 		else
823 			iev.iev_keyix = k->wk_keyix;
824 		iev.iev_keyrsc = k->wk_keyrsc[tid];
825 		iev.iev_rsc = rsc;
826 		rt_ieee80211msg(ifp, RTM_IEEE80211_REPLAY, &iev, sizeof(iev));
827 	}
828 }
829 
830 void
831 ieee80211_notify_michael_failure(struct ieee80211vap *vap,
832 	const struct ieee80211_frame *wh, u_int keyix)
833 {
834 	struct ifnet *ifp = vap->iv_ifp;
835 
836 	IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, wh->i_addr2,
837 	    "michael MIC verification failed <keyix %u>", keyix);
838 	vap->iv_stats.is_rx_tkipmic++;
839 
840 	if (ifp != NULL) {		/* NB: for cipher test modules */
841 		struct ieee80211_michael_event iev;
842 
843 		IEEE80211_ADDR_COPY(iev.iev_dst, wh->i_addr1);
844 		IEEE80211_ADDR_COPY(iev.iev_src, wh->i_addr2);
845 		iev.iev_cipher = IEEE80211_CIPHER_TKIP;
846 		iev.iev_keyix = keyix;
847 		rt_ieee80211msg(ifp, RTM_IEEE80211_MICHAEL, &iev, sizeof(iev));
848 	}
849 }
850 
851 void
852 ieee80211_notify_wds_discover(struct ieee80211_node *ni)
853 {
854 	struct ieee80211vap *vap = ni->ni_vap;
855 	struct ifnet *ifp = vap->iv_ifp;
856 
857 	notify_macaddr(ifp, RTM_IEEE80211_WDS, ni->ni_macaddr);
858 }
859 
860 void
861 ieee80211_notify_csa(struct ieee80211com *ic,
862 	const struct ieee80211_channel *c, int mode, int count)
863 {
864 	struct ieee80211vap *vap;
865 	struct ifnet *ifp;
866 	struct ieee80211_csa_event iev;
867 
868 	memset(&iev, 0, sizeof(iev));
869 	iev.iev_flags = c->ic_flags;
870 	iev.iev_freq = c->ic_freq;
871 	iev.iev_ieee = c->ic_ieee;
872 	iev.iev_mode = mode;
873 	iev.iev_count = count;
874 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
875 		ifp = vap->iv_ifp;
876 		rt_ieee80211msg(ifp, RTM_IEEE80211_CSA, &iev, sizeof(iev));
877 	}
878 }
879 
880 void
881 ieee80211_notify_radar(struct ieee80211com *ic,
882 	const struct ieee80211_channel *c)
883 {
884 	struct ieee80211_radar_event iev;
885 	struct ieee80211vap *vap;
886 	struct ifnet *ifp;
887 
888 	memset(&iev, 0, sizeof(iev));
889 	iev.iev_flags = c->ic_flags;
890 	iev.iev_freq = c->ic_freq;
891 	iev.iev_ieee = c->ic_ieee;
892 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
893 		ifp = vap->iv_ifp;
894 		rt_ieee80211msg(ifp, RTM_IEEE80211_RADAR, &iev, sizeof(iev));
895 	}
896 }
897 
898 void
899 ieee80211_notify_cac(struct ieee80211com *ic,
900 	const struct ieee80211_channel *c, enum ieee80211_notify_cac_event type)
901 {
902 	struct ieee80211_cac_event iev;
903 	struct ieee80211vap *vap;
904 	struct ifnet *ifp;
905 
906 	memset(&iev, 0, sizeof(iev));
907 	iev.iev_flags = c->ic_flags;
908 	iev.iev_freq = c->ic_freq;
909 	iev.iev_ieee = c->ic_ieee;
910 	iev.iev_type = type;
911 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
912 		ifp = vap->iv_ifp;
913 		rt_ieee80211msg(ifp, RTM_IEEE80211_CAC, &iev, sizeof(iev));
914 	}
915 }
916 
917 void
918 ieee80211_notify_node_deauth(struct ieee80211_node *ni)
919 {
920 	struct ieee80211vap *vap = ni->ni_vap;
921 	struct ifnet *ifp = vap->iv_ifp;
922 
923 	IEEE80211_NOTE(vap, IEEE80211_MSG_NODE, ni, "%s", "node deauth");
924 
925 	notify_macaddr(ifp, RTM_IEEE80211_DEAUTH, ni->ni_macaddr);
926 }
927 
928 void
929 ieee80211_notify_node_auth(struct ieee80211_node *ni)
930 {
931 	struct ieee80211vap *vap = ni->ni_vap;
932 	struct ifnet *ifp = vap->iv_ifp;
933 
934 	IEEE80211_NOTE(vap, IEEE80211_MSG_NODE, ni, "%s", "node auth");
935 
936 	notify_macaddr(ifp, RTM_IEEE80211_AUTH, ni->ni_macaddr);
937 }
938 
939 void
940 ieee80211_notify_country(struct ieee80211vap *vap,
941 	const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t cc[2])
942 {
943 	struct ifnet *ifp = vap->iv_ifp;
944 	struct ieee80211_country_event iev;
945 
946 	memset(&iev, 0, sizeof(iev));
947 	IEEE80211_ADDR_COPY(iev.iev_addr, bssid);
948 	iev.iev_cc[0] = cc[0];
949 	iev.iev_cc[1] = cc[1];
950 	rt_ieee80211msg(ifp, RTM_IEEE80211_COUNTRY, &iev, sizeof(iev));
951 }
952 
953 void
954 ieee80211_notify_radio(struct ieee80211com *ic, int state)
955 {
956 	struct ieee80211_radio_event iev;
957 	struct ieee80211vap *vap;
958 	struct ifnet *ifp;
959 
960 	memset(&iev, 0, sizeof(iev));
961 	iev.iev_state = state;
962 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
963 		ifp = vap->iv_ifp;
964 		rt_ieee80211msg(ifp, RTM_IEEE80211_RADIO, &iev, sizeof(iev));
965 	}
966 }
967 
968 /* IEEE Std 802.11a-1999, page 9, table 79 */
969 #define IEEE80211_OFDM_SYM_TIME                 4
970 #define IEEE80211_OFDM_PREAMBLE_TIME            16
971 #define IEEE80211_OFDM_SIGNAL_TIME              4
972 /* IEEE Std 802.11g-2003, page 44 */
973 #define IEEE80211_OFDM_SIGNAL_EXT_TIME          6
974 
975 /* IEEE Std 802.11a-1999, page 7, figure 107 */
976 #define IEEE80211_OFDM_PLCP_SERVICE_NBITS       16
977 #define IEEE80211_OFDM_TAIL_NBITS               6
978 
979 #define IEEE80211_OFDM_NBITS(frmlen) \
980 	(IEEE80211_OFDM_PLCP_SERVICE_NBITS + \
981 	((frmlen) * NBBY) + \
982 	IEEE80211_OFDM_TAIL_NBITS)
983 
984 #define IEEE80211_OFDM_NBITS_PER_SYM(kbps) \
985 	(((kbps) * IEEE80211_OFDM_SYM_TIME) / 1000)
986 
987 #define IEEE80211_OFDM_NSYMS(kbps, frmlen) \
988 	howmany(IEEE80211_OFDM_NBITS((frmlen)), \
989 	IEEE80211_OFDM_NBITS_PER_SYM((kbps)))
990 
991 #define IEEE80211_OFDM_TXTIME(kbps, frmlen) \
992 	(IEEE80211_OFDM_PREAMBLE_TIME + \
993 	IEEE80211_OFDM_SIGNAL_TIME + \
994 	(IEEE80211_OFDM_NSYMS((kbps), (frmlen)) * IEEE80211_OFDM_SYM_TIME))
995 
996 /* IEEE Std 802.11b-1999, page 28, subclause 18.3.4 */
997 #define IEEE80211_CCK_PREAMBLE_LEN      144
998 #define IEEE80211_CCK_PLCP_HDR_TIME     48
999 #define IEEE80211_CCK_SHPREAMBLE_LEN    72
1000 #define IEEE80211_CCK_SHPLCP_HDR_TIME   24
1001 
1002 #define IEEE80211_CCK_NBITS(frmlen)     ((frmlen) * NBBY)
1003 #define IEEE80211_CCK_TXTIME(kbps, frmlen) \
1004 	(((IEEE80211_CCK_NBITS((frmlen)) * 1000) + (kbps) - 1) / (kbps))
1005 
1006 uint16_t
1007 ieee80211_txtime(struct ieee80211_node *ni, u_int len, uint8_t rs_rate,
1008 		uint32_t flags)
1009 {
1010 	struct ieee80211vap *vap = ni->ni_vap;
1011 	uint16_t txtime;
1012 	int rate;
1013 
1014 	rs_rate &= IEEE80211_RATE_VAL;
1015 	rate = rs_rate * 500;   /* ieee80211 rate -> kbps */
1016 
1017 	if (vap->iv_ic->ic_phytype == IEEE80211_T_OFDM) {
1018 		/*
1019 		 * IEEE Std 802.11a-1999, page 37, equation (29)
1020 		 * IEEE Std 802.11g-2003, page 44, equation (42)
1021 		 */
1022 		txtime = IEEE80211_OFDM_TXTIME(rate, len);
1023 		if (vap->iv_ic->ic_curmode == IEEE80211_MODE_11G)
1024 			txtime += IEEE80211_OFDM_SIGNAL_EXT_TIME;
1025 	} else {
1026 		/*
1027 		 * IEEE Std 802.11b-1999, page 28, subclause 18.3.4
1028 		 * IEEE Std 802.11g-2003, page 45, equation (43)
1029 		 */
1030 		if (vap->iv_ic->ic_phytype == IEEE80211_T_OFDM_QUARTER+1)
1031 			++len;
1032 		txtime = IEEE80211_CCK_TXTIME(rate, len);
1033 
1034 		/*
1035 		 * Short preamble is not applicable for DS 1Mbits/s
1036 		 */
1037 		if (rs_rate != 2 && (flags & IEEE80211_F_SHPREAMBLE)) {
1038 			txtime += IEEE80211_CCK_SHPREAMBLE_LEN +
1039 				IEEE80211_CCK_SHPLCP_HDR_TIME;
1040 		} else {
1041 			txtime += IEEE80211_CCK_PREAMBLE_LEN +
1042 			IEEE80211_CCK_PLCP_HDR_TIME;
1043 		}
1044 	}
1045 	return txtime;
1046 }
1047 
1048 void
1049 ieee80211_load_module(const char *modname)
1050 {
1051 
1052 #ifdef notyet
1053 	(void)kern_kldload(curthread, modname, NULL);
1054 #else
1055 	kprintf("%s: load the %s module by hand for now.\n", __func__, modname);
1056 #endif
1057 }
1058 
1059 static eventhandler_tag wlan_bpfevent;
1060 static eventhandler_tag wlan_ifllevent;
1061 
1062 static void
1063 bpf_track_event(void *arg, struct ifnet *ifp, int dlt, int attach)
1064 {
1065 	/* NB: identify vap's by if_start */
1066 
1067 	if (dlt == DLT_IEEE802_11_RADIO &&
1068 	    ifp->if_start == ieee80211_vap_start) {
1069 		struct ieee80211vap *vap = ifp->if_softc;
1070 		/*
1071 		 * Track bpf radiotap listener state.  We mark the vap
1072 		 * to indicate if any listener is present and the com
1073 		 * to indicate if any listener exists on any associated
1074 		 * vap.  This flag is used by drivers to prepare radiotap
1075 		 * state only when needed.
1076 		 */
1077 		if (attach) {
1078 			ieee80211_syncflag_ext(vap, IEEE80211_FEXT_BPF);
1079 			if (vap->iv_opmode == IEEE80211_M_MONITOR)
1080 				atomic_add_int(&vap->iv_ic->ic_montaps, 1);
1081 		} else if (!vap->iv_rawbpf) {
1082 			ieee80211_syncflag_ext(vap, -IEEE80211_FEXT_BPF);
1083 			if (vap->iv_opmode == IEEE80211_M_MONITOR)
1084 				atomic_subtract_int(&vap->iv_ic->ic_montaps, 1);
1085 		}
1086 	}
1087 }
1088 
1089 const char *
1090 ether_sprintf(const u_char *buf)
1091 {
1092 	static char ethstr[MAXCPU][ETHER_ADDRSTRLEN + 1];
1093 	char *ptr = ethstr[mycpu->gd_cpuid];
1094 
1095 	kether_ntoa(buf, ptr);
1096 	return (ptr);
1097 }
1098 
1099 /*
1100  * Change MAC address on the vap (if was not started).
1101  */
1102 static void
1103 wlan_iflladdr_event(void *arg __unused, struct ifnet *ifp)
1104 {
1105 	/* NB: identify vap's by if_init */
1106 	if (ifp->if_init == ieee80211_init &&
1107 	    (ifp->if_flags & IFF_UP) == 0) {
1108 		struct ieee80211vap *vap = ifp->if_softc;
1109 		IEEE80211_ADDR_COPY(vap->iv_myaddr, IF_LLADDR(ifp));
1110 	}
1111 }
1112 
1113 /*
1114  * Module glue.
1115  *
1116  * NB: the module name is "wlan" for compatibility with NetBSD.
1117  */
1118 static int
1119 wlan_modevent(module_t mod, int type, void *unused)
1120 {
1121 	int error;
1122 
1123 	switch (type) {
1124 	case MOD_LOAD:
1125 		if (bootverbose)
1126 			kprintf("wlan: <802.11 Link Layer>\n");
1127 		wlan_bpfevent = EVENTHANDLER_REGISTER(bpf_track,
1128 					bpf_track_event, 0,
1129 					EVENTHANDLER_PRI_ANY);
1130 		wlan_ifllevent = EVENTHANDLER_REGISTER(iflladdr_event,
1131 					wlan_iflladdr_event, NULL,
1132 					EVENTHANDLER_PRI_ANY);
1133 		if_clone_attach(&wlan_cloner);
1134 		error = 0;
1135 		break;
1136 	case MOD_UNLOAD:
1137 		if_clone_detach(&wlan_cloner);
1138 		EVENTHANDLER_DEREGISTER(bpf_track, wlan_bpfevent);
1139 		EVENTHANDLER_DEREGISTER(iflladdr_event, wlan_ifllevent);
1140 		error = 0;
1141 		break;
1142 	default:
1143 		error = EINVAL;
1144 		break;
1145 	}
1146 	return error;
1147 }
1148 
1149 static moduledata_t wlan_mod = {
1150 	"wlan",
1151 	wlan_modevent,
1152 	0
1153 };
1154 DECLARE_MODULE(wlan, wlan_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
1155 MODULE_VERSION(wlan, 1);
1156 MODULE_DEPEND(wlan, ether, 1, 1, 1);
1157