xref: /kernel/linux/linux-5.10/net/ipv4/nexthop.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0
2/* Generic nexthop implementation
3 *
4 * Copyright (c) 2017-19 Cumulus Networks
5 * Copyright (c) 2017-19 David Ahern <dsa@cumulusnetworks.com>
6 */
7
8#include <linux/nexthop.h>
9#include <linux/rtnetlink.h>
10#include <linux/slab.h>
11#include <net/arp.h>
12#include <net/ipv6_stubs.h>
13#include <net/lwtunnel.h>
14#include <net/ndisc.h>
15#include <net/nexthop.h>
16#include <net/route.h>
17#include <net/sock.h>
18
19static void remove_nexthop(struct net *net, struct nexthop *nh,
20			   struct nl_info *nlinfo);
21
22#define NH_DEV_HASHBITS  8
23#define NH_DEV_HASHSIZE (1U << NH_DEV_HASHBITS)
24
25static const struct nla_policy rtm_nh_policy[NHA_MAX + 1] = {
26	[NHA_ID]		= { .type = NLA_U32 },
27	[NHA_GROUP]		= { .type = NLA_BINARY },
28	[NHA_GROUP_TYPE]	= { .type = NLA_U16 },
29	[NHA_BLACKHOLE]		= { .type = NLA_FLAG },
30	[NHA_OIF]		= { .type = NLA_U32 },
31	[NHA_GATEWAY]		= { .type = NLA_BINARY },
32	[NHA_ENCAP_TYPE]	= { .type = NLA_U16 },
33	[NHA_ENCAP]		= { .type = NLA_NESTED },
34	[NHA_GROUPS]		= { .type = NLA_FLAG },
35	[NHA_MASTER]		= { .type = NLA_U32 },
36	[NHA_FDB]		= { .type = NLA_FLAG },
37};
38
39static int call_nexthop_notifiers(struct net *net,
40				  enum nexthop_event_type event_type,
41				  struct nexthop *nh)
42{
43	int err;
44
45	err = blocking_notifier_call_chain(&net->nexthop.notifier_chain,
46					   event_type, nh);
47	return notifier_to_errno(err);
48}
49
50static unsigned int nh_dev_hashfn(unsigned int val)
51{
52	unsigned int mask = NH_DEV_HASHSIZE - 1;
53
54	return (val ^
55		(val >> NH_DEV_HASHBITS) ^
56		(val >> (NH_DEV_HASHBITS * 2))) & mask;
57}
58
59static void nexthop_devhash_add(struct net *net, struct nh_info *nhi)
60{
61	struct net_device *dev = nhi->fib_nhc.nhc_dev;
62	struct hlist_head *head;
63	unsigned int hash;
64
65	WARN_ON(!dev);
66
67	hash = nh_dev_hashfn(dev->ifindex);
68	head = &net->nexthop.devhash[hash];
69	hlist_add_head(&nhi->dev_hash, head);
70}
71
72static void nexthop_free_mpath(struct nexthop *nh)
73{
74	struct nh_group *nhg;
75	int i;
76
77	nhg = rcu_dereference_raw(nh->nh_grp);
78	for (i = 0; i < nhg->num_nh; ++i) {
79		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
80
81		WARN_ON(!list_empty(&nhge->nh_list));
82		nexthop_put(nhge->nh);
83	}
84
85	WARN_ON(nhg->spare == nhg);
86
87	kfree(nhg->spare);
88	kfree(nhg);
89}
90
91static void nexthop_free_single(struct nexthop *nh)
92{
93	struct nh_info *nhi;
94
95	nhi = rcu_dereference_raw(nh->nh_info);
96	switch (nhi->family) {
97	case AF_INET:
98		fib_nh_release(nh->net, &nhi->fib_nh);
99		break;
100	case AF_INET6:
101		ipv6_stub->fib6_nh_release(&nhi->fib6_nh);
102		break;
103	}
104	kfree(nhi);
105}
106
107void nexthop_free_rcu(struct rcu_head *head)
108{
109	struct nexthop *nh = container_of(head, struct nexthop, rcu);
110
111	if (nh->is_group)
112		nexthop_free_mpath(nh);
113	else
114		nexthop_free_single(nh);
115
116	kfree(nh);
117}
118EXPORT_SYMBOL_GPL(nexthop_free_rcu);
119
120static struct nexthop *nexthop_alloc(void)
121{
122	struct nexthop *nh;
123
124	nh = kzalloc(sizeof(struct nexthop), GFP_KERNEL);
125	if (nh) {
126		INIT_LIST_HEAD(&nh->fi_list);
127		INIT_LIST_HEAD(&nh->f6i_list);
128		INIT_LIST_HEAD(&nh->grp_list);
129		INIT_LIST_HEAD(&nh->fdb_list);
130	}
131	return nh;
132}
133
134static struct nh_group *nexthop_grp_alloc(u16 num_nh)
135{
136	struct nh_group *nhg;
137
138	nhg = kzalloc(struct_size(nhg, nh_entries, num_nh), GFP_KERNEL);
139	if (nhg)
140		nhg->num_nh = num_nh;
141
142	return nhg;
143}
144
145static void nh_base_seq_inc(struct net *net)
146{
147	while (++net->nexthop.seq == 0)
148		;
149}
150
151/* no reference taken; rcu lock or rtnl must be held */
152struct nexthop *nexthop_find_by_id(struct net *net, u32 id)
153{
154	struct rb_node **pp, *parent = NULL, *next;
155
156	pp = &net->nexthop.rb_root.rb_node;
157	while (1) {
158		struct nexthop *nh;
159
160		next = rcu_dereference_raw(*pp);
161		if (!next)
162			break;
163		parent = next;
164
165		nh = rb_entry(parent, struct nexthop, rb_node);
166		if (id < nh->id)
167			pp = &next->rb_left;
168		else if (id > nh->id)
169			pp = &next->rb_right;
170		else
171			return nh;
172	}
173	return NULL;
174}
175EXPORT_SYMBOL_GPL(nexthop_find_by_id);
176
177/* used for auto id allocation; called with rtnl held */
178static u32 nh_find_unused_id(struct net *net)
179{
180	u32 id_start = net->nexthop.last_id_allocated;
181
182	while (1) {
183		net->nexthop.last_id_allocated++;
184		if (net->nexthop.last_id_allocated == id_start)
185			break;
186
187		if (!nexthop_find_by_id(net, net->nexthop.last_id_allocated))
188			return net->nexthop.last_id_allocated;
189	}
190	return 0;
191}
192
193static int nla_put_nh_group(struct sk_buff *skb, struct nh_group *nhg)
194{
195	struct nexthop_grp *p;
196	size_t len = nhg->num_nh * sizeof(*p);
197	struct nlattr *nla;
198	u16 group_type = 0;
199	int i;
200
201	if (nhg->mpath)
202		group_type = NEXTHOP_GRP_TYPE_MPATH;
203
204	if (nla_put_u16(skb, NHA_GROUP_TYPE, group_type))
205		goto nla_put_failure;
206
207	nla = nla_reserve(skb, NHA_GROUP, len);
208	if (!nla)
209		goto nla_put_failure;
210
211	p = nla_data(nla);
212	for (i = 0; i < nhg->num_nh; ++i) {
213		*p++ = (struct nexthop_grp) {
214			.id = nhg->nh_entries[i].nh->id,
215			.weight = nhg->nh_entries[i].weight - 1,
216		};
217	}
218
219	return 0;
220
221nla_put_failure:
222	return -EMSGSIZE;
223}
224
225static int nh_fill_node(struct sk_buff *skb, struct nexthop *nh,
226			int event, u32 portid, u32 seq, unsigned int nlflags)
227{
228	struct fib6_nh *fib6_nh;
229	struct fib_nh *fib_nh;
230	struct nlmsghdr *nlh;
231	struct nh_info *nhi;
232	struct nhmsg *nhm;
233
234	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nhm), nlflags);
235	if (!nlh)
236		return -EMSGSIZE;
237
238	nhm = nlmsg_data(nlh);
239	nhm->nh_family = AF_UNSPEC;
240	nhm->nh_flags = nh->nh_flags;
241	nhm->nh_protocol = nh->protocol;
242	nhm->nh_scope = 0;
243	nhm->resvd = 0;
244
245	if (nla_put_u32(skb, NHA_ID, nh->id))
246		goto nla_put_failure;
247
248	if (nh->is_group) {
249		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
250
251		if (nhg->fdb_nh && nla_put_flag(skb, NHA_FDB))
252			goto nla_put_failure;
253		if (nla_put_nh_group(skb, nhg))
254			goto nla_put_failure;
255		goto out;
256	}
257
258	nhi = rtnl_dereference(nh->nh_info);
259	nhm->nh_family = nhi->family;
260	if (nhi->reject_nh) {
261		if (nla_put_flag(skb, NHA_BLACKHOLE))
262			goto nla_put_failure;
263		goto out;
264	} else if (nhi->fdb_nh) {
265		if (nla_put_flag(skb, NHA_FDB))
266			goto nla_put_failure;
267	} else {
268		const struct net_device *dev;
269
270		dev = nhi->fib_nhc.nhc_dev;
271		if (dev && nla_put_u32(skb, NHA_OIF, dev->ifindex))
272			goto nla_put_failure;
273	}
274
275	nhm->nh_scope = nhi->fib_nhc.nhc_scope;
276	switch (nhi->family) {
277	case AF_INET:
278		fib_nh = &nhi->fib_nh;
279		if (fib_nh->fib_nh_gw_family &&
280		    nla_put_be32(skb, NHA_GATEWAY, fib_nh->fib_nh_gw4))
281			goto nla_put_failure;
282		break;
283
284	case AF_INET6:
285		fib6_nh = &nhi->fib6_nh;
286		if (fib6_nh->fib_nh_gw_family &&
287		    nla_put_in6_addr(skb, NHA_GATEWAY, &fib6_nh->fib_nh_gw6))
288			goto nla_put_failure;
289		break;
290	}
291
292	if (nhi->fib_nhc.nhc_lwtstate &&
293	    lwtunnel_fill_encap(skb, nhi->fib_nhc.nhc_lwtstate,
294				NHA_ENCAP, NHA_ENCAP_TYPE) < 0)
295		goto nla_put_failure;
296
297out:
298	nlmsg_end(skb, nlh);
299	return 0;
300
301nla_put_failure:
302	nlmsg_cancel(skb, nlh);
303	return -EMSGSIZE;
304}
305
306static size_t nh_nlmsg_size_grp(struct nexthop *nh)
307{
308	struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
309	size_t sz = sizeof(struct nexthop_grp) * nhg->num_nh;
310
311	return nla_total_size(sz) +
312	       nla_total_size(2);  /* NHA_GROUP_TYPE */
313}
314
315static size_t nh_nlmsg_size_single(struct nexthop *nh)
316{
317	struct nh_info *nhi = rtnl_dereference(nh->nh_info);
318	size_t sz;
319
320	/* covers NHA_BLACKHOLE since NHA_OIF and BLACKHOLE
321	 * are mutually exclusive
322	 */
323	sz = nla_total_size(4);  /* NHA_OIF */
324
325	switch (nhi->family) {
326	case AF_INET:
327		if (nhi->fib_nh.fib_nh_gw_family)
328			sz += nla_total_size(4);  /* NHA_GATEWAY */
329		break;
330
331	case AF_INET6:
332		/* NHA_GATEWAY */
333		if (nhi->fib6_nh.fib_nh_gw_family)
334			sz += nla_total_size(sizeof(const struct in6_addr));
335		break;
336	}
337
338	if (nhi->fib_nhc.nhc_lwtstate) {
339		sz += lwtunnel_get_encap_size(nhi->fib_nhc.nhc_lwtstate);
340		sz += nla_total_size(2);  /* NHA_ENCAP_TYPE */
341	}
342
343	return sz;
344}
345
346static size_t nh_nlmsg_size(struct nexthop *nh)
347{
348	size_t sz = NLMSG_ALIGN(sizeof(struct nhmsg));
349
350	sz += nla_total_size(4); /* NHA_ID */
351
352	if (nh->is_group)
353		sz += nh_nlmsg_size_grp(nh);
354	else
355		sz += nh_nlmsg_size_single(nh);
356
357	return sz;
358}
359
360static void nexthop_notify(int event, struct nexthop *nh, struct nl_info *info)
361{
362	unsigned int nlflags = info->nlh ? info->nlh->nlmsg_flags : 0;
363	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
364	struct sk_buff *skb;
365	int err = -ENOBUFS;
366
367	skb = nlmsg_new(nh_nlmsg_size(nh), gfp_any());
368	if (!skb)
369		goto errout;
370
371	err = nh_fill_node(skb, nh, event, info->portid, seq, nlflags);
372	if (err < 0) {
373		/* -EMSGSIZE implies BUG in nh_nlmsg_size() */
374		WARN_ON(err == -EMSGSIZE);
375		kfree_skb(skb);
376		goto errout;
377	}
378
379	rtnl_notify(skb, info->nl_net, info->portid, RTNLGRP_NEXTHOP,
380		    info->nlh, gfp_any());
381	return;
382errout:
383	if (err < 0)
384		rtnl_set_sk_err(info->nl_net, RTNLGRP_NEXTHOP, err);
385}
386
387static bool valid_group_nh(struct nexthop *nh, unsigned int npaths,
388			   bool *is_fdb, struct netlink_ext_ack *extack)
389{
390	if (nh->is_group) {
391		struct nh_group *nhg = rtnl_dereference(nh->nh_grp);
392
393		/* nested multipath (group within a group) is not
394		 * supported
395		 */
396		if (nhg->mpath) {
397			NL_SET_ERR_MSG(extack,
398				       "Multipath group can not be a nexthop within a group");
399			return false;
400		}
401		*is_fdb = nhg->fdb_nh;
402	} else {
403		struct nh_info *nhi = rtnl_dereference(nh->nh_info);
404
405		if (nhi->reject_nh && npaths > 1) {
406			NL_SET_ERR_MSG(extack,
407				       "Blackhole nexthop can not be used in a group with more than 1 path");
408			return false;
409		}
410		*is_fdb = nhi->fdb_nh;
411	}
412
413	return true;
414}
415
416static int nh_check_attr_fdb_group(struct nexthop *nh, u8 *nh_family,
417				   struct netlink_ext_ack *extack)
418{
419	struct nh_info *nhi;
420
421	nhi = rtnl_dereference(nh->nh_info);
422
423	if (!nhi->fdb_nh) {
424		NL_SET_ERR_MSG(extack, "FDB nexthop group can only have fdb nexthops");
425		return -EINVAL;
426	}
427
428	if (*nh_family == AF_UNSPEC) {
429		*nh_family = nhi->family;
430	} else if (*nh_family != nhi->family) {
431		NL_SET_ERR_MSG(extack, "FDB nexthop group cannot have mixed family nexthops");
432		return -EINVAL;
433	}
434
435	return 0;
436}
437
438static int nh_check_attr_group(struct net *net, struct nlattr *tb[],
439			       struct netlink_ext_ack *extack)
440{
441	unsigned int len = nla_len(tb[NHA_GROUP]);
442	u8 nh_family = AF_UNSPEC;
443	struct nexthop_grp *nhg;
444	unsigned int i, j;
445	u8 nhg_fdb = 0;
446
447	if (!len || len & (sizeof(struct nexthop_grp) - 1)) {
448		NL_SET_ERR_MSG(extack,
449			       "Invalid length for nexthop group attribute");
450		return -EINVAL;
451	}
452
453	/* convert len to number of nexthop ids */
454	len /= sizeof(*nhg);
455
456	nhg = nla_data(tb[NHA_GROUP]);
457	for (i = 0; i < len; ++i) {
458		if (nhg[i].resvd1 || nhg[i].resvd2) {
459			NL_SET_ERR_MSG(extack, "Reserved fields in nexthop_grp must be 0");
460			return -EINVAL;
461		}
462		if (nhg[i].weight > 254) {
463			NL_SET_ERR_MSG(extack, "Invalid value for weight");
464			return -EINVAL;
465		}
466		for (j = i + 1; j < len; ++j) {
467			if (nhg[i].id == nhg[j].id) {
468				NL_SET_ERR_MSG(extack, "Nexthop id can not be used twice in a group");
469				return -EINVAL;
470			}
471		}
472	}
473
474	if (tb[NHA_FDB])
475		nhg_fdb = 1;
476	nhg = nla_data(tb[NHA_GROUP]);
477	for (i = 0; i < len; ++i) {
478		struct nexthop *nh;
479		bool is_fdb_nh;
480
481		nh = nexthop_find_by_id(net, nhg[i].id);
482		if (!nh) {
483			NL_SET_ERR_MSG(extack, "Invalid nexthop id");
484			return -EINVAL;
485		}
486		if (!valid_group_nh(nh, len, &is_fdb_nh, extack))
487			return -EINVAL;
488
489		if (nhg_fdb && nh_check_attr_fdb_group(nh, &nh_family, extack))
490			return -EINVAL;
491
492		if (!nhg_fdb && is_fdb_nh) {
493			NL_SET_ERR_MSG(extack, "Non FDB nexthop group cannot have fdb nexthops");
494			return -EINVAL;
495		}
496	}
497	for (i = NHA_GROUP_TYPE + 1; i < __NHA_MAX; ++i) {
498		if (!tb[i])
499			continue;
500		if (i == NHA_FDB)
501			continue;
502		NL_SET_ERR_MSG(extack,
503			       "No other attributes can be set in nexthop groups");
504		return -EINVAL;
505	}
506
507	return 0;
508}
509
510static bool ipv6_good_nh(const struct fib6_nh *nh)
511{
512	int state = NUD_REACHABLE;
513	struct neighbour *n;
514
515	rcu_read_lock_bh();
516
517	n = __ipv6_neigh_lookup_noref_stub(nh->fib_nh_dev, &nh->fib_nh_gw6);
518	if (n)
519		state = n->nud_state;
520
521	rcu_read_unlock_bh();
522
523	return !!(state & NUD_VALID);
524}
525
526static bool ipv4_good_nh(const struct fib_nh *nh)
527{
528	int state = NUD_REACHABLE;
529	struct neighbour *n;
530
531	rcu_read_lock_bh();
532
533	n = __ipv4_neigh_lookup_noref(nh->fib_nh_dev,
534				      (__force u32)nh->fib_nh_gw4);
535	if (n)
536		state = n->nud_state;
537
538	rcu_read_unlock_bh();
539
540	return !!(state & NUD_VALID);
541}
542
543struct nexthop *nexthop_select_path(struct nexthop *nh, int hash)
544{
545	struct nexthop *rc = NULL;
546	struct nh_group *nhg;
547	int i;
548
549	if (!nh->is_group)
550		return nh;
551
552	nhg = rcu_dereference(nh->nh_grp);
553	for (i = 0; i < nhg->num_nh; ++i) {
554		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
555		struct nh_info *nhi;
556
557		if (hash > atomic_read(&nhge->upper_bound))
558			continue;
559
560		nhi = rcu_dereference(nhge->nh->nh_info);
561		if (nhi->fdb_nh)
562			return nhge->nh;
563
564		/* nexthops always check if it is good and does
565		 * not rely on a sysctl for this behavior
566		 */
567		switch (nhi->family) {
568		case AF_INET:
569			if (ipv4_good_nh(&nhi->fib_nh))
570				return nhge->nh;
571			break;
572		case AF_INET6:
573			if (ipv6_good_nh(&nhi->fib6_nh))
574				return nhge->nh;
575			break;
576		}
577
578		if (!rc)
579			rc = nhge->nh;
580	}
581
582	return rc;
583}
584EXPORT_SYMBOL_GPL(nexthop_select_path);
585
586int nexthop_for_each_fib6_nh(struct nexthop *nh,
587			     int (*cb)(struct fib6_nh *nh, void *arg),
588			     void *arg)
589{
590	struct nh_info *nhi;
591	int err;
592
593	if (nh->is_group) {
594		struct nh_group *nhg;
595		int i;
596
597		nhg = rcu_dereference_rtnl(nh->nh_grp);
598		for (i = 0; i < nhg->num_nh; i++) {
599			struct nh_grp_entry *nhge = &nhg->nh_entries[i];
600
601			nhi = rcu_dereference_rtnl(nhge->nh->nh_info);
602			err = cb(&nhi->fib6_nh, arg);
603			if (err)
604				return err;
605		}
606	} else {
607		nhi = rcu_dereference_rtnl(nh->nh_info);
608		err = cb(&nhi->fib6_nh, arg);
609		if (err)
610			return err;
611	}
612
613	return 0;
614}
615EXPORT_SYMBOL_GPL(nexthop_for_each_fib6_nh);
616
617static int check_src_addr(const struct in6_addr *saddr,
618			  struct netlink_ext_ack *extack)
619{
620	if (!ipv6_addr_any(saddr)) {
621		NL_SET_ERR_MSG(extack, "IPv6 routes using source address can not use nexthop objects");
622		return -EINVAL;
623	}
624	return 0;
625}
626
627int fib6_check_nexthop(struct nexthop *nh, struct fib6_config *cfg,
628		       struct netlink_ext_ack *extack)
629{
630	struct nh_info *nhi;
631	bool is_fdb_nh;
632
633	/* fib6_src is unique to a fib6_info and limits the ability to cache
634	 * routes in fib6_nh within a nexthop that is potentially shared
635	 * across multiple fib entries. If the config wants to use source
636	 * routing it can not use nexthop objects. mlxsw also does not allow
637	 * fib6_src on routes.
638	 */
639	if (cfg && check_src_addr(&cfg->fc_src, extack) < 0)
640		return -EINVAL;
641
642	if (nh->is_group) {
643		struct nh_group *nhg;
644
645		nhg = rtnl_dereference(nh->nh_grp);
646		if (nhg->has_v4)
647			goto no_v4_nh;
648		is_fdb_nh = nhg->fdb_nh;
649	} else {
650		nhi = rtnl_dereference(nh->nh_info);
651		if (nhi->family == AF_INET)
652			goto no_v4_nh;
653		is_fdb_nh = nhi->fdb_nh;
654	}
655
656	if (is_fdb_nh) {
657		NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
658		return -EINVAL;
659	}
660
661	return 0;
662no_v4_nh:
663	NL_SET_ERR_MSG(extack, "IPv6 routes can not use an IPv4 nexthop");
664	return -EINVAL;
665}
666EXPORT_SYMBOL_GPL(fib6_check_nexthop);
667
668/* if existing nexthop has ipv6 routes linked to it, need
669 * to verify this new spec works with ipv6
670 */
671static int fib6_check_nh_list(struct nexthop *old, struct nexthop *new,
672			      struct netlink_ext_ack *extack)
673{
674	struct fib6_info *f6i;
675
676	if (list_empty(&old->f6i_list))
677		return 0;
678
679	list_for_each_entry(f6i, &old->f6i_list, nh_list) {
680		if (check_src_addr(&f6i->fib6_src.addr, extack) < 0)
681			return -EINVAL;
682	}
683
684	return fib6_check_nexthop(new, NULL, extack);
685}
686
687static int nexthop_check_scope(struct nh_info *nhi, u8 scope,
688			       struct netlink_ext_ack *extack)
689{
690	if (scope == RT_SCOPE_HOST && nhi->fib_nhc.nhc_gw_family) {
691		NL_SET_ERR_MSG(extack,
692			       "Route with host scope can not have a gateway");
693		return -EINVAL;
694	}
695
696	if (nhi->fib_nhc.nhc_flags & RTNH_F_ONLINK && scope >= RT_SCOPE_LINK) {
697		NL_SET_ERR_MSG(extack, "Scope mismatch with nexthop");
698		return -EINVAL;
699	}
700
701	return 0;
702}
703
704/* Invoked by fib add code to verify nexthop by id is ok with
705 * config for prefix; parts of fib_check_nh not done when nexthop
706 * object is used.
707 */
708int fib_check_nexthop(struct nexthop *nh, u8 scope,
709		      struct netlink_ext_ack *extack)
710{
711	struct nh_info *nhi;
712	int err = 0;
713
714	if (nh->is_group) {
715		struct nh_group *nhg;
716
717		nhg = rtnl_dereference(nh->nh_grp);
718		if (nhg->fdb_nh) {
719			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
720			err = -EINVAL;
721			goto out;
722		}
723
724		if (scope == RT_SCOPE_HOST) {
725			NL_SET_ERR_MSG(extack, "Route with host scope can not have multiple nexthops");
726			err = -EINVAL;
727			goto out;
728		}
729
730		/* all nexthops in a group have the same scope */
731		nhi = rtnl_dereference(nhg->nh_entries[0].nh->nh_info);
732		err = nexthop_check_scope(nhi, scope, extack);
733	} else {
734		nhi = rtnl_dereference(nh->nh_info);
735		if (nhi->fdb_nh) {
736			NL_SET_ERR_MSG(extack, "Route cannot point to a fdb nexthop");
737			err = -EINVAL;
738			goto out;
739		}
740		err = nexthop_check_scope(nhi, scope, extack);
741	}
742
743out:
744	return err;
745}
746
747static int fib_check_nh_list(struct nexthop *old, struct nexthop *new,
748			     struct netlink_ext_ack *extack)
749{
750	struct fib_info *fi;
751
752	list_for_each_entry(fi, &old->fi_list, nh_list) {
753		int err;
754
755		err = fib_check_nexthop(new, fi->fib_scope, extack);
756		if (err)
757			return err;
758	}
759	return 0;
760}
761
762static void nh_group_rebalance(struct nh_group *nhg)
763{
764	int total = 0;
765	int w = 0;
766	int i;
767
768	for (i = 0; i < nhg->num_nh; ++i)
769		total += nhg->nh_entries[i].weight;
770
771	for (i = 0; i < nhg->num_nh; ++i) {
772		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
773		int upper_bound;
774
775		w += nhge->weight;
776		upper_bound = DIV_ROUND_CLOSEST_ULL((u64)w << 31, total) - 1;
777		atomic_set(&nhge->upper_bound, upper_bound);
778	}
779}
780
781static void remove_nh_grp_entry(struct net *net, struct nh_grp_entry *nhge,
782				struct nl_info *nlinfo)
783{
784	struct nh_grp_entry *nhges, *new_nhges;
785	struct nexthop *nhp = nhge->nh_parent;
786	struct nexthop *nh = nhge->nh;
787	struct nh_group *nhg, *newg;
788	int i, j;
789
790	WARN_ON(!nh);
791
792	nhg = rtnl_dereference(nhp->nh_grp);
793	newg = nhg->spare;
794
795	/* last entry, keep it visible and remove the parent */
796	if (nhg->num_nh == 1) {
797		remove_nexthop(net, nhp, nlinfo);
798		return;
799	}
800
801	newg->has_v4 = false;
802	newg->mpath = nhg->mpath;
803	newg->fdb_nh = nhg->fdb_nh;
804	newg->num_nh = nhg->num_nh;
805
806	/* copy old entries to new except the one getting removed */
807	nhges = nhg->nh_entries;
808	new_nhges = newg->nh_entries;
809	for (i = 0, j = 0; i < nhg->num_nh; ++i) {
810		struct nh_info *nhi;
811
812		/* current nexthop getting removed */
813		if (nhg->nh_entries[i].nh == nh) {
814			newg->num_nh--;
815			continue;
816		}
817
818		nhi = rtnl_dereference(nhges[i].nh->nh_info);
819		if (nhi->family == AF_INET)
820			newg->has_v4 = true;
821
822		list_del(&nhges[i].nh_list);
823		new_nhges[j].nh_parent = nhges[i].nh_parent;
824		new_nhges[j].nh = nhges[i].nh;
825		new_nhges[j].weight = nhges[i].weight;
826		list_add(&new_nhges[j].nh_list, &new_nhges[j].nh->grp_list);
827		j++;
828	}
829
830	nh_group_rebalance(newg);
831	rcu_assign_pointer(nhp->nh_grp, newg);
832
833	list_del(&nhge->nh_list);
834	nexthop_put(nhge->nh);
835
836	if (nlinfo)
837		nexthop_notify(RTM_NEWNEXTHOP, nhp, nlinfo);
838}
839
840static void remove_nexthop_from_groups(struct net *net, struct nexthop *nh,
841				       struct nl_info *nlinfo)
842{
843	struct nh_grp_entry *nhge, *tmp;
844
845	list_for_each_entry_safe(nhge, tmp, &nh->grp_list, nh_list)
846		remove_nh_grp_entry(net, nhge, nlinfo);
847
848	/* make sure all see the newly published array before releasing rtnl */
849	synchronize_net();
850}
851
852static void remove_nexthop_group(struct nexthop *nh, struct nl_info *nlinfo)
853{
854	struct nh_group *nhg = rcu_dereference_rtnl(nh->nh_grp);
855	int i, num_nh = nhg->num_nh;
856
857	for (i = 0; i < num_nh; ++i) {
858		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
859
860		if (WARN_ON(!nhge->nh))
861			continue;
862
863		list_del_init(&nhge->nh_list);
864	}
865}
866
867/* not called for nexthop replace */
868static void __remove_nexthop_fib(struct net *net, struct nexthop *nh)
869{
870	struct fib6_info *f6i, *tmp;
871	bool do_flush = false;
872	struct fib_info *fi;
873
874	list_for_each_entry(fi, &nh->fi_list, nh_list) {
875		fi->fib_flags |= RTNH_F_DEAD;
876		do_flush = true;
877	}
878	if (do_flush)
879		fib_flush(net);
880
881	/* ip6_del_rt removes the entry from this list hence the _safe */
882	list_for_each_entry_safe(f6i, tmp, &nh->f6i_list, nh_list) {
883		/* __ip6_del_rt does a release, so do a hold here */
884		fib6_info_hold(f6i);
885		ipv6_stub->ip6_del_rt(net, f6i,
886				      !READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode));
887	}
888}
889
890static void __remove_nexthop(struct net *net, struct nexthop *nh,
891			     struct nl_info *nlinfo)
892{
893	__remove_nexthop_fib(net, nh);
894
895	if (nh->is_group) {
896		remove_nexthop_group(nh, nlinfo);
897	} else {
898		struct nh_info *nhi;
899
900		nhi = rtnl_dereference(nh->nh_info);
901		if (nhi->fib_nhc.nhc_dev)
902			hlist_del(&nhi->dev_hash);
903
904		remove_nexthop_from_groups(net, nh, nlinfo);
905	}
906}
907
908static void remove_nexthop(struct net *net, struct nexthop *nh,
909			   struct nl_info *nlinfo)
910{
911	call_nexthop_notifiers(net, NEXTHOP_EVENT_DEL, nh);
912
913	/* remove from the tree */
914	rb_erase(&nh->rb_node, &net->nexthop.rb_root);
915
916	if (nlinfo)
917		nexthop_notify(RTM_DELNEXTHOP, nh, nlinfo);
918
919	__remove_nexthop(net, nh, nlinfo);
920	nh_base_seq_inc(net);
921
922	nexthop_put(nh);
923}
924
925/* if any FIB entries reference this nexthop, any dst entries
926 * need to be regenerated
927 */
928static void nh_rt_cache_flush(struct net *net, struct nexthop *nh,
929			      struct nexthop *replaced_nh)
930{
931	struct fib6_info *f6i;
932	struct nh_group *nhg;
933	int i;
934
935	if (!list_empty(&nh->fi_list))
936		rt_cache_flush(net);
937
938	list_for_each_entry(f6i, &nh->f6i_list, nh_list)
939		ipv6_stub->fib6_update_sernum(net, f6i);
940
941	/* if an IPv6 group was replaced, we have to release all old
942	 * dsts to make sure all refcounts are released
943	 */
944	if (!replaced_nh->is_group)
945		return;
946
947	/* new dsts must use only the new nexthop group */
948	synchronize_net();
949
950	nhg = rtnl_dereference(replaced_nh->nh_grp);
951	for (i = 0; i < nhg->num_nh; i++) {
952		struct nh_grp_entry *nhge = &nhg->nh_entries[i];
953		struct nh_info *nhi = rtnl_dereference(nhge->nh->nh_info);
954
955		if (nhi->family == AF_INET6)
956			ipv6_stub->fib6_nh_release_dsts(&nhi->fib6_nh);
957	}
958}
959
960static int replace_nexthop_grp(struct net *net, struct nexthop *old,
961			       struct nexthop *new,
962			       struct netlink_ext_ack *extack)
963{
964	struct nh_group *oldg, *newg;
965	int i;
966
967	if (!new->is_group) {
968		NL_SET_ERR_MSG(extack, "Can not replace a nexthop group with a nexthop.");
969		return -EINVAL;
970	}
971
972	oldg = rtnl_dereference(old->nh_grp);
973	newg = rtnl_dereference(new->nh_grp);
974
975	/* update parents - used by nexthop code for cleanup */
976	for (i = 0; i < newg->num_nh; i++)
977		newg->nh_entries[i].nh_parent = old;
978
979	rcu_assign_pointer(old->nh_grp, newg);
980
981	for (i = 0; i < oldg->num_nh; i++)
982		oldg->nh_entries[i].nh_parent = new;
983
984	rcu_assign_pointer(new->nh_grp, oldg);
985
986	return 0;
987}
988
989static void nh_group_v4_update(struct nh_group *nhg)
990{
991	struct nh_grp_entry *nhges;
992	bool has_v4 = false;
993	int i;
994
995	nhges = nhg->nh_entries;
996	for (i = 0; i < nhg->num_nh; i++) {
997		struct nh_info *nhi;
998
999		nhi = rtnl_dereference(nhges[i].nh->nh_info);
1000		if (nhi->family == AF_INET)
1001			has_v4 = true;
1002	}
1003	nhg->has_v4 = has_v4;
1004}
1005
1006static int replace_nexthop_single(struct net *net, struct nexthop *old,
1007				  struct nexthop *new,
1008				  struct netlink_ext_ack *extack)
1009{
1010	struct nh_info *oldi, *newi;
1011
1012	if (new->is_group) {
1013		NL_SET_ERR_MSG(extack, "Can not replace a nexthop with a nexthop group.");
1014		return -EINVAL;
1015	}
1016
1017	oldi = rtnl_dereference(old->nh_info);
1018	newi = rtnl_dereference(new->nh_info);
1019
1020	newi->nh_parent = old;
1021	oldi->nh_parent = new;
1022
1023	old->protocol = new->protocol;
1024	old->nh_flags = new->nh_flags;
1025
1026	rcu_assign_pointer(old->nh_info, newi);
1027	rcu_assign_pointer(new->nh_info, oldi);
1028
1029	/* When replacing an IPv4 nexthop with an IPv6 nexthop, potentially
1030	 * update IPv4 indication in all the groups using the nexthop.
1031	 */
1032	if (oldi->family == AF_INET && newi->family == AF_INET6) {
1033		struct nh_grp_entry *nhge;
1034
1035		list_for_each_entry(nhge, &old->grp_list, nh_list) {
1036			struct nexthop *nhp = nhge->nh_parent;
1037			struct nh_group *nhg;
1038
1039			nhg = rtnl_dereference(nhp->nh_grp);
1040			nh_group_v4_update(nhg);
1041		}
1042	}
1043
1044	return 0;
1045}
1046
1047static void __nexthop_replace_notify(struct net *net, struct nexthop *nh,
1048				     struct nl_info *info)
1049{
1050	struct fib6_info *f6i;
1051
1052	if (!list_empty(&nh->fi_list)) {
1053		struct fib_info *fi;
1054
1055		/* expectation is a few fib_info per nexthop and then
1056		 * a lot of routes per fib_info. So mark the fib_info
1057		 * and then walk the fib tables once
1058		 */
1059		list_for_each_entry(fi, &nh->fi_list, nh_list)
1060			fi->nh_updated = true;
1061
1062		fib_info_notify_update(net, info);
1063
1064		list_for_each_entry(fi, &nh->fi_list, nh_list)
1065			fi->nh_updated = false;
1066	}
1067
1068	list_for_each_entry(f6i, &nh->f6i_list, nh_list)
1069		ipv6_stub->fib6_rt_update(net, f6i, info);
1070}
1071
1072/* send RTM_NEWROUTE with REPLACE flag set for all FIB entries
1073 * linked to this nexthop and for all groups that the nexthop
1074 * is a member of
1075 */
1076static void nexthop_replace_notify(struct net *net, struct nexthop *nh,
1077				   struct nl_info *info)
1078{
1079	struct nh_grp_entry *nhge;
1080
1081	__nexthop_replace_notify(net, nh, info);
1082
1083	list_for_each_entry(nhge, &nh->grp_list, nh_list)
1084		__nexthop_replace_notify(net, nhge->nh_parent, info);
1085}
1086
1087static int replace_nexthop(struct net *net, struct nexthop *old,
1088			   struct nexthop *new, struct netlink_ext_ack *extack)
1089{
1090	bool new_is_reject = false;
1091	struct nh_grp_entry *nhge;
1092	int err;
1093
1094	/* check that existing FIB entries are ok with the
1095	 * new nexthop definition
1096	 */
1097	err = fib_check_nh_list(old, new, extack);
1098	if (err)
1099		return err;
1100
1101	err = fib6_check_nh_list(old, new, extack);
1102	if (err)
1103		return err;
1104
1105	if (!new->is_group) {
1106		struct nh_info *nhi = rtnl_dereference(new->nh_info);
1107
1108		new_is_reject = nhi->reject_nh;
1109	}
1110
1111	list_for_each_entry(nhge, &old->grp_list, nh_list) {
1112		/* if new nexthop is a blackhole, any groups using this
1113		 * nexthop cannot have more than 1 path
1114		 */
1115		if (new_is_reject &&
1116		    nexthop_num_path(nhge->nh_parent) > 1) {
1117			NL_SET_ERR_MSG(extack, "Blackhole nexthop can not be a member of a group with more than one path");
1118			return -EINVAL;
1119		}
1120
1121		err = fib_check_nh_list(nhge->nh_parent, new, extack);
1122		if (err)
1123			return err;
1124
1125		err = fib6_check_nh_list(nhge->nh_parent, new, extack);
1126		if (err)
1127			return err;
1128	}
1129
1130	if (old->is_group)
1131		err = replace_nexthop_grp(net, old, new, extack);
1132	else
1133		err = replace_nexthop_single(net, old, new, extack);
1134
1135	if (!err) {
1136		nh_rt_cache_flush(net, old, new);
1137
1138		__remove_nexthop(net, new, NULL);
1139		nexthop_put(new);
1140	}
1141
1142	return err;
1143}
1144
1145/* called with rtnl_lock held */
1146static int insert_nexthop(struct net *net, struct nexthop *new_nh,
1147			  struct nh_config *cfg, struct netlink_ext_ack *extack)
1148{
1149	struct rb_node **pp, *parent = NULL, *next;
1150	struct rb_root *root = &net->nexthop.rb_root;
1151	bool replace = !!(cfg->nlflags & NLM_F_REPLACE);
1152	bool create = !!(cfg->nlflags & NLM_F_CREATE);
1153	u32 new_id = new_nh->id;
1154	int replace_notify = 0;
1155	int rc = -EEXIST;
1156
1157	pp = &root->rb_node;
1158	while (1) {
1159		struct nexthop *nh;
1160
1161		next = *pp;
1162		if (!next)
1163			break;
1164
1165		parent = next;
1166
1167		nh = rb_entry(parent, struct nexthop, rb_node);
1168		if (new_id < nh->id) {
1169			pp = &next->rb_left;
1170		} else if (new_id > nh->id) {
1171			pp = &next->rb_right;
1172		} else if (replace) {
1173			rc = replace_nexthop(net, nh, new_nh, extack);
1174			if (!rc) {
1175				new_nh = nh; /* send notification with old nh */
1176				replace_notify = 1;
1177			}
1178			goto out;
1179		} else {
1180			/* id already exists and not a replace */
1181			goto out;
1182		}
1183	}
1184
1185	if (replace && !create) {
1186		NL_SET_ERR_MSG(extack, "Replace specified without create and no entry exists");
1187		rc = -ENOENT;
1188		goto out;
1189	}
1190
1191	rb_link_node_rcu(&new_nh->rb_node, parent, pp);
1192	rb_insert_color(&new_nh->rb_node, root);
1193	rc = 0;
1194out:
1195	if (!rc) {
1196		nh_base_seq_inc(net);
1197		nexthop_notify(RTM_NEWNEXTHOP, new_nh, &cfg->nlinfo);
1198		if (replace_notify &&
1199		    READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode))
1200			nexthop_replace_notify(net, new_nh, &cfg->nlinfo);
1201	}
1202
1203	return rc;
1204}
1205
1206/* rtnl */
1207/* remove all nexthops tied to a device being deleted */
1208static void nexthop_flush_dev(struct net_device *dev, unsigned long event)
1209{
1210	unsigned int hash = nh_dev_hashfn(dev->ifindex);
1211	struct net *net = dev_net(dev);
1212	struct hlist_head *head = &net->nexthop.devhash[hash];
1213	struct hlist_node *n;
1214	struct nh_info *nhi;
1215
1216	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
1217		if (nhi->fib_nhc.nhc_dev != dev)
1218			continue;
1219
1220		if (nhi->reject_nh &&
1221		    (event == NETDEV_DOWN || event == NETDEV_CHANGE))
1222			continue;
1223
1224		remove_nexthop(net, nhi->nh_parent, NULL);
1225	}
1226}
1227
1228/* rtnl; called when net namespace is deleted */
1229static void flush_all_nexthops(struct net *net)
1230{
1231	struct rb_root *root = &net->nexthop.rb_root;
1232	struct rb_node *node;
1233	struct nexthop *nh;
1234
1235	while ((node = rb_first(root))) {
1236		nh = rb_entry(node, struct nexthop, rb_node);
1237		remove_nexthop(net, nh, NULL);
1238		cond_resched();
1239	}
1240}
1241
1242static struct nexthop *nexthop_create_group(struct net *net,
1243					    struct nh_config *cfg)
1244{
1245	struct nlattr *grps_attr = cfg->nh_grp;
1246	struct nexthop_grp *entry = nla_data(grps_attr);
1247	u16 num_nh = nla_len(grps_attr) / sizeof(*entry);
1248	struct nh_group *nhg;
1249	struct nexthop *nh;
1250	int i;
1251
1252	if (WARN_ON(!num_nh))
1253		return ERR_PTR(-EINVAL);
1254
1255	nh = nexthop_alloc();
1256	if (!nh)
1257		return ERR_PTR(-ENOMEM);
1258
1259	nh->is_group = 1;
1260
1261	nhg = nexthop_grp_alloc(num_nh);
1262	if (!nhg) {
1263		kfree(nh);
1264		return ERR_PTR(-ENOMEM);
1265	}
1266
1267	/* spare group used for removals */
1268	nhg->spare = nexthop_grp_alloc(num_nh);
1269	if (!nhg->spare) {
1270		kfree(nhg);
1271		kfree(nh);
1272		return ERR_PTR(-ENOMEM);
1273	}
1274	nhg->spare->spare = nhg;
1275
1276	for (i = 0; i < nhg->num_nh; ++i) {
1277		struct nexthop *nhe;
1278		struct nh_info *nhi;
1279
1280		nhe = nexthop_find_by_id(net, entry[i].id);
1281		if (!nexthop_get(nhe))
1282			goto out_no_nh;
1283
1284		nhi = rtnl_dereference(nhe->nh_info);
1285		if (nhi->family == AF_INET)
1286			nhg->has_v4 = true;
1287
1288		nhg->nh_entries[i].nh = nhe;
1289		nhg->nh_entries[i].weight = entry[i].weight + 1;
1290		list_add(&nhg->nh_entries[i].nh_list, &nhe->grp_list);
1291		nhg->nh_entries[i].nh_parent = nh;
1292	}
1293
1294	if (cfg->nh_grp_type == NEXTHOP_GRP_TYPE_MPATH) {
1295		nhg->mpath = 1;
1296		nh_group_rebalance(nhg);
1297	}
1298
1299	if (cfg->nh_fdb)
1300		nhg->fdb_nh = 1;
1301
1302	rcu_assign_pointer(nh->nh_grp, nhg);
1303
1304	return nh;
1305
1306out_no_nh:
1307	for (i--; i >= 0; --i) {
1308		list_del(&nhg->nh_entries[i].nh_list);
1309		nexthop_put(nhg->nh_entries[i].nh);
1310	}
1311
1312	kfree(nhg->spare);
1313	kfree(nhg);
1314	kfree(nh);
1315
1316	return ERR_PTR(-ENOENT);
1317}
1318
1319static int nh_create_ipv4(struct net *net, struct nexthop *nh,
1320			  struct nh_info *nhi, struct nh_config *cfg,
1321			  struct netlink_ext_ack *extack)
1322{
1323	struct fib_nh *fib_nh = &nhi->fib_nh;
1324	struct fib_config fib_cfg = {
1325		.fc_oif   = cfg->nh_ifindex,
1326		.fc_gw4   = cfg->gw.ipv4,
1327		.fc_gw_family = cfg->gw.ipv4 ? AF_INET : 0,
1328		.fc_flags = cfg->nh_flags,
1329		.fc_nlinfo = cfg->nlinfo,
1330		.fc_encap = cfg->nh_encap,
1331		.fc_encap_type = cfg->nh_encap_type,
1332	};
1333	u32 tb_id = (cfg->dev ? l3mdev_fib_table(cfg->dev) : RT_TABLE_MAIN);
1334	int err;
1335
1336	err = fib_nh_init(net, fib_nh, &fib_cfg, 1, extack);
1337	if (err) {
1338		fib_nh_release(net, fib_nh);
1339		goto out;
1340	}
1341
1342	if (nhi->fdb_nh)
1343		goto out;
1344
1345	/* sets nh_dev if successful */
1346	err = fib_check_nh(net, fib_nh, tb_id, 0, extack);
1347	if (!err) {
1348		nh->nh_flags = fib_nh->fib_nh_flags;
1349		fib_info_update_nhc_saddr(net, &fib_nh->nh_common,
1350					  !fib_nh->fib_nh_scope ? 0 : fib_nh->fib_nh_scope - 1);
1351	} else {
1352		fib_nh_release(net, fib_nh);
1353	}
1354out:
1355	return err;
1356}
1357
1358static int nh_create_ipv6(struct net *net,  struct nexthop *nh,
1359			  struct nh_info *nhi, struct nh_config *cfg,
1360			  struct netlink_ext_ack *extack)
1361{
1362	struct fib6_nh *fib6_nh = &nhi->fib6_nh;
1363	struct fib6_config fib6_cfg = {
1364		.fc_table = l3mdev_fib_table(cfg->dev),
1365		.fc_ifindex = cfg->nh_ifindex,
1366		.fc_gateway = cfg->gw.ipv6,
1367		.fc_flags = cfg->nh_flags,
1368		.fc_nlinfo = cfg->nlinfo,
1369		.fc_encap = cfg->nh_encap,
1370		.fc_encap_type = cfg->nh_encap_type,
1371		.fc_is_fdb = cfg->nh_fdb,
1372	};
1373	int err;
1374
1375	if (!ipv6_addr_any(&cfg->gw.ipv6))
1376		fib6_cfg.fc_flags |= RTF_GATEWAY;
1377
1378	/* sets nh_dev if successful */
1379	err = ipv6_stub->fib6_nh_init(net, fib6_nh, &fib6_cfg, GFP_KERNEL,
1380				      extack);
1381	if (err) {
1382		/* IPv6 is not enabled, don't call fib6_nh_release */
1383		if (err == -EAFNOSUPPORT)
1384			goto out;
1385		ipv6_stub->fib6_nh_release(fib6_nh);
1386	} else {
1387		nh->nh_flags = fib6_nh->fib_nh_flags;
1388	}
1389out:
1390	return err;
1391}
1392
1393static struct nexthop *nexthop_create(struct net *net, struct nh_config *cfg,
1394				      struct netlink_ext_ack *extack)
1395{
1396	struct nh_info *nhi;
1397	struct nexthop *nh;
1398	int err = 0;
1399
1400	nh = nexthop_alloc();
1401	if (!nh)
1402		return ERR_PTR(-ENOMEM);
1403
1404	nhi = kzalloc(sizeof(*nhi), GFP_KERNEL);
1405	if (!nhi) {
1406		kfree(nh);
1407		return ERR_PTR(-ENOMEM);
1408	}
1409
1410	nh->nh_flags = cfg->nh_flags;
1411	nh->net = net;
1412
1413	nhi->nh_parent = nh;
1414	nhi->family = cfg->nh_family;
1415	nhi->fib_nhc.nhc_scope = RT_SCOPE_LINK;
1416
1417	if (cfg->nh_fdb)
1418		nhi->fdb_nh = 1;
1419
1420	if (cfg->nh_blackhole) {
1421		nhi->reject_nh = 1;
1422		cfg->nh_ifindex = net->loopback_dev->ifindex;
1423	}
1424
1425	switch (cfg->nh_family) {
1426	case AF_INET:
1427		err = nh_create_ipv4(net, nh, nhi, cfg, extack);
1428		break;
1429	case AF_INET6:
1430		err = nh_create_ipv6(net, nh, nhi, cfg, extack);
1431		break;
1432	}
1433
1434	if (err) {
1435		kfree(nhi);
1436		kfree(nh);
1437		return ERR_PTR(err);
1438	}
1439
1440	/* add the entry to the device based hash */
1441	if (!nhi->fdb_nh)
1442		nexthop_devhash_add(net, nhi);
1443
1444	rcu_assign_pointer(nh->nh_info, nhi);
1445
1446	return nh;
1447}
1448
1449/* called with rtnl lock held */
1450static struct nexthop *nexthop_add(struct net *net, struct nh_config *cfg,
1451				   struct netlink_ext_ack *extack)
1452{
1453	struct nexthop *nh;
1454	int err;
1455
1456	if (cfg->nlflags & NLM_F_REPLACE && !cfg->nh_id) {
1457		NL_SET_ERR_MSG(extack, "Replace requires nexthop id");
1458		return ERR_PTR(-EINVAL);
1459	}
1460
1461	if (!cfg->nh_id) {
1462		cfg->nh_id = nh_find_unused_id(net);
1463		if (!cfg->nh_id) {
1464			NL_SET_ERR_MSG(extack, "No unused id");
1465			return ERR_PTR(-EINVAL);
1466		}
1467	}
1468
1469	if (cfg->nh_grp)
1470		nh = nexthop_create_group(net, cfg);
1471	else
1472		nh = nexthop_create(net, cfg, extack);
1473
1474	if (IS_ERR(nh))
1475		return nh;
1476
1477	refcount_set(&nh->refcnt, 1);
1478	nh->id = cfg->nh_id;
1479	nh->protocol = cfg->nh_protocol;
1480	nh->net = net;
1481
1482	err = insert_nexthop(net, nh, cfg, extack);
1483	if (err) {
1484		__remove_nexthop(net, nh, NULL);
1485		nexthop_put(nh);
1486		nh = ERR_PTR(err);
1487	}
1488
1489	return nh;
1490}
1491
1492static int rtm_to_nh_config(struct net *net, struct sk_buff *skb,
1493			    struct nlmsghdr *nlh, struct nh_config *cfg,
1494			    struct netlink_ext_ack *extack)
1495{
1496	struct nhmsg *nhm = nlmsg_data(nlh);
1497	struct nlattr *tb[NHA_MAX + 1];
1498	int err;
1499
1500	err = nlmsg_parse(nlh, sizeof(*nhm), tb, NHA_MAX, rtm_nh_policy,
1501			  extack);
1502	if (err < 0)
1503		return err;
1504
1505	err = -EINVAL;
1506	if (nhm->resvd || nhm->nh_scope) {
1507		NL_SET_ERR_MSG(extack, "Invalid values in ancillary header");
1508		goto out;
1509	}
1510	if (nhm->nh_flags & ~NEXTHOP_VALID_USER_FLAGS) {
1511		NL_SET_ERR_MSG(extack, "Invalid nexthop flags in ancillary header");
1512		goto out;
1513	}
1514
1515	switch (nhm->nh_family) {
1516	case AF_INET:
1517	case AF_INET6:
1518		break;
1519	case AF_UNSPEC:
1520		if (tb[NHA_GROUP])
1521			break;
1522		fallthrough;
1523	default:
1524		NL_SET_ERR_MSG(extack, "Invalid address family");
1525		goto out;
1526	}
1527
1528	if (tb[NHA_GROUPS] || tb[NHA_MASTER]) {
1529		NL_SET_ERR_MSG(extack, "Invalid attributes in request");
1530		goto out;
1531	}
1532
1533	memset(cfg, 0, sizeof(*cfg));
1534	cfg->nlflags = nlh->nlmsg_flags;
1535	cfg->nlinfo.portid = NETLINK_CB(skb).portid;
1536	cfg->nlinfo.nlh = nlh;
1537	cfg->nlinfo.nl_net = net;
1538
1539	cfg->nh_family = nhm->nh_family;
1540	cfg->nh_protocol = nhm->nh_protocol;
1541	cfg->nh_flags = nhm->nh_flags;
1542
1543	if (tb[NHA_ID])
1544		cfg->nh_id = nla_get_u32(tb[NHA_ID]);
1545
1546	if (tb[NHA_FDB]) {
1547		if (tb[NHA_OIF] || tb[NHA_BLACKHOLE] ||
1548		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE]) {
1549			NL_SET_ERR_MSG(extack, "Fdb attribute can not be used with encap, oif or blackhole");
1550			goto out;
1551		}
1552		if (nhm->nh_flags) {
1553			NL_SET_ERR_MSG(extack, "Unsupported nexthop flags in ancillary header");
1554			goto out;
1555		}
1556		cfg->nh_fdb = nla_get_flag(tb[NHA_FDB]);
1557	}
1558
1559	if (tb[NHA_GROUP]) {
1560		if (nhm->nh_family != AF_UNSPEC) {
1561			NL_SET_ERR_MSG(extack, "Invalid family for group");
1562			goto out;
1563		}
1564		cfg->nh_grp = tb[NHA_GROUP];
1565
1566		cfg->nh_grp_type = NEXTHOP_GRP_TYPE_MPATH;
1567		if (tb[NHA_GROUP_TYPE])
1568			cfg->nh_grp_type = nla_get_u16(tb[NHA_GROUP_TYPE]);
1569
1570		if (cfg->nh_grp_type > NEXTHOP_GRP_TYPE_MAX) {
1571			NL_SET_ERR_MSG(extack, "Invalid group type");
1572			goto out;
1573		}
1574		err = nh_check_attr_group(net, tb, extack);
1575
1576		/* no other attributes should be set */
1577		goto out;
1578	}
1579
1580	if (tb[NHA_BLACKHOLE]) {
1581		if (tb[NHA_GATEWAY] || tb[NHA_OIF] ||
1582		    tb[NHA_ENCAP]   || tb[NHA_ENCAP_TYPE] || tb[NHA_FDB]) {
1583			NL_SET_ERR_MSG(extack, "Blackhole attribute can not be used with gateway, oif, encap or fdb");
1584			goto out;
1585		}
1586
1587		cfg->nh_blackhole = 1;
1588		err = 0;
1589		goto out;
1590	}
1591
1592	if (!cfg->nh_fdb && !tb[NHA_OIF]) {
1593		NL_SET_ERR_MSG(extack, "Device attribute required for non-blackhole and non-fdb nexthops");
1594		goto out;
1595	}
1596
1597	if (!cfg->nh_fdb && tb[NHA_OIF]) {
1598		cfg->nh_ifindex = nla_get_u32(tb[NHA_OIF]);
1599		if (cfg->nh_ifindex)
1600			cfg->dev = __dev_get_by_index(net, cfg->nh_ifindex);
1601
1602		if (!cfg->dev) {
1603			NL_SET_ERR_MSG(extack, "Invalid device index");
1604			goto out;
1605		} else if (!(cfg->dev->flags & IFF_UP)) {
1606			NL_SET_ERR_MSG(extack, "Nexthop device is not up");
1607			err = -ENETDOWN;
1608			goto out;
1609		} else if (!netif_carrier_ok(cfg->dev)) {
1610			NL_SET_ERR_MSG(extack, "Carrier for nexthop device is down");
1611			err = -ENETDOWN;
1612			goto out;
1613		}
1614	}
1615
1616	err = -EINVAL;
1617	if (tb[NHA_GATEWAY]) {
1618		struct nlattr *gwa = tb[NHA_GATEWAY];
1619
1620		switch (cfg->nh_family) {
1621		case AF_INET:
1622			if (nla_len(gwa) != sizeof(u32)) {
1623				NL_SET_ERR_MSG(extack, "Invalid gateway");
1624				goto out;
1625			}
1626			cfg->gw.ipv4 = nla_get_be32(gwa);
1627			break;
1628		case AF_INET6:
1629			if (nla_len(gwa) != sizeof(struct in6_addr)) {
1630				NL_SET_ERR_MSG(extack, "Invalid gateway");
1631				goto out;
1632			}
1633			cfg->gw.ipv6 = nla_get_in6_addr(gwa);
1634			break;
1635		default:
1636			NL_SET_ERR_MSG(extack,
1637				       "Unknown address family for gateway");
1638			goto out;
1639		}
1640	} else {
1641		/* device only nexthop (no gateway) */
1642		if (cfg->nh_flags & RTNH_F_ONLINK) {
1643			NL_SET_ERR_MSG(extack,
1644				       "ONLINK flag can not be set for nexthop without a gateway");
1645			goto out;
1646		}
1647	}
1648
1649	if (tb[NHA_ENCAP]) {
1650		cfg->nh_encap = tb[NHA_ENCAP];
1651
1652		if (!tb[NHA_ENCAP_TYPE]) {
1653			NL_SET_ERR_MSG(extack, "LWT encapsulation type is missing");
1654			goto out;
1655		}
1656
1657		cfg->nh_encap_type = nla_get_u16(tb[NHA_ENCAP_TYPE]);
1658		err = lwtunnel_valid_encap_type(cfg->nh_encap_type, extack);
1659		if (err < 0)
1660			goto out;
1661
1662	} else if (tb[NHA_ENCAP_TYPE]) {
1663		NL_SET_ERR_MSG(extack, "LWT encapsulation attribute is missing");
1664		goto out;
1665	}
1666
1667
1668	err = 0;
1669out:
1670	return err;
1671}
1672
1673/* rtnl */
1674static int rtm_new_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
1675			   struct netlink_ext_ack *extack)
1676{
1677	struct net *net = sock_net(skb->sk);
1678	struct nh_config cfg;
1679	struct nexthop *nh;
1680	int err;
1681
1682	err = rtm_to_nh_config(net, skb, nlh, &cfg, extack);
1683	if (!err) {
1684		nh = nexthop_add(net, &cfg, extack);
1685		if (IS_ERR(nh))
1686			err = PTR_ERR(nh);
1687	}
1688
1689	return err;
1690}
1691
1692static int nh_valid_get_del_req(struct nlmsghdr *nlh, u32 *id,
1693				struct netlink_ext_ack *extack)
1694{
1695	struct nhmsg *nhm = nlmsg_data(nlh);
1696	struct nlattr *tb[NHA_MAX + 1];
1697	int err, i;
1698
1699	err = nlmsg_parse(nlh, sizeof(*nhm), tb, NHA_MAX, rtm_nh_policy,
1700			  extack);
1701	if (err < 0)
1702		return err;
1703
1704	err = -EINVAL;
1705	for (i = 0; i < __NHA_MAX; ++i) {
1706		if (!tb[i])
1707			continue;
1708
1709		switch (i) {
1710		case NHA_ID:
1711			break;
1712		default:
1713			NL_SET_ERR_MSG_ATTR(extack, tb[i],
1714					    "Unexpected attribute in request");
1715			goto out;
1716		}
1717	}
1718	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
1719		NL_SET_ERR_MSG(extack, "Invalid values in header");
1720		goto out;
1721	}
1722
1723	if (!tb[NHA_ID]) {
1724		NL_SET_ERR_MSG(extack, "Nexthop id is missing");
1725		goto out;
1726	}
1727
1728	*id = nla_get_u32(tb[NHA_ID]);
1729	if (!(*id))
1730		NL_SET_ERR_MSG(extack, "Invalid nexthop id");
1731	else
1732		err = 0;
1733out:
1734	return err;
1735}
1736
1737/* rtnl */
1738static int rtm_del_nexthop(struct sk_buff *skb, struct nlmsghdr *nlh,
1739			   struct netlink_ext_ack *extack)
1740{
1741	struct net *net = sock_net(skb->sk);
1742	struct nl_info nlinfo = {
1743		.nlh = nlh,
1744		.nl_net = net,
1745		.portid = NETLINK_CB(skb).portid,
1746	};
1747	struct nexthop *nh;
1748	int err;
1749	u32 id;
1750
1751	err = nh_valid_get_del_req(nlh, &id, extack);
1752	if (err)
1753		return err;
1754
1755	nh = nexthop_find_by_id(net, id);
1756	if (!nh)
1757		return -ENOENT;
1758
1759	remove_nexthop(net, nh, &nlinfo);
1760
1761	return 0;
1762}
1763
1764/* rtnl */
1765static int rtm_get_nexthop(struct sk_buff *in_skb, struct nlmsghdr *nlh,
1766			   struct netlink_ext_ack *extack)
1767{
1768	struct net *net = sock_net(in_skb->sk);
1769	struct sk_buff *skb = NULL;
1770	struct nexthop *nh;
1771	int err;
1772	u32 id;
1773
1774	err = nh_valid_get_del_req(nlh, &id, extack);
1775	if (err)
1776		return err;
1777
1778	err = -ENOBUFS;
1779	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
1780	if (!skb)
1781		goto out;
1782
1783	err = -ENOENT;
1784	nh = nexthop_find_by_id(net, id);
1785	if (!nh)
1786		goto errout_free;
1787
1788	err = nh_fill_node(skb, nh, RTM_NEWNEXTHOP, NETLINK_CB(in_skb).portid,
1789			   nlh->nlmsg_seq, 0);
1790	if (err < 0) {
1791		WARN_ON(err == -EMSGSIZE);
1792		goto errout_free;
1793	}
1794
1795	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
1796out:
1797	return err;
1798errout_free:
1799	kfree_skb(skb);
1800	goto out;
1801}
1802
1803static bool nh_dump_filtered(struct nexthop *nh, int dev_idx, int master_idx,
1804			     bool group_filter, u8 family)
1805{
1806	const struct net_device *dev;
1807	const struct nh_info *nhi;
1808
1809	if (group_filter && !nh->is_group)
1810		return true;
1811
1812	if (!dev_idx && !master_idx && !family)
1813		return false;
1814
1815	if (nh->is_group)
1816		return true;
1817
1818	nhi = rtnl_dereference(nh->nh_info);
1819	if (family && nhi->family != family)
1820		return true;
1821
1822	dev = nhi->fib_nhc.nhc_dev;
1823	if (dev_idx && (!dev || dev->ifindex != dev_idx))
1824		return true;
1825
1826	if (master_idx) {
1827		struct net_device *master;
1828
1829		if (!dev)
1830			return true;
1831
1832		master = netdev_master_upper_dev_get((struct net_device *)dev);
1833		if (!master || master->ifindex != master_idx)
1834			return true;
1835	}
1836
1837	return false;
1838}
1839
1840static int nh_valid_dump_req(const struct nlmsghdr *nlh, int *dev_idx,
1841			     int *master_idx, bool *group_filter,
1842			     bool *fdb_filter, struct netlink_callback *cb)
1843{
1844	struct netlink_ext_ack *extack = cb->extack;
1845	struct nlattr *tb[NHA_MAX + 1];
1846	struct nhmsg *nhm;
1847	int err, i;
1848	u32 idx;
1849
1850	err = nlmsg_parse(nlh, sizeof(*nhm), tb, NHA_MAX, rtm_nh_policy,
1851			  NULL);
1852	if (err < 0)
1853		return err;
1854
1855	for (i = 0; i <= NHA_MAX; ++i) {
1856		if (!tb[i])
1857			continue;
1858
1859		switch (i) {
1860		case NHA_OIF:
1861			idx = nla_get_u32(tb[i]);
1862			if (idx > INT_MAX) {
1863				NL_SET_ERR_MSG(extack, "Invalid device index");
1864				return -EINVAL;
1865			}
1866			*dev_idx = idx;
1867			break;
1868		case NHA_MASTER:
1869			idx = nla_get_u32(tb[i]);
1870			if (idx > INT_MAX) {
1871				NL_SET_ERR_MSG(extack, "Invalid master device index");
1872				return -EINVAL;
1873			}
1874			*master_idx = idx;
1875			break;
1876		case NHA_GROUPS:
1877			*group_filter = true;
1878			break;
1879		case NHA_FDB:
1880			*fdb_filter = true;
1881			break;
1882		default:
1883			NL_SET_ERR_MSG(extack, "Unsupported attribute in dump request");
1884			return -EINVAL;
1885		}
1886	}
1887
1888	nhm = nlmsg_data(nlh);
1889	if (nhm->nh_protocol || nhm->resvd || nhm->nh_scope || nhm->nh_flags) {
1890		NL_SET_ERR_MSG(extack, "Invalid values in header for nexthop dump request");
1891		return -EINVAL;
1892	}
1893
1894	return 0;
1895}
1896
1897/* rtnl */
1898static int rtm_dump_nexthop(struct sk_buff *skb, struct netlink_callback *cb)
1899{
1900	bool group_filter = false, fdb_filter = false;
1901	struct nhmsg *nhm = nlmsg_data(cb->nlh);
1902	int dev_filter_idx = 0, master_idx = 0;
1903	struct net *net = sock_net(skb->sk);
1904	struct rb_root *root = &net->nexthop.rb_root;
1905	struct rb_node *node;
1906	int idx = 0, s_idx;
1907	int err;
1908
1909	err = nh_valid_dump_req(cb->nlh, &dev_filter_idx, &master_idx,
1910				&group_filter, &fdb_filter, cb);
1911	if (err < 0)
1912		return err;
1913
1914	s_idx = cb->args[0];
1915	for (node = rb_first(root); node; node = rb_next(node)) {
1916		struct nexthop *nh;
1917
1918		if (idx < s_idx)
1919			goto cont;
1920
1921		nh = rb_entry(node, struct nexthop, rb_node);
1922		if (nh_dump_filtered(nh, dev_filter_idx, master_idx,
1923				     group_filter, nhm->nh_family))
1924			goto cont;
1925
1926		err = nh_fill_node(skb, nh, RTM_NEWNEXTHOP,
1927				   NETLINK_CB(cb->skb).portid,
1928				   cb->nlh->nlmsg_seq, NLM_F_MULTI);
1929		if (err < 0) {
1930			if (likely(skb->len))
1931				goto out;
1932
1933			goto out_err;
1934		}
1935cont:
1936		idx++;
1937	}
1938
1939out:
1940	err = skb->len;
1941out_err:
1942	cb->args[0] = idx;
1943	cb->seq = net->nexthop.seq;
1944	nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1945
1946	return err;
1947}
1948
1949static void nexthop_sync_mtu(struct net_device *dev, u32 orig_mtu)
1950{
1951	unsigned int hash = nh_dev_hashfn(dev->ifindex);
1952	struct net *net = dev_net(dev);
1953	struct hlist_head *head = &net->nexthop.devhash[hash];
1954	struct hlist_node *n;
1955	struct nh_info *nhi;
1956
1957	hlist_for_each_entry_safe(nhi, n, head, dev_hash) {
1958		if (nhi->fib_nhc.nhc_dev == dev) {
1959			if (nhi->family == AF_INET)
1960				fib_nhc_update_mtu(&nhi->fib_nhc, dev->mtu,
1961						   orig_mtu);
1962		}
1963	}
1964}
1965
1966/* rtnl */
1967static int nh_netdev_event(struct notifier_block *this,
1968			   unsigned long event, void *ptr)
1969{
1970	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1971	struct netdev_notifier_info_ext *info_ext;
1972
1973	switch (event) {
1974	case NETDEV_DOWN:
1975	case NETDEV_UNREGISTER:
1976		nexthop_flush_dev(dev, event);
1977		break;
1978	case NETDEV_CHANGE:
1979		if (!(dev_get_flags(dev) & (IFF_RUNNING | IFF_LOWER_UP)))
1980			nexthop_flush_dev(dev, event);
1981		break;
1982	case NETDEV_CHANGEMTU:
1983		info_ext = ptr;
1984		nexthop_sync_mtu(dev, info_ext->ext.mtu);
1985		rt_cache_flush(dev_net(dev));
1986		break;
1987	}
1988	return NOTIFY_DONE;
1989}
1990
1991static struct notifier_block nh_netdev_notifier = {
1992	.notifier_call = nh_netdev_event,
1993};
1994
1995int register_nexthop_notifier(struct net *net, struct notifier_block *nb)
1996{
1997	return blocking_notifier_chain_register(&net->nexthop.notifier_chain,
1998						nb);
1999}
2000EXPORT_SYMBOL(register_nexthop_notifier);
2001
2002int unregister_nexthop_notifier(struct net *net, struct notifier_block *nb)
2003{
2004	return blocking_notifier_chain_unregister(&net->nexthop.notifier_chain,
2005						  nb);
2006}
2007EXPORT_SYMBOL(unregister_nexthop_notifier);
2008
2009static void __net_exit nexthop_net_exit(struct net *net)
2010{
2011	rtnl_lock();
2012	flush_all_nexthops(net);
2013	rtnl_unlock();
2014	kfree(net->nexthop.devhash);
2015}
2016
2017static int __net_init nexthop_net_init(struct net *net)
2018{
2019	size_t sz = sizeof(struct hlist_head) * NH_DEV_HASHSIZE;
2020
2021	net->nexthop.rb_root = RB_ROOT;
2022	net->nexthop.devhash = kzalloc(sz, GFP_KERNEL);
2023	if (!net->nexthop.devhash)
2024		return -ENOMEM;
2025	BLOCKING_INIT_NOTIFIER_HEAD(&net->nexthop.notifier_chain);
2026
2027	return 0;
2028}
2029
2030static struct pernet_operations nexthop_net_ops = {
2031	.init = nexthop_net_init,
2032	.exit = nexthop_net_exit,
2033};
2034
2035static int __init nexthop_init(void)
2036{
2037	register_pernet_subsys(&nexthop_net_ops);
2038
2039	register_netdevice_notifier(&nh_netdev_notifier);
2040
2041	rtnl_register(PF_UNSPEC, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
2042	rtnl_register(PF_UNSPEC, RTM_DELNEXTHOP, rtm_del_nexthop, NULL, 0);
2043	rtnl_register(PF_UNSPEC, RTM_GETNEXTHOP, rtm_get_nexthop,
2044		      rtm_dump_nexthop, 0);
2045
2046	rtnl_register(PF_INET, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
2047	rtnl_register(PF_INET, RTM_GETNEXTHOP, NULL, rtm_dump_nexthop, 0);
2048
2049	rtnl_register(PF_INET6, RTM_NEWNEXTHOP, rtm_new_nexthop, NULL, 0);
2050	rtnl_register(PF_INET6, RTM_GETNEXTHOP, NULL, rtm_dump_nexthop, 0);
2051
2052	return 0;
2053}
2054subsys_initcall(nexthop_init);
2055