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