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