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