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