]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net80211/ieee80211_mesh.c
PERR update to be called from mesh code.
[FreeBSD/FreeBSD.git] / sys / net80211 / ieee80211_mesh.c
1 /*- 
2  * Copyright (c) 2009 The FreeBSD Foundation 
3  * All rights reserved. 
4  * 
5  * This software was developed by Rui Paulo under sponsorship from the
6  * FreeBSD Foundation. 
7  *  
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions 
10  * are met: 
11  * 1. Redistributions of source code must retain the above copyright 
12  *    notice, this list of conditions and the following disclaimer. 
13  * 2. Redistributions in binary form must reproduce the above copyright 
14  *    notice, this list of conditions and the following disclaimer in the 
15  *    documentation and/or other materials provided with the distribution. 
16  * 
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
27  * SUCH DAMAGE. 
28  */ 
29 #include <sys/cdefs.h>
30 #ifdef __FreeBSD__
31 __FBSDID("$FreeBSD$");
32 #endif
33
34 /*
35  * IEEE 802.11s Mesh Point (MBSS) support.
36  *
37  * Based on March 2009, D3.0 802.11s draft spec.
38  */
39 #include "opt_inet.h"
40 #include "opt_wlan.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h> 
44 #include <sys/mbuf.h>   
45 #include <sys/malloc.h>
46 #include <sys/kernel.h>
47
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <sys/endian.h>
51 #include <sys/errno.h>
52 #include <sys/proc.h>
53 #include <sys/sysctl.h>
54
55 #include <net/if.h>
56 #include <net/if_media.h>
57 #include <net/if_llc.h>
58 #include <net/ethernet.h>
59
60 #include <net80211/ieee80211_var.h>
61 #include <net80211/ieee80211_action.h>
62 #include <net80211/ieee80211_input.h>
63 #include <net80211/ieee80211_mesh.h>
64
65 static void     mesh_rt_flush_invalid(struct ieee80211vap *);
66 static int      mesh_select_proto_path(struct ieee80211vap *, const char *);
67 static int      mesh_select_proto_metric(struct ieee80211vap *, const char *);
68 static void     mesh_vattach(struct ieee80211vap *);
69 static int      mesh_newstate(struct ieee80211vap *, enum ieee80211_state, int);
70 static void     mesh_rt_cleanup_cb(void *);
71 static void     mesh_linkchange(struct ieee80211_node *,
72                     enum ieee80211_mesh_mlstate);
73 static void     mesh_checkid(void *, struct ieee80211_node *);
74 static uint32_t mesh_generateid(struct ieee80211vap *);
75 static int      mesh_checkpseq(struct ieee80211vap *,
76                     const uint8_t [IEEE80211_ADDR_LEN], uint32_t);
77 static struct ieee80211_node *
78                 mesh_find_txnode(struct ieee80211vap *,
79                     const uint8_t [IEEE80211_ADDR_LEN]);
80 static void     mesh_forward(struct ieee80211vap *, struct mbuf *,
81                     const struct ieee80211_meshcntl *);
82 static int      mesh_input(struct ieee80211_node *, struct mbuf *, int, int);
83 static void     mesh_recv_mgmt(struct ieee80211_node *, struct mbuf *, int,
84                     int, int);
85 static void     mesh_recv_ctl(struct ieee80211_node *, struct mbuf *, int);
86 static void     mesh_peer_timeout_setup(struct ieee80211_node *);
87 static void     mesh_peer_timeout_backoff(struct ieee80211_node *);
88 static void     mesh_peer_timeout_cb(void *);
89 static __inline void
90                 mesh_peer_timeout_stop(struct ieee80211_node *);
91 static int      mesh_verify_meshid(struct ieee80211vap *, const uint8_t *);
92 static int      mesh_verify_meshconf(struct ieee80211vap *, const uint8_t *);
93 static int      mesh_verify_meshpeer(struct ieee80211vap *, uint8_t,
94                     const uint8_t *);
95 uint32_t        mesh_airtime_calc(struct ieee80211_node *);
96
97 /*
98  * Timeout values come from the specification and are in milliseconds.
99  */
100 static SYSCTL_NODE(_net_wlan, OID_AUTO, mesh, CTLFLAG_RD, 0,
101     "IEEE 802.11s parameters");
102 static int ieee80211_mesh_retrytimeout = -1;
103 SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, retrytimeout, CTLTYPE_INT | CTLFLAG_RW,
104     &ieee80211_mesh_retrytimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
105     "Retry timeout (msec)");
106 static int ieee80211_mesh_holdingtimeout = -1;
107 SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, holdingtimeout, CTLTYPE_INT | CTLFLAG_RW,
108     &ieee80211_mesh_holdingtimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
109     "Holding state timeout (msec)");
110 static int ieee80211_mesh_confirmtimeout = -1;
111 SYSCTL_PROC(_net_wlan_mesh, OID_AUTO, confirmtimeout, CTLTYPE_INT | CTLFLAG_RW,
112     &ieee80211_mesh_confirmtimeout, 0, ieee80211_sysctl_msecs_ticks, "I",
113     "Confirm state timeout (msec)");
114 static int ieee80211_mesh_maxretries = 2;
115 SYSCTL_INT(_net_wlan_mesh, OID_AUTO, maxretries, CTLTYPE_INT | CTLFLAG_RW,
116     &ieee80211_mesh_maxretries, 0,
117     "Maximum retries during peer link establishment");
118
119 static const uint8_t broadcastaddr[IEEE80211_ADDR_LEN] =
120         { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
121
122 static  ieee80211_recv_action_func mesh_recv_action_meshpeering_open;
123 static  ieee80211_recv_action_func mesh_recv_action_meshpeering_confirm;
124 static  ieee80211_recv_action_func mesh_recv_action_meshpeering_close;
125 static  ieee80211_recv_action_func mesh_recv_action_meshlmetric;
126
127 static  ieee80211_send_action_func mesh_send_action_meshpeering_open;
128 static  ieee80211_send_action_func mesh_send_action_meshpeering_confirm;
129 static  ieee80211_send_action_func mesh_send_action_meshpeering_close;
130 static  ieee80211_send_action_func mesh_send_action_meshlmetric;
131
132 static const struct ieee80211_mesh_proto_metric mesh_metric_airtime = {
133         .mpm_descr      = "AIRTIME",
134         .mpm_ie         = IEEE80211_MESHCONF_METRIC_AIRTIME,
135         .mpm_metric     = mesh_airtime_calc,
136 };
137
138 static struct ieee80211_mesh_proto_path         mesh_proto_paths[4];
139 static struct ieee80211_mesh_proto_metric       mesh_proto_metrics[4];
140
141 #define RT_ENTRY_LOCK(rt)       mtx_lock(&(rt)->rt_lock)
142 #define RT_ENTRY_LOCK_ASSERT(rt) mtx_assert(&(rt)->rt_lock, MA_OWNED)
143 #define RT_ENTRY_UNLOCK(rt)     mtx_unlock(&(rt)->rt_lock)
144
145 #define MESH_RT_LOCK(ms)        mtx_lock(&(ms)->ms_rt_lock)
146 #define MESH_RT_LOCK_ASSERT(ms) mtx_assert(&(ms)->ms_rt_lock, MA_OWNED)
147 #define MESH_RT_UNLOCK(ms)      mtx_unlock(&(ms)->ms_rt_lock)
148
149 MALLOC_DEFINE(M_80211_MESH_PREQ, "80211preq", "802.11 MESH Path Request frame");
150 MALLOC_DEFINE(M_80211_MESH_PREP, "80211prep", "802.11 MESH Path Reply frame");
151 MALLOC_DEFINE(M_80211_MESH_PERR, "80211perr", "802.11 MESH Path Error frame");
152
153 /* The longer one of the lifetime should be stored as new lifetime */
154 #define MESH_ROUTE_LIFETIME_MAX(a, b)   (a > b ? a : b)
155
156 MALLOC_DEFINE(M_80211_MESH_RT, "80211mesh", "802.11s routing table");
157
158 /*
159  * Helper functions to manipulate the Mesh routing table.
160  */
161
162 static struct ieee80211_mesh_route *
163 mesh_rt_find_locked(struct ieee80211_mesh_state *ms,
164     const uint8_t dest[IEEE80211_ADDR_LEN])
165 {
166         struct ieee80211_mesh_route *rt;
167
168         MESH_RT_LOCK_ASSERT(ms);
169
170         TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
171                 if (IEEE80211_ADDR_EQ(dest, rt->rt_dest))
172                         return rt;
173         }
174         return NULL;
175 }
176
177 static struct ieee80211_mesh_route *
178 mesh_rt_add_locked(struct ieee80211_mesh_state *ms,
179     const uint8_t dest[IEEE80211_ADDR_LEN])
180 {
181         struct ieee80211_mesh_route *rt;
182
183         KASSERT(!IEEE80211_ADDR_EQ(broadcastaddr, dest),
184             ("%s: adding broadcast to the routing table", __func__));
185
186         MESH_RT_LOCK_ASSERT(ms);
187
188         rt = malloc(ALIGN(sizeof(struct ieee80211_mesh_route)) +
189             ms->ms_ppath->mpp_privlen, M_80211_MESH_RT, M_NOWAIT | M_ZERO);
190         if (rt != NULL) {
191                 IEEE80211_ADDR_COPY(rt->rt_dest, dest);
192                 rt->rt_priv = (void *)ALIGN(&rt[1]);
193                 mtx_init(&rt->rt_lock, "MBSS_RT", "802.11s route entry", MTX_DEF);
194                 rt->rt_updtime = ticks; /* create time */
195                 TAILQ_INSERT_TAIL(&ms->ms_routes, rt, rt_next);
196         }
197         return rt;
198 }
199
200 struct ieee80211_mesh_route *
201 ieee80211_mesh_rt_find(struct ieee80211vap *vap,
202     const uint8_t dest[IEEE80211_ADDR_LEN])
203 {
204         struct ieee80211_mesh_state *ms = vap->iv_mesh;
205         struct ieee80211_mesh_route *rt;
206
207         MESH_RT_LOCK(ms);
208         rt = mesh_rt_find_locked(ms, dest);
209         MESH_RT_UNLOCK(ms);
210         return rt;
211 }
212
213 struct ieee80211_mesh_route *
214 ieee80211_mesh_rt_add(struct ieee80211vap *vap,
215     const uint8_t dest[IEEE80211_ADDR_LEN])
216 {
217         struct ieee80211_mesh_state *ms = vap->iv_mesh;
218         struct ieee80211_mesh_route *rt;
219
220         KASSERT(ieee80211_mesh_rt_find(vap, dest) == NULL,
221             ("%s: duplicate entry in the routing table", __func__));
222         KASSERT(!IEEE80211_ADDR_EQ(vap->iv_myaddr, dest),
223             ("%s: adding self to the routing table", __func__));
224
225         MESH_RT_LOCK(ms);
226         rt = mesh_rt_add_locked(ms, dest);
227         MESH_RT_UNLOCK(ms);
228         return rt;
229 }
230
231 /*
232  * Update the route lifetime and returns the updated lifetime.
233  * If new_lifetime is zero and route is timedout it will be invalidated.
234  * new_lifetime is in msec
235  */
236 int
237 ieee80211_mesh_rt_update(struct ieee80211_mesh_route *rt, int new_lifetime)
238 {
239         int timesince, now;
240         uint32_t lifetime = 0;
241
242         KASSERT(rt != NULL, ("route is NULL"));
243
244         now = ticks;
245         RT_ENTRY_LOCK(rt);
246
247         /* dont clobber a proxy entry gated by us */
248         if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY && rt->rt_nhops == 0) {
249                 RT_ENTRY_UNLOCK(rt);
250                 return rt->rt_lifetime;
251         }
252
253         timesince = ticks_to_msecs(now - rt->rt_updtime);
254         rt->rt_updtime = now;
255         if (timesince >= rt->rt_lifetime) {
256                 if (new_lifetime != 0) {
257                         rt->rt_lifetime = new_lifetime;
258                 }
259                 else {
260                         rt->rt_flags &= ~IEEE80211_MESHRT_FLAGS_VALID;
261                         rt->rt_lifetime = 0;
262                 }
263         } else {
264                 /* update what is left of lifetime */
265                 rt->rt_lifetime = rt->rt_lifetime - timesince;
266                 rt->rt_lifetime  = MESH_ROUTE_LIFETIME_MAX(
267                         new_lifetime, rt->rt_lifetime);
268         }
269         lifetime = rt->rt_lifetime;
270         RT_ENTRY_UNLOCK(rt);
271
272         return lifetime;
273 }
274
275 /*
276  * Add a proxy route (as needed) for the specified destination.
277  */
278 void
279 ieee80211_mesh_proxy_check(struct ieee80211vap *vap,
280     const uint8_t dest[IEEE80211_ADDR_LEN])
281 {
282         struct ieee80211_mesh_state *ms = vap->iv_mesh;
283         struct ieee80211_mesh_route *rt;
284
285         MESH_RT_LOCK(ms);
286         rt = mesh_rt_find_locked(ms, dest);
287         if (rt == NULL) {
288                 rt = mesh_rt_add_locked(ms, dest);
289                 if (rt == NULL) {
290                         IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
291                             "%s", "unable to add proxy entry");
292                         vap->iv_stats.is_mesh_rtaddfailed++;
293                 } else {
294                         IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
295                             "%s", "add proxy entry");
296                         IEEE80211_ADDR_COPY(rt->rt_mesh_gate, vap->iv_myaddr);
297                         IEEE80211_ADDR_COPY(rt->rt_nexthop, vap->iv_myaddr);
298                         rt->rt_flags |= IEEE80211_MESHRT_FLAGS_VALID
299                                      |  IEEE80211_MESHRT_FLAGS_PROXY;
300                 }
301         } else if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0) {
302                 KASSERT(rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY,
303                     ("no proxy flag for poxy entry"));
304                 struct ieee80211com *ic = vap->iv_ic;
305                 /*
306                  * Fix existing entry created by received frames from
307                  * stations that have some memory of dest.  We also
308                  * flush any frames held on the staging queue; delivering
309                  * them is too much trouble right now.
310                  */
311                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
312                     "%s", "fix proxy entry");
313                 IEEE80211_ADDR_COPY(rt->rt_nexthop, vap->iv_myaddr);
314                 rt->rt_flags |= IEEE80211_MESHRT_FLAGS_VALID
315                              |  IEEE80211_MESHRT_FLAGS_PROXY;
316                 /* XXX belongs in hwmp */
317                 ieee80211_ageq_drain_node(&ic->ic_stageq,
318                    (void *)(uintptr_t) ieee80211_mac_hash(ic, dest));
319                 /* XXX stat? */
320         }
321         MESH_RT_UNLOCK(ms);
322 }
323
324 static __inline void
325 mesh_rt_del(struct ieee80211_mesh_state *ms, struct ieee80211_mesh_route *rt)
326 {
327         TAILQ_REMOVE(&ms->ms_routes, rt, rt_next);
328         /*
329          * Grab the lock before destroying it, to be sure no one else
330          * is holding the route.
331          */
332         RT_ENTRY_LOCK(rt);
333         mtx_destroy(&rt->rt_lock);
334         free(rt, M_80211_MESH_RT);
335 }
336
337 void
338 ieee80211_mesh_rt_del(struct ieee80211vap *vap,
339     const uint8_t dest[IEEE80211_ADDR_LEN])
340 {
341         struct ieee80211_mesh_state *ms = vap->iv_mesh;
342         struct ieee80211_mesh_route *rt, *next;
343
344         MESH_RT_LOCK(ms);
345         TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
346                 if (IEEE80211_ADDR_EQ(rt->rt_dest, dest)) {
347                         if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) {
348                                 ms->ms_ppath->mpp_senderror(vap, dest, rt,
349                                     IEEE80211_REASON_MESH_PERR_NO_PROXY);
350                         } else {
351                                 ms->ms_ppath->mpp_senderror(vap, dest, rt,
352                                     IEEE80211_REASON_MESH_PERR_DEST_UNREACH);
353                         }
354                         mesh_rt_del(ms, rt);
355                         MESH_RT_UNLOCK(ms);
356                         return;
357                 }
358         }
359         MESH_RT_UNLOCK(ms);
360 }
361
362 void
363 ieee80211_mesh_rt_flush(struct ieee80211vap *vap)
364 {
365         struct ieee80211_mesh_state *ms = vap->iv_mesh;
366         struct ieee80211_mesh_route *rt, *next;
367
368         if (ms == NULL)
369                 return;
370         MESH_RT_LOCK(ms);
371         TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next)
372                 mesh_rt_del(ms, rt);
373         MESH_RT_UNLOCK(ms);
374 }
375
376 void
377 ieee80211_mesh_rt_flush_peer(struct ieee80211vap *vap,
378     const uint8_t peer[IEEE80211_ADDR_LEN])
379 {
380         struct ieee80211_mesh_state *ms = vap->iv_mesh;
381         struct ieee80211_mesh_route *rt, *next;
382
383         MESH_RT_LOCK(ms);
384         TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
385                 if (IEEE80211_ADDR_EQ(rt->rt_nexthop, peer))
386                         mesh_rt_del(ms, rt);
387         }
388         MESH_RT_UNLOCK(ms);
389 }
390
391 /*
392  * Flush expired routing entries, i.e. those in invalid state for
393  * some time.
394  */
395 static void
396 mesh_rt_flush_invalid(struct ieee80211vap *vap)
397 {
398         struct ieee80211_mesh_state *ms = vap->iv_mesh;
399         struct ieee80211_mesh_route *rt, *next;
400
401         if (ms == NULL)
402                 return;
403         MESH_RT_LOCK(ms);
404         TAILQ_FOREACH_SAFE(rt, &ms->ms_routes, rt_next, next) {
405                 ieee80211_mesh_rt_update(rt, 0);
406                 /*
407                  * NB: we check for lifetime == 0 so that we give a chance
408                  * for route discovery to complete.
409                  */
410                 if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0 &&
411                     rt->rt_lifetime == 0)
412                         mesh_rt_del(ms, rt);
413         }
414         MESH_RT_UNLOCK(ms);
415 }
416
417 #define N(a)    (sizeof(a) / sizeof(a[0]))
418 int
419 ieee80211_mesh_register_proto_path(const struct ieee80211_mesh_proto_path *mpp)
420 {
421         int i, firstempty = -1;
422
423         for (i = 0; i < N(mesh_proto_paths); i++) {
424                 if (strncmp(mpp->mpp_descr, mesh_proto_paths[i].mpp_descr,
425                     IEEE80211_MESH_PROTO_DSZ) == 0)
426                         return EEXIST;
427                 if (!mesh_proto_paths[i].mpp_active && firstempty == -1)
428                         firstempty = i;
429         }
430         if (firstempty < 0)
431                 return ENOSPC;
432         memcpy(&mesh_proto_paths[firstempty], mpp, sizeof(*mpp));
433         mesh_proto_paths[firstempty].mpp_active = 1;
434         return 0;
435 }
436
437 int
438 ieee80211_mesh_register_proto_metric(const struct
439     ieee80211_mesh_proto_metric *mpm)
440 {
441         int i, firstempty = -1;
442
443         for (i = 0; i < N(mesh_proto_metrics); i++) {
444                 if (strncmp(mpm->mpm_descr, mesh_proto_metrics[i].mpm_descr,
445                     IEEE80211_MESH_PROTO_DSZ) == 0)
446                         return EEXIST;
447                 if (!mesh_proto_metrics[i].mpm_active && firstempty == -1)
448                         firstempty = i;
449         }
450         if (firstempty < 0)
451                 return ENOSPC;
452         memcpy(&mesh_proto_metrics[firstempty], mpm, sizeof(*mpm));
453         mesh_proto_metrics[firstempty].mpm_active = 1;
454         return 0;
455 }
456
457 static int
458 mesh_select_proto_path(struct ieee80211vap *vap, const char *name)
459 {
460         struct ieee80211_mesh_state *ms = vap->iv_mesh;
461         int i;
462
463         for (i = 0; i < N(mesh_proto_paths); i++) {
464                 if (strcasecmp(mesh_proto_paths[i].mpp_descr, name) == 0) {
465                         ms->ms_ppath = &mesh_proto_paths[i];
466                         return 0;
467                 }
468         }
469         return ENOENT;
470 }
471
472 static int
473 mesh_select_proto_metric(struct ieee80211vap *vap, const char *name)
474 {
475         struct ieee80211_mesh_state *ms = vap->iv_mesh;
476         int i;
477
478         for (i = 0; i < N(mesh_proto_metrics); i++) {
479                 if (strcasecmp(mesh_proto_metrics[i].mpm_descr, name) == 0) {
480                         ms->ms_pmetric = &mesh_proto_metrics[i];
481                         return 0;
482                 }
483         }
484         return ENOENT;
485 }
486 #undef  N
487
488 static void
489 ieee80211_mesh_init(void)
490 {
491
492         memset(mesh_proto_paths, 0, sizeof(mesh_proto_paths));
493         memset(mesh_proto_metrics, 0, sizeof(mesh_proto_metrics));
494
495         /*
496          * Setup mesh parameters that depends on the clock frequency.
497          */
498         ieee80211_mesh_retrytimeout = msecs_to_ticks(40);
499         ieee80211_mesh_holdingtimeout = msecs_to_ticks(40);
500         ieee80211_mesh_confirmtimeout = msecs_to_ticks(40);
501
502         /*
503          * Register action frame handlers.
504          */
505         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
506             IEEE80211_ACTION_MESHPEERING_OPEN,
507             mesh_recv_action_meshpeering_open);
508         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
509             IEEE80211_ACTION_MESHPEERING_CONFIRM,
510             mesh_recv_action_meshpeering_confirm);
511         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
512             IEEE80211_ACTION_MESHPEERING_CLOSE,
513             mesh_recv_action_meshpeering_close);
514         ieee80211_recv_action_register(IEEE80211_ACTION_CAT_MESH,
515             IEEE80211_ACTION_MESH_LMETRIC, mesh_recv_action_meshlmetric);
516
517         ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
518             IEEE80211_ACTION_MESHPEERING_OPEN,
519             mesh_send_action_meshpeering_open);
520         ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
521             IEEE80211_ACTION_MESHPEERING_CONFIRM,
522             mesh_send_action_meshpeering_confirm);
523         ieee80211_send_action_register(IEEE80211_ACTION_CAT_SELF_PROT,
524             IEEE80211_ACTION_MESHPEERING_CLOSE,
525             mesh_send_action_meshpeering_close);
526         ieee80211_send_action_register(IEEE80211_ACTION_CAT_MESH,
527             IEEE80211_ACTION_MESH_LMETRIC,
528             mesh_send_action_meshlmetric);
529
530         /*
531          * Register Airtime Link Metric.
532          */
533         ieee80211_mesh_register_proto_metric(&mesh_metric_airtime);
534
535 }
536 SYSINIT(wlan_mesh, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_mesh_init, NULL);
537
538 void
539 ieee80211_mesh_attach(struct ieee80211com *ic)
540 {
541         ic->ic_vattach[IEEE80211_M_MBSS] = mesh_vattach;
542 }
543
544 void
545 ieee80211_mesh_detach(struct ieee80211com *ic)
546 {
547 }
548
549 static void
550 mesh_vdetach_peers(void *arg, struct ieee80211_node *ni)
551 {
552         struct ieee80211com *ic = ni->ni_ic;
553         uint16_t args[3];
554
555         if (ni->ni_mlstate == IEEE80211_NODE_MESH_ESTABLISHED) {
556                 args[0] = ni->ni_mlpid;
557                 args[1] = ni->ni_mllid;
558                 args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
559                 ieee80211_send_action(ni,
560                     IEEE80211_ACTION_CAT_SELF_PROT,
561                     IEEE80211_ACTION_MESHPEERING_CLOSE,
562                     args);
563         }
564         callout_drain(&ni->ni_mltimer);
565         /* XXX belongs in hwmp */
566         ieee80211_ageq_drain_node(&ic->ic_stageq,
567            (void *)(uintptr_t) ieee80211_mac_hash(ic, ni->ni_macaddr));
568 }
569
570 static void
571 mesh_vdetach(struct ieee80211vap *vap)
572 {
573         struct ieee80211_mesh_state *ms = vap->iv_mesh;
574
575         callout_drain(&ms->ms_cleantimer);
576         ieee80211_iterate_nodes(&vap->iv_ic->ic_sta, mesh_vdetach_peers,
577             NULL);
578         ieee80211_mesh_rt_flush(vap);
579         mtx_destroy(&ms->ms_rt_lock);
580         ms->ms_ppath->mpp_vdetach(vap);
581         free(vap->iv_mesh, M_80211_VAP);
582         vap->iv_mesh = NULL;
583 }
584
585 static void
586 mesh_vattach(struct ieee80211vap *vap)
587 {
588         struct ieee80211_mesh_state *ms;
589         vap->iv_newstate = mesh_newstate;
590         vap->iv_input = mesh_input;
591         vap->iv_opdetach = mesh_vdetach;
592         vap->iv_recv_mgmt = mesh_recv_mgmt;
593         vap->iv_recv_ctl = mesh_recv_ctl;
594         ms = malloc(sizeof(struct ieee80211_mesh_state), M_80211_VAP,
595             M_NOWAIT | M_ZERO);
596         if (ms == NULL) {
597                 printf("%s: couldn't alloc MBSS state\n", __func__);
598                 return;
599         }
600         vap->iv_mesh = ms;
601         ms->ms_seq = 0;
602         ms->ms_flags = (IEEE80211_MESHFLAGS_AP | IEEE80211_MESHFLAGS_FWD);
603         ms->ms_ttl = IEEE80211_MESH_DEFAULT_TTL;
604         TAILQ_INIT(&ms->ms_routes);
605         mtx_init(&ms->ms_rt_lock, "MBSS", "802.11s routing table", MTX_DEF);
606         callout_init(&ms->ms_cleantimer, CALLOUT_MPSAFE);
607         mesh_select_proto_metric(vap, "AIRTIME");
608         KASSERT(ms->ms_pmetric, ("ms_pmetric == NULL"));
609         mesh_select_proto_path(vap, "HWMP");
610         KASSERT(ms->ms_ppath, ("ms_ppath == NULL"));
611         ms->ms_ppath->mpp_vattach(vap);
612 }
613
614 /*
615  * IEEE80211_M_MBSS vap state machine handler.
616  */
617 static int
618 mesh_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
619 {
620         struct ieee80211_mesh_state *ms = vap->iv_mesh;
621         struct ieee80211com *ic = vap->iv_ic;
622         struct ieee80211_node *ni;
623         enum ieee80211_state ostate;
624
625         IEEE80211_LOCK_ASSERT(ic);
626
627         ostate = vap->iv_state;
628         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE, "%s: %s -> %s (%d)\n",
629             __func__, ieee80211_state_name[ostate],
630             ieee80211_state_name[nstate], arg);
631         vap->iv_state = nstate;         /* state transition */
632         if (ostate != IEEE80211_S_SCAN)
633                 ieee80211_cancel_scan(vap);     /* background scan */
634         ni = vap->iv_bss;                       /* NB: no reference held */
635         if (nstate != IEEE80211_S_RUN && ostate == IEEE80211_S_RUN)
636                 callout_drain(&ms->ms_cleantimer);
637         switch (nstate) {
638         case IEEE80211_S_INIT:
639                 switch (ostate) {
640                 case IEEE80211_S_SCAN:
641                         ieee80211_cancel_scan(vap);
642                         break;
643                 case IEEE80211_S_CAC:
644                         ieee80211_dfs_cac_stop(vap);
645                         break;
646                 case IEEE80211_S_RUN:
647                         ieee80211_iterate_nodes(&ic->ic_sta,
648                             mesh_vdetach_peers, NULL);
649                         break;
650                 default:
651                         break;
652                 }
653                 if (ostate != IEEE80211_S_INIT) {
654                         /* NB: optimize INIT -> INIT case */
655                         ieee80211_reset_bss(vap);
656                         ieee80211_mesh_rt_flush(vap);
657                 }
658                 break;
659         case IEEE80211_S_SCAN:
660                 switch (ostate) {
661                 case IEEE80211_S_INIT:
662                         if (vap->iv_des_chan != IEEE80211_CHAN_ANYC &&
663                             !IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan) &&
664                             ms->ms_idlen != 0) {
665                                 /*
666                                  * Already have a channel and a mesh ID; bypass
667                                  * the scan and startup immediately.
668                                  */
669                                 ieee80211_create_ibss(vap, vap->iv_des_chan);
670                                 break;
671                         }
672                         /*
673                          * Initiate a scan.  We can come here as a result
674                          * of an IEEE80211_IOC_SCAN_REQ too in which case
675                          * the vap will be marked with IEEE80211_FEXT_SCANREQ
676                          * and the scan request parameters will be present
677                          * in iv_scanreq.  Otherwise we do the default.
678                         */
679                         if (vap->iv_flags_ext & IEEE80211_FEXT_SCANREQ) {
680                                 ieee80211_check_scan(vap,
681                                     vap->iv_scanreq_flags,
682                                     vap->iv_scanreq_duration,
683                                     vap->iv_scanreq_mindwell,
684                                     vap->iv_scanreq_maxdwell,
685                                     vap->iv_scanreq_nssid, vap->iv_scanreq_ssid);
686                                 vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANREQ;
687                         } else
688                                 ieee80211_check_scan_current(vap);
689                         break;
690                 default:
691                         break;
692                 }
693                 break;
694         case IEEE80211_S_CAC:
695                 /*
696                  * Start CAC on a DFS channel.  We come here when starting
697                  * a bss on a DFS channel (see ieee80211_create_ibss).
698                  */
699                 ieee80211_dfs_cac_start(vap);
700                 break;
701         case IEEE80211_S_RUN:
702                 switch (ostate) {
703                 case IEEE80211_S_INIT:
704                         /*
705                          * Already have a channel; bypass the
706                          * scan and startup immediately.
707                          * Note that ieee80211_create_ibss will call
708                          * back to do a RUN->RUN state change.
709                          */
710                         ieee80211_create_ibss(vap,
711                             ieee80211_ht_adjust_channel(ic,
712                                 ic->ic_curchan, vap->iv_flags_ht));
713                         /* NB: iv_bss is changed on return */
714                         break;
715                 case IEEE80211_S_CAC:
716                         /*
717                          * NB: This is the normal state change when CAC
718                          * expires and no radar was detected; no need to
719                          * clear the CAC timer as it's already expired.
720                          */
721                         /* fall thru... */
722                 case IEEE80211_S_CSA:
723 #if 0
724                         /*
725                          * Shorten inactivity timer of associated stations
726                          * to weed out sta's that don't follow a CSA.
727                          */
728                         ieee80211_iterate_nodes(&ic->ic_sta, sta_csa, vap);
729 #endif
730                         /*
731                          * Update bss node channel to reflect where
732                          * we landed after CSA.
733                          */
734                         ieee80211_node_set_chan(vap->iv_bss,
735                             ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
736                                 ieee80211_htchanflags(vap->iv_bss->ni_chan)));
737                         /* XXX bypass debug msgs */
738                         break;
739                 case IEEE80211_S_SCAN:
740                 case IEEE80211_S_RUN:
741 #ifdef IEEE80211_DEBUG
742                         if (ieee80211_msg_debug(vap)) {
743                                 struct ieee80211_node *ni = vap->iv_bss;
744                                 ieee80211_note(vap,
745                                     "synchronized with %s meshid ",
746                                     ether_sprintf(ni->ni_meshid));
747                                 ieee80211_print_essid(ni->ni_meshid,
748                                     ni->ni_meshidlen);
749                                 /* XXX MCS/HT */
750                                 printf(" channel %d\n",
751                                     ieee80211_chan2ieee(ic, ic->ic_curchan));
752                         }
753 #endif
754                         break;
755                 default:
756                         break;
757                 }
758                 ieee80211_node_authorize(vap->iv_bss);
759                 callout_reset(&ms->ms_cleantimer, ms->ms_ppath->mpp_inact,
760                     mesh_rt_cleanup_cb, vap);
761                 break;
762         default:
763                 break;
764         }
765         /* NB: ostate not nstate */
766         ms->ms_ppath->mpp_newstate(vap, ostate, arg);
767         return 0;
768 }
769
770 static void
771 mesh_rt_cleanup_cb(void *arg)
772 {
773         struct ieee80211vap *vap = arg;
774         struct ieee80211_mesh_state *ms = vap->iv_mesh;
775
776         mesh_rt_flush_invalid(vap);
777         callout_reset(&ms->ms_cleantimer, ms->ms_ppath->mpp_inact,
778             mesh_rt_cleanup_cb, vap);
779 }
780
781
782 /*
783  * Helper function to note the Mesh Peer Link FSM change.
784  */
785 static void
786 mesh_linkchange(struct ieee80211_node *ni, enum ieee80211_mesh_mlstate state)
787 {
788         struct ieee80211vap *vap = ni->ni_vap;
789         struct ieee80211_mesh_state *ms = vap->iv_mesh;
790 #ifdef IEEE80211_DEBUG
791         static const char *meshlinkstates[] = {
792                 [IEEE80211_NODE_MESH_IDLE]              = "IDLE",
793                 [IEEE80211_NODE_MESH_OPENSNT]           = "OPEN SENT",
794                 [IEEE80211_NODE_MESH_OPENRCV]           = "OPEN RECEIVED",
795                 [IEEE80211_NODE_MESH_CONFIRMRCV]        = "CONFIRM RECEIVED",
796                 [IEEE80211_NODE_MESH_ESTABLISHED]       = "ESTABLISHED",
797                 [IEEE80211_NODE_MESH_HOLDING]           = "HOLDING"
798         };
799 #endif
800         IEEE80211_NOTE(vap, IEEE80211_MSG_MESH,
801             ni, "peer link: %s -> %s",
802             meshlinkstates[ni->ni_mlstate], meshlinkstates[state]);
803
804         /* track neighbor count */
805         if (state == IEEE80211_NODE_MESH_ESTABLISHED &&
806             ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED) {
807                 KASSERT(ms->ms_neighbors < 65535, ("neighbor count overflow"));
808                 ms->ms_neighbors++;
809                 ieee80211_beacon_notify(vap, IEEE80211_BEACON_MESHCONF);
810         } else if (ni->ni_mlstate == IEEE80211_NODE_MESH_ESTABLISHED &&
811             state != IEEE80211_NODE_MESH_ESTABLISHED) {
812                 KASSERT(ms->ms_neighbors > 0, ("neighbor count 0"));
813                 ms->ms_neighbors--;
814                 ieee80211_beacon_notify(vap, IEEE80211_BEACON_MESHCONF);
815         }
816         ni->ni_mlstate = state;
817         switch (state) {
818         case IEEE80211_NODE_MESH_HOLDING:
819                 ms->ms_ppath->mpp_peerdown(ni);
820                 break;
821         case IEEE80211_NODE_MESH_ESTABLISHED:
822                 ieee80211_mesh_discover(vap, ni->ni_macaddr, NULL);
823                 break;
824         default:
825                 break;
826         }
827 }
828
829 /*
830  * Helper function to generate a unique local ID required for mesh
831  * peer establishment.
832  */
833 static void
834 mesh_checkid(void *arg, struct ieee80211_node *ni)
835 {
836         uint16_t *r = arg;
837         
838         if (*r == ni->ni_mllid)
839                 *(uint16_t *)arg = 0;
840 }
841
842 static uint32_t
843 mesh_generateid(struct ieee80211vap *vap)
844 {
845         int maxiter = 4;
846         uint16_t r;
847
848         do {
849                 get_random_bytes(&r, 2);
850                 ieee80211_iterate_nodes(&vap->iv_ic->ic_sta, mesh_checkid, &r);
851                 maxiter--;
852         } while (r == 0 && maxiter > 0);
853         return r;
854 }
855
856 /*
857  * Verifies if we already received this packet by checking its
858  * sequence number.
859  * Returns 0 if the frame is to be accepted, 1 otherwise.
860  */
861 static int
862 mesh_checkpseq(struct ieee80211vap *vap,
863     const uint8_t source[IEEE80211_ADDR_LEN], uint32_t seq)
864 {
865         struct ieee80211_mesh_route *rt;
866
867         rt = ieee80211_mesh_rt_find(vap, source);
868         if (rt == NULL) {
869                 rt = ieee80211_mesh_rt_add(vap, source);
870                 if (rt == NULL) {
871                         IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, source,
872                             "%s", "add mcast route failed");
873                         vap->iv_stats.is_mesh_rtaddfailed++;
874                         return 1;
875                 }
876                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, source,
877                     "add mcast route, mesh seqno %d", seq);
878                 rt->rt_lastmseq = seq;
879                 return 0;
880         }
881         if (IEEE80211_MESH_SEQ_GEQ(rt->rt_lastmseq, seq)) {
882                 return 1;
883         } else {
884                 rt->rt_lastmseq = seq;
885                 return 0;
886         }
887 }
888
889 /*
890  * Iterate the routing table and locate the next hop.
891  */
892 static struct ieee80211_node *
893 mesh_find_txnode(struct ieee80211vap *vap,
894     const uint8_t dest[IEEE80211_ADDR_LEN])
895 {
896         struct ieee80211_mesh_route *rt;
897
898         rt = ieee80211_mesh_rt_find(vap, dest);
899         if (rt == NULL)
900                 return NULL;
901         if ((rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) == 0 ||
902             (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY)) {
903                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, dest,
904                     "%s: !valid or proxy, flags 0x%x", __func__, rt->rt_flags);
905                 /* XXX stat */
906                 return NULL;
907         }
908         return ieee80211_find_txnode(vap, rt->rt_nexthop);
909 }
910
911 /*
912  * Forward the specified frame.
913  * Decrement the TTL and set TA to our MAC address.
914  */
915 static void
916 mesh_forward(struct ieee80211vap *vap, struct mbuf *m,
917     const struct ieee80211_meshcntl *mc)
918 {
919         struct ieee80211com *ic = vap->iv_ic;
920         struct ieee80211_mesh_state *ms = vap->iv_mesh;
921         struct ifnet *ifp = vap->iv_ifp;
922         struct ifnet *parent = ic->ic_ifp;
923         const struct ieee80211_frame *wh =
924             mtod(m, const struct ieee80211_frame *);
925         struct mbuf *mcopy;
926         struct ieee80211_meshcntl *mccopy;
927         struct ieee80211_frame *whcopy;
928         struct ieee80211_node *ni;
929         int err;
930
931         /*
932          * mesh ttl of 1 means we are the last one receving it,
933          * according to amendment we decrement and then check if
934          * 0, if so we dont forward.
935          */
936         if (mc->mc_ttl < 1) {
937                 IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
938                     "%s", "frame not fwd'd, ttl 1");
939                 vap->iv_stats.is_mesh_fwd_ttl++;
940                 return;
941         }
942         if (!(ms->ms_flags & IEEE80211_MESHFLAGS_FWD)) {
943                 IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
944                     "%s", "frame not fwd'd, fwding disabled");
945                 vap->iv_stats.is_mesh_fwd_disabled++;
946                 return;
947         }
948         mcopy = m_dup(m, M_DONTWAIT);
949         if (mcopy == NULL) {
950                 IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
951                     "%s", "frame not fwd'd, cannot dup");
952                 vap->iv_stats.is_mesh_fwd_nobuf++;
953                 ifp->if_oerrors++;
954                 return;
955         }
956         mcopy = m_pullup(mcopy, ieee80211_hdrspace(ic, wh) +
957             sizeof(struct ieee80211_meshcntl));
958         if (mcopy == NULL) {
959                 IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
960                     "%s", "frame not fwd'd, too short");
961                 vap->iv_stats.is_mesh_fwd_tooshort++;
962                 ifp->if_oerrors++;
963                 m_freem(mcopy);
964                 return;
965         }
966         whcopy = mtod(mcopy, struct ieee80211_frame *);
967         mccopy = (struct ieee80211_meshcntl *)
968             (mtod(mcopy, uint8_t *) + ieee80211_hdrspace(ic, wh));
969         /* XXX clear other bits? */
970         whcopy->i_fc[1] &= ~IEEE80211_FC1_RETRY;
971         IEEE80211_ADDR_COPY(whcopy->i_addr2, vap->iv_myaddr);
972         if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
973                 ni = ieee80211_ref_node(vap->iv_bss);
974                 mcopy->m_flags |= M_MCAST;
975         } else {
976                 ni = mesh_find_txnode(vap, whcopy->i_addr3);
977                 if (ni == NULL) {
978                         /*
979                          * [Optional] any of the following three actions:
980                          * o silently discard
981                          * o trigger a path discovery
982                          * o inform TA that meshDA is unknown.
983                          */
984                         IEEE80211_NOTE_FRAME(vap, IEEE80211_MSG_MESH, wh,
985                             "%s", "frame not fwd'd, no path");
986                         ms->ms_ppath->mpp_senderror(vap, whcopy->i_addr3, NULL,
987                             IEEE80211_REASON_MESH_PERR_NO_FI);
988                         vap->iv_stats.is_mesh_fwd_nopath++;
989                         m_freem(mcopy);
990                         return;
991                 }
992                 IEEE80211_ADDR_COPY(whcopy->i_addr1, ni->ni_macaddr);
993         }
994         KASSERT(mccopy->mc_ttl > 0, ("%s called with wrong ttl", __func__));
995         mccopy->mc_ttl--;
996
997         /* XXX calculate priority so drivers can find the tx queue */
998         M_WME_SETAC(mcopy, WME_AC_BE);
999
1000         /* XXX do we know m_nextpkt is NULL? */
1001         mcopy->m_pkthdr.rcvif = (void *) ni;
1002         err = parent->if_transmit(parent, mcopy);
1003         if (err != 0) {
1004                 /* NB: IFQ_HANDOFF reclaims mbuf */
1005                 ieee80211_free_node(ni);
1006         } else {
1007                 ifp->if_opackets++;
1008         }
1009 }
1010
1011 static struct mbuf *
1012 mesh_decap(struct ieee80211vap *vap, struct mbuf *m, int hdrlen, int meshdrlen)
1013 {
1014 #define WHDIR(wh)       ((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK)
1015 #define MC01(mc)        ((const struct ieee80211_meshcntl_ae01 *)mc)
1016         uint8_t b[sizeof(struct ieee80211_qosframe_addr4) +
1017                   sizeof(struct ieee80211_meshcntl_ae10)];
1018         const struct ieee80211_qosframe_addr4 *wh;
1019         const struct ieee80211_meshcntl_ae10 *mc;
1020         struct ether_header *eh;
1021         struct llc *llc;
1022         int ae;
1023
1024         if (m->m_len < hdrlen + sizeof(*llc) &&
1025             (m = m_pullup(m, hdrlen + sizeof(*llc))) == NULL) {
1026                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
1027                     "discard data frame: %s", "m_pullup failed");
1028                 vap->iv_stats.is_rx_tooshort++;
1029                 return NULL;
1030         }
1031         memcpy(b, mtod(m, caddr_t), hdrlen);
1032         wh = (const struct ieee80211_qosframe_addr4 *)&b[0];
1033         mc = (const struct ieee80211_meshcntl_ae10 *)&b[hdrlen - meshdrlen];
1034         KASSERT(WHDIR(wh) == IEEE80211_FC1_DIR_FROMDS ||
1035                 WHDIR(wh) == IEEE80211_FC1_DIR_DSTODS,
1036             ("bogus dir, fc 0x%x:0x%x", wh->i_fc[0], wh->i_fc[1]));
1037
1038         llc = (struct llc *)(mtod(m, caddr_t) + hdrlen);
1039         if (llc->llc_dsap == LLC_SNAP_LSAP && llc->llc_ssap == LLC_SNAP_LSAP &&
1040             llc->llc_control == LLC_UI && llc->llc_snap.org_code[0] == 0 &&
1041             llc->llc_snap.org_code[1] == 0 && llc->llc_snap.org_code[2] == 0 &&
1042             /* NB: preserve AppleTalk frames that have a native SNAP hdr */
1043             !(llc->llc_snap.ether_type == htons(ETHERTYPE_AARP) ||
1044               llc->llc_snap.ether_type == htons(ETHERTYPE_IPX))) {
1045                 m_adj(m, hdrlen + sizeof(struct llc) - sizeof(*eh));
1046                 llc = NULL;
1047         } else {
1048                 m_adj(m, hdrlen - sizeof(*eh));
1049         }
1050         eh = mtod(m, struct ether_header *);
1051         ae = mc->mc_flags & IEEE80211_MESH_AE_MASK;
1052         if (WHDIR(wh) == IEEE80211_FC1_DIR_FROMDS) {
1053                 IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr1);
1054                 if (ae == IEEE80211_MESH_AE_00) {
1055                         IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr3);
1056                 } else if (ae == IEEE80211_MESH_AE_01) {
1057                         IEEE80211_ADDR_COPY(eh->ether_shost,
1058                             MC01(mc)->mc_addr4);
1059                 } else {
1060                         IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
1061                             (const struct ieee80211_frame *)wh, NULL,
1062                             "bad AE %d", ae);
1063                         vap->iv_stats.is_mesh_badae++;
1064                         m_freem(m);
1065                         return NULL;
1066                 }
1067         } else {
1068                 if (ae == IEEE80211_MESH_AE_00) {
1069                         IEEE80211_ADDR_COPY(eh->ether_dhost, wh->i_addr3);
1070                         IEEE80211_ADDR_COPY(eh->ether_shost, wh->i_addr4);
1071                 } else if (ae == IEEE80211_MESH_AE_10) {
1072                         IEEE80211_ADDR_COPY(eh->ether_dhost, mc->mc_addr5);
1073                         IEEE80211_ADDR_COPY(eh->ether_shost, mc->mc_addr6);
1074                 } else {
1075                         IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
1076                             (const struct ieee80211_frame *)wh, NULL,
1077                             "bad AE %d", ae);
1078                         vap->iv_stats.is_mesh_badae++;
1079                         m_freem(m);
1080                         return NULL;
1081                 }
1082         }
1083 #ifdef ALIGNED_POINTER
1084         if (!ALIGNED_POINTER(mtod(m, caddr_t) + sizeof(*eh), uint32_t)) {
1085                 m = ieee80211_realign(vap, m, sizeof(*eh));
1086                 if (m == NULL)
1087                         return NULL;
1088         }
1089 #endif /* ALIGNED_POINTER */
1090         if (llc != NULL) {
1091                 eh = mtod(m, struct ether_header *);
1092                 eh->ether_type = htons(m->m_pkthdr.len - sizeof(*eh));
1093         }
1094         return m;
1095 #undef  WDIR
1096 #undef  MC01
1097 }
1098
1099 /*
1100  * Return non-zero if the unicast mesh data frame should be processed
1101  * locally.  Frames that are not proxy'd have our address, otherwise
1102  * we need to consult the routing table to look for a proxy entry.
1103  */
1104 static __inline int
1105 mesh_isucastforme(struct ieee80211vap *vap, const struct ieee80211_frame *wh,
1106     const struct ieee80211_meshcntl *mc)
1107 {
1108         int ae = mc->mc_flags & 3;
1109
1110         KASSERT((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS,
1111             ("bad dir 0x%x:0x%x", wh->i_fc[0], wh->i_fc[1]));
1112         KASSERT(ae == IEEE80211_MESH_AE_00 || ae == IEEE80211_MESH_AE_10,
1113             ("bad AE %d", ae));
1114         if (ae == IEEE80211_MESH_AE_10) {       /* ucast w/ proxy */
1115                 const struct ieee80211_meshcntl_ae10 *mc10 =
1116                     (const struct ieee80211_meshcntl_ae10 *) mc;
1117                 struct ieee80211_mesh_route *rt =
1118                     ieee80211_mesh_rt_find(vap, mc10->mc_addr5);
1119                 /* check for proxy route to ourself */
1120                 return (rt != NULL &&
1121                     (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY));
1122         } else                                  /* ucast w/o proxy */
1123                 return IEEE80211_ADDR_EQ(wh->i_addr3, vap->iv_myaddr);
1124 }
1125
1126 /*
1127  * Verifies transmitter, updates lifetime, precursor list and forwards data.
1128  * > 0 means we have forwarded data and no need to process locally
1129  * == 0 means we want to process locally (and we may have forwarded data
1130  * < 0 means there was an error and data should be discarded
1131  */
1132 static int
1133 mesh_recv_indiv_data_to_fwrd(struct ieee80211vap *vap, struct mbuf *m,
1134     struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
1135 {
1136         struct ieee80211_qosframe_addr4 *qwh;
1137         struct ieee80211_mesh_state *ms = vap->iv_mesh;
1138         struct ieee80211_mesh_route *rt_meshda, *rt_meshsa;
1139
1140         qwh = (struct ieee80211_qosframe_addr4 *)wh;
1141
1142         /*
1143          * TODO:
1144          * o verify addr2 is  a legitimate transmitter
1145          * o lifetime of precursor of addr3 (addr2) is max(init, curr)
1146          * o lifetime of precursor of addr4 (nexthop) is max(init, curr)
1147          */
1148
1149         /* set lifetime of addr3 (meshDA) to initial value */
1150         rt_meshda = ieee80211_mesh_rt_find(vap, qwh->i_addr3);
1151         if (rt_meshda == NULL) {
1152                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH, qwh->i_addr2,
1153                     "no route to meshDA(%6D)", qwh->i_addr3, ":");
1154                 /*
1155                  * [Optional] any of the following three actions:
1156                  * o silently discard                           [X]
1157                  * o trigger a path discovery                   [ ]
1158                  * o inform TA that meshDA is unknown.          [ ]
1159                  */
1160                 /* XXX: stats */
1161                 return (-1);
1162         }
1163
1164         ieee80211_mesh_rt_update(rt_meshda, ticks_to_msecs(
1165             ms->ms_ppath->mpp_inact));
1166
1167         /* set lifetime of addr4 (meshSA) to initial value */
1168         rt_meshsa = ieee80211_mesh_rt_find(vap, qwh->i_addr4);
1169         KASSERT(rt_meshsa != NULL, ("no route"));
1170         ieee80211_mesh_rt_update(rt_meshsa, ticks_to_msecs(
1171             ms->ms_ppath->mpp_inact));
1172
1173         mesh_forward(vap, m, mc);
1174         return (1); /* dont process locally */
1175 }
1176
1177 /*
1178  * Verifies transmitter, updates lifetime, precursor list and process data
1179  * locally, if data is is proxy with AE = 10 it could mean data should go
1180  * on another mesh path or data should be forwarded to the DS.
1181  *
1182  * > 0 means we have forwarded data and no need to process locally
1183  * == 0 means we want to process locally (and we may have forwarded data
1184  * < 0 means there was an error and data should be discarded
1185  */
1186 static int
1187 mesh_recv_indiv_data_to_me(struct ieee80211vap *vap, struct mbuf *m,
1188     struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
1189 {
1190         struct ieee80211_qosframe_addr4 *qwh;
1191         const struct ieee80211_meshcntl_ae10 *mc10;
1192         struct ieee80211_mesh_state *ms = vap->iv_mesh;
1193         struct ieee80211_mesh_route *rt;
1194         int ae;
1195
1196         qwh = (struct ieee80211_qosframe_addr4 *)wh;
1197         mc10 = (const struct ieee80211_meshcntl_ae10 *)mc;
1198
1199         /*
1200          * TODO:
1201          * o verify addr2 is  a legitimate transmitter
1202          * o lifetime of precursor entry is max(init, curr)
1203          */
1204
1205         /* set lifetime of addr4 (meshSA) to initial value */
1206         rt = ieee80211_mesh_rt_find(vap, qwh->i_addr4);
1207         KASSERT(rt != NULL, ("no route"));
1208         ieee80211_mesh_rt_update(rt, ticks_to_msecs(ms->ms_ppath->mpp_inact));
1209         rt = NULL;
1210
1211         ae = mc10->mc_flags & IEEE80211_MESH_AE_MASK;
1212         KASSERT(ae == IEEE80211_MESH_AE_00 ||
1213             ae == IEEE80211_MESH_AE_10, ("bad AE %d", ae));
1214         if (ae == IEEE80211_MESH_AE_10) {
1215                 if (IEEE80211_ADDR_EQ(mc10->mc_addr5, qwh->i_addr3)) {
1216                         return (0); /* process locally */
1217                 }
1218
1219                 rt =  ieee80211_mesh_rt_find(vap, mc10->mc_addr5);
1220                 if (rt != NULL &&
1221                     (rt->rt_flags & IEEE80211_MESHRT_FLAGS_VALID) &&
1222                     (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) == 0) {
1223                         /*
1224                          * Forward on another mesh-path, according to
1225                          * amendment as specified in 9.32.4.1
1226                          */
1227                         IEEE80211_ADDR_COPY(qwh->i_addr3, mc10->mc_addr5);
1228                         mesh_forward(vap, m,
1229                             (const struct ieee80211_meshcntl *)mc10);
1230                         return (1); /* dont process locally */
1231                 }
1232                 /*
1233                  * All other cases: forward of MSDUs from the MBSS to DS indiv.
1234                  * addressed according to 13.11.3.2.
1235                  */
1236         }
1237         return (0); /* process locally */
1238 }
1239
1240 /*
1241  * Try to forward the group addressed data on to other mesh STAs, and
1242  * also to the DS.
1243  *
1244  * > 0 means we have forwarded data and no need to process locally
1245  * == 0 means we want to process locally (and we may have forwarded data
1246  * < 0 means there was an error and data should be discarded
1247  */
1248 static int
1249 mesh_recv_group_data(struct ieee80211vap *vap, struct mbuf *m,
1250     struct ieee80211_frame *wh, const struct ieee80211_meshcntl *mc)
1251 {
1252 #define MC01(mc)        ((const struct ieee80211_meshcntl_ae01 *)mc)
1253         struct ieee80211_mesh_state *ms = vap->iv_mesh;
1254
1255         mesh_forward(vap, m, mc);
1256
1257         if(mc->mc_ttl > 0) {
1258                 if (mc->mc_flags & IEEE80211_MESH_AE_01) {
1259                         /*
1260                          * Forward of MSDUs from the MBSS to DS group addressed
1261                          * (according to 13.11.3.2)
1262                          * This happens by delivering the packet, and a bridge
1263                          * will sent it on another port member.
1264                          */
1265                         if (ms->ms_flags & IEEE80211_MESHFLAGS_PORTAL &&
1266                             ms->ms_flags & IEEE80211_MESHFLAGS_FWD)
1267                                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_MESH,
1268                                     MC01(mc)->mc_addr4, "%s",
1269                                     "forward from MBSS to the DS");
1270                 }
1271         }
1272         return (0); /* process locally */
1273 #undef  MC01
1274 }
1275
1276 static int
1277 mesh_input(struct ieee80211_node *ni, struct mbuf *m, int rssi, int nf)
1278 {
1279 #define HAS_SEQ(type)   ((type & 0x4) == 0)
1280 #define MC01(mc)        ((const struct ieee80211_meshcntl_ae01 *)mc)
1281 #define MC10(mc)        ((const struct ieee80211_meshcntl_ae10 *)mc)
1282         struct ieee80211vap *vap = ni->ni_vap;
1283         struct ieee80211com *ic = ni->ni_ic;
1284         struct ifnet *ifp = vap->iv_ifp;
1285         struct ieee80211_frame *wh;
1286         const struct ieee80211_meshcntl *mc;
1287         int hdrspace, meshdrlen, need_tap, error;
1288         uint8_t dir, type, subtype, ae;
1289         uint32_t seq;
1290         const uint8_t *addr;
1291         uint8_t qos[2];
1292         ieee80211_seq rxseq;
1293
1294         KASSERT(ni != NULL, ("null node"));
1295         ni->ni_inact = ni->ni_inact_reload;
1296
1297         need_tap = 1;                   /* mbuf need to be tapped. */
1298         type = -1;                      /* undefined */
1299
1300         if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_min)) {
1301                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
1302                     ni->ni_macaddr, NULL,
1303                     "too short (1): len %u", m->m_pkthdr.len);
1304                 vap->iv_stats.is_rx_tooshort++;
1305                 goto out;
1306         }
1307         /*
1308          * Bit of a cheat here, we use a pointer for a 3-address
1309          * frame format but don't reference fields past outside
1310          * ieee80211_frame_min w/o first validating the data is
1311          * present.
1312         */
1313         wh = mtod(m, struct ieee80211_frame *);
1314
1315         if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
1316             IEEE80211_FC0_VERSION_0) {
1317                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
1318                     ni->ni_macaddr, NULL, "wrong version %x", wh->i_fc[0]);
1319                 vap->iv_stats.is_rx_badversion++;
1320                 goto err;
1321         }
1322         dir = wh->i_fc[1] & IEEE80211_FC1_DIR_MASK;
1323         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1324         subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1325         if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1326                 IEEE80211_RSSI_LPF(ni->ni_avgrssi, rssi);
1327                 ni->ni_noise = nf;
1328                 if (HAS_SEQ(type)) {
1329                         uint8_t tid = ieee80211_gettid(wh);
1330
1331                         if (IEEE80211_QOS_HAS_SEQ(wh) &&
1332                             TID_TO_WME_AC(tid) >= WME_AC_VI)
1333                                 ic->ic_wme.wme_hipri_traffic++;
1334                         rxseq = le16toh(*(uint16_t *)wh->i_seq);
1335                         if (! ieee80211_check_rxseq(ni, wh)) {
1336                                 /* duplicate, discard */
1337                                 IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
1338                                     wh->i_addr1, "duplicate",
1339                                     "seqno <%u,%u> fragno <%u,%u> tid %u",
1340                                     rxseq >> IEEE80211_SEQ_SEQ_SHIFT,
1341                                     ni->ni_rxseqs[tid] >>
1342                                     IEEE80211_SEQ_SEQ_SHIFT,
1343                                     rxseq & IEEE80211_SEQ_FRAG_MASK,
1344                                     ni->ni_rxseqs[tid] &
1345                                     IEEE80211_SEQ_FRAG_MASK,
1346                                     tid);
1347                                 vap->iv_stats.is_rx_dup++;
1348                                 IEEE80211_NODE_STAT(ni, rx_dup);
1349                                 goto out;
1350                         }
1351                         ni->ni_rxseqs[tid] = rxseq;
1352                 }
1353         }
1354 #ifdef IEEE80211_DEBUG
1355         /*
1356          * It's easier, but too expensive, to simulate different mesh
1357          * topologies by consulting the ACL policy very early, so do this
1358          * only under DEBUG.
1359          *
1360          * NB: this check is also done upon peering link initiation.
1361          */
1362         if (vap->iv_acl != NULL && !vap->iv_acl->iac_check(vap, wh)) {
1363                 IEEE80211_DISCARD(vap, IEEE80211_MSG_ACL,
1364                     wh, NULL, "%s", "disallowed by ACL");
1365                 vap->iv_stats.is_rx_acl++;
1366                 goto out;
1367         }
1368 #endif
1369         switch (type) {
1370         case IEEE80211_FC0_TYPE_DATA:
1371                 if (ni == vap->iv_bss)
1372                         goto out;
1373                 if (ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED) {
1374                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
1375                             ni->ni_macaddr, NULL,
1376                             "peer link not yet established (%d)",
1377                             ni->ni_mlstate);
1378                         vap->iv_stats.is_mesh_nolink++;
1379                         goto out;
1380                 }
1381                 if (dir != IEEE80211_FC1_DIR_FROMDS &&
1382                     dir != IEEE80211_FC1_DIR_DSTODS) {
1383                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1384                             wh, "data", "incorrect dir 0x%x", dir);
1385                         vap->iv_stats.is_rx_wrongdir++;
1386                         goto err;
1387                 }
1388
1389                 /* All Mesh data frames are QoS subtype */
1390                 if (!HAS_SEQ(type)) {
1391                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1392                             wh, "data", "incorrect subtype 0x%x", subtype);
1393                         vap->iv_stats.is_rx_badsubtype++;
1394                         goto err;
1395                 }
1396
1397                 /*
1398                  * Next up, any fragmentation.
1399                  * XXX: we defrag before we even try to forward,
1400                  * Mesh Control field is not present in sub-sequent
1401                  * fragmented frames. This is in contrast to Draft 4.0.
1402                  */
1403                 hdrspace = ieee80211_hdrspace(ic, wh);
1404                 if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1405                         m = ieee80211_defrag(ni, m, hdrspace);
1406                         if (m == NULL) {
1407                                 /* Fragment dropped or frame not complete yet */
1408                                 goto out;
1409                         }
1410                 }
1411                 wh = mtod(m, struct ieee80211_frame *); /* NB: after defrag */
1412
1413                 /*
1414                  * Now we have a complete Mesh Data frame.
1415                  */
1416
1417                 /*
1418                  * Only fromDStoDS data frames use 4 address qos frames
1419                  * as specified in amendment. Otherwise addr4 is located
1420                  * in the Mesh Control field and a 3 address qos frame
1421                  * is used.
1422                  */
1423                 if (IEEE80211_IS_DSTODS(wh))
1424                         *(uint16_t *)qos = *(uint16_t *)
1425                             ((struct ieee80211_qosframe_addr4 *)wh)->i_qos;
1426                 else
1427                         *(uint16_t *)qos = *(uint16_t *)
1428                             ((struct ieee80211_qosframe *)wh)->i_qos;
1429
1430                 /*
1431                  * NB: The mesh STA sets the Mesh Control Present
1432                  * subfield to 1 in the Mesh Data frame containing
1433                  * an unfragmented MSDU, an A-MSDU, or the first
1434                  * fragment of an MSDU.
1435                  * After defrag it should always be present.
1436                  */
1437                 if (!(qos[1] & IEEE80211_QOS_MC)) {
1438                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_MESH,
1439                             ni->ni_macaddr, NULL,
1440                             "%s", "Mesh control field not present");
1441                         vap->iv_stats.is_rx_elem_missing++; /* XXX: kinda */
1442                         goto err;
1443                 }
1444
1445                 /* pull up enough to get to the mesh control */
1446                 if (m->m_len < hdrspace + sizeof(struct ieee80211_meshcntl) &&
1447                     (m = m_pullup(m, hdrspace +
1448                         sizeof(struct ieee80211_meshcntl))) == NULL) {
1449                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
1450                             ni->ni_macaddr, NULL,
1451                             "data too short: expecting %u", hdrspace);
1452                         vap->iv_stats.is_rx_tooshort++;
1453                         goto out;               /* XXX */
1454                 }
1455                 /*
1456                  * Now calculate the full extent of the headers. Note
1457                  * mesh_decap will pull up anything we didn't get
1458                  * above when it strips the 802.11 headers.
1459                  */
1460                 mc = (const struct ieee80211_meshcntl *)
1461                     (mtod(m, const uint8_t *) + hdrspace);
1462                 ae = mc->mc_flags & IEEE80211_MESH_AE_MASK;
1463                 meshdrlen = sizeof(struct ieee80211_meshcntl) +
1464                     ae * IEEE80211_ADDR_LEN;
1465                 hdrspace += meshdrlen;
1466
1467                 /* pull complete hdrspace = ieee80211_hdrspace + meshcontrol */
1468                 if ((meshdrlen > sizeof(struct ieee80211_meshcntl)) &&
1469                     (m->m_len < hdrspace) &&
1470                     ((m = m_pullup(m, hdrspace)) == NULL)) {
1471                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
1472                             ni->ni_macaddr, NULL,
1473                             "data too short: expecting %u", hdrspace);
1474                         vap->iv_stats.is_rx_tooshort++;
1475                         goto out;               /* XXX */
1476                 }
1477                 /* XXX: are we sure there is no reallocating after m_pullup? */
1478
1479                 seq = LE_READ_4(mc->mc_seq);
1480                 if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1481                         addr = wh->i_addr3;
1482                 else if (ae == IEEE80211_MESH_AE_01)
1483                         addr = MC01(mc)->mc_addr4;
1484                 else
1485                         addr = ((struct ieee80211_qosframe_addr4 *)wh)->i_addr4;
1486                 if (IEEE80211_ADDR_EQ(vap->iv_myaddr, addr)) {
1487                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
1488                             addr, "data", "%s", "not to me");
1489                         vap->iv_stats.is_rx_wrongbss++; /* XXX kinda */
1490                         goto out;
1491                 }
1492                 if (mesh_checkpseq(vap, addr, seq) != 0) {
1493                         vap->iv_stats.is_rx_dup++;
1494                         goto out;
1495                 }
1496
1497                 /* This code "routes" the frame to the right control path */
1498                 if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1499                         if (IEEE80211_ADDR_EQ(vap->iv_myaddr, wh->i_addr3))
1500                                 error =
1501                                     mesh_recv_indiv_data_to_me(vap, m, wh, mc);
1502                         else if (IEEE80211_IS_MULTICAST(wh->i_addr3))
1503                                 error = mesh_recv_group_data(vap, m, wh, mc);
1504                         else
1505                                 error = mesh_recv_indiv_data_to_fwrd(vap, m,
1506                                     wh, mc);
1507                 } else
1508                         error = mesh_recv_group_data(vap, m, wh, mc);
1509                 if (error < 0)
1510                         goto err;
1511                 else if (error > 0)
1512                         goto out;
1513
1514                 if (ieee80211_radiotap_active_vap(vap))
1515                         ieee80211_radiotap_rx(vap, m);
1516                 need_tap = 0;
1517
1518                 /*
1519                  * Finally, strip the 802.11 header.
1520                  */
1521                 m = mesh_decap(vap, m, hdrspace, meshdrlen);
1522                 if (m == NULL) {
1523                         /* XXX mask bit to check for both */
1524                         /* don't count Null data frames as errors */
1525                         if (subtype == IEEE80211_FC0_SUBTYPE_NODATA ||
1526                             subtype == IEEE80211_FC0_SUBTYPE_QOS_NULL)
1527                                 goto out;
1528                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_INPUT,
1529                             ni->ni_macaddr, "data", "%s", "decap error");
1530                         vap->iv_stats.is_rx_decap++;
1531                         IEEE80211_NODE_STAT(ni, rx_decap);
1532                         goto err;
1533                 }
1534                 if (qos[0] & IEEE80211_QOS_AMSDU) {
1535                         m = ieee80211_decap_amsdu(ni, m);
1536                         if (m == NULL)
1537                                 return IEEE80211_FC0_TYPE_DATA;
1538                 }
1539                 ieee80211_deliver_data(vap, ni, m);
1540                 return type;
1541         case IEEE80211_FC0_TYPE_MGT:
1542                 vap->iv_stats.is_rx_mgmt++;
1543                 IEEE80211_NODE_STAT(ni, rx_mgmt);
1544                 if (dir != IEEE80211_FC1_DIR_NODS) {
1545                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1546                             wh, "mgt", "incorrect dir 0x%x", dir);
1547                         vap->iv_stats.is_rx_wrongdir++;
1548                         goto err;
1549                 }
1550                 if (m->m_pkthdr.len < sizeof(struct ieee80211_frame)) {
1551                         IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_ANY,
1552                             ni->ni_macaddr, "mgt", "too short: len %u",
1553                             m->m_pkthdr.len);
1554                         vap->iv_stats.is_rx_tooshort++;
1555                         goto out;
1556                 }
1557 #ifdef IEEE80211_DEBUG
1558                 if ((ieee80211_msg_debug(vap) && 
1559                     (vap->iv_ic->ic_flags & IEEE80211_F_SCAN)) ||
1560                     ieee80211_msg_dumppkts(vap)) {
1561                         if_printf(ifp, "received %s from %s rssi %d\n",
1562                             ieee80211_mgt_subtype_name[subtype >>
1563                             IEEE80211_FC0_SUBTYPE_SHIFT],
1564                             ether_sprintf(wh->i_addr2), rssi);
1565                 }
1566 #endif
1567                 if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1568                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1569                             wh, NULL, "%s", "WEP set but not permitted");
1570                         vap->iv_stats.is_rx_mgtdiscard++; /* XXX */
1571                         goto out;
1572                 }
1573                 vap->iv_recv_mgmt(ni, m, subtype, rssi, nf);
1574                 goto out;
1575         case IEEE80211_FC0_TYPE_CTL:
1576                 vap->iv_stats.is_rx_ctl++;
1577                 IEEE80211_NODE_STAT(ni, rx_ctrl);
1578                 goto out;
1579         default:
1580                 IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
1581                     wh, "bad", "frame type 0x%x", type);
1582                 /* should not come here */
1583                 break;
1584         }
1585 err:
1586         ifp->if_ierrors++;
1587 out:
1588         if (m != NULL) {
1589                 if (need_tap && ieee80211_radiotap_active_vap(vap))
1590                         ieee80211_radiotap_rx(vap, m);
1591                 m_freem(m);
1592         }
1593         return type;
1594 #undef  HAS_SEQ
1595 #undef  MC01
1596 #undef  MC10
1597 }
1598
1599 static void
1600 mesh_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m0, int subtype,
1601     int rssi, int nf)
1602 {
1603         struct ieee80211vap *vap = ni->ni_vap;
1604         struct ieee80211_mesh_state *ms = vap->iv_mesh;
1605         struct ieee80211com *ic = ni->ni_ic;
1606         struct ieee80211_frame *wh;
1607         struct ieee80211_mesh_route *rt;
1608         uint8_t *frm, *efrm;
1609
1610         wh = mtod(m0, struct ieee80211_frame *);
1611         frm = (uint8_t *)&wh[1];
1612         efrm = mtod(m0, uint8_t *) + m0->m_len;
1613         switch (subtype) {
1614         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1615         case IEEE80211_FC0_SUBTYPE_BEACON:
1616         {
1617                 struct ieee80211_scanparams scan;
1618                 /*
1619                  * We process beacon/probe response
1620                  * frames to discover neighbors.
1621                  */
1622                 if (ieee80211_parse_beacon(ni, m0, &scan) != 0)
1623                         return;
1624                 /*
1625                  * Count frame now that we know it's to be processed.
1626                  */
1627                 if (subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
1628                         vap->iv_stats.is_rx_beacon++;   /* XXX remove */
1629                         IEEE80211_NODE_STAT(ni, rx_beacons);
1630                 } else
1631                         IEEE80211_NODE_STAT(ni, rx_proberesp);
1632                 /*
1633                  * If scanning, just pass information to the scan module.
1634                  */
1635                 if (ic->ic_flags & IEEE80211_F_SCAN) {
1636                         if (ic->ic_flags_ext & IEEE80211_FEXT_PROBECHAN) {
1637                                 /*
1638                                  * Actively scanning a channel marked passive;
1639                                  * send a probe request now that we know there
1640                                  * is 802.11 traffic present.
1641                                  *
1642                                  * XXX check if the beacon we recv'd gives
1643                                  * us what we need and suppress the probe req
1644                                  */
1645                                 ieee80211_probe_curchan(vap, 1);
1646                                 ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
1647                         }
1648                         ieee80211_add_scan(vap, &scan, wh,
1649                             subtype, rssi, nf);
1650                         return;
1651                 }
1652
1653                 /* The rest of this code assumes we are running */
1654                 if (vap->iv_state != IEEE80211_S_RUN)
1655                         return;
1656                 /*
1657                  * Ignore non-mesh STAs.
1658                  */
1659                 if ((scan.capinfo &
1660                      (IEEE80211_CAPINFO_ESS|IEEE80211_CAPINFO_IBSS)) ||
1661                     scan.meshid == NULL || scan.meshconf == NULL) {
1662                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1663                             wh, "beacon", "%s", "not a mesh sta");
1664                         vap->iv_stats.is_mesh_wrongmesh++;
1665                         return;
1666                 }
1667                 /*
1668                  * Ignore STAs for other mesh networks.
1669                  */
1670                 if (memcmp(scan.meshid+2, ms->ms_id, ms->ms_idlen) != 0 ||
1671                     mesh_verify_meshconf(vap, scan.meshconf)) {
1672                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1673                             wh, "beacon", "%s", "not for our mesh");
1674                         vap->iv_stats.is_mesh_wrongmesh++;
1675                         return;
1676                 }
1677                 /*
1678                  * Peer only based on the current ACL policy.
1679                  */
1680                 if (vap->iv_acl != NULL && !vap->iv_acl->iac_check(vap, wh)) {
1681                         IEEE80211_DISCARD(vap, IEEE80211_MSG_ACL,
1682                             wh, NULL, "%s", "disallowed by ACL");
1683                         vap->iv_stats.is_rx_acl++;
1684                         return;
1685                 }
1686                 /*
1687                  * Do neighbor discovery.
1688                  */
1689                 if (!IEEE80211_ADDR_EQ(wh->i_addr2, ni->ni_macaddr)) {
1690                         /*
1691                          * Create a new entry in the neighbor table.
1692                          */
1693                         ni = ieee80211_add_neighbor(vap, wh, &scan);
1694                 }
1695                 /*
1696                  * Automatically peer with discovered nodes if possible.
1697                  * XXX backoff on repeated failure
1698                  */
1699                 if (ni != vap->iv_bss &&
1700                     (ms->ms_flags & IEEE80211_MESHFLAGS_AP)) {
1701                         switch (ni->ni_mlstate) {
1702                         case IEEE80211_NODE_MESH_IDLE:
1703                         {
1704                                 uint16_t args[1];
1705
1706                                 ni->ni_mlpid = mesh_generateid(vap);
1707                                 if (ni->ni_mlpid == 0)
1708                                         return;
1709                                 mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENSNT);
1710                                 args[0] = ni->ni_mlpid;
1711                                 ieee80211_send_action(ni,
1712                                 IEEE80211_ACTION_CAT_SELF_PROT,
1713                                 IEEE80211_ACTION_MESHPEERING_OPEN, args);
1714                                 ni->ni_mlrcnt = 0;
1715                                 mesh_peer_timeout_setup(ni);
1716                                 break;
1717                         }
1718                         case IEEE80211_NODE_MESH_ESTABLISHED:
1719                         {
1720                                 /*
1721                                  * Valid beacon from a peer mesh STA
1722                                  * bump TA lifetime
1723                                  */
1724                                 rt = ieee80211_mesh_rt_find(vap, wh->i_addr2);
1725                                 if(rt != NULL) {
1726                                         ieee80211_mesh_rt_update(rt,
1727                                             ticks_to_msecs(
1728                                             ms->ms_ppath->mpp_inact));
1729                                 }
1730                                 break;
1731                         }
1732                         default:
1733                                 break; /* ignore */
1734                         }
1735                 }
1736                 break;
1737         }
1738         case IEEE80211_FC0_SUBTYPE_PROBE_REQ:
1739         {
1740                 uint8_t *ssid, *meshid, *rates, *xrates;
1741                 uint8_t *sfrm;
1742
1743                 if (vap->iv_state != IEEE80211_S_RUN) {
1744                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1745                             wh, NULL, "wrong state %s",
1746                             ieee80211_state_name[vap->iv_state]);
1747                         vap->iv_stats.is_rx_mgtdiscard++;
1748                         return;
1749                 }
1750                 if (IEEE80211_IS_MULTICAST(wh->i_addr2)) {
1751                         /* frame must be directed */
1752                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1753                             wh, NULL, "%s", "not unicast");
1754                         vap->iv_stats.is_rx_mgtdiscard++;       /* XXX stat */
1755                         return;
1756                 }
1757                 /*
1758                  * prreq frame format
1759                  *      [tlv] ssid
1760                  *      [tlv] supported rates
1761                  *      [tlv] extended supported rates
1762                  *      [tlv] mesh id
1763                  */
1764                 ssid = meshid = rates = xrates = NULL;
1765                 sfrm = frm;
1766                 while (efrm - frm > 1) {
1767                         IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return);
1768                         switch (*frm) {
1769                         case IEEE80211_ELEMID_SSID:
1770                                 ssid = frm;
1771                                 break;
1772                         case IEEE80211_ELEMID_RATES:
1773                                 rates = frm;
1774                                 break;
1775                         case IEEE80211_ELEMID_XRATES:
1776                                 xrates = frm;
1777                                 break;
1778                         case IEEE80211_ELEMID_MESHID:
1779                                 meshid = frm;
1780                                 break;
1781                         }
1782                         frm += frm[1] + 2;
1783                 }
1784                 IEEE80211_VERIFY_ELEMENT(ssid, IEEE80211_NWID_LEN, return);
1785                 IEEE80211_VERIFY_ELEMENT(rates, IEEE80211_RATE_MAXSIZE, return);
1786                 if (xrates != NULL)
1787                         IEEE80211_VERIFY_ELEMENT(xrates,
1788                             IEEE80211_RATE_MAXSIZE - rates[1], return);
1789                 if (meshid != NULL) {
1790                         IEEE80211_VERIFY_ELEMENT(meshid,
1791                             IEEE80211_MESHID_LEN, return);
1792                         /* NB: meshid, not ssid */
1793                         IEEE80211_VERIFY_SSID(vap->iv_bss, meshid, return);
1794                 }
1795
1796                 /* XXX find a better class or define it's own */
1797                 IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_INPUT, wh->i_addr2,
1798                     "%s", "recv probe req");
1799                 /*
1800                  * Some legacy 11b clients cannot hack a complete
1801                  * probe response frame.  When the request includes
1802                  * only a bare-bones rate set, communicate this to
1803                  * the transmit side.
1804                  */
1805                 ieee80211_send_proberesp(vap, wh->i_addr2, 0);
1806                 break;
1807         }
1808
1809         case IEEE80211_FC0_SUBTYPE_ACTION:
1810         case IEEE80211_FC0_SUBTYPE_ACTION_NOACK:
1811                 if (ni == vap->iv_bss) {
1812                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1813                             wh, NULL, "%s", "unknown node");
1814                         vap->iv_stats.is_rx_mgtdiscard++;
1815                 } else if (!IEEE80211_ADDR_EQ(vap->iv_myaddr, wh->i_addr1) &&
1816                     !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1817                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1818                             wh, NULL, "%s", "not for us");
1819                         vap->iv_stats.is_rx_mgtdiscard++;
1820                 } else if (vap->iv_state != IEEE80211_S_RUN) {
1821                         IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1822                             wh, NULL, "wrong state %s",
1823                             ieee80211_state_name[vap->iv_state]);
1824                         vap->iv_stats.is_rx_mgtdiscard++;
1825                 } else {
1826                         if (ieee80211_parse_action(ni, m0) == 0)
1827                                 (void)ic->ic_recv_action(ni, wh, frm, efrm);
1828                 }
1829                 break;
1830
1831         case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1832         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1833         case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1834         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1835         case IEEE80211_FC0_SUBTYPE_ATIM:
1836         case IEEE80211_FC0_SUBTYPE_DISASSOC:
1837         case IEEE80211_FC0_SUBTYPE_AUTH:
1838         case IEEE80211_FC0_SUBTYPE_DEAUTH:
1839                 IEEE80211_DISCARD(vap, IEEE80211_MSG_INPUT,
1840                     wh, NULL, "%s", "not handled");
1841                 vap->iv_stats.is_rx_mgtdiscard++;
1842                 break;
1843
1844         default:
1845                 IEEE80211_DISCARD(vap, IEEE80211_MSG_ANY,
1846                     wh, "mgt", "subtype 0x%x not handled", subtype);
1847                 vap->iv_stats.is_rx_badsubtype++;
1848                 break;
1849         }
1850 }
1851
1852 static void
1853 mesh_recv_ctl(struct ieee80211_node *ni, struct mbuf *m, int subtype)
1854 {
1855
1856         switch (subtype) {
1857         case IEEE80211_FC0_SUBTYPE_BAR:
1858                 ieee80211_recv_bar(ni, m);
1859                 break;
1860         }
1861 }
1862
1863 /*
1864  * Parse meshpeering action ie's for MPM frames
1865  */
1866 static const struct ieee80211_meshpeer_ie *
1867 mesh_parse_meshpeering_action(struct ieee80211_node *ni,
1868         const struct ieee80211_frame *wh,       /* XXX for VERIFY_LENGTH */
1869         const uint8_t *frm, const uint8_t *efrm,
1870         struct ieee80211_meshpeer_ie *mp, uint8_t subtype)
1871 {
1872         struct ieee80211vap *vap = ni->ni_vap;
1873         const struct ieee80211_meshpeer_ie *mpie;
1874         uint16_t args[3];
1875         const uint8_t *meshid, *meshconf, *meshpeer;
1876         uint8_t sendclose = 0; /* 1 = MPM frame rejected, close will be sent */
1877
1878         meshid = meshconf = meshpeer = NULL;
1879         while (efrm - frm > 1) {
1880                 IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return NULL);
1881                 switch (*frm) {
1882                 case IEEE80211_ELEMID_MESHID:
1883                         meshid = frm;
1884                         break;
1885                 case IEEE80211_ELEMID_MESHCONF:
1886                         meshconf = frm;
1887                         break;
1888                 case IEEE80211_ELEMID_MESHPEER:
1889                         meshpeer = frm;
1890                         mpie = (const struct ieee80211_meshpeer_ie *) frm;
1891                         memset(mp, 0, sizeof(*mp));
1892                         mp->peer_len = mpie->peer_len;
1893                         mp->peer_proto = LE_READ_2(&mpie->peer_proto);
1894                         mp->peer_llinkid = LE_READ_2(&mpie->peer_llinkid);
1895                         switch (subtype) {
1896                         case IEEE80211_ACTION_MESHPEERING_CONFIRM:
1897                                 mp->peer_linkid =
1898                                     LE_READ_2(&mpie->peer_linkid);
1899                                 break;
1900                         case IEEE80211_ACTION_MESHPEERING_CLOSE:
1901                                 /* NB: peer link ID is optional */
1902                                 if (mpie->peer_len ==
1903                                     (IEEE80211_MPM_BASE_SZ + 2)) {
1904                                         mp->peer_linkid = 0;
1905                                         mp->peer_rcode =
1906                                             LE_READ_2(&mpie->peer_linkid);
1907                                 } else {
1908                                         mp->peer_linkid =
1909                                             LE_READ_2(&mpie->peer_linkid);
1910                                         mp->peer_rcode =
1911                                             LE_READ_2(&mpie->peer_rcode);
1912                                 }
1913                                 break;
1914                         }
1915                         break;
1916                 }
1917                 frm += frm[1] + 2;
1918         }
1919
1920         /*
1921          * Verify the contents of the frame.
1922          * If it fails validation, close the peer link.
1923          */
1924         if (mesh_verify_meshpeer(vap, subtype, (const uint8_t *)mp)) {
1925                 sendclose = 1;
1926                 IEEE80211_DISCARD(vap,
1927                     IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
1928                     wh, NULL, "%s", "MPM validation failed");
1929         }
1930
1931         /* If meshid is not the same reject any frames type. */
1932         if (sendclose == 0 && mesh_verify_meshid(vap, meshid)) {
1933                 sendclose = 1;
1934                 IEEE80211_DISCARD(vap,
1935                     IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
1936                     wh, NULL, "%s", "not for our mesh");
1937                 if (subtype == IEEE80211_ACTION_MESHPEERING_CLOSE) {
1938                         /*
1939                          * Standard not clear about this, if we dont ignore
1940                          * there will be an endless loop between nodes sending
1941                          * CLOSE frames between each other with wrong meshid.
1942                          * Discard and timers will bring FSM to IDLE state.
1943                          */
1944                         return NULL;
1945                 }
1946         }
1947         
1948         /*
1949          * Close frames are accepted if meshid is the same.
1950          * Verify the other two types.
1951          */
1952         if (sendclose == 0 && subtype != IEEE80211_ACTION_MESHPEERING_CLOSE &&
1953             mesh_verify_meshconf(vap, meshconf)) {
1954                 sendclose = 1;
1955                 IEEE80211_DISCARD(vap,
1956                     IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
1957                     wh, NULL, "%s", "configuration missmatch");
1958         }
1959
1960         if (sendclose) {
1961                 vap->iv_stats.is_rx_mgtdiscard++;
1962                 switch (ni->ni_mlstate) {
1963                 case IEEE80211_NODE_MESH_IDLE:
1964                 case IEEE80211_NODE_MESH_ESTABLISHED:
1965                 case IEEE80211_NODE_MESH_HOLDING:
1966                         /* ignore */
1967                         break;
1968                 case IEEE80211_NODE_MESH_OPENSNT:
1969                 case IEEE80211_NODE_MESH_OPENRCV:
1970                 case IEEE80211_NODE_MESH_CONFIRMRCV:
1971                         args[0] = ni->ni_mlpid;
1972                         args[1] = ni->ni_mllid;
1973                         /* Reason codes for rejection */
1974                         switch (subtype) {
1975                         case IEEE80211_ACTION_MESHPEERING_OPEN:
1976                                 args[2] = IEEE80211_REASON_MESH_CPVIOLATION;
1977                                 break;
1978                         case IEEE80211_ACTION_MESHPEERING_CONFIRM:
1979                                 args[2] = IEEE80211_REASON_MESH_INCONS_PARAMS;
1980                                 break;
1981                         }
1982                         ieee80211_send_action(ni,
1983                             IEEE80211_ACTION_CAT_SELF_PROT,
1984                             IEEE80211_ACTION_MESHPEERING_CLOSE,
1985                             args);
1986                         mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
1987                         mesh_peer_timeout_setup(ni);
1988                         break;
1989                 }
1990                 return NULL;
1991         }
1992         
1993         return (const struct ieee80211_meshpeer_ie *) mp;
1994 }
1995
1996 static int
1997 mesh_recv_action_meshpeering_open(struct ieee80211_node *ni,
1998         const struct ieee80211_frame *wh,
1999         const uint8_t *frm, const uint8_t *efrm)
2000 {
2001         struct ieee80211vap *vap = ni->ni_vap;
2002         struct ieee80211_mesh_state *ms = vap->iv_mesh;
2003         struct ieee80211_meshpeer_ie ie;
2004         const struct ieee80211_meshpeer_ie *meshpeer;
2005         uint16_t args[3];
2006
2007         /* +2+2 for action + code + capabilites */
2008         meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2+2, efrm, &ie,
2009             IEEE80211_ACTION_MESHPEERING_OPEN);
2010         if (meshpeer == NULL) {
2011                 return 0;
2012         }
2013
2014         /* XXX move up */
2015         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
2016             "recv PEER OPEN, lid 0x%x", meshpeer->peer_llinkid);
2017
2018         switch (ni->ni_mlstate) {
2019         case IEEE80211_NODE_MESH_IDLE:
2020                 /* Reject open request if reached our maximum neighbor count */
2021                 if (ms->ms_neighbors >= IEEE80211_MESH_MAX_NEIGHBORS) {
2022                         args[0] = meshpeer->peer_llinkid;
2023                         args[1] = 0;
2024                         args[2] = IEEE80211_REASON_MESH_MAX_PEERS;
2025                         ieee80211_send_action(ni,
2026                             IEEE80211_ACTION_CAT_SELF_PROT,
2027                             IEEE80211_ACTION_MESHPEERING_CLOSE,
2028                             args);
2029                         /* stay in IDLE state */
2030                         return (0);
2031                 }
2032                 /* Open frame accepted */
2033                 mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENRCV);
2034                 ni->ni_mllid = meshpeer->peer_llinkid;
2035                 ni->ni_mlpid = mesh_generateid(vap);
2036                 if (ni->ni_mlpid == 0)
2037                         return 0;               /* XXX */
2038                 args[0] = ni->ni_mlpid;
2039                 /* Announce we're open too... */
2040                 ieee80211_send_action(ni,
2041                     IEEE80211_ACTION_CAT_SELF_PROT,
2042                     IEEE80211_ACTION_MESHPEERING_OPEN, args);
2043                 /* ...and confirm the link. */
2044                 args[0] = ni->ni_mlpid;
2045                 args[1] = ni->ni_mllid;
2046                 ieee80211_send_action(ni,
2047                     IEEE80211_ACTION_CAT_SELF_PROT,
2048                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2049                     args);
2050                 mesh_peer_timeout_setup(ni);
2051                 break;
2052         case IEEE80211_NODE_MESH_OPENRCV:
2053                 /* Wrong Link ID */
2054                 if (ni->ni_mllid != meshpeer->peer_llinkid) {
2055                         args[0] = ni->ni_mllid;
2056                         args[1] = ni->ni_mlpid;
2057                         args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2058                         ieee80211_send_action(ni,
2059                             IEEE80211_ACTION_CAT_SELF_PROT,
2060                             IEEE80211_ACTION_MESHPEERING_CLOSE,
2061                             args);
2062                         mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2063                         mesh_peer_timeout_setup(ni);
2064                         break;
2065                 }
2066                 /* Duplicate open, confirm again. */
2067                 args[0] = ni->ni_mlpid;
2068                 args[1] = ni->ni_mllid;
2069                 ieee80211_send_action(ni,
2070                     IEEE80211_ACTION_CAT_SELF_PROT,
2071                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2072                     args);
2073                 break;
2074         case IEEE80211_NODE_MESH_OPENSNT:
2075                 ni->ni_mllid = meshpeer->peer_llinkid;
2076                 mesh_linkchange(ni, IEEE80211_NODE_MESH_OPENRCV);
2077                 args[0] = ni->ni_mlpid;
2078                 args[1] = ni->ni_mllid;
2079                 ieee80211_send_action(ni,
2080                     IEEE80211_ACTION_CAT_SELF_PROT,
2081                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2082                     args);
2083                 /* NB: don't setup/clear any timeout */
2084                 break;
2085         case IEEE80211_NODE_MESH_CONFIRMRCV:
2086                 if (ni->ni_mlpid != meshpeer->peer_linkid ||
2087                     ni->ni_mllid != meshpeer->peer_llinkid) {
2088                         args[0] = ni->ni_mlpid;
2089                         args[1] = ni->ni_mllid;
2090                         args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2091                         ieee80211_send_action(ni,
2092                             IEEE80211_ACTION_CAT_SELF_PROT,
2093                             IEEE80211_ACTION_MESHPEERING_CLOSE,
2094                             args);
2095                         mesh_linkchange(ni,
2096                             IEEE80211_NODE_MESH_HOLDING);
2097                         mesh_peer_timeout_setup(ni);
2098                         break;
2099                 }
2100                 mesh_linkchange(ni, IEEE80211_NODE_MESH_ESTABLISHED);
2101                 ni->ni_mllid = meshpeer->peer_llinkid;
2102                 args[0] = ni->ni_mlpid;
2103                 args[1] = ni->ni_mllid;
2104                 ieee80211_send_action(ni,
2105                     IEEE80211_ACTION_CAT_SELF_PROT,
2106                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2107                     args);
2108                 mesh_peer_timeout_stop(ni);
2109                 break;
2110         case IEEE80211_NODE_MESH_ESTABLISHED:
2111                 if (ni->ni_mllid != meshpeer->peer_llinkid) {
2112                         args[0] = ni->ni_mllid;
2113                         args[1] = ni->ni_mlpid;
2114                         args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2115                         ieee80211_send_action(ni,
2116                             IEEE80211_ACTION_CAT_SELF_PROT,
2117                             IEEE80211_ACTION_MESHPEERING_CLOSE,
2118                             args);
2119                         mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2120                         mesh_peer_timeout_setup(ni);
2121                         break;
2122                 }
2123                 args[0] = ni->ni_mlpid;
2124                 args[1] = ni->ni_mllid;
2125                 ieee80211_send_action(ni,
2126                     IEEE80211_ACTION_CAT_SELF_PROT,
2127                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2128                     args);
2129                 break;
2130         case IEEE80211_NODE_MESH_HOLDING:
2131                 args[0] = ni->ni_mlpid;
2132                 args[1] = meshpeer->peer_llinkid;
2133                 /* Standard not clear about what the reaason code should be */
2134                 args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2135                 ieee80211_send_action(ni,
2136                     IEEE80211_ACTION_CAT_SELF_PROT,
2137                     IEEE80211_ACTION_MESHPEERING_CLOSE,
2138                     args);
2139                 break;
2140         }
2141         return 0;
2142 }
2143
2144 static int
2145 mesh_recv_action_meshpeering_confirm(struct ieee80211_node *ni,
2146         const struct ieee80211_frame *wh,
2147         const uint8_t *frm, const uint8_t *efrm)
2148 {
2149         struct ieee80211vap *vap = ni->ni_vap;
2150         struct ieee80211_meshpeer_ie ie;
2151         const struct ieee80211_meshpeer_ie *meshpeer;
2152         uint16_t args[3];
2153
2154         /* +2+2+2+2 for action + code + capabilites + status code + AID */
2155         meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2+2+2+2, efrm, &ie,
2156             IEEE80211_ACTION_MESHPEERING_CONFIRM);
2157         if (meshpeer == NULL) {
2158                 return 0;
2159         }
2160
2161         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
2162             "recv PEER CONFIRM, local id 0x%x, peer id 0x%x",
2163             meshpeer->peer_llinkid, meshpeer->peer_linkid);
2164
2165         switch (ni->ni_mlstate) {
2166         case IEEE80211_NODE_MESH_OPENRCV:
2167                 mesh_linkchange(ni, IEEE80211_NODE_MESH_ESTABLISHED);
2168                 mesh_peer_timeout_stop(ni);
2169                 break;
2170         case IEEE80211_NODE_MESH_OPENSNT:
2171                 mesh_linkchange(ni, IEEE80211_NODE_MESH_CONFIRMRCV);
2172                 mesh_peer_timeout_setup(ni);
2173                 break;
2174         case IEEE80211_NODE_MESH_HOLDING:
2175                 args[0] = ni->ni_mlpid;
2176                 args[1] = meshpeer->peer_llinkid;
2177                 /* Standard not clear about what the reaason code should be */
2178                 args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2179                 ieee80211_send_action(ni,
2180                     IEEE80211_ACTION_CAT_SELF_PROT,
2181                     IEEE80211_ACTION_MESHPEERING_CLOSE,
2182                     args);
2183                 break;
2184         case IEEE80211_NODE_MESH_CONFIRMRCV:
2185                 if (ni->ni_mllid != meshpeer->peer_llinkid) {
2186                         args[0] = ni->ni_mlpid;
2187                         args[1] = ni->ni_mllid;
2188                         args[2] = IEEE80211_REASON_PEER_LINK_CANCELED;
2189                         ieee80211_send_action(ni,
2190                             IEEE80211_ACTION_CAT_SELF_PROT,
2191                             IEEE80211_ACTION_MESHPEERING_CLOSE,
2192                             args);
2193                         mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2194                         mesh_peer_timeout_setup(ni);
2195                 }
2196                 break;
2197         default:
2198                 IEEE80211_DISCARD(vap,
2199                     IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
2200                     wh, NULL, "received confirm in invalid state %d",
2201                     ni->ni_mlstate);
2202                 vap->iv_stats.is_rx_mgtdiscard++;
2203                 break;
2204         }
2205         return 0;
2206 }
2207
2208 static int
2209 mesh_recv_action_meshpeering_close(struct ieee80211_node *ni,
2210         const struct ieee80211_frame *wh,
2211         const uint8_t *frm, const uint8_t *efrm)
2212 {
2213         struct ieee80211_meshpeer_ie ie;
2214         const struct ieee80211_meshpeer_ie *meshpeer;
2215         uint16_t args[3];
2216
2217         /* +2 for action + code */
2218         meshpeer = mesh_parse_meshpeering_action(ni, wh, frm+2, efrm, &ie,
2219             IEEE80211_ACTION_MESHPEERING_CLOSE);
2220         if (meshpeer == NULL) {
2221                 return 0;
2222         }
2223
2224         /*
2225          * XXX: check reason code, for example we could receive
2226          * IEEE80211_REASON_MESH_MAX_PEERS then we should not attempt
2227          * to peer again.
2228          */
2229
2230         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
2231             ni, "%s", "recv PEER CLOSE");
2232
2233         switch (ni->ni_mlstate) {
2234         case IEEE80211_NODE_MESH_IDLE:
2235                 /* ignore */
2236                 break;
2237         case IEEE80211_NODE_MESH_OPENRCV:
2238         case IEEE80211_NODE_MESH_OPENSNT:
2239         case IEEE80211_NODE_MESH_CONFIRMRCV:
2240         case IEEE80211_NODE_MESH_ESTABLISHED:
2241                 args[0] = ni->ni_mlpid;
2242                 args[1] = ni->ni_mllid;
2243                 args[2] = IEEE80211_REASON_MESH_CLOSE_RCVD;
2244                 ieee80211_send_action(ni,
2245                     IEEE80211_ACTION_CAT_SELF_PROT,
2246                     IEEE80211_ACTION_MESHPEERING_CLOSE,
2247                     args);
2248                 mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2249                 mesh_peer_timeout_setup(ni);
2250                 break;
2251         case IEEE80211_NODE_MESH_HOLDING:
2252                 mesh_linkchange(ni, IEEE80211_NODE_MESH_IDLE);
2253                 mesh_peer_timeout_stop(ni);
2254                 break;
2255         }
2256         return 0;
2257 }
2258
2259 /*
2260  * Link Metric handling.
2261  */
2262 static int
2263 mesh_recv_action_meshlmetric(struct ieee80211_node *ni,
2264         const struct ieee80211_frame *wh,
2265         const uint8_t *frm, const uint8_t *efrm)
2266 {
2267         const struct ieee80211_meshlmetric_ie *ie =
2268             (const struct ieee80211_meshlmetric_ie *)
2269             (frm+2); /* action + code */
2270         struct ieee80211_meshlmetric_ie lm_rep;
2271         
2272         if (ie->lm_flags & IEEE80211_MESH_LMETRIC_FLAGS_REQ) {
2273                 lm_rep.lm_flags = 0;
2274                 lm_rep.lm_metric = mesh_airtime_calc(ni);
2275                 ieee80211_send_action(ni,
2276                     IEEE80211_ACTION_CAT_MESH,
2277                     IEEE80211_ACTION_MESH_LMETRIC,
2278                     &lm_rep);
2279         }
2280         /* XXX: else do nothing for now */
2281         return 0;
2282 }
2283
2284 static int
2285 mesh_send_action(struct ieee80211_node *ni, struct mbuf *m)
2286 {
2287         struct ieee80211_bpf_params params;
2288
2289         memset(&params, 0, sizeof(params));
2290         params.ibp_pri = WME_AC_VO;
2291         params.ibp_rate0 = ni->ni_txparms->mgmtrate;
2292         /* XXX ucast/mcast */
2293         params.ibp_try0 = ni->ni_txparms->maxretry;
2294         params.ibp_power = ni->ni_txpower;
2295         return ieee80211_mgmt_output(ni, m, IEEE80211_FC0_SUBTYPE_ACTION,
2296              &params);
2297 }
2298
2299 #define ADDSHORT(frm, v) do {                   \
2300         frm[0] = (v) & 0xff;                    \
2301         frm[1] = (v) >> 8;                      \
2302         frm += 2;                               \
2303 } while (0)
2304 #define ADDWORD(frm, v) do {                    \
2305         frm[0] = (v) & 0xff;                    \
2306         frm[1] = ((v) >> 8) & 0xff;             \
2307         frm[2] = ((v) >> 16) & 0xff;            \
2308         frm[3] = ((v) >> 24) & 0xff;            \
2309         frm += 4;                               \
2310 } while (0)
2311
2312 static int
2313 mesh_send_action_meshpeering_open(struct ieee80211_node *ni,
2314         int category, int action, void *args0)
2315 {
2316         struct ieee80211vap *vap = ni->ni_vap;
2317         struct ieee80211com *ic = ni->ni_ic;
2318         uint16_t *args = args0;
2319         const struct ieee80211_rateset *rs;
2320         struct mbuf *m;
2321         uint8_t *frm;
2322
2323         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
2324             "send PEER OPEN action: localid 0x%x", args[0]);
2325
2326         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2327             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2328             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2329         ieee80211_ref_node(ni);
2330
2331         m = ieee80211_getmgtframe(&frm,
2332             ic->ic_headroom + sizeof(struct ieee80211_frame),
2333             sizeof(uint16_t)    /* action+category */
2334             + sizeof(uint16_t)  /* capabilites */
2335             + 2 + IEEE80211_RATE_SIZE
2336             + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2337             + 2 + IEEE80211_MESHID_LEN
2338             + sizeof(struct ieee80211_meshconf_ie)
2339             + sizeof(struct ieee80211_meshpeer_ie)
2340         );
2341         if (m != NULL) {
2342                 /*
2343                  * mesh peer open action frame format:
2344                  *   [1] category
2345                  *   [1] action
2346                  *   [2] capabilities
2347                  *   [tlv] rates
2348                  *   [tlv] xrates
2349                  *   [tlv] mesh id
2350                  *   [tlv] mesh conf
2351                  *   [tlv] mesh peer link mgmt
2352                  */
2353                 *frm++ = category;
2354                 *frm++ = action;
2355                 ADDSHORT(frm, ieee80211_getcapinfo(vap, ni->ni_chan));
2356                 rs = ieee80211_get_suprates(ic, ic->ic_curchan);
2357                 frm = ieee80211_add_rates(frm, rs);
2358                 frm = ieee80211_add_xrates(frm, rs);
2359                 frm = ieee80211_add_meshid(frm, vap);
2360                 frm = ieee80211_add_meshconf(frm, vap);
2361                 frm = ieee80211_add_meshpeer(frm, IEEE80211_ACTION_MESHPEERING_OPEN,
2362                     args[0], 0, 0);
2363                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2364                 return mesh_send_action(ni, m);
2365         } else {
2366                 vap->iv_stats.is_tx_nobuf++;
2367                 ieee80211_free_node(ni);
2368                 return ENOMEM;
2369         }
2370 }
2371
2372 static int
2373 mesh_send_action_meshpeering_confirm(struct ieee80211_node *ni,
2374         int category, int action, void *args0)
2375 {
2376         struct ieee80211vap *vap = ni->ni_vap;
2377         struct ieee80211com *ic = ni->ni_ic;
2378         uint16_t *args = args0;
2379         const struct ieee80211_rateset *rs;
2380         struct mbuf *m;
2381         uint8_t *frm;
2382
2383         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
2384             "send PEER CONFIRM action: localid 0x%x, peerid 0x%x",
2385             args[0], args[1]);
2386
2387         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2388             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2389             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2390         ieee80211_ref_node(ni);
2391
2392         m = ieee80211_getmgtframe(&frm,
2393             ic->ic_headroom + sizeof(struct ieee80211_frame),
2394             sizeof(uint16_t)    /* action+category */
2395             + sizeof(uint16_t)  /* capabilites */
2396             + sizeof(uint16_t)  /* status code */
2397             + sizeof(uint16_t)  /* AID */
2398             + 2 + IEEE80211_RATE_SIZE
2399             + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2400             + 2 + IEEE80211_MESHID_LEN
2401             + sizeof(struct ieee80211_meshconf_ie)
2402             + sizeof(struct ieee80211_meshpeer_ie)
2403         );
2404         if (m != NULL) {
2405                 /*
2406                  * mesh peer confirm action frame format:
2407                  *   [1] category
2408                  *   [1] action
2409                  *   [2] capabilities
2410                  *   [2] status code
2411                  *   [2] association id (peer ID)
2412                  *   [tlv] rates
2413                  *   [tlv] xrates
2414                  *   [tlv] mesh id
2415                  *   [tlv] mesh conf
2416                  *   [tlv] mesh peer link mgmt
2417                  */
2418                 *frm++ = category;
2419                 *frm++ = action;
2420                 ADDSHORT(frm, ieee80211_getcapinfo(vap, ni->ni_chan));
2421                 ADDSHORT(frm, 0);               /* status code */
2422                 ADDSHORT(frm, args[1]);         /* AID */
2423                 rs = ieee80211_get_suprates(ic, ic->ic_curchan);
2424                 frm = ieee80211_add_rates(frm, rs);
2425                 frm = ieee80211_add_xrates(frm, rs);
2426                 frm = ieee80211_add_meshid(frm, vap);
2427                 frm = ieee80211_add_meshconf(frm, vap);
2428                 frm = ieee80211_add_meshpeer(frm,
2429                     IEEE80211_ACTION_MESHPEERING_CONFIRM,
2430                     args[0], args[1], 0);
2431                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2432                 return mesh_send_action(ni, m);
2433         } else {
2434                 vap->iv_stats.is_tx_nobuf++;
2435                 ieee80211_free_node(ni);
2436                 return ENOMEM;
2437         }
2438 }
2439
2440 static int
2441 mesh_send_action_meshpeering_close(struct ieee80211_node *ni,
2442         int category, int action, void *args0)
2443 {
2444         struct ieee80211vap *vap = ni->ni_vap;
2445         struct ieee80211com *ic = ni->ni_ic;
2446         uint16_t *args = args0;
2447         struct mbuf *m;
2448         uint8_t *frm;
2449
2450         IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH, ni,
2451             "send PEER CLOSE action: localid 0x%x, peerid 0x%x reason %d",
2452             args[0], args[1], args[2]);
2453
2454         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2455             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2456             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2457         ieee80211_ref_node(ni);
2458
2459         m = ieee80211_getmgtframe(&frm,
2460             ic->ic_headroom + sizeof(struct ieee80211_frame),
2461             sizeof(uint16_t)    /* action+category */
2462             + sizeof(uint16_t)  /* reason code */
2463             + 2 + IEEE80211_MESHID_LEN
2464             + sizeof(struct ieee80211_meshpeer_ie)
2465         );
2466         if (m != NULL) {
2467                 /*
2468                  * mesh peer close action frame format:
2469                  *   [1] category
2470                  *   [1] action
2471                  *   [tlv] mesh id
2472                  *   [tlv] mesh peer link mgmt
2473                  */
2474                 *frm++ = category;
2475                 *frm++ = action;
2476                 frm = ieee80211_add_meshid(frm, vap);
2477                 frm = ieee80211_add_meshpeer(frm,
2478                     IEEE80211_ACTION_MESHPEERING_CLOSE,
2479                     args[0], args[1], args[2]);
2480                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2481                 return mesh_send_action(ni, m);
2482         } else {
2483                 vap->iv_stats.is_tx_nobuf++;
2484                 ieee80211_free_node(ni);
2485                 return ENOMEM;
2486         }
2487 }
2488
2489 static int
2490 mesh_send_action_meshlmetric(struct ieee80211_node *ni,
2491         int category, int action, void *arg0)
2492 {
2493         struct ieee80211vap *vap = ni->ni_vap;
2494         struct ieee80211com *ic = ni->ni_ic;
2495         struct ieee80211_meshlmetric_ie *ie = arg0;
2496         struct mbuf *m;
2497         uint8_t *frm;
2498
2499         if (ie->lm_flags & IEEE80211_MESH_LMETRIC_FLAGS_REQ) {
2500                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
2501                     ni, "%s", "send LINK METRIC REQUEST action");
2502         } else {
2503                 IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
2504                     ni, "send LINK METRIC REPLY action: metric 0x%x",
2505                     ie->lm_metric);
2506         }
2507         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2508             "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__,
2509             ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1);
2510         ieee80211_ref_node(ni);
2511
2512         m = ieee80211_getmgtframe(&frm,
2513             ic->ic_headroom + sizeof(struct ieee80211_frame),
2514             sizeof(uint16_t) +  /* action+category */
2515             sizeof(struct ieee80211_meshlmetric_ie)
2516         );
2517         if (m != NULL) {
2518                 /*
2519                  * mesh link metric
2520                  *   [1] category
2521                  *   [1] action
2522                  *   [tlv] mesh link metric
2523                  */
2524                 *frm++ = category;
2525                 *frm++ = action;
2526                 frm = ieee80211_add_meshlmetric(frm,
2527                     ie->lm_flags, ie->lm_metric);
2528                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2529                 return mesh_send_action(ni, m);
2530         } else {
2531                 vap->iv_stats.is_tx_nobuf++;
2532                 ieee80211_free_node(ni);
2533                 return ENOMEM;
2534         }
2535 }
2536
2537 static void
2538 mesh_peer_timeout_setup(struct ieee80211_node *ni)
2539 {
2540         switch (ni->ni_mlstate) {
2541         case IEEE80211_NODE_MESH_HOLDING:
2542                 ni->ni_mltval = ieee80211_mesh_holdingtimeout;
2543                 break;
2544         case IEEE80211_NODE_MESH_CONFIRMRCV:
2545                 ni->ni_mltval = ieee80211_mesh_confirmtimeout;
2546                 break;
2547         case IEEE80211_NODE_MESH_IDLE:
2548                 ni->ni_mltval = 0;
2549                 break;
2550         default:
2551                 ni->ni_mltval = ieee80211_mesh_retrytimeout;
2552                 break;
2553         }
2554         if (ni->ni_mltval)
2555                 callout_reset(&ni->ni_mltimer, ni->ni_mltval,
2556                     mesh_peer_timeout_cb, ni);
2557 }
2558
2559 /*
2560  * Same as above but backoffs timer statisically 50%.
2561  */
2562 static void
2563 mesh_peer_timeout_backoff(struct ieee80211_node *ni)
2564 {
2565         uint32_t r;
2566         
2567         r = arc4random();
2568         ni->ni_mltval += r % ni->ni_mltval;
2569         callout_reset(&ni->ni_mltimer, ni->ni_mltval, mesh_peer_timeout_cb,
2570             ni);
2571 }
2572
2573 static __inline void
2574 mesh_peer_timeout_stop(struct ieee80211_node *ni)
2575 {
2576         callout_drain(&ni->ni_mltimer);
2577 }
2578
2579 /*
2580  * Mesh Peer Link Management FSM timeout handling.
2581  */
2582 static void
2583 mesh_peer_timeout_cb(void *arg)
2584 {
2585         struct ieee80211_node *ni = (struct ieee80211_node *)arg;
2586         uint16_t args[3];
2587
2588         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_MESH,
2589             ni, "mesh link timeout, state %d, retry counter %d",
2590             ni->ni_mlstate, ni->ni_mlrcnt);
2591         
2592         switch (ni->ni_mlstate) {
2593         case IEEE80211_NODE_MESH_IDLE:
2594         case IEEE80211_NODE_MESH_ESTABLISHED:
2595                 break;
2596         case IEEE80211_NODE_MESH_OPENSNT:
2597         case IEEE80211_NODE_MESH_OPENRCV:
2598                 if (ni->ni_mlrcnt == ieee80211_mesh_maxretries) {
2599                         args[0] = ni->ni_mlpid;
2600                         args[2] = IEEE80211_REASON_MESH_MAX_RETRIES;
2601                         ieee80211_send_action(ni,
2602                             IEEE80211_ACTION_CAT_SELF_PROT,
2603                             IEEE80211_ACTION_MESHPEERING_CLOSE, args);
2604                         ni->ni_mlrcnt = 0;
2605                         mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2606                         mesh_peer_timeout_setup(ni);
2607                 } else {
2608                         args[0] = ni->ni_mlpid;
2609                         ieee80211_send_action(ni,
2610                             IEEE80211_ACTION_CAT_SELF_PROT,
2611                             IEEE80211_ACTION_MESHPEERING_OPEN, args);
2612                         ni->ni_mlrcnt++;
2613                         mesh_peer_timeout_backoff(ni);
2614                 }
2615                 break;
2616         case IEEE80211_NODE_MESH_CONFIRMRCV:
2617                 args[0] = ni->ni_mlpid;
2618                 args[2] = IEEE80211_REASON_MESH_CONFIRM_TIMEOUT;
2619                 ieee80211_send_action(ni,
2620                     IEEE80211_ACTION_CAT_SELF_PROT,
2621                     IEEE80211_ACTION_MESHPEERING_CLOSE, args);
2622                 mesh_linkchange(ni, IEEE80211_NODE_MESH_HOLDING);
2623                 mesh_peer_timeout_setup(ni);
2624                 break;
2625         case IEEE80211_NODE_MESH_HOLDING:
2626                 mesh_linkchange(ni, IEEE80211_NODE_MESH_IDLE);
2627                 break;
2628         }
2629 }
2630
2631 static int
2632 mesh_verify_meshid(struct ieee80211vap *vap, const uint8_t *ie)
2633 {
2634         struct ieee80211_mesh_state *ms = vap->iv_mesh;
2635
2636         if (ie == NULL || ie[1] != ms->ms_idlen)
2637                 return 1;
2638         return memcmp(ms->ms_id, ie + 2, ms->ms_idlen);
2639 }
2640
2641 /*
2642  * Check if we are using the same algorithms for this mesh.
2643  */
2644 static int
2645 mesh_verify_meshconf(struct ieee80211vap *vap, const uint8_t *ie)
2646 {
2647         const struct ieee80211_meshconf_ie *meshconf =
2648             (const struct ieee80211_meshconf_ie *) ie;
2649         const struct ieee80211_mesh_state *ms = vap->iv_mesh;
2650
2651         if (meshconf == NULL)
2652                 return 1;
2653         if (meshconf->conf_pselid != ms->ms_ppath->mpp_ie) {
2654                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2655                     "unknown path selection algorithm: 0x%x\n",
2656                     meshconf->conf_pselid);
2657                 return 1;
2658         }
2659         if (meshconf->conf_pmetid != ms->ms_pmetric->mpm_ie) {
2660                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2661                     "unknown path metric algorithm: 0x%x\n",
2662                     meshconf->conf_pmetid);
2663                 return 1;
2664         }
2665         if (meshconf->conf_ccid != 0) {
2666                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2667                     "unknown congestion control algorithm: 0x%x\n",
2668                     meshconf->conf_ccid);
2669                 return 1;
2670         }
2671         if (meshconf->conf_syncid != IEEE80211_MESHCONF_SYNC_NEIGHOFF) {
2672                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2673                     "unknown sync algorithm: 0x%x\n",
2674                     meshconf->conf_syncid);
2675                 return 1;
2676         }
2677         if (meshconf->conf_authid != 0) {
2678                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2679                     "unknown auth auth algorithm: 0x%x\n",
2680                     meshconf->conf_pselid);
2681                 return 1;
2682         }
2683         /* Not accepting peers */
2684         if (!(meshconf->conf_cap & IEEE80211_MESHCONF_CAP_AP)) {
2685                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_MESH,
2686                     "not accepting peers: 0x%x\n", meshconf->conf_cap);
2687                 return 1;
2688         }
2689         return 0;
2690 }
2691
2692 static int
2693 mesh_verify_meshpeer(struct ieee80211vap *vap, uint8_t subtype,
2694     const uint8_t *ie)
2695 {
2696         const struct ieee80211_meshpeer_ie *meshpeer =
2697             (const struct ieee80211_meshpeer_ie *) ie;
2698
2699         if (meshpeer == NULL ||
2700             meshpeer->peer_len < IEEE80211_MPM_BASE_SZ ||
2701             meshpeer->peer_len > IEEE80211_MPM_MAX_SZ)
2702                 return 1;
2703         if (meshpeer->peer_proto != IEEE80211_MPPID_MPM) {
2704                 IEEE80211_DPRINTF(vap,
2705                     IEEE80211_MSG_ACTION | IEEE80211_MSG_MESH,
2706                     "Only MPM protocol is supported (proto: 0x%02X)",
2707                     meshpeer->peer_proto);
2708                 return 1;
2709         }
2710         switch (subtype) {
2711         case IEEE80211_ACTION_MESHPEERING_OPEN:
2712                 if (meshpeer->peer_len != IEEE80211_MPM_BASE_SZ)
2713                         return 1;
2714                 break;
2715         case IEEE80211_ACTION_MESHPEERING_CONFIRM:
2716                 if (meshpeer->peer_len != IEEE80211_MPM_BASE_SZ + 2)
2717                         return 1;
2718                 break;
2719         case IEEE80211_ACTION_MESHPEERING_CLOSE:
2720                 if (meshpeer->peer_len < IEEE80211_MPM_BASE_SZ + 2)
2721                         return 1;
2722                 if (meshpeer->peer_len == (IEEE80211_MPM_BASE_SZ + 2) &&
2723                     meshpeer->peer_linkid != 0)
2724                         return 1;
2725                 if (meshpeer->peer_rcode == 0)
2726                         return 1;
2727                 break;
2728         }
2729         return 0;
2730 }
2731
2732 /*
2733  * Add a Mesh ID IE to a frame.
2734  */
2735 uint8_t *
2736 ieee80211_add_meshid(uint8_t *frm, struct ieee80211vap *vap)
2737 {
2738         struct ieee80211_mesh_state *ms = vap->iv_mesh;
2739
2740         KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a mbss vap"));
2741
2742         *frm++ = IEEE80211_ELEMID_MESHID;
2743         *frm++ = ms->ms_idlen;
2744         memcpy(frm, ms->ms_id, ms->ms_idlen);
2745         return frm + ms->ms_idlen;
2746 }
2747
2748 /*
2749  * Add a Mesh Configuration IE to a frame.
2750  * For now just use HWMP routing, Airtime link metric, Null Congestion
2751  * Signaling, Null Sync Protocol and Null Authentication.
2752  */
2753 uint8_t *
2754 ieee80211_add_meshconf(uint8_t *frm, struct ieee80211vap *vap)
2755 {
2756         const struct ieee80211_mesh_state *ms = vap->iv_mesh;
2757         uint16_t caps;
2758
2759         KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a MBSS vap"));
2760
2761         *frm++ = IEEE80211_ELEMID_MESHCONF;
2762         *frm++ = IEEE80211_MESH_CONF_SZ;
2763         *frm++ = ms->ms_ppath->mpp_ie;          /* path selection */
2764         *frm++ = ms->ms_pmetric->mpm_ie;        /* link metric */
2765         *frm++ = IEEE80211_MESHCONF_CC_DISABLED;
2766         *frm++ = IEEE80211_MESHCONF_SYNC_NEIGHOFF;
2767         *frm++ = IEEE80211_MESHCONF_AUTH_DISABLED;
2768         /* NB: set the number of neighbors before the rest */
2769         *frm = (ms->ms_neighbors > IEEE80211_MESH_MAX_NEIGHBORS ?
2770             IEEE80211_MESH_MAX_NEIGHBORS : ms->ms_neighbors) << 1;
2771         if (ms->ms_flags & IEEE80211_MESHFLAGS_PORTAL)
2772                 *frm |= IEEE80211_MESHCONF_FORM_MP;
2773         frm += 1;
2774         caps = 0;
2775         if (ms->ms_flags & IEEE80211_MESHFLAGS_AP)
2776                 caps |= IEEE80211_MESHCONF_CAP_AP;
2777         if (ms->ms_flags & IEEE80211_MESHFLAGS_FWD)
2778                 caps |= IEEE80211_MESHCONF_CAP_FWRD;
2779         *frm++ = caps;
2780         return frm;
2781 }
2782
2783 /*
2784  * Add a Mesh Peer Management IE to a frame.
2785  */
2786 uint8_t *
2787 ieee80211_add_meshpeer(uint8_t *frm, uint8_t subtype, uint16_t localid,
2788     uint16_t peerid, uint16_t reason)
2789 {
2790
2791         KASSERT(localid != 0, ("localid == 0"));
2792
2793         *frm++ = IEEE80211_ELEMID_MESHPEER;
2794         switch (subtype) {
2795         case IEEE80211_ACTION_MESHPEERING_OPEN:
2796                 *frm++ = IEEE80211_MPM_BASE_SZ;         /* length */
2797                 ADDSHORT(frm, IEEE80211_MPPID_MPM);     /* proto */
2798                 ADDSHORT(frm, localid);                 /* local ID */
2799                 break;
2800         case IEEE80211_ACTION_MESHPEERING_CONFIRM:
2801                 KASSERT(peerid != 0, ("sending peer confirm without peer id"));
2802                 *frm++ = IEEE80211_MPM_BASE_SZ + 2;     /* length */
2803                 ADDSHORT(frm, IEEE80211_MPPID_MPM);     /* proto */
2804                 ADDSHORT(frm, localid);                 /* local ID */
2805                 ADDSHORT(frm, peerid);                  /* peer ID */
2806                 break;
2807         case IEEE80211_ACTION_MESHPEERING_CLOSE:
2808                 if (peerid)
2809                         *frm++ = IEEE80211_MPM_MAX_SZ;  /* length */
2810                 else
2811                         *frm++ = IEEE80211_MPM_BASE_SZ + 2; /* length */
2812                 ADDSHORT(frm, IEEE80211_MPPID_MPM);     /* proto */
2813                 ADDSHORT(frm, localid); /* local ID */
2814                 if (peerid)
2815                         ADDSHORT(frm, peerid);  /* peer ID */
2816                 ADDSHORT(frm, reason);
2817                 break;
2818         }
2819         return frm;
2820 }
2821
2822 /*
2823  * Compute an Airtime Link Metric for the link with this node.
2824  *
2825  * Based on Draft 3.0 spec (11B.10, p.149).
2826  */
2827 /*
2828  * Max 802.11s overhead.
2829  */
2830 #define IEEE80211_MESH_MAXOVERHEAD \
2831         (sizeof(struct ieee80211_qosframe_addr4) \
2832          + sizeof(struct ieee80211_meshcntl_ae10) \
2833         + sizeof(struct llc) \
2834         + IEEE80211_ADDR_LEN \
2835         + IEEE80211_WEP_IVLEN \
2836         + IEEE80211_WEP_KIDLEN \
2837         + IEEE80211_WEP_CRCLEN \
2838         + IEEE80211_WEP_MICLEN \
2839         + IEEE80211_CRC_LEN)
2840 uint32_t
2841 mesh_airtime_calc(struct ieee80211_node *ni)
2842 {
2843 #define M_BITS 8
2844 #define S_FACTOR (2 * M_BITS)
2845         struct ieee80211com *ic = ni->ni_ic;
2846         struct ifnet *ifp = ni->ni_vap->iv_ifp;
2847         const static int nbits = 8192 << M_BITS;
2848         uint32_t overhead, rate, errrate;
2849         uint64_t res;
2850
2851         /* Time to transmit a frame */
2852         rate = ni->ni_txrate;
2853         overhead = ieee80211_compute_duration(ic->ic_rt,
2854             ifp->if_mtu + IEEE80211_MESH_MAXOVERHEAD, rate, 0) << M_BITS;
2855         /* Error rate in percentage */
2856         /* XXX assuming small failures are ok */
2857         errrate = (((ifp->if_oerrors +
2858             ifp->if_ierrors) / 100) << M_BITS) / 100;
2859         res = (overhead + (nbits / rate)) *
2860             ((1 << S_FACTOR) / ((1 << M_BITS) - errrate));
2861
2862         return (uint32_t)(res >> S_FACTOR);
2863 #undef M_BITS
2864 #undef S_FACTOR
2865 }
2866
2867 /*
2868  * Add a Mesh Link Metric report IE to a frame.
2869  */
2870 uint8_t *
2871 ieee80211_add_meshlmetric(uint8_t *frm, uint8_t flags, uint32_t metric)
2872 {
2873         *frm++ = IEEE80211_ELEMID_MESHLINK;
2874         *frm++ = 5;
2875         *frm++ = flags;
2876         ADDWORD(frm, metric);
2877         return frm;
2878 }
2879 #undef ADDSHORT
2880 #undef ADDWORD
2881
2882 /*
2883  * Initialize any mesh-specific node state.
2884  */
2885 void
2886 ieee80211_mesh_node_init(struct ieee80211vap *vap, struct ieee80211_node *ni)
2887 {
2888         ni->ni_flags |= IEEE80211_NODE_QOS;
2889         callout_init(&ni->ni_mltimer, CALLOUT_MPSAFE);
2890 }
2891
2892 /*
2893  * Cleanup any mesh-specific node state.
2894  */
2895 void
2896 ieee80211_mesh_node_cleanup(struct ieee80211_node *ni)
2897 {
2898         struct ieee80211vap *vap = ni->ni_vap;
2899         struct ieee80211_mesh_state *ms = vap->iv_mesh;
2900
2901         callout_drain(&ni->ni_mltimer);
2902         /* NB: short-circuit callbacks after mesh_vdetach */
2903         if (vap->iv_mesh != NULL)
2904                 ms->ms_ppath->mpp_peerdown(ni);
2905 }
2906
2907 void
2908 ieee80211_parse_meshid(struct ieee80211_node *ni, const uint8_t *ie)
2909 {
2910         ni->ni_meshidlen = ie[1];
2911         memcpy(ni->ni_meshid, ie + 2, ie[1]);
2912 }
2913
2914 /*
2915  * Setup mesh-specific node state on neighbor discovery.
2916  */
2917 void
2918 ieee80211_mesh_init_neighbor(struct ieee80211_node *ni,
2919         const struct ieee80211_frame *wh,
2920         const struct ieee80211_scanparams *sp)
2921 {
2922         ieee80211_parse_meshid(ni, sp->meshid);
2923 }
2924
2925 void
2926 ieee80211_mesh_update_beacon(struct ieee80211vap *vap,
2927         struct ieee80211_beacon_offsets *bo)
2928 {
2929         KASSERT(vap->iv_opmode == IEEE80211_M_MBSS, ("not a MBSS vap"));
2930
2931         if (isset(bo->bo_flags, IEEE80211_BEACON_MESHCONF)) {
2932                 (void)ieee80211_add_meshconf(bo->bo_meshconf, vap);
2933                 clrbit(bo->bo_flags, IEEE80211_BEACON_MESHCONF);
2934         }
2935 }
2936
2937 static int
2938 mesh_ioctl_get80211(struct ieee80211vap *vap, struct ieee80211req *ireq)
2939 {
2940         struct ieee80211_mesh_state *ms = vap->iv_mesh;
2941         uint8_t tmpmeshid[IEEE80211_NWID_LEN];
2942         struct ieee80211_mesh_route *rt;
2943         struct ieee80211req_mesh_route *imr;
2944         size_t len, off;
2945         uint8_t *p;
2946         int error;
2947
2948         if (vap->iv_opmode != IEEE80211_M_MBSS)
2949                 return ENOSYS;
2950
2951         error = 0;
2952         switch (ireq->i_type) {
2953         case IEEE80211_IOC_MESH_ID:
2954                 ireq->i_len = ms->ms_idlen;
2955                 memcpy(tmpmeshid, ms->ms_id, ireq->i_len);
2956                 error = copyout(tmpmeshid, ireq->i_data, ireq->i_len);
2957                 break;
2958         case IEEE80211_IOC_MESH_AP:
2959                 ireq->i_val = (ms->ms_flags & IEEE80211_MESHFLAGS_AP) != 0;
2960                 break;
2961         case IEEE80211_IOC_MESH_FWRD:
2962                 ireq->i_val = (ms->ms_flags & IEEE80211_MESHFLAGS_FWD) != 0;
2963                 break;
2964         case IEEE80211_IOC_MESH_TTL:
2965                 ireq->i_val = ms->ms_ttl;
2966                 break;
2967         case IEEE80211_IOC_MESH_RTCMD:
2968                 switch (ireq->i_val) {
2969                 case IEEE80211_MESH_RTCMD_LIST:
2970                         len = 0;
2971                         MESH_RT_LOCK(ms);
2972                         TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
2973                                 len += sizeof(*imr);
2974                         }
2975                         MESH_RT_UNLOCK(ms);
2976                         if (len > ireq->i_len || ireq->i_len < sizeof(*imr)) {
2977                                 ireq->i_len = len;
2978                                 return ENOMEM;
2979                         }
2980                         ireq->i_len = len;
2981                         /* XXX M_WAIT? */
2982                         p = malloc(len, M_TEMP, M_NOWAIT | M_ZERO);
2983                         if (p == NULL)
2984                                 return ENOMEM;
2985                         off = 0;
2986                         MESH_RT_LOCK(ms);
2987                         TAILQ_FOREACH(rt, &ms->ms_routes, rt_next) {
2988                                 if (off >= len)
2989                                         break;
2990                                 imr = (struct ieee80211req_mesh_route *)
2991                                     (p + off);
2992                                 IEEE80211_ADDR_COPY(imr->imr_dest,
2993                                     rt->rt_dest);
2994                                 IEEE80211_ADDR_COPY(imr->imr_nexthop,
2995                                     rt->rt_nexthop);
2996                                 imr->imr_metric = rt->rt_metric;
2997                                 imr->imr_nhops = rt->rt_nhops;
2998                                 imr->imr_lifetime =
2999                                     ieee80211_mesh_rt_update(rt, 0);
3000                                 imr->imr_lastmseq = rt->rt_lastmseq;
3001                                 imr->imr_flags = rt->rt_flags; /* last */
3002                                 off += sizeof(*imr);
3003                         }
3004                         MESH_RT_UNLOCK(ms);
3005                         error = copyout(p, (uint8_t *)ireq->i_data,
3006                             ireq->i_len);
3007                         free(p, M_TEMP);
3008                         break;
3009                 case IEEE80211_MESH_RTCMD_FLUSH:
3010                 case IEEE80211_MESH_RTCMD_ADD:
3011                 case IEEE80211_MESH_RTCMD_DELETE:
3012                         return EINVAL;
3013                 default:
3014                         return ENOSYS;
3015                 }
3016                 break;
3017         case IEEE80211_IOC_MESH_PR_METRIC:
3018                 len = strlen(ms->ms_pmetric->mpm_descr);
3019                 if (ireq->i_len < len)
3020                         return EINVAL;
3021                 ireq->i_len = len;
3022                 error = copyout(ms->ms_pmetric->mpm_descr,
3023                     (uint8_t *)ireq->i_data, len);
3024                 break;
3025         case IEEE80211_IOC_MESH_PR_PATH:
3026                 len = strlen(ms->ms_ppath->mpp_descr);
3027                 if (ireq->i_len < len)
3028                         return EINVAL;
3029                 ireq->i_len = len;
3030                 error = copyout(ms->ms_ppath->mpp_descr,
3031                     (uint8_t *)ireq->i_data, len);
3032                 break;
3033         default:
3034                 return ENOSYS;
3035         }
3036
3037         return error;
3038 }
3039 IEEE80211_IOCTL_GET(mesh, mesh_ioctl_get80211);
3040
3041 static int
3042 mesh_ioctl_set80211(struct ieee80211vap *vap, struct ieee80211req *ireq)
3043 {
3044         struct ieee80211_mesh_state *ms = vap->iv_mesh;
3045         uint8_t tmpmeshid[IEEE80211_NWID_LEN];
3046         uint8_t tmpaddr[IEEE80211_ADDR_LEN];
3047         char tmpproto[IEEE80211_MESH_PROTO_DSZ];
3048         int error;
3049
3050         if (vap->iv_opmode != IEEE80211_M_MBSS)
3051                 return ENOSYS;
3052
3053         error = 0;
3054         switch (ireq->i_type) {
3055         case IEEE80211_IOC_MESH_ID:
3056                 if (ireq->i_val != 0 || ireq->i_len > IEEE80211_MESHID_LEN)
3057                         return EINVAL;
3058                 error = copyin(ireq->i_data, tmpmeshid, ireq->i_len);
3059                 if (error != 0)
3060                         break;
3061                 memset(ms->ms_id, 0, IEEE80211_NWID_LEN);
3062                 ms->ms_idlen = ireq->i_len;
3063                 memcpy(ms->ms_id, tmpmeshid, ireq->i_len);
3064                 error = ENETRESET;
3065                 break;
3066         case IEEE80211_IOC_MESH_AP:
3067                 if (ireq->i_val)
3068                         ms->ms_flags |= IEEE80211_MESHFLAGS_AP;
3069                 else
3070                         ms->ms_flags &= ~IEEE80211_MESHFLAGS_AP;
3071                 error = ENETRESET;
3072                 break;
3073         case IEEE80211_IOC_MESH_FWRD:
3074                 if (ireq->i_val)
3075                         ms->ms_flags |= IEEE80211_MESHFLAGS_FWD;
3076                 else
3077                         ms->ms_flags &= ~IEEE80211_MESHFLAGS_FWD;
3078                 break;
3079         case IEEE80211_IOC_MESH_TTL:
3080                 ms->ms_ttl = (uint8_t) ireq->i_val;
3081                 break;
3082         case IEEE80211_IOC_MESH_RTCMD:
3083                 switch (ireq->i_val) {
3084                 case IEEE80211_MESH_RTCMD_LIST:
3085                         return EINVAL;
3086                 case IEEE80211_MESH_RTCMD_FLUSH:
3087                         ieee80211_mesh_rt_flush(vap);
3088                         break;
3089                 case IEEE80211_MESH_RTCMD_ADD:
3090                         if (IEEE80211_ADDR_EQ(vap->iv_myaddr, ireq->i_data) ||
3091                             IEEE80211_ADDR_EQ(broadcastaddr, ireq->i_data))
3092                                 return EINVAL;
3093                         error = copyin(ireq->i_data, &tmpaddr,
3094                             IEEE80211_ADDR_LEN);
3095                         if (error == 0)
3096                                 ieee80211_mesh_discover(vap, tmpaddr, NULL);
3097                         break;
3098                 case IEEE80211_MESH_RTCMD_DELETE:
3099                         ieee80211_mesh_rt_del(vap, ireq->i_data);
3100                         break;
3101                 default:
3102                         return ENOSYS;
3103                 }
3104                 break;
3105         case IEEE80211_IOC_MESH_PR_METRIC:
3106                 error = copyin(ireq->i_data, tmpproto, sizeof(tmpproto));
3107                 if (error == 0) {
3108                         error = mesh_select_proto_metric(vap, tmpproto);
3109                         if (error == 0)
3110                                 error = ENETRESET;
3111                 }
3112                 break;
3113         case IEEE80211_IOC_MESH_PR_PATH:
3114                 error = copyin(ireq->i_data, tmpproto, sizeof(tmpproto));
3115                 if (error == 0) {
3116                         error = mesh_select_proto_path(vap, tmpproto);
3117                         if (error == 0)
3118                                 error = ENETRESET;
3119                 }
3120                 break;
3121         default:
3122                 return ENOSYS;
3123         }
3124         return error;
3125 }
3126 IEEE80211_IOCTL_SET(mesh, mesh_ioctl_set80211);