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