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