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