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