xref: /linux/net/ipv6/route.c (revision 3186a8e55ae3428ec1e06af09075e20885376e4e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	Linux INET6 implementation
4  *	FIB front-end.
5  *
6  *	Authors:
7  *	Pedro Roque		<roque@di.fc.ul.pt>
8  */
9 
10 /*	Changes:
11  *
12  *	YOSHIFUJI Hideaki @USAGI
13  *		reworked default router selection.
14  *		- respect outgoing interface
15  *		- select from (probably) reachable routers (i.e.
16  *		routers in REACHABLE, STALE, DELAY or PROBE states).
17  *		- always select the same router if it is (probably)
18  *		reachable.  otherwise, round-robin the list.
19  *	Ville Nuorvala
20  *		Fixed routing subtrees.
21  */
22 
23 #define pr_fmt(fmt) "IPv6: " fmt
24 
25 #include <linux/capability.h>
26 #include <linux/errno.h>
27 #include <linux/export.h>
28 #include <linux/types.h>
29 #include <linux/times.h>
30 #include <linux/socket.h>
31 #include <linux/sockios.h>
32 #include <linux/net.h>
33 #include <linux/route.h>
34 #include <linux/netdevice.h>
35 #include <linux/in6.h>
36 #include <linux/mroute6.h>
37 #include <linux/init.h>
38 #include <linux/if_arp.h>
39 #include <linux/proc_fs.h>
40 #include <linux/seq_file.h>
41 #include <linux/nsproxy.h>
42 #include <linux/slab.h>
43 #include <linux/jhash.h>
44 #include <linux/siphash.h>
45 #include <net/net_namespace.h>
46 #include <net/snmp.h>
47 #include <net/ipv6.h>
48 #include <net/ip6_fib.h>
49 #include <net/ip6_route.h>
50 #include <net/ndisc.h>
51 #include <net/addrconf.h>
52 #include <net/tcp.h>
53 #include <linux/rtnetlink.h>
54 #include <net/dst.h>
55 #include <net/dst_metadata.h>
56 #include <net/xfrm.h>
57 #include <net/netevent.h>
58 #include <net/netlink.h>
59 #include <net/rtnh.h>
60 #include <net/lwtunnel.h>
61 #include <net/ip_tunnels.h>
62 #include <net/l3mdev.h>
63 #include <net/ip.h>
64 #include <linux/uaccess.h>
65 #include <linux/btf_ids.h>
66 
67 #ifdef CONFIG_SYSCTL
68 #include <linux/sysctl.h>
69 #endif
70 
71 static int ip6_rt_type_to_error(u8 fib6_type);
72 
73 #define CREATE_TRACE_POINTS
74 #include <trace/events/fib6.h>
75 EXPORT_TRACEPOINT_SYMBOL_GPL(fib6_table_lookup);
76 #undef CREATE_TRACE_POINTS
77 
78 enum rt6_nud_state {
79 	RT6_NUD_FAIL_HARD = -3,
80 	RT6_NUD_FAIL_PROBE = -2,
81 	RT6_NUD_FAIL_DO_RR = -1,
82 	RT6_NUD_SUCCEED = 1
83 };
84 
85 INDIRECT_CALLABLE_SCOPE
86 struct dst_entry	*ip6_dst_check(struct dst_entry *dst, u32 cookie);
87 static unsigned int	 ip6_default_advmss(const struct dst_entry *dst);
88 INDIRECT_CALLABLE_SCOPE
89 unsigned int		ip6_mtu(const struct dst_entry *dst);
90 static void		ip6_negative_advice(struct sock *sk,
91 					    struct dst_entry *dst);
92 static void		ip6_dst_destroy(struct dst_entry *);
93 static void		ip6_dst_ifdown(struct dst_entry *,
94 				       struct net_device *dev);
95 static void		 ip6_dst_gc(struct dst_ops *ops);
96 
97 static int		ip6_pkt_discard(struct sk_buff *skb);
98 static int		ip6_pkt_discard_out(struct net *net, struct sock *sk, struct sk_buff *skb);
99 static int		ip6_pkt_prohibit(struct sk_buff *skb);
100 static int		ip6_pkt_prohibit_out(struct net *net, struct sock *sk, struct sk_buff *skb);
101 static void		ip6_link_failure(struct sk_buff *skb);
102 static void		ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
103 					   struct sk_buff *skb, u32 mtu,
104 					   bool confirm_neigh);
105 static void		rt6_do_redirect(struct dst_entry *dst, struct sock *sk,
106 					struct sk_buff *skb);
107 static int rt6_score_route(const struct fib6_nh *nh, u32 fib6_flags, int oif,
108 			   int strict);
109 static size_t rt6_nlmsg_size(struct fib6_info *f6i);
110 static int rt6_fill_node(struct net *net, struct sk_buff *skb,
111 			 struct fib6_info *rt, struct dst_entry *dst,
112 			 struct in6_addr *dest, struct in6_addr *src,
113 			 int iif, int type, u32 portid, u32 seq,
114 			 unsigned int flags);
115 static struct rt6_info *rt6_find_cached_rt(const struct fib6_result *res,
116 					   const struct in6_addr *daddr,
117 					   const struct in6_addr *saddr);
118 
119 #ifdef CONFIG_IPV6_ROUTE_INFO
120 static struct fib6_info *rt6_add_route_info(struct net *net,
121 					   const struct in6_addr *prefix, int prefixlen,
122 					   const struct in6_addr *gwaddr,
123 					   struct net_device *dev,
124 					   unsigned int pref);
125 static struct fib6_info *rt6_get_route_info(struct net *net,
126 					   const struct in6_addr *prefix, int prefixlen,
127 					   const struct in6_addr *gwaddr,
128 					   struct net_device *dev);
129 #endif
130 
131 struct uncached_list {
132 	spinlock_t		lock;
133 	struct list_head	head;
134 };
135 
136 static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt6_uncached_list);
137 
138 void rt6_uncached_list_add(struct rt6_info *rt)
139 {
140 	struct uncached_list *ul = raw_cpu_ptr(&rt6_uncached_list);
141 
142 	rt->dst.rt_uncached_list = ul;
143 
144 	spin_lock_bh(&ul->lock);
145 	list_add_tail(&rt->dst.rt_uncached, &ul->head);
146 	spin_unlock_bh(&ul->lock);
147 }
148 
149 void rt6_uncached_list_del(struct rt6_info *rt)
150 {
151 	if (!list_empty(&rt->dst.rt_uncached)) {
152 		struct uncached_list *ul = rt->dst.rt_uncached_list;
153 
154 		spin_lock_bh(&ul->lock);
155 		list_del_init(&rt->dst.rt_uncached);
156 		spin_unlock_bh(&ul->lock);
157 	}
158 }
159 
160 static void rt6_uncached_list_flush_dev(struct net_device *dev)
161 {
162 	int cpu;
163 
164 	for_each_possible_cpu(cpu) {
165 		struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu);
166 		struct rt6_info *rt, *safe;
167 
168 		if (list_empty(&ul->head))
169 			continue;
170 
171 		spin_lock_bh(&ul->lock);
172 		list_for_each_entry_safe(rt, safe, &ul->head, dst.rt_uncached) {
173 			struct inet6_dev *rt_idev = rt->rt6i_idev;
174 			struct net_device *rt_dev = rt->dst.dev;
175 			bool handled = false;
176 
177 			if (rt_idev && rt_idev->dev == dev) {
178 				rt->rt6i_idev = in6_dev_get(blackhole_netdev);
179 				in6_dev_put(rt_idev);
180 				handled = true;
181 			}
182 
183 			if (rt_dev == dev) {
184 				rt->dst.dev = blackhole_netdev;
185 				netdev_ref_replace(rt_dev, blackhole_netdev,
186 						   &rt->dst.dev_tracker,
187 						   GFP_ATOMIC);
188 				handled = true;
189 			}
190 			if (handled)
191 				list_del_init(&rt->dst.rt_uncached);
192 		}
193 		spin_unlock_bh(&ul->lock);
194 	}
195 }
196 
197 static inline const void *choose_neigh_daddr(const struct in6_addr *p,
198 					     struct sk_buff *skb,
199 					     const void *daddr)
200 {
201 	if (!ipv6_addr_any(p))
202 		return (const void *) p;
203 	else if (skb)
204 		return &ipv6_hdr(skb)->daddr;
205 	return daddr;
206 }
207 
208 struct neighbour *ip6_neigh_lookup(const struct in6_addr *gw,
209 				   struct net_device *dev,
210 				   struct sk_buff *skb,
211 				   const void *daddr)
212 {
213 	struct neighbour *n;
214 
215 	daddr = choose_neigh_daddr(gw, skb, daddr);
216 	n = __ipv6_neigh_lookup(dev, daddr);
217 	if (n)
218 		return n;
219 
220 	n = neigh_create(&nd_tbl, daddr, dev);
221 	return IS_ERR(n) ? NULL : n;
222 }
223 
224 static struct neighbour *ip6_dst_neigh_lookup(const struct dst_entry *dst,
225 					      struct sk_buff *skb,
226 					      const void *daddr)
227 {
228 	const struct rt6_info *rt = dst_rt6_info(dst);
229 
230 	return ip6_neigh_lookup(rt6_nexthop(rt, &in6addr_any),
231 				dst->dev, skb, daddr);
232 }
233 
234 static void ip6_confirm_neigh(const struct dst_entry *dst, const void *daddr)
235 {
236 	const struct rt6_info *rt = dst_rt6_info(dst);
237 	struct net_device *dev = dst->dev;
238 
239 	daddr = choose_neigh_daddr(rt6_nexthop(rt, &in6addr_any), NULL, daddr);
240 	if (!daddr)
241 		return;
242 	if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
243 		return;
244 	if (ipv6_addr_is_multicast((const struct in6_addr *)daddr))
245 		return;
246 	__ipv6_confirm_neigh(dev, daddr);
247 }
248 
249 static struct dst_ops ip6_dst_ops_template = {
250 	.family			=	AF_INET6,
251 	.gc			=	ip6_dst_gc,
252 	.gc_thresh		=	1024,
253 	.check			=	ip6_dst_check,
254 	.default_advmss		=	ip6_default_advmss,
255 	.mtu			=	ip6_mtu,
256 	.cow_metrics		=	dst_cow_metrics_generic,
257 	.destroy		=	ip6_dst_destroy,
258 	.ifdown			=	ip6_dst_ifdown,
259 	.negative_advice	=	ip6_negative_advice,
260 	.link_failure		=	ip6_link_failure,
261 	.update_pmtu		=	ip6_rt_update_pmtu,
262 	.redirect		=	rt6_do_redirect,
263 	.local_out		=	__ip6_local_out,
264 	.neigh_lookup		=	ip6_dst_neigh_lookup,
265 	.confirm_neigh		=	ip6_confirm_neigh,
266 };
267 
268 static struct dst_ops ip6_dst_blackhole_ops = {
269 	.family			= AF_INET6,
270 	.default_advmss		= ip6_default_advmss,
271 	.neigh_lookup		= ip6_dst_neigh_lookup,
272 	.check			= ip6_dst_check,
273 	.destroy		= ip6_dst_destroy,
274 	.cow_metrics		= dst_cow_metrics_generic,
275 	.update_pmtu		= dst_blackhole_update_pmtu,
276 	.redirect		= dst_blackhole_redirect,
277 	.mtu			= dst_blackhole_mtu,
278 };
279 
280 static const u32 ip6_template_metrics[RTAX_MAX] = {
281 	[RTAX_HOPLIMIT - 1] = 0,
282 };
283 
284 static const struct fib6_info fib6_null_entry_template = {
285 	.fib6_flags	= (RTF_REJECT | RTF_NONEXTHOP),
286 	.fib6_protocol  = RTPROT_KERNEL,
287 	.fib6_metric	= ~(u32)0,
288 	.fib6_ref	= REFCOUNT_INIT(1),
289 	.fib6_type	= RTN_UNREACHABLE,
290 	.fib6_metrics	= (struct dst_metrics *)&dst_default_metrics,
291 };
292 
293 static const struct rt6_info ip6_null_entry_template = {
294 	.dst = {
295 		.__rcuref	= RCUREF_INIT(1),
296 		.__use		= 1,
297 		.obsolete	= DST_OBSOLETE_FORCE_CHK,
298 		.error		= -ENETUNREACH,
299 		.input		= ip6_pkt_discard,
300 		.output		= ip6_pkt_discard_out,
301 	},
302 	.rt6i_flags	= (RTF_REJECT | RTF_NONEXTHOP),
303 };
304 
305 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
306 
307 static const struct rt6_info ip6_prohibit_entry_template = {
308 	.dst = {
309 		.__rcuref	= RCUREF_INIT(1),
310 		.__use		= 1,
311 		.obsolete	= DST_OBSOLETE_FORCE_CHK,
312 		.error		= -EACCES,
313 		.input		= ip6_pkt_prohibit,
314 		.output		= ip6_pkt_prohibit_out,
315 	},
316 	.rt6i_flags	= (RTF_REJECT | RTF_NONEXTHOP),
317 };
318 
319 static const struct rt6_info ip6_blk_hole_entry_template = {
320 	.dst = {
321 		.__rcuref	= RCUREF_INIT(1),
322 		.__use		= 1,
323 		.obsolete	= DST_OBSOLETE_FORCE_CHK,
324 		.error		= -EINVAL,
325 		.input		= dst_discard,
326 		.output		= dst_discard_out,
327 	},
328 	.rt6i_flags	= (RTF_REJECT | RTF_NONEXTHOP),
329 };
330 
331 #endif
332 
333 static void rt6_info_init(struct rt6_info *rt)
334 {
335 	memset_after(rt, 0, dst);
336 }
337 
338 /* allocate dst with ip6_dst_ops */
339 struct rt6_info *ip6_dst_alloc(struct net *net, struct net_device *dev,
340 			       int flags)
341 {
342 	struct rt6_info *rt = dst_alloc(&net->ipv6.ip6_dst_ops, dev,
343 					DST_OBSOLETE_FORCE_CHK, flags);
344 
345 	if (rt) {
346 		rt6_info_init(rt);
347 		atomic_inc(&net->ipv6.rt6_stats->fib_rt_alloc);
348 	}
349 
350 	return rt;
351 }
352 EXPORT_SYMBOL(ip6_dst_alloc);
353 
354 static void ip6_dst_destroy(struct dst_entry *dst)
355 {
356 	struct rt6_info *rt = dst_rt6_info(dst);
357 	struct fib6_info *from;
358 	struct inet6_dev *idev;
359 
360 	ip_dst_metrics_put(dst);
361 	rt6_uncached_list_del(rt);
362 
363 	idev = rt->rt6i_idev;
364 	if (idev) {
365 		rt->rt6i_idev = NULL;
366 		in6_dev_put(idev);
367 	}
368 
369 	from = unrcu_pointer(xchg(&rt->from, NULL));
370 	fib6_info_release(from);
371 }
372 
373 static void ip6_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
374 {
375 	struct rt6_info *rt = dst_rt6_info(dst);
376 	struct inet6_dev *idev = rt->rt6i_idev;
377 	struct fib6_info *from;
378 
379 	if (idev && idev->dev != blackhole_netdev) {
380 		struct inet6_dev *blackhole_idev = in6_dev_get(blackhole_netdev);
381 
382 		if (blackhole_idev) {
383 			rt->rt6i_idev = blackhole_idev;
384 			in6_dev_put(idev);
385 		}
386 	}
387 	from = unrcu_pointer(xchg(&rt->from, NULL));
388 	fib6_info_release(from);
389 }
390 
391 static bool __rt6_check_expired(const struct rt6_info *rt)
392 {
393 	if (rt->rt6i_flags & RTF_EXPIRES)
394 		return time_after(jiffies, rt->dst.expires);
395 	else
396 		return false;
397 }
398 
399 static bool rt6_check_expired(const struct rt6_info *rt)
400 {
401 	struct fib6_info *from;
402 
403 	from = rcu_dereference(rt->from);
404 
405 	if (rt->rt6i_flags & RTF_EXPIRES) {
406 		if (time_after(jiffies, rt->dst.expires))
407 			return true;
408 	} else if (from) {
409 		return rt->dst.obsolete != DST_OBSOLETE_FORCE_CHK ||
410 			fib6_check_expired(from);
411 	}
412 	return false;
413 }
414 
415 static struct fib6_info *
416 rt6_multipath_first_sibling_rcu(const struct fib6_info *rt)
417 {
418 	struct fib6_info *iter;
419 	struct fib6_node *fn;
420 
421 	fn = rcu_dereference(rt->fib6_node);
422 	if (!fn)
423 		goto out;
424 	iter = rcu_dereference(fn->leaf);
425 	if (!iter)
426 		goto out;
427 
428 	while (iter) {
429 		if (iter->fib6_metric == rt->fib6_metric &&
430 		    rt6_qualify_for_ecmp(iter))
431 			return iter;
432 		iter = rcu_dereference(iter->fib6_next);
433 	}
434 
435 out:
436 	return NULL;
437 }
438 
439 void fib6_select_path(const struct net *net, struct fib6_result *res,
440 		      struct flowi6 *fl6, int oif, bool have_oif_match,
441 		      const struct sk_buff *skb, int strict)
442 {
443 	struct fib6_info *first, *match = res->f6i;
444 	struct fib6_info *sibling;
445 	int hash;
446 
447 	if (!match->nh && (!match->fib6_nsiblings || have_oif_match))
448 		goto out;
449 
450 	if (match->nh && have_oif_match && res->nh)
451 		return;
452 
453 	if (skb)
454 		IP6CB(skb)->flags |= IP6SKB_MULTIPATH;
455 
456 	/* We might have already computed the hash for ICMPv6 errors. In such
457 	 * case it will always be non-zero. Otherwise now is the time to do it.
458 	 */
459 	if (!fl6->mp_hash &&
460 	    (!match->nh || nexthop_is_multipath(match->nh)))
461 		fl6->mp_hash = rt6_multipath_hash(net, fl6, skb, NULL);
462 
463 	if (unlikely(match->nh)) {
464 		nexthop_path_fib6_result(res, fl6->mp_hash);
465 		return;
466 	}
467 
468 	first = rt6_multipath_first_sibling_rcu(match);
469 	if (!first)
470 		goto out;
471 
472 	hash = fl6->mp_hash;
473 	if (hash <= atomic_read(&first->fib6_nh->fib_nh_upper_bound)) {
474 		if (rt6_score_route(first->fib6_nh, first->fib6_flags, oif,
475 				    strict) >= 0)
476 			match = first;
477 		goto out;
478 	}
479 
480 	list_for_each_entry_rcu(sibling, &first->fib6_siblings,
481 				fib6_siblings) {
482 		const struct fib6_nh *nh = sibling->fib6_nh;
483 		int nh_upper_bound;
484 
485 		nh_upper_bound = atomic_read(&nh->fib_nh_upper_bound);
486 		if (hash > nh_upper_bound)
487 			continue;
488 		if (rt6_score_route(nh, sibling->fib6_flags, oif, strict) < 0)
489 			break;
490 		match = sibling;
491 		break;
492 	}
493 
494 out:
495 	res->f6i = match;
496 	res->nh = match->fib6_nh;
497 }
498 
499 /*
500  *	Route lookup. rcu_read_lock() should be held.
501  */
502 
503 static bool __rt6_device_match(struct net *net, const struct fib6_nh *nh,
504 			       const struct in6_addr *saddr, int oif, int flags)
505 {
506 	const struct net_device *dev;
507 
508 	if (nh->fib_nh_flags & RTNH_F_DEAD)
509 		return false;
510 
511 	dev = nh->fib_nh_dev;
512 	if (oif) {
513 		if (dev->ifindex == oif)
514 			return true;
515 	} else {
516 		if (ipv6_chk_addr(net, saddr, dev,
517 				  flags & RT6_LOOKUP_F_IFACE))
518 			return true;
519 	}
520 
521 	return false;
522 }
523 
524 struct fib6_nh_dm_arg {
525 	struct net		*net;
526 	const struct in6_addr	*saddr;
527 	int			oif;
528 	int			flags;
529 	struct fib6_nh		*nh;
530 };
531 
532 static int __rt6_nh_dev_match(struct fib6_nh *nh, void *_arg)
533 {
534 	struct fib6_nh_dm_arg *arg = _arg;
535 
536 	arg->nh = nh;
537 	return __rt6_device_match(arg->net, nh, arg->saddr, arg->oif,
538 				  arg->flags);
539 }
540 
541 /* returns fib6_nh from nexthop or NULL */
542 static struct fib6_nh *rt6_nh_dev_match(struct net *net, struct nexthop *nh,
543 					struct fib6_result *res,
544 					const struct in6_addr *saddr,
545 					int oif, int flags)
546 {
547 	struct fib6_nh_dm_arg arg = {
548 		.net   = net,
549 		.saddr = saddr,
550 		.oif   = oif,
551 		.flags = flags,
552 	};
553 
554 	if (nexthop_is_blackhole(nh))
555 		return NULL;
556 
557 	if (nexthop_for_each_fib6_nh(nh, __rt6_nh_dev_match, &arg))
558 		return arg.nh;
559 
560 	return NULL;
561 }
562 
563 static void rt6_device_match(struct net *net, struct fib6_result *res,
564 			     const struct in6_addr *saddr, int oif, int flags)
565 {
566 	struct fib6_info *f6i = res->f6i;
567 	struct fib6_info *spf6i;
568 	struct fib6_nh *nh;
569 
570 	if (!oif && ipv6_addr_any(saddr)) {
571 		if (unlikely(f6i->nh)) {
572 			nh = nexthop_fib6_nh(f6i->nh);
573 			if (nexthop_is_blackhole(f6i->nh))
574 				goto out_blackhole;
575 		} else {
576 			nh = f6i->fib6_nh;
577 		}
578 		if (!(nh->fib_nh_flags & RTNH_F_DEAD))
579 			goto out;
580 	}
581 
582 	for (spf6i = f6i; spf6i; spf6i = rcu_dereference(spf6i->fib6_next)) {
583 		bool matched = false;
584 
585 		if (unlikely(spf6i->nh)) {
586 			nh = rt6_nh_dev_match(net, spf6i->nh, res, saddr,
587 					      oif, flags);
588 			if (nh)
589 				matched = true;
590 		} else {
591 			nh = spf6i->fib6_nh;
592 			if (__rt6_device_match(net, nh, saddr, oif, flags))
593 				matched = true;
594 		}
595 		if (matched) {
596 			res->f6i = spf6i;
597 			goto out;
598 		}
599 	}
600 
601 	if (oif && flags & RT6_LOOKUP_F_IFACE) {
602 		res->f6i = net->ipv6.fib6_null_entry;
603 		nh = res->f6i->fib6_nh;
604 		goto out;
605 	}
606 
607 	if (unlikely(f6i->nh)) {
608 		nh = nexthop_fib6_nh(f6i->nh);
609 		if (nexthop_is_blackhole(f6i->nh))
610 			goto out_blackhole;
611 	} else {
612 		nh = f6i->fib6_nh;
613 	}
614 
615 	if (nh->fib_nh_flags & RTNH_F_DEAD) {
616 		res->f6i = net->ipv6.fib6_null_entry;
617 		nh = res->f6i->fib6_nh;
618 	}
619 out:
620 	res->nh = nh;
621 	res->fib6_type = res->f6i->fib6_type;
622 	res->fib6_flags = res->f6i->fib6_flags;
623 	return;
624 
625 out_blackhole:
626 	res->fib6_flags |= RTF_REJECT;
627 	res->fib6_type = RTN_BLACKHOLE;
628 	res->nh = nh;
629 }
630 
631 #ifdef CONFIG_IPV6_ROUTER_PREF
632 struct __rt6_probe_work {
633 	struct work_struct work;
634 	struct in6_addr target;
635 	struct net_device *dev;
636 	netdevice_tracker dev_tracker;
637 };
638 
639 static void rt6_probe_deferred(struct work_struct *w)
640 {
641 	struct in6_addr mcaddr;
642 	struct __rt6_probe_work *work =
643 		container_of(w, struct __rt6_probe_work, work);
644 
645 	addrconf_addr_solict_mult(&work->target, &mcaddr);
646 	ndisc_send_ns(work->dev, &work->target, &mcaddr, NULL, 0);
647 	netdev_put(work->dev, &work->dev_tracker);
648 	kfree(work);
649 }
650 
651 static void rt6_probe(struct fib6_nh *fib6_nh)
652 {
653 	struct __rt6_probe_work *work = NULL;
654 	const struct in6_addr *nh_gw;
655 	unsigned long last_probe;
656 	struct neighbour *neigh;
657 	struct net_device *dev;
658 	struct inet6_dev *idev;
659 
660 	/*
661 	 * Okay, this does not seem to be appropriate
662 	 * for now, however, we need to check if it
663 	 * is really so; aka Router Reachability Probing.
664 	 *
665 	 * Router Reachability Probe MUST be rate-limited
666 	 * to no more than one per minute.
667 	 */
668 	if (!fib6_nh->fib_nh_gw_family)
669 		return;
670 
671 	nh_gw = &fib6_nh->fib_nh_gw6;
672 	dev = fib6_nh->fib_nh_dev;
673 	rcu_read_lock();
674 	last_probe = READ_ONCE(fib6_nh->last_probe);
675 	idev = __in6_dev_get(dev);
676 	if (!idev)
677 		goto out;
678 	neigh = __ipv6_neigh_lookup_noref(dev, nh_gw);
679 	if (neigh) {
680 		if (READ_ONCE(neigh->nud_state) & NUD_VALID)
681 			goto out;
682 
683 		write_lock_bh(&neigh->lock);
684 		if (!(neigh->nud_state & NUD_VALID) &&
685 		    time_after(jiffies,
686 			       neigh->updated +
687 			       READ_ONCE(idev->cnf.rtr_probe_interval))) {
688 			work = kmalloc(sizeof(*work), GFP_ATOMIC);
689 			if (work)
690 				__neigh_set_probe_once(neigh);
691 		}
692 		write_unlock_bh(&neigh->lock);
693 	} else if (time_after(jiffies, last_probe +
694 				       READ_ONCE(idev->cnf.rtr_probe_interval))) {
695 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
696 	}
697 
698 	if (!work || cmpxchg(&fib6_nh->last_probe,
699 			     last_probe, jiffies) != last_probe) {
700 		kfree(work);
701 	} else {
702 		INIT_WORK(&work->work, rt6_probe_deferred);
703 		work->target = *nh_gw;
704 		netdev_hold(dev, &work->dev_tracker, GFP_ATOMIC);
705 		work->dev = dev;
706 		schedule_work(&work->work);
707 	}
708 
709 out:
710 	rcu_read_unlock();
711 }
712 #else
713 static inline void rt6_probe(struct fib6_nh *fib6_nh)
714 {
715 }
716 #endif
717 
718 /*
719  * Default Router Selection (RFC 2461 6.3.6)
720  */
721 static enum rt6_nud_state rt6_check_neigh(const struct fib6_nh *fib6_nh)
722 {
723 	enum rt6_nud_state ret = RT6_NUD_FAIL_HARD;
724 	struct neighbour *neigh;
725 
726 	rcu_read_lock();
727 	neigh = __ipv6_neigh_lookup_noref(fib6_nh->fib_nh_dev,
728 					  &fib6_nh->fib_nh_gw6);
729 	if (neigh) {
730 		u8 nud_state = READ_ONCE(neigh->nud_state);
731 
732 		if (nud_state & NUD_VALID)
733 			ret = RT6_NUD_SUCCEED;
734 #ifdef CONFIG_IPV6_ROUTER_PREF
735 		else if (!(nud_state & NUD_FAILED))
736 			ret = RT6_NUD_SUCCEED;
737 		else
738 			ret = RT6_NUD_FAIL_PROBE;
739 #endif
740 	} else {
741 		ret = IS_ENABLED(CONFIG_IPV6_ROUTER_PREF) ?
742 		      RT6_NUD_SUCCEED : RT6_NUD_FAIL_DO_RR;
743 	}
744 	rcu_read_unlock();
745 
746 	return ret;
747 }
748 
749 static int rt6_score_route(const struct fib6_nh *nh, u32 fib6_flags, int oif,
750 			   int strict)
751 {
752 	int m = 0;
753 
754 	if (!oif || nh->fib_nh_dev->ifindex == oif)
755 		m = 2;
756 
757 	if (!m && (strict & RT6_LOOKUP_F_IFACE))
758 		return RT6_NUD_FAIL_HARD;
759 #ifdef CONFIG_IPV6_ROUTER_PREF
760 	m |= IPV6_DECODE_PREF(IPV6_EXTRACT_PREF(fib6_flags)) << 2;
761 #endif
762 	if ((strict & RT6_LOOKUP_F_REACHABLE) &&
763 	    !(fib6_flags & RTF_NONEXTHOP) && nh->fib_nh_gw_family) {
764 		int n = rt6_check_neigh(nh);
765 		if (n < 0)
766 			return n;
767 	}
768 	return m;
769 }
770 
771 static bool find_match(struct fib6_nh *nh, u32 fib6_flags,
772 		       int oif, int strict, int *mpri, bool *do_rr)
773 {
774 	bool match_do_rr = false;
775 	bool rc = false;
776 	int m;
777 
778 	if (nh->fib_nh_flags & RTNH_F_DEAD)
779 		goto out;
780 
781 	if (ip6_ignore_linkdown(nh->fib_nh_dev) &&
782 	    nh->fib_nh_flags & RTNH_F_LINKDOWN &&
783 	    !(strict & RT6_LOOKUP_F_IGNORE_LINKSTATE))
784 		goto out;
785 
786 	m = rt6_score_route(nh, fib6_flags, oif, strict);
787 	if (m == RT6_NUD_FAIL_DO_RR) {
788 		match_do_rr = true;
789 		m = 0; /* lowest valid score */
790 	} else if (m == RT6_NUD_FAIL_HARD) {
791 		goto out;
792 	}
793 
794 	if (strict & RT6_LOOKUP_F_REACHABLE)
795 		rt6_probe(nh);
796 
797 	/* note that m can be RT6_NUD_FAIL_PROBE at this point */
798 	if (m > *mpri) {
799 		*do_rr = match_do_rr;
800 		*mpri = m;
801 		rc = true;
802 	}
803 out:
804 	return rc;
805 }
806 
807 struct fib6_nh_frl_arg {
808 	u32		flags;
809 	int		oif;
810 	int		strict;
811 	int		*mpri;
812 	bool		*do_rr;
813 	struct fib6_nh	*nh;
814 };
815 
816 static int rt6_nh_find_match(struct fib6_nh *nh, void *_arg)
817 {
818 	struct fib6_nh_frl_arg *arg = _arg;
819 
820 	arg->nh = nh;
821 	return find_match(nh, arg->flags, arg->oif, arg->strict,
822 			  arg->mpri, arg->do_rr);
823 }
824 
825 static void __find_rr_leaf(struct fib6_info *f6i_start,
826 			   struct fib6_info *nomatch, u32 metric,
827 			   struct fib6_result *res, struct fib6_info **cont,
828 			   int oif, int strict, bool *do_rr, int *mpri)
829 {
830 	struct fib6_info *f6i;
831 
832 	for (f6i = f6i_start;
833 	     f6i && f6i != nomatch;
834 	     f6i = rcu_dereference(f6i->fib6_next)) {
835 		bool matched = false;
836 		struct fib6_nh *nh;
837 
838 		if (cont && f6i->fib6_metric != metric) {
839 			*cont = f6i;
840 			return;
841 		}
842 
843 		if (fib6_check_expired(f6i))
844 			continue;
845 
846 		if (unlikely(f6i->nh)) {
847 			struct fib6_nh_frl_arg arg = {
848 				.flags  = f6i->fib6_flags,
849 				.oif    = oif,
850 				.strict = strict,
851 				.mpri   = mpri,
852 				.do_rr  = do_rr
853 			};
854 
855 			if (nexthop_is_blackhole(f6i->nh)) {
856 				res->fib6_flags = RTF_REJECT;
857 				res->fib6_type = RTN_BLACKHOLE;
858 				res->f6i = f6i;
859 				res->nh = nexthop_fib6_nh(f6i->nh);
860 				return;
861 			}
862 			if (nexthop_for_each_fib6_nh(f6i->nh, rt6_nh_find_match,
863 						     &arg)) {
864 				matched = true;
865 				nh = arg.nh;
866 			}
867 		} else {
868 			nh = f6i->fib6_nh;
869 			if (find_match(nh, f6i->fib6_flags, oif, strict,
870 				       mpri, do_rr))
871 				matched = true;
872 		}
873 		if (matched) {
874 			res->f6i = f6i;
875 			res->nh = nh;
876 			res->fib6_flags = f6i->fib6_flags;
877 			res->fib6_type = f6i->fib6_type;
878 		}
879 	}
880 }
881 
882 static void find_rr_leaf(struct fib6_node *fn, struct fib6_info *leaf,
883 			 struct fib6_info *rr_head, int oif, int strict,
884 			 bool *do_rr, struct fib6_result *res)
885 {
886 	u32 metric = rr_head->fib6_metric;
887 	struct fib6_info *cont = NULL;
888 	int mpri = -1;
889 
890 	__find_rr_leaf(rr_head, NULL, metric, res, &cont,
891 		       oif, strict, do_rr, &mpri);
892 
893 	__find_rr_leaf(leaf, rr_head, metric, res, &cont,
894 		       oif, strict, do_rr, &mpri);
895 
896 	if (res->f6i || !cont)
897 		return;
898 
899 	__find_rr_leaf(cont, NULL, metric, res, NULL,
900 		       oif, strict, do_rr, &mpri);
901 }
902 
903 static void rt6_select(struct net *net, struct fib6_node *fn, int oif,
904 		       struct fib6_result *res, int strict)
905 {
906 	struct fib6_info *leaf = rcu_dereference(fn->leaf);
907 	struct fib6_info *rt0;
908 	bool do_rr = false;
909 	int key_plen;
910 
911 	/* make sure this function or its helpers sets f6i */
912 	res->f6i = NULL;
913 
914 	if (!leaf || leaf == net->ipv6.fib6_null_entry)
915 		goto out;
916 
917 	rt0 = rcu_dereference(fn->rr_ptr);
918 	if (!rt0)
919 		rt0 = leaf;
920 
921 	/* Double check to make sure fn is not an intermediate node
922 	 * and fn->leaf does not points to its child's leaf
923 	 * (This might happen if all routes under fn are deleted from
924 	 * the tree and fib6_repair_tree() is called on the node.)
925 	 */
926 	key_plen = rt0->fib6_dst.plen;
927 #ifdef CONFIG_IPV6_SUBTREES
928 	if (rt0->fib6_src.plen)
929 		key_plen = rt0->fib6_src.plen;
930 #endif
931 	if (fn->fn_bit != key_plen)
932 		goto out;
933 
934 	find_rr_leaf(fn, leaf, rt0, oif, strict, &do_rr, res);
935 	if (do_rr) {
936 		struct fib6_info *next = rcu_dereference(rt0->fib6_next);
937 
938 		/* no entries matched; do round-robin */
939 		if (!next || next->fib6_metric != rt0->fib6_metric)
940 			next = leaf;
941 
942 		if (next != rt0) {
943 			spin_lock_bh(&leaf->fib6_table->tb6_lock);
944 			/* make sure next is not being deleted from the tree */
945 			if (next->fib6_node)
946 				rcu_assign_pointer(fn->rr_ptr, next);
947 			spin_unlock_bh(&leaf->fib6_table->tb6_lock);
948 		}
949 	}
950 
951 out:
952 	if (!res->f6i) {
953 		res->f6i = net->ipv6.fib6_null_entry;
954 		res->nh = res->f6i->fib6_nh;
955 		res->fib6_flags = res->f6i->fib6_flags;
956 		res->fib6_type = res->f6i->fib6_type;
957 	}
958 }
959 
960 static bool rt6_is_gw_or_nonexthop(const struct fib6_result *res)
961 {
962 	return (res->f6i->fib6_flags & RTF_NONEXTHOP) ||
963 	       res->nh->fib_nh_gw_family;
964 }
965 
966 #ifdef CONFIG_IPV6_ROUTE_INFO
967 int rt6_route_rcv(struct net_device *dev, u8 *opt, int len,
968 		  const struct in6_addr *gwaddr)
969 {
970 	struct net *net = dev_net(dev);
971 	struct route_info *rinfo = (struct route_info *) opt;
972 	struct in6_addr prefix_buf, *prefix;
973 	struct fib6_table *table;
974 	unsigned int pref;
975 	unsigned long lifetime;
976 	struct fib6_info *rt;
977 
978 	if (len < sizeof(struct route_info)) {
979 		return -EINVAL;
980 	}
981 
982 	/* Sanity check for prefix_len and length */
983 	if (rinfo->length > 3) {
984 		return -EINVAL;
985 	} else if (rinfo->prefix_len > 128) {
986 		return -EINVAL;
987 	} else if (rinfo->prefix_len > 64) {
988 		if (rinfo->length < 2) {
989 			return -EINVAL;
990 		}
991 	} else if (rinfo->prefix_len > 0) {
992 		if (rinfo->length < 1) {
993 			return -EINVAL;
994 		}
995 	}
996 
997 	pref = rinfo->route_pref;
998 	if (pref == ICMPV6_ROUTER_PREF_INVALID)
999 		return -EINVAL;
1000 
1001 	lifetime = addrconf_timeout_fixup(ntohl(rinfo->lifetime), HZ);
1002 
1003 	if (rinfo->length == 3)
1004 		prefix = (struct in6_addr *)rinfo->prefix;
1005 	else {
1006 		/* this function is safe */
1007 		ipv6_addr_prefix(&prefix_buf,
1008 				 (struct in6_addr *)rinfo->prefix,
1009 				 rinfo->prefix_len);
1010 		prefix = &prefix_buf;
1011 	}
1012 
1013 	if (rinfo->prefix_len == 0)
1014 		rt = rt6_get_dflt_router(net, gwaddr, dev);
1015 	else
1016 		rt = rt6_get_route_info(net, prefix, rinfo->prefix_len,
1017 					gwaddr, dev);
1018 
1019 	if (rt && !lifetime) {
1020 		ip6_del_rt(net, rt, false);
1021 		rt = NULL;
1022 	}
1023 
1024 	if (!rt && lifetime)
1025 		rt = rt6_add_route_info(net, prefix, rinfo->prefix_len, gwaddr,
1026 					dev, pref);
1027 	else if (rt)
1028 		rt->fib6_flags = RTF_ROUTEINFO |
1029 				 (rt->fib6_flags & ~RTF_PREF_MASK) | RTF_PREF(pref);
1030 
1031 	if (rt) {
1032 		table = rt->fib6_table;
1033 		spin_lock_bh(&table->tb6_lock);
1034 
1035 		if (!addrconf_finite_timeout(lifetime)) {
1036 			fib6_clean_expires(rt);
1037 			fib6_remove_gc_list(rt);
1038 		} else {
1039 			fib6_set_expires(rt, jiffies + HZ * lifetime);
1040 			fib6_add_gc_list(rt);
1041 		}
1042 
1043 		spin_unlock_bh(&table->tb6_lock);
1044 
1045 		fib6_info_release(rt);
1046 	}
1047 	return 0;
1048 }
1049 #endif
1050 
1051 /*
1052  *	Misc support functions
1053  */
1054 
1055 /* called with rcu_lock held */
1056 static struct net_device *ip6_rt_get_dev_rcu(const struct fib6_result *res)
1057 {
1058 	struct net_device *dev = res->nh->fib_nh_dev;
1059 
1060 	if (res->fib6_flags & (RTF_LOCAL | RTF_ANYCAST)) {
1061 		/* for copies of local routes, dst->dev needs to be the
1062 		 * device if it is a master device, the master device if
1063 		 * device is enslaved, and the loopback as the default
1064 		 */
1065 		if (netif_is_l3_slave(dev) &&
1066 		    !rt6_need_strict(&res->f6i->fib6_dst.addr))
1067 			dev = l3mdev_master_dev_rcu(dev);
1068 		else if (!netif_is_l3_master(dev))
1069 			dev = dev_net(dev)->loopback_dev;
1070 		/* last case is netif_is_l3_master(dev) is true in which
1071 		 * case we want dev returned to be dev
1072 		 */
1073 	}
1074 
1075 	return dev;
1076 }
1077 
1078 static const int fib6_prop[RTN_MAX + 1] = {
1079 	[RTN_UNSPEC]	= 0,
1080 	[RTN_UNICAST]	= 0,
1081 	[RTN_LOCAL]	= 0,
1082 	[RTN_BROADCAST]	= 0,
1083 	[RTN_ANYCAST]	= 0,
1084 	[RTN_MULTICAST]	= 0,
1085 	[RTN_BLACKHOLE]	= -EINVAL,
1086 	[RTN_UNREACHABLE] = -EHOSTUNREACH,
1087 	[RTN_PROHIBIT]	= -EACCES,
1088 	[RTN_THROW]	= -EAGAIN,
1089 	[RTN_NAT]	= -EINVAL,
1090 	[RTN_XRESOLVE]	= -EINVAL,
1091 };
1092 
1093 static int ip6_rt_type_to_error(u8 fib6_type)
1094 {
1095 	return fib6_prop[fib6_type];
1096 }
1097 
1098 static unsigned short fib6_info_dst_flags(struct fib6_info *rt)
1099 {
1100 	unsigned short flags = 0;
1101 
1102 	if (rt->dst_nocount)
1103 		flags |= DST_NOCOUNT;
1104 	if (rt->dst_nopolicy)
1105 		flags |= DST_NOPOLICY;
1106 
1107 	return flags;
1108 }
1109 
1110 static void ip6_rt_init_dst_reject(struct rt6_info *rt, u8 fib6_type)
1111 {
1112 	rt->dst.error = ip6_rt_type_to_error(fib6_type);
1113 
1114 	switch (fib6_type) {
1115 	case RTN_BLACKHOLE:
1116 		rt->dst.output = dst_discard_out;
1117 		rt->dst.input = dst_discard;
1118 		break;
1119 	case RTN_PROHIBIT:
1120 		rt->dst.output = ip6_pkt_prohibit_out;
1121 		rt->dst.input = ip6_pkt_prohibit;
1122 		break;
1123 	case RTN_THROW:
1124 	case RTN_UNREACHABLE:
1125 	default:
1126 		rt->dst.output = ip6_pkt_discard_out;
1127 		rt->dst.input = ip6_pkt_discard;
1128 		break;
1129 	}
1130 }
1131 
1132 static void ip6_rt_init_dst(struct rt6_info *rt, const struct fib6_result *res)
1133 {
1134 	struct fib6_info *f6i = res->f6i;
1135 
1136 	if (res->fib6_flags & RTF_REJECT) {
1137 		ip6_rt_init_dst_reject(rt, res->fib6_type);
1138 		return;
1139 	}
1140 
1141 	rt->dst.error = 0;
1142 	rt->dst.output = ip6_output;
1143 
1144 	if (res->fib6_type == RTN_LOCAL || res->fib6_type == RTN_ANYCAST) {
1145 		rt->dst.input = ip6_input;
1146 	} else if (ipv6_addr_type(&f6i->fib6_dst.addr) & IPV6_ADDR_MULTICAST) {
1147 		rt->dst.input = ip6_mc_input;
1148 	} else {
1149 		rt->dst.input = ip6_forward;
1150 	}
1151 
1152 	if (res->nh->fib_nh_lws) {
1153 		rt->dst.lwtstate = lwtstate_get(res->nh->fib_nh_lws);
1154 		lwtunnel_set_redirect(&rt->dst);
1155 	}
1156 
1157 	rt->dst.lastuse = jiffies;
1158 }
1159 
1160 /* Caller must already hold reference to @from */
1161 static void rt6_set_from(struct rt6_info *rt, struct fib6_info *from)
1162 {
1163 	rt->rt6i_flags &= ~RTF_EXPIRES;
1164 	rcu_assign_pointer(rt->from, from);
1165 	ip_dst_init_metrics(&rt->dst, from->fib6_metrics);
1166 }
1167 
1168 /* Caller must already hold reference to f6i in result */
1169 static void ip6_rt_copy_init(struct rt6_info *rt, const struct fib6_result *res)
1170 {
1171 	const struct fib6_nh *nh = res->nh;
1172 	const struct net_device *dev = nh->fib_nh_dev;
1173 	struct fib6_info *f6i = res->f6i;
1174 
1175 	ip6_rt_init_dst(rt, res);
1176 
1177 	rt->rt6i_dst = f6i->fib6_dst;
1178 	rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL;
1179 	rt->rt6i_flags = res->fib6_flags;
1180 	if (nh->fib_nh_gw_family) {
1181 		rt->rt6i_gateway = nh->fib_nh_gw6;
1182 		rt->rt6i_flags |= RTF_GATEWAY;
1183 	}
1184 	rt6_set_from(rt, f6i);
1185 #ifdef CONFIG_IPV6_SUBTREES
1186 	rt->rt6i_src = f6i->fib6_src;
1187 #endif
1188 }
1189 
1190 static struct fib6_node* fib6_backtrack(struct fib6_node *fn,
1191 					struct in6_addr *saddr)
1192 {
1193 	struct fib6_node *pn, *sn;
1194 	while (1) {
1195 		if (fn->fn_flags & RTN_TL_ROOT)
1196 			return NULL;
1197 		pn = rcu_dereference(fn->parent);
1198 		sn = FIB6_SUBTREE(pn);
1199 		if (sn && sn != fn)
1200 			fn = fib6_node_lookup(sn, NULL, saddr);
1201 		else
1202 			fn = pn;
1203 		if (fn->fn_flags & RTN_RTINFO)
1204 			return fn;
1205 	}
1206 }
1207 
1208 static bool ip6_hold_safe(struct net *net, struct rt6_info **prt)
1209 {
1210 	struct rt6_info *rt = *prt;
1211 
1212 	if (dst_hold_safe(&rt->dst))
1213 		return true;
1214 	if (net) {
1215 		rt = net->ipv6.ip6_null_entry;
1216 		dst_hold(&rt->dst);
1217 	} else {
1218 		rt = NULL;
1219 	}
1220 	*prt = rt;
1221 	return false;
1222 }
1223 
1224 /* called with rcu_lock held */
1225 static struct rt6_info *ip6_create_rt_rcu(const struct fib6_result *res)
1226 {
1227 	struct net_device *dev = res->nh->fib_nh_dev;
1228 	struct fib6_info *f6i = res->f6i;
1229 	unsigned short flags;
1230 	struct rt6_info *nrt;
1231 
1232 	if (!fib6_info_hold_safe(f6i))
1233 		goto fallback;
1234 
1235 	flags = fib6_info_dst_flags(f6i);
1236 	nrt = ip6_dst_alloc(dev_net(dev), dev, flags);
1237 	if (!nrt) {
1238 		fib6_info_release(f6i);
1239 		goto fallback;
1240 	}
1241 
1242 	ip6_rt_copy_init(nrt, res);
1243 	return nrt;
1244 
1245 fallback:
1246 	nrt = dev_net(dev)->ipv6.ip6_null_entry;
1247 	dst_hold(&nrt->dst);
1248 	return nrt;
1249 }
1250 
1251 INDIRECT_CALLABLE_SCOPE struct rt6_info *ip6_pol_route_lookup(struct net *net,
1252 					     struct fib6_table *table,
1253 					     struct flowi6 *fl6,
1254 					     const struct sk_buff *skb,
1255 					     int flags)
1256 {
1257 	struct fib6_result res = {};
1258 	struct fib6_node *fn;
1259 	struct rt6_info *rt;
1260 
1261 	rcu_read_lock();
1262 	fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
1263 restart:
1264 	res.f6i = rcu_dereference(fn->leaf);
1265 	if (!res.f6i)
1266 		res.f6i = net->ipv6.fib6_null_entry;
1267 	else
1268 		rt6_device_match(net, &res, &fl6->saddr, fl6->flowi6_oif,
1269 				 flags);
1270 
1271 	if (res.f6i == net->ipv6.fib6_null_entry) {
1272 		fn = fib6_backtrack(fn, &fl6->saddr);
1273 		if (fn)
1274 			goto restart;
1275 
1276 		rt = net->ipv6.ip6_null_entry;
1277 		dst_hold(&rt->dst);
1278 		goto out;
1279 	} else if (res.fib6_flags & RTF_REJECT) {
1280 		goto do_create;
1281 	}
1282 
1283 	fib6_select_path(net, &res, fl6, fl6->flowi6_oif,
1284 			 fl6->flowi6_oif != 0, skb, flags);
1285 
1286 	/* Search through exception table */
1287 	rt = rt6_find_cached_rt(&res, &fl6->daddr, &fl6->saddr);
1288 	if (rt) {
1289 		if (ip6_hold_safe(net, &rt))
1290 			dst_use_noref(&rt->dst, jiffies);
1291 	} else {
1292 do_create:
1293 		rt = ip6_create_rt_rcu(&res);
1294 	}
1295 
1296 out:
1297 	trace_fib6_table_lookup(net, &res, table, fl6);
1298 
1299 	rcu_read_unlock();
1300 
1301 	return rt;
1302 }
1303 
1304 struct dst_entry *ip6_route_lookup(struct net *net, struct flowi6 *fl6,
1305 				   const struct sk_buff *skb, int flags)
1306 {
1307 	return fib6_rule_lookup(net, fl6, skb, flags, ip6_pol_route_lookup);
1308 }
1309 EXPORT_SYMBOL_GPL(ip6_route_lookup);
1310 
1311 struct rt6_info *rt6_lookup(struct net *net, const struct in6_addr *daddr,
1312 			    const struct in6_addr *saddr, int oif,
1313 			    const struct sk_buff *skb, int strict)
1314 {
1315 	struct flowi6 fl6 = {
1316 		.flowi6_oif = oif,
1317 		.daddr = *daddr,
1318 	};
1319 	struct dst_entry *dst;
1320 	int flags = strict ? RT6_LOOKUP_F_IFACE : 0;
1321 
1322 	if (saddr) {
1323 		memcpy(&fl6.saddr, saddr, sizeof(*saddr));
1324 		flags |= RT6_LOOKUP_F_HAS_SADDR;
1325 	}
1326 
1327 	dst = fib6_rule_lookup(net, &fl6, skb, flags, ip6_pol_route_lookup);
1328 	if (dst->error == 0)
1329 		return dst_rt6_info(dst);
1330 
1331 	dst_release(dst);
1332 
1333 	return NULL;
1334 }
1335 EXPORT_SYMBOL(rt6_lookup);
1336 
1337 /* ip6_ins_rt is called with FREE table->tb6_lock.
1338  * It takes new route entry, the addition fails by any reason the
1339  * route is released.
1340  * Caller must hold dst before calling it.
1341  */
1342 
1343 static int __ip6_ins_rt(struct fib6_info *rt, struct nl_info *info,
1344 			struct netlink_ext_ack *extack)
1345 {
1346 	int err;
1347 	struct fib6_table *table;
1348 
1349 	table = rt->fib6_table;
1350 	spin_lock_bh(&table->tb6_lock);
1351 	err = fib6_add(&table->tb6_root, rt, info, extack);
1352 	spin_unlock_bh(&table->tb6_lock);
1353 
1354 	return err;
1355 }
1356 
1357 int ip6_ins_rt(struct net *net, struct fib6_info *rt)
1358 {
1359 	struct nl_info info = {	.nl_net = net, };
1360 
1361 	return __ip6_ins_rt(rt, &info, NULL);
1362 }
1363 
1364 static struct rt6_info *ip6_rt_cache_alloc(const struct fib6_result *res,
1365 					   const struct in6_addr *daddr,
1366 					   const struct in6_addr *saddr)
1367 {
1368 	struct fib6_info *f6i = res->f6i;
1369 	struct net_device *dev;
1370 	struct rt6_info *rt;
1371 
1372 	/*
1373 	 *	Clone the route.
1374 	 */
1375 
1376 	if (!fib6_info_hold_safe(f6i))
1377 		return NULL;
1378 
1379 	dev = ip6_rt_get_dev_rcu(res);
1380 	rt = ip6_dst_alloc(dev_net(dev), dev, 0);
1381 	if (!rt) {
1382 		fib6_info_release(f6i);
1383 		return NULL;
1384 	}
1385 
1386 	ip6_rt_copy_init(rt, res);
1387 	rt->rt6i_flags |= RTF_CACHE;
1388 	rt->rt6i_dst.addr = *daddr;
1389 	rt->rt6i_dst.plen = 128;
1390 
1391 	if (!rt6_is_gw_or_nonexthop(res)) {
1392 		if (f6i->fib6_dst.plen != 128 &&
1393 		    ipv6_addr_equal(&f6i->fib6_dst.addr, daddr))
1394 			rt->rt6i_flags |= RTF_ANYCAST;
1395 #ifdef CONFIG_IPV6_SUBTREES
1396 		if (rt->rt6i_src.plen && saddr) {
1397 			rt->rt6i_src.addr = *saddr;
1398 			rt->rt6i_src.plen = 128;
1399 		}
1400 #endif
1401 	}
1402 
1403 	return rt;
1404 }
1405 
1406 static struct rt6_info *ip6_rt_pcpu_alloc(const struct fib6_result *res)
1407 {
1408 	struct fib6_info *f6i = res->f6i;
1409 	unsigned short flags = fib6_info_dst_flags(f6i);
1410 	struct net_device *dev;
1411 	struct rt6_info *pcpu_rt;
1412 
1413 	if (!fib6_info_hold_safe(f6i))
1414 		return NULL;
1415 
1416 	rcu_read_lock();
1417 	dev = ip6_rt_get_dev_rcu(res);
1418 	pcpu_rt = ip6_dst_alloc(dev_net(dev), dev, flags | DST_NOCOUNT);
1419 	rcu_read_unlock();
1420 	if (!pcpu_rt) {
1421 		fib6_info_release(f6i);
1422 		return NULL;
1423 	}
1424 	ip6_rt_copy_init(pcpu_rt, res);
1425 	pcpu_rt->rt6i_flags |= RTF_PCPU;
1426 
1427 	if (f6i->nh)
1428 		pcpu_rt->sernum = rt_genid_ipv6(dev_net(dev));
1429 
1430 	return pcpu_rt;
1431 }
1432 
1433 static bool rt6_is_valid(const struct rt6_info *rt6)
1434 {
1435 	return rt6->sernum == rt_genid_ipv6(dev_net(rt6->dst.dev));
1436 }
1437 
1438 /* It should be called with rcu_read_lock() acquired */
1439 static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res)
1440 {
1441 	struct rt6_info *pcpu_rt;
1442 
1443 	pcpu_rt = this_cpu_read(*res->nh->rt6i_pcpu);
1444 
1445 	if (pcpu_rt && pcpu_rt->sernum && !rt6_is_valid(pcpu_rt)) {
1446 		struct rt6_info *prev, **p;
1447 
1448 		p = this_cpu_ptr(res->nh->rt6i_pcpu);
1449 		/* Paired with READ_ONCE() in __fib6_drop_pcpu_from() */
1450 		prev = xchg(p, NULL);
1451 		if (prev) {
1452 			dst_dev_put(&prev->dst);
1453 			dst_release(&prev->dst);
1454 		}
1455 
1456 		pcpu_rt = NULL;
1457 	}
1458 
1459 	return pcpu_rt;
1460 }
1461 
1462 static struct rt6_info *rt6_make_pcpu_route(struct net *net,
1463 					    const struct fib6_result *res)
1464 {
1465 	struct rt6_info *pcpu_rt, *prev, **p;
1466 
1467 	pcpu_rt = ip6_rt_pcpu_alloc(res);
1468 	if (!pcpu_rt)
1469 		return NULL;
1470 
1471 	p = this_cpu_ptr(res->nh->rt6i_pcpu);
1472 	prev = cmpxchg(p, NULL, pcpu_rt);
1473 	BUG_ON(prev);
1474 
1475 	if (res->f6i->fib6_destroying) {
1476 		struct fib6_info *from;
1477 
1478 		from = unrcu_pointer(xchg(&pcpu_rt->from, NULL));
1479 		fib6_info_release(from);
1480 	}
1481 
1482 	return pcpu_rt;
1483 }
1484 
1485 /* exception hash table implementation
1486  */
1487 static DEFINE_SPINLOCK(rt6_exception_lock);
1488 
1489 /* Remove rt6_ex from hash table and free the memory
1490  * Caller must hold rt6_exception_lock
1491  */
1492 static void rt6_remove_exception(struct rt6_exception_bucket *bucket,
1493 				 struct rt6_exception *rt6_ex)
1494 {
1495 	struct net *net;
1496 
1497 	if (!bucket || !rt6_ex)
1498 		return;
1499 
1500 	net = dev_net(rt6_ex->rt6i->dst.dev);
1501 	net->ipv6.rt6_stats->fib_rt_cache--;
1502 
1503 	/* purge completely the exception to allow releasing the held resources:
1504 	 * some [sk] cache may keep the dst around for unlimited time
1505 	 */
1506 	dst_dev_put(&rt6_ex->rt6i->dst);
1507 
1508 	hlist_del_rcu(&rt6_ex->hlist);
1509 	dst_release(&rt6_ex->rt6i->dst);
1510 	kfree_rcu(rt6_ex, rcu);
1511 	WARN_ON_ONCE(!bucket->depth);
1512 	bucket->depth--;
1513 }
1514 
1515 /* Remove oldest rt6_ex in bucket and free the memory
1516  * Caller must hold rt6_exception_lock
1517  */
1518 static void rt6_exception_remove_oldest(struct rt6_exception_bucket *bucket)
1519 {
1520 	struct rt6_exception *rt6_ex, *oldest = NULL;
1521 
1522 	if (!bucket)
1523 		return;
1524 
1525 	hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
1526 		if (!oldest || time_before(rt6_ex->stamp, oldest->stamp))
1527 			oldest = rt6_ex;
1528 	}
1529 	rt6_remove_exception(bucket, oldest);
1530 }
1531 
1532 static u32 rt6_exception_hash(const struct in6_addr *dst,
1533 			      const struct in6_addr *src)
1534 {
1535 	static siphash_aligned_key_t rt6_exception_key;
1536 	struct {
1537 		struct in6_addr dst;
1538 		struct in6_addr src;
1539 	} __aligned(SIPHASH_ALIGNMENT) combined = {
1540 		.dst = *dst,
1541 	};
1542 	u64 val;
1543 
1544 	net_get_random_once(&rt6_exception_key, sizeof(rt6_exception_key));
1545 
1546 #ifdef CONFIG_IPV6_SUBTREES
1547 	if (src)
1548 		combined.src = *src;
1549 #endif
1550 	val = siphash(&combined, sizeof(combined), &rt6_exception_key);
1551 
1552 	return hash_64(val, FIB6_EXCEPTION_BUCKET_SIZE_SHIFT);
1553 }
1554 
1555 /* Helper function to find the cached rt in the hash table
1556  * and update bucket pointer to point to the bucket for this
1557  * (daddr, saddr) pair
1558  * Caller must hold rt6_exception_lock
1559  */
1560 static struct rt6_exception *
1561 __rt6_find_exception_spinlock(struct rt6_exception_bucket **bucket,
1562 			      const struct in6_addr *daddr,
1563 			      const struct in6_addr *saddr)
1564 {
1565 	struct rt6_exception *rt6_ex;
1566 	u32 hval;
1567 
1568 	if (!(*bucket) || !daddr)
1569 		return NULL;
1570 
1571 	hval = rt6_exception_hash(daddr, saddr);
1572 	*bucket += hval;
1573 
1574 	hlist_for_each_entry(rt6_ex, &(*bucket)->chain, hlist) {
1575 		struct rt6_info *rt6 = rt6_ex->rt6i;
1576 		bool matched = ipv6_addr_equal(daddr, &rt6->rt6i_dst.addr);
1577 
1578 #ifdef CONFIG_IPV6_SUBTREES
1579 		if (matched && saddr)
1580 			matched = ipv6_addr_equal(saddr, &rt6->rt6i_src.addr);
1581 #endif
1582 		if (matched)
1583 			return rt6_ex;
1584 	}
1585 	return NULL;
1586 }
1587 
1588 /* Helper function to find the cached rt in the hash table
1589  * and update bucket pointer to point to the bucket for this
1590  * (daddr, saddr) pair
1591  * Caller must hold rcu_read_lock()
1592  */
1593 static struct rt6_exception *
1594 __rt6_find_exception_rcu(struct rt6_exception_bucket **bucket,
1595 			 const struct in6_addr *daddr,
1596 			 const struct in6_addr *saddr)
1597 {
1598 	struct rt6_exception *rt6_ex;
1599 	u32 hval;
1600 
1601 	WARN_ON_ONCE(!rcu_read_lock_held());
1602 
1603 	if (!(*bucket) || !daddr)
1604 		return NULL;
1605 
1606 	hval = rt6_exception_hash(daddr, saddr);
1607 	*bucket += hval;
1608 
1609 	hlist_for_each_entry_rcu(rt6_ex, &(*bucket)->chain, hlist) {
1610 		struct rt6_info *rt6 = rt6_ex->rt6i;
1611 		bool matched = ipv6_addr_equal(daddr, &rt6->rt6i_dst.addr);
1612 
1613 #ifdef CONFIG_IPV6_SUBTREES
1614 		if (matched && saddr)
1615 			matched = ipv6_addr_equal(saddr, &rt6->rt6i_src.addr);
1616 #endif
1617 		if (matched)
1618 			return rt6_ex;
1619 	}
1620 	return NULL;
1621 }
1622 
1623 static unsigned int fib6_mtu(const struct fib6_result *res)
1624 {
1625 	const struct fib6_nh *nh = res->nh;
1626 	unsigned int mtu;
1627 
1628 	if (res->f6i->fib6_pmtu) {
1629 		mtu = res->f6i->fib6_pmtu;
1630 	} else {
1631 		struct net_device *dev = nh->fib_nh_dev;
1632 		struct inet6_dev *idev;
1633 
1634 		rcu_read_lock();
1635 		idev = __in6_dev_get(dev);
1636 		mtu = READ_ONCE(idev->cnf.mtu6);
1637 		rcu_read_unlock();
1638 	}
1639 
1640 	mtu = min_t(unsigned int, mtu, IP6_MAX_MTU);
1641 
1642 	return mtu - lwtunnel_headroom(nh->fib_nh_lws, mtu);
1643 }
1644 
1645 #define FIB6_EXCEPTION_BUCKET_FLUSHED  0x1UL
1646 
1647 /* used when the flushed bit is not relevant, only access to the bucket
1648  * (ie., all bucket users except rt6_insert_exception);
1649  *
1650  * called under rcu lock; sometimes called with rt6_exception_lock held
1651  */
1652 static
1653 struct rt6_exception_bucket *fib6_nh_get_excptn_bucket(const struct fib6_nh *nh,
1654 						       spinlock_t *lock)
1655 {
1656 	struct rt6_exception_bucket *bucket;
1657 
1658 	if (lock)
1659 		bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1660 						   lockdep_is_held(lock));
1661 	else
1662 		bucket = rcu_dereference(nh->rt6i_exception_bucket);
1663 
1664 	/* remove bucket flushed bit if set */
1665 	if (bucket) {
1666 		unsigned long p = (unsigned long)bucket;
1667 
1668 		p &= ~FIB6_EXCEPTION_BUCKET_FLUSHED;
1669 		bucket = (struct rt6_exception_bucket *)p;
1670 	}
1671 
1672 	return bucket;
1673 }
1674 
1675 static bool fib6_nh_excptn_bucket_flushed(struct rt6_exception_bucket *bucket)
1676 {
1677 	unsigned long p = (unsigned long)bucket;
1678 
1679 	return !!(p & FIB6_EXCEPTION_BUCKET_FLUSHED);
1680 }
1681 
1682 /* called with rt6_exception_lock held */
1683 static void fib6_nh_excptn_bucket_set_flushed(struct fib6_nh *nh,
1684 					      spinlock_t *lock)
1685 {
1686 	struct rt6_exception_bucket *bucket;
1687 	unsigned long p;
1688 
1689 	bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1690 					   lockdep_is_held(lock));
1691 
1692 	p = (unsigned long)bucket;
1693 	p |= FIB6_EXCEPTION_BUCKET_FLUSHED;
1694 	bucket = (struct rt6_exception_bucket *)p;
1695 	rcu_assign_pointer(nh->rt6i_exception_bucket, bucket);
1696 }
1697 
1698 static int rt6_insert_exception(struct rt6_info *nrt,
1699 				const struct fib6_result *res)
1700 {
1701 	struct net *net = dev_net(nrt->dst.dev);
1702 	struct rt6_exception_bucket *bucket;
1703 	struct fib6_info *f6i = res->f6i;
1704 	struct in6_addr *src_key = NULL;
1705 	struct rt6_exception *rt6_ex;
1706 	struct fib6_nh *nh = res->nh;
1707 	int max_depth;
1708 	int err = 0;
1709 
1710 	spin_lock_bh(&rt6_exception_lock);
1711 
1712 	bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1713 					  lockdep_is_held(&rt6_exception_lock));
1714 	if (!bucket) {
1715 		bucket = kcalloc(FIB6_EXCEPTION_BUCKET_SIZE, sizeof(*bucket),
1716 				 GFP_ATOMIC);
1717 		if (!bucket) {
1718 			err = -ENOMEM;
1719 			goto out;
1720 		}
1721 		rcu_assign_pointer(nh->rt6i_exception_bucket, bucket);
1722 	} else if (fib6_nh_excptn_bucket_flushed(bucket)) {
1723 		err = -EINVAL;
1724 		goto out;
1725 	}
1726 
1727 #ifdef CONFIG_IPV6_SUBTREES
1728 	/* fib6_src.plen != 0 indicates f6i is in subtree
1729 	 * and exception table is indexed by a hash of
1730 	 * both fib6_dst and fib6_src.
1731 	 * Otherwise, the exception table is indexed by
1732 	 * a hash of only fib6_dst.
1733 	 */
1734 	if (f6i->fib6_src.plen)
1735 		src_key = &nrt->rt6i_src.addr;
1736 #endif
1737 	/* rt6_mtu_change() might lower mtu on f6i.
1738 	 * Only insert this exception route if its mtu
1739 	 * is less than f6i's mtu value.
1740 	 */
1741 	if (dst_metric_raw(&nrt->dst, RTAX_MTU) >= fib6_mtu(res)) {
1742 		err = -EINVAL;
1743 		goto out;
1744 	}
1745 
1746 	rt6_ex = __rt6_find_exception_spinlock(&bucket, &nrt->rt6i_dst.addr,
1747 					       src_key);
1748 	if (rt6_ex)
1749 		rt6_remove_exception(bucket, rt6_ex);
1750 
1751 	rt6_ex = kzalloc(sizeof(*rt6_ex), GFP_ATOMIC);
1752 	if (!rt6_ex) {
1753 		err = -ENOMEM;
1754 		goto out;
1755 	}
1756 	rt6_ex->rt6i = nrt;
1757 	rt6_ex->stamp = jiffies;
1758 	hlist_add_head_rcu(&rt6_ex->hlist, &bucket->chain);
1759 	bucket->depth++;
1760 	net->ipv6.rt6_stats->fib_rt_cache++;
1761 
1762 	/* Randomize max depth to avoid some side channels attacks. */
1763 	max_depth = FIB6_MAX_DEPTH + get_random_u32_below(FIB6_MAX_DEPTH);
1764 	while (bucket->depth > max_depth)
1765 		rt6_exception_remove_oldest(bucket);
1766 
1767 out:
1768 	spin_unlock_bh(&rt6_exception_lock);
1769 
1770 	/* Update fn->fn_sernum to invalidate all cached dst */
1771 	if (!err) {
1772 		spin_lock_bh(&f6i->fib6_table->tb6_lock);
1773 		fib6_update_sernum(net, f6i);
1774 		fib6_add_gc_list(f6i);
1775 		spin_unlock_bh(&f6i->fib6_table->tb6_lock);
1776 		fib6_force_start_gc(net);
1777 	}
1778 
1779 	return err;
1780 }
1781 
1782 static void fib6_nh_flush_exceptions(struct fib6_nh *nh, struct fib6_info *from)
1783 {
1784 	struct rt6_exception_bucket *bucket;
1785 	struct rt6_exception *rt6_ex;
1786 	struct hlist_node *tmp;
1787 	int i;
1788 
1789 	spin_lock_bh(&rt6_exception_lock);
1790 
1791 	bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1792 	if (!bucket)
1793 		goto out;
1794 
1795 	/* Prevent rt6_insert_exception() to recreate the bucket list */
1796 	if (!from)
1797 		fib6_nh_excptn_bucket_set_flushed(nh, &rt6_exception_lock);
1798 
1799 	for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
1800 		hlist_for_each_entry_safe(rt6_ex, tmp, &bucket->chain, hlist) {
1801 			if (!from ||
1802 			    rcu_access_pointer(rt6_ex->rt6i->from) == from)
1803 				rt6_remove_exception(bucket, rt6_ex);
1804 		}
1805 		WARN_ON_ONCE(!from && bucket->depth);
1806 		bucket++;
1807 	}
1808 out:
1809 	spin_unlock_bh(&rt6_exception_lock);
1810 }
1811 
1812 static int rt6_nh_flush_exceptions(struct fib6_nh *nh, void *arg)
1813 {
1814 	struct fib6_info *f6i = arg;
1815 
1816 	fib6_nh_flush_exceptions(nh, f6i);
1817 
1818 	return 0;
1819 }
1820 
1821 void rt6_flush_exceptions(struct fib6_info *f6i)
1822 {
1823 	if (f6i->nh)
1824 		nexthop_for_each_fib6_nh(f6i->nh, rt6_nh_flush_exceptions,
1825 					 f6i);
1826 	else
1827 		fib6_nh_flush_exceptions(f6i->fib6_nh, f6i);
1828 }
1829 
1830 /* Find cached rt in the hash table inside passed in rt
1831  * Caller has to hold rcu_read_lock()
1832  */
1833 static struct rt6_info *rt6_find_cached_rt(const struct fib6_result *res,
1834 					   const struct in6_addr *daddr,
1835 					   const struct in6_addr *saddr)
1836 {
1837 	const struct in6_addr *src_key = NULL;
1838 	struct rt6_exception_bucket *bucket;
1839 	struct rt6_exception *rt6_ex;
1840 	struct rt6_info *ret = NULL;
1841 
1842 #ifdef CONFIG_IPV6_SUBTREES
1843 	/* fib6i_src.plen != 0 indicates f6i is in subtree
1844 	 * and exception table is indexed by a hash of
1845 	 * both fib6_dst and fib6_src.
1846 	 * However, the src addr used to create the hash
1847 	 * might not be exactly the passed in saddr which
1848 	 * is a /128 addr from the flow.
1849 	 * So we need to use f6i->fib6_src to redo lookup
1850 	 * if the passed in saddr does not find anything.
1851 	 * (See the logic in ip6_rt_cache_alloc() on how
1852 	 * rt->rt6i_src is updated.)
1853 	 */
1854 	if (res->f6i->fib6_src.plen)
1855 		src_key = saddr;
1856 find_ex:
1857 #endif
1858 	bucket = fib6_nh_get_excptn_bucket(res->nh, NULL);
1859 	rt6_ex = __rt6_find_exception_rcu(&bucket, daddr, src_key);
1860 
1861 	if (rt6_ex && !rt6_check_expired(rt6_ex->rt6i))
1862 		ret = rt6_ex->rt6i;
1863 
1864 #ifdef CONFIG_IPV6_SUBTREES
1865 	/* Use fib6_src as src_key and redo lookup */
1866 	if (!ret && src_key && src_key != &res->f6i->fib6_src.addr) {
1867 		src_key = &res->f6i->fib6_src.addr;
1868 		goto find_ex;
1869 	}
1870 #endif
1871 
1872 	return ret;
1873 }
1874 
1875 /* Remove the passed in cached rt from the hash table that contains it */
1876 static int fib6_nh_remove_exception(const struct fib6_nh *nh, int plen,
1877 				    const struct rt6_info *rt)
1878 {
1879 	const struct in6_addr *src_key = NULL;
1880 	struct rt6_exception_bucket *bucket;
1881 	struct rt6_exception *rt6_ex;
1882 	int err;
1883 
1884 	if (!rcu_access_pointer(nh->rt6i_exception_bucket))
1885 		return -ENOENT;
1886 
1887 	spin_lock_bh(&rt6_exception_lock);
1888 	bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1889 
1890 #ifdef CONFIG_IPV6_SUBTREES
1891 	/* rt6i_src.plen != 0 indicates 'from' is in subtree
1892 	 * and exception table is indexed by a hash of
1893 	 * both rt6i_dst and rt6i_src.
1894 	 * Otherwise, the exception table is indexed by
1895 	 * a hash of only rt6i_dst.
1896 	 */
1897 	if (plen)
1898 		src_key = &rt->rt6i_src.addr;
1899 #endif
1900 	rt6_ex = __rt6_find_exception_spinlock(&bucket,
1901 					       &rt->rt6i_dst.addr,
1902 					       src_key);
1903 	if (rt6_ex) {
1904 		rt6_remove_exception(bucket, rt6_ex);
1905 		err = 0;
1906 	} else {
1907 		err = -ENOENT;
1908 	}
1909 
1910 	spin_unlock_bh(&rt6_exception_lock);
1911 	return err;
1912 }
1913 
1914 struct fib6_nh_excptn_arg {
1915 	struct rt6_info	*rt;
1916 	int		plen;
1917 };
1918 
1919 static int rt6_nh_remove_exception_rt(struct fib6_nh *nh, void *_arg)
1920 {
1921 	struct fib6_nh_excptn_arg *arg = _arg;
1922 	int err;
1923 
1924 	err = fib6_nh_remove_exception(nh, arg->plen, arg->rt);
1925 	if (err == 0)
1926 		return 1;
1927 
1928 	return 0;
1929 }
1930 
1931 static int rt6_remove_exception_rt(struct rt6_info *rt)
1932 {
1933 	struct fib6_info *from;
1934 
1935 	from = rcu_dereference(rt->from);
1936 	if (!from || !(rt->rt6i_flags & RTF_CACHE))
1937 		return -EINVAL;
1938 
1939 	if (from->nh) {
1940 		struct fib6_nh_excptn_arg arg = {
1941 			.rt = rt,
1942 			.plen = from->fib6_src.plen
1943 		};
1944 		int rc;
1945 
1946 		/* rc = 1 means an entry was found */
1947 		rc = nexthop_for_each_fib6_nh(from->nh,
1948 					      rt6_nh_remove_exception_rt,
1949 					      &arg);
1950 		return rc ? 0 : -ENOENT;
1951 	}
1952 
1953 	return fib6_nh_remove_exception(from->fib6_nh,
1954 					from->fib6_src.plen, rt);
1955 }
1956 
1957 /* Find rt6_ex which contains the passed in rt cache and
1958  * refresh its stamp
1959  */
1960 static void fib6_nh_update_exception(const struct fib6_nh *nh, int plen,
1961 				     const struct rt6_info *rt)
1962 {
1963 	const struct in6_addr *src_key = NULL;
1964 	struct rt6_exception_bucket *bucket;
1965 	struct rt6_exception *rt6_ex;
1966 
1967 	bucket = fib6_nh_get_excptn_bucket(nh, NULL);
1968 #ifdef CONFIG_IPV6_SUBTREES
1969 	/* rt6i_src.plen != 0 indicates 'from' is in subtree
1970 	 * and exception table is indexed by a hash of
1971 	 * both rt6i_dst and rt6i_src.
1972 	 * Otherwise, the exception table is indexed by
1973 	 * a hash of only rt6i_dst.
1974 	 */
1975 	if (plen)
1976 		src_key = &rt->rt6i_src.addr;
1977 #endif
1978 	rt6_ex = __rt6_find_exception_rcu(&bucket, &rt->rt6i_dst.addr, src_key);
1979 	if (rt6_ex)
1980 		rt6_ex->stamp = jiffies;
1981 }
1982 
1983 struct fib6_nh_match_arg {
1984 	const struct net_device *dev;
1985 	const struct in6_addr	*gw;
1986 	struct fib6_nh		*match;
1987 };
1988 
1989 /* determine if fib6_nh has given device and gateway */
1990 static int fib6_nh_find_match(struct fib6_nh *nh, void *_arg)
1991 {
1992 	struct fib6_nh_match_arg *arg = _arg;
1993 
1994 	if (arg->dev != nh->fib_nh_dev ||
1995 	    (arg->gw && !nh->fib_nh_gw_family) ||
1996 	    (!arg->gw && nh->fib_nh_gw_family) ||
1997 	    (arg->gw && !ipv6_addr_equal(arg->gw, &nh->fib_nh_gw6)))
1998 		return 0;
1999 
2000 	arg->match = nh;
2001 
2002 	/* found a match, break the loop */
2003 	return 1;
2004 }
2005 
2006 static void rt6_update_exception_stamp_rt(struct rt6_info *rt)
2007 {
2008 	struct fib6_info *from;
2009 	struct fib6_nh *fib6_nh;
2010 
2011 	rcu_read_lock();
2012 
2013 	from = rcu_dereference(rt->from);
2014 	if (!from || !(rt->rt6i_flags & RTF_CACHE))
2015 		goto unlock;
2016 
2017 	if (from->nh) {
2018 		struct fib6_nh_match_arg arg = {
2019 			.dev = rt->dst.dev,
2020 			.gw = &rt->rt6i_gateway,
2021 		};
2022 
2023 		nexthop_for_each_fib6_nh(from->nh, fib6_nh_find_match, &arg);
2024 
2025 		if (!arg.match)
2026 			goto unlock;
2027 		fib6_nh = arg.match;
2028 	} else {
2029 		fib6_nh = from->fib6_nh;
2030 	}
2031 	fib6_nh_update_exception(fib6_nh, from->fib6_src.plen, rt);
2032 unlock:
2033 	rcu_read_unlock();
2034 }
2035 
2036 static bool rt6_mtu_change_route_allowed(struct inet6_dev *idev,
2037 					 struct rt6_info *rt, int mtu)
2038 {
2039 	/* If the new MTU is lower than the route PMTU, this new MTU will be the
2040 	 * lowest MTU in the path: always allow updating the route PMTU to
2041 	 * reflect PMTU decreases.
2042 	 *
2043 	 * If the new MTU is higher, and the route PMTU is equal to the local
2044 	 * MTU, this means the old MTU is the lowest in the path, so allow
2045 	 * updating it: if other nodes now have lower MTUs, PMTU discovery will
2046 	 * handle this.
2047 	 */
2048 
2049 	if (dst_mtu(&rt->dst) >= mtu)
2050 		return true;
2051 
2052 	if (dst_mtu(&rt->dst) == idev->cnf.mtu6)
2053 		return true;
2054 
2055 	return false;
2056 }
2057 
2058 static void rt6_exceptions_update_pmtu(struct inet6_dev *idev,
2059 				       const struct fib6_nh *nh, int mtu)
2060 {
2061 	struct rt6_exception_bucket *bucket;
2062 	struct rt6_exception *rt6_ex;
2063 	int i;
2064 
2065 	bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
2066 	if (!bucket)
2067 		return;
2068 
2069 	for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
2070 		hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
2071 			struct rt6_info *entry = rt6_ex->rt6i;
2072 
2073 			/* For RTF_CACHE with rt6i_pmtu == 0 (i.e. a redirected
2074 			 * route), the metrics of its rt->from have already
2075 			 * been updated.
2076 			 */
2077 			if (dst_metric_raw(&entry->dst, RTAX_MTU) &&
2078 			    rt6_mtu_change_route_allowed(idev, entry, mtu))
2079 				dst_metric_set(&entry->dst, RTAX_MTU, mtu);
2080 		}
2081 		bucket++;
2082 	}
2083 }
2084 
2085 #define RTF_CACHE_GATEWAY	(RTF_GATEWAY | RTF_CACHE)
2086 
2087 static void fib6_nh_exceptions_clean_tohost(const struct fib6_nh *nh,
2088 					    const struct in6_addr *gateway)
2089 {
2090 	struct rt6_exception_bucket *bucket;
2091 	struct rt6_exception *rt6_ex;
2092 	struct hlist_node *tmp;
2093 	int i;
2094 
2095 	if (!rcu_access_pointer(nh->rt6i_exception_bucket))
2096 		return;
2097 
2098 	spin_lock_bh(&rt6_exception_lock);
2099 	bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
2100 	if (bucket) {
2101 		for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
2102 			hlist_for_each_entry_safe(rt6_ex, tmp,
2103 						  &bucket->chain, hlist) {
2104 				struct rt6_info *entry = rt6_ex->rt6i;
2105 
2106 				if ((entry->rt6i_flags & RTF_CACHE_GATEWAY) ==
2107 				    RTF_CACHE_GATEWAY &&
2108 				    ipv6_addr_equal(gateway,
2109 						    &entry->rt6i_gateway)) {
2110 					rt6_remove_exception(bucket, rt6_ex);
2111 				}
2112 			}
2113 			bucket++;
2114 		}
2115 	}
2116 
2117 	spin_unlock_bh(&rt6_exception_lock);
2118 }
2119 
2120 static void rt6_age_examine_exception(struct rt6_exception_bucket *bucket,
2121 				      struct rt6_exception *rt6_ex,
2122 				      struct fib6_gc_args *gc_args,
2123 				      unsigned long now)
2124 {
2125 	struct rt6_info *rt = rt6_ex->rt6i;
2126 
2127 	/* we are pruning and obsoleting aged-out and non gateway exceptions
2128 	 * even if others have still references to them, so that on next
2129 	 * dst_check() such references can be dropped.
2130 	 * EXPIRES exceptions - e.g. pmtu-generated ones are pruned when
2131 	 * expired, independently from their aging, as per RFC 8201 section 4
2132 	 */
2133 	if (!(rt->rt6i_flags & RTF_EXPIRES)) {
2134 		if (time_after_eq(now, rt->dst.lastuse + gc_args->timeout)) {
2135 			pr_debug("aging clone %p\n", rt);
2136 			rt6_remove_exception(bucket, rt6_ex);
2137 			return;
2138 		}
2139 	} else if (time_after(jiffies, rt->dst.expires)) {
2140 		pr_debug("purging expired route %p\n", rt);
2141 		rt6_remove_exception(bucket, rt6_ex);
2142 		return;
2143 	}
2144 
2145 	if (rt->rt6i_flags & RTF_GATEWAY) {
2146 		struct neighbour *neigh;
2147 
2148 		neigh = __ipv6_neigh_lookup_noref(rt->dst.dev, &rt->rt6i_gateway);
2149 
2150 		if (!(neigh && (neigh->flags & NTF_ROUTER))) {
2151 			pr_debug("purging route %p via non-router but gateway\n",
2152 				 rt);
2153 			rt6_remove_exception(bucket, rt6_ex);
2154 			return;
2155 		}
2156 	}
2157 
2158 	gc_args->more++;
2159 }
2160 
2161 static void fib6_nh_age_exceptions(const struct fib6_nh *nh,
2162 				   struct fib6_gc_args *gc_args,
2163 				   unsigned long now)
2164 {
2165 	struct rt6_exception_bucket *bucket;
2166 	struct rt6_exception *rt6_ex;
2167 	struct hlist_node *tmp;
2168 	int i;
2169 
2170 	if (!rcu_access_pointer(nh->rt6i_exception_bucket))
2171 		return;
2172 
2173 	rcu_read_lock_bh();
2174 	spin_lock(&rt6_exception_lock);
2175 	bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
2176 	if (bucket) {
2177 		for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
2178 			hlist_for_each_entry_safe(rt6_ex, tmp,
2179 						  &bucket->chain, hlist) {
2180 				rt6_age_examine_exception(bucket, rt6_ex,
2181 							  gc_args, now);
2182 			}
2183 			bucket++;
2184 		}
2185 	}
2186 	spin_unlock(&rt6_exception_lock);
2187 	rcu_read_unlock_bh();
2188 }
2189 
2190 struct fib6_nh_age_excptn_arg {
2191 	struct fib6_gc_args	*gc_args;
2192 	unsigned long		now;
2193 };
2194 
2195 static int rt6_nh_age_exceptions(struct fib6_nh *nh, void *_arg)
2196 {
2197 	struct fib6_nh_age_excptn_arg *arg = _arg;
2198 
2199 	fib6_nh_age_exceptions(nh, arg->gc_args, arg->now);
2200 	return 0;
2201 }
2202 
2203 void rt6_age_exceptions(struct fib6_info *f6i,
2204 			struct fib6_gc_args *gc_args,
2205 			unsigned long now)
2206 {
2207 	if (f6i->nh) {
2208 		struct fib6_nh_age_excptn_arg arg = {
2209 			.gc_args = gc_args,
2210 			.now = now
2211 		};
2212 
2213 		nexthop_for_each_fib6_nh(f6i->nh, rt6_nh_age_exceptions,
2214 					 &arg);
2215 	} else {
2216 		fib6_nh_age_exceptions(f6i->fib6_nh, gc_args, now);
2217 	}
2218 }
2219 
2220 /* must be called with rcu lock held */
2221 int fib6_table_lookup(struct net *net, struct fib6_table *table, int oif,
2222 		      struct flowi6 *fl6, struct fib6_result *res, int strict)
2223 {
2224 	struct fib6_node *fn, *saved_fn;
2225 
2226 	fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
2227 	saved_fn = fn;
2228 
2229 redo_rt6_select:
2230 	rt6_select(net, fn, oif, res, strict);
2231 	if (res->f6i == net->ipv6.fib6_null_entry) {
2232 		fn = fib6_backtrack(fn, &fl6->saddr);
2233 		if (fn)
2234 			goto redo_rt6_select;
2235 		else if (strict & RT6_LOOKUP_F_REACHABLE) {
2236 			/* also consider unreachable route */
2237 			strict &= ~RT6_LOOKUP_F_REACHABLE;
2238 			fn = saved_fn;
2239 			goto redo_rt6_select;
2240 		}
2241 	}
2242 
2243 	trace_fib6_table_lookup(net, res, table, fl6);
2244 
2245 	return 0;
2246 }
2247 
2248 struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table,
2249 			       int oif, struct flowi6 *fl6,
2250 			       const struct sk_buff *skb, int flags)
2251 {
2252 	struct fib6_result res = {};
2253 	struct rt6_info *rt = NULL;
2254 	int strict = 0;
2255 
2256 	WARN_ON_ONCE((flags & RT6_LOOKUP_F_DST_NOREF) &&
2257 		     !rcu_read_lock_held());
2258 
2259 	strict |= flags & RT6_LOOKUP_F_IFACE;
2260 	strict |= flags & RT6_LOOKUP_F_IGNORE_LINKSTATE;
2261 	if (READ_ONCE(net->ipv6.devconf_all->forwarding) == 0)
2262 		strict |= RT6_LOOKUP_F_REACHABLE;
2263 
2264 	rcu_read_lock();
2265 
2266 	fib6_table_lookup(net, table, oif, fl6, &res, strict);
2267 	if (res.f6i == net->ipv6.fib6_null_entry)
2268 		goto out;
2269 
2270 	fib6_select_path(net, &res, fl6, oif, false, skb, strict);
2271 
2272 	/*Search through exception table */
2273 	rt = rt6_find_cached_rt(&res, &fl6->daddr, &fl6->saddr);
2274 	if (rt) {
2275 		goto out;
2276 	} else if (unlikely((fl6->flowi6_flags & FLOWI_FLAG_KNOWN_NH) &&
2277 			    !res.nh->fib_nh_gw_family)) {
2278 		/* Create a RTF_CACHE clone which will not be
2279 		 * owned by the fib6 tree.  It is for the special case where
2280 		 * the daddr in the skb during the neighbor look-up is different
2281 		 * from the fl6->daddr used to look-up route here.
2282 		 */
2283 		rt = ip6_rt_cache_alloc(&res, &fl6->daddr, NULL);
2284 
2285 		if (rt) {
2286 			/* 1 refcnt is taken during ip6_rt_cache_alloc().
2287 			 * As rt6_uncached_list_add() does not consume refcnt,
2288 			 * this refcnt is always returned to the caller even
2289 			 * if caller sets RT6_LOOKUP_F_DST_NOREF flag.
2290 			 */
2291 			rt6_uncached_list_add(rt);
2292 			rcu_read_unlock();
2293 
2294 			return rt;
2295 		}
2296 	} else {
2297 		/* Get a percpu copy */
2298 		local_bh_disable();
2299 		rt = rt6_get_pcpu_route(&res);
2300 
2301 		if (!rt)
2302 			rt = rt6_make_pcpu_route(net, &res);
2303 
2304 		local_bh_enable();
2305 	}
2306 out:
2307 	if (!rt)
2308 		rt = net->ipv6.ip6_null_entry;
2309 	if (!(flags & RT6_LOOKUP_F_DST_NOREF))
2310 		ip6_hold_safe(net, &rt);
2311 	rcu_read_unlock();
2312 
2313 	return rt;
2314 }
2315 EXPORT_SYMBOL_GPL(ip6_pol_route);
2316 
2317 INDIRECT_CALLABLE_SCOPE struct rt6_info *ip6_pol_route_input(struct net *net,
2318 					    struct fib6_table *table,
2319 					    struct flowi6 *fl6,
2320 					    const struct sk_buff *skb,
2321 					    int flags)
2322 {
2323 	return ip6_pol_route(net, table, fl6->flowi6_iif, fl6, skb, flags);
2324 }
2325 
2326 struct dst_entry *ip6_route_input_lookup(struct net *net,
2327 					 struct net_device *dev,
2328 					 struct flowi6 *fl6,
2329 					 const struct sk_buff *skb,
2330 					 int flags)
2331 {
2332 	if (rt6_need_strict(&fl6->daddr) && dev->type != ARPHRD_PIMREG)
2333 		flags |= RT6_LOOKUP_F_IFACE;
2334 
2335 	return fib6_rule_lookup(net, fl6, skb, flags, ip6_pol_route_input);
2336 }
2337 EXPORT_SYMBOL_GPL(ip6_route_input_lookup);
2338 
2339 static void ip6_multipath_l3_keys(const struct sk_buff *skb,
2340 				  struct flow_keys *keys,
2341 				  struct flow_keys *flkeys)
2342 {
2343 	const struct ipv6hdr *outer_iph = ipv6_hdr(skb);
2344 	const struct ipv6hdr *key_iph = outer_iph;
2345 	struct flow_keys *_flkeys = flkeys;
2346 	const struct ipv6hdr *inner_iph;
2347 	const struct icmp6hdr *icmph;
2348 	struct ipv6hdr _inner_iph;
2349 	struct icmp6hdr _icmph;
2350 
2351 	if (likely(outer_iph->nexthdr != IPPROTO_ICMPV6))
2352 		goto out;
2353 
2354 	icmph = skb_header_pointer(skb, skb_transport_offset(skb),
2355 				   sizeof(_icmph), &_icmph);
2356 	if (!icmph)
2357 		goto out;
2358 
2359 	if (!icmpv6_is_err(icmph->icmp6_type))
2360 		goto out;
2361 
2362 	inner_iph = skb_header_pointer(skb,
2363 				       skb_transport_offset(skb) + sizeof(*icmph),
2364 				       sizeof(_inner_iph), &_inner_iph);
2365 	if (!inner_iph)
2366 		goto out;
2367 
2368 	key_iph = inner_iph;
2369 	_flkeys = NULL;
2370 out:
2371 	if (_flkeys) {
2372 		keys->addrs.v6addrs.src = _flkeys->addrs.v6addrs.src;
2373 		keys->addrs.v6addrs.dst = _flkeys->addrs.v6addrs.dst;
2374 		keys->tags.flow_label = _flkeys->tags.flow_label;
2375 		keys->basic.ip_proto = _flkeys->basic.ip_proto;
2376 	} else {
2377 		keys->addrs.v6addrs.src = key_iph->saddr;
2378 		keys->addrs.v6addrs.dst = key_iph->daddr;
2379 		keys->tags.flow_label = ip6_flowlabel(key_iph);
2380 		keys->basic.ip_proto = key_iph->nexthdr;
2381 	}
2382 }
2383 
2384 static u32 rt6_multipath_custom_hash_outer(const struct net *net,
2385 					   const struct sk_buff *skb,
2386 					   bool *p_has_inner)
2387 {
2388 	u32 hash_fields = ip6_multipath_hash_fields(net);
2389 	struct flow_keys keys, hash_keys;
2390 
2391 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_OUTER_MASK))
2392 		return 0;
2393 
2394 	memset(&hash_keys, 0, sizeof(hash_keys));
2395 	skb_flow_dissect_flow_keys(skb, &keys, FLOW_DISSECTOR_F_STOP_AT_ENCAP);
2396 
2397 	hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2398 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_IP)
2399 		hash_keys.addrs.v6addrs.src = keys.addrs.v6addrs.src;
2400 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_IP)
2401 		hash_keys.addrs.v6addrs.dst = keys.addrs.v6addrs.dst;
2402 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_IP_PROTO)
2403 		hash_keys.basic.ip_proto = keys.basic.ip_proto;
2404 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_FLOWLABEL)
2405 		hash_keys.tags.flow_label = keys.tags.flow_label;
2406 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_PORT)
2407 		hash_keys.ports.src = keys.ports.src;
2408 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_PORT)
2409 		hash_keys.ports.dst = keys.ports.dst;
2410 
2411 	*p_has_inner = !!(keys.control.flags & FLOW_DIS_ENCAPSULATION);
2412 	return fib_multipath_hash_from_keys(net, &hash_keys);
2413 }
2414 
2415 static u32 rt6_multipath_custom_hash_inner(const struct net *net,
2416 					   const struct sk_buff *skb,
2417 					   bool has_inner)
2418 {
2419 	u32 hash_fields = ip6_multipath_hash_fields(net);
2420 	struct flow_keys keys, hash_keys;
2421 
2422 	/* We assume the packet carries an encapsulation, but if none was
2423 	 * encountered during dissection of the outer flow, then there is no
2424 	 * point in calling the flow dissector again.
2425 	 */
2426 	if (!has_inner)
2427 		return 0;
2428 
2429 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_MASK))
2430 		return 0;
2431 
2432 	memset(&hash_keys, 0, sizeof(hash_keys));
2433 	skb_flow_dissect_flow_keys(skb, &keys, 0);
2434 
2435 	if (!(keys.control.flags & FLOW_DIS_ENCAPSULATION))
2436 		return 0;
2437 
2438 	if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
2439 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2440 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_IP)
2441 			hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
2442 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_IP)
2443 			hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst;
2444 	} else if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
2445 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2446 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_IP)
2447 			hash_keys.addrs.v6addrs.src = keys.addrs.v6addrs.src;
2448 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_IP)
2449 			hash_keys.addrs.v6addrs.dst = keys.addrs.v6addrs.dst;
2450 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_FLOWLABEL)
2451 			hash_keys.tags.flow_label = keys.tags.flow_label;
2452 	}
2453 
2454 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_IP_PROTO)
2455 		hash_keys.basic.ip_proto = keys.basic.ip_proto;
2456 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_PORT)
2457 		hash_keys.ports.src = keys.ports.src;
2458 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_PORT)
2459 		hash_keys.ports.dst = keys.ports.dst;
2460 
2461 	return fib_multipath_hash_from_keys(net, &hash_keys);
2462 }
2463 
2464 static u32 rt6_multipath_custom_hash_skb(const struct net *net,
2465 					 const struct sk_buff *skb)
2466 {
2467 	u32 mhash, mhash_inner;
2468 	bool has_inner = true;
2469 
2470 	mhash = rt6_multipath_custom_hash_outer(net, skb, &has_inner);
2471 	mhash_inner = rt6_multipath_custom_hash_inner(net, skb, has_inner);
2472 
2473 	return jhash_2words(mhash, mhash_inner, 0);
2474 }
2475 
2476 static u32 rt6_multipath_custom_hash_fl6(const struct net *net,
2477 					 const struct flowi6 *fl6)
2478 {
2479 	u32 hash_fields = ip6_multipath_hash_fields(net);
2480 	struct flow_keys hash_keys;
2481 
2482 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_OUTER_MASK))
2483 		return 0;
2484 
2485 	memset(&hash_keys, 0, sizeof(hash_keys));
2486 	hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2487 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_IP)
2488 		hash_keys.addrs.v6addrs.src = fl6->saddr;
2489 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_IP)
2490 		hash_keys.addrs.v6addrs.dst = fl6->daddr;
2491 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_IP_PROTO)
2492 		hash_keys.basic.ip_proto = fl6->flowi6_proto;
2493 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_FLOWLABEL)
2494 		hash_keys.tags.flow_label = (__force u32)flowi6_get_flowlabel(fl6);
2495 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_PORT) {
2496 		if (fl6->flowi6_flags & FLOWI_FLAG_ANY_SPORT)
2497 			hash_keys.ports.src = (__force __be16)get_random_u16();
2498 		else
2499 			hash_keys.ports.src = fl6->fl6_sport;
2500 	}
2501 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_PORT)
2502 		hash_keys.ports.dst = fl6->fl6_dport;
2503 
2504 	return fib_multipath_hash_from_keys(net, &hash_keys);
2505 }
2506 
2507 /* if skb is set it will be used and fl6 can be NULL */
2508 u32 rt6_multipath_hash(const struct net *net, const struct flowi6 *fl6,
2509 		       const struct sk_buff *skb, struct flow_keys *flkeys)
2510 {
2511 	struct flow_keys hash_keys;
2512 	u32 mhash = 0;
2513 
2514 	switch (ip6_multipath_hash_policy(net)) {
2515 	case 0:
2516 		memset(&hash_keys, 0, sizeof(hash_keys));
2517 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2518 		if (skb) {
2519 			ip6_multipath_l3_keys(skb, &hash_keys, flkeys);
2520 		} else {
2521 			hash_keys.addrs.v6addrs.src = fl6->saddr;
2522 			hash_keys.addrs.v6addrs.dst = fl6->daddr;
2523 			hash_keys.tags.flow_label = (__force u32)flowi6_get_flowlabel(fl6);
2524 			hash_keys.basic.ip_proto = fl6->flowi6_proto;
2525 		}
2526 		mhash = fib_multipath_hash_from_keys(net, &hash_keys);
2527 		break;
2528 	case 1:
2529 		if (skb) {
2530 			unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP;
2531 			struct flow_keys keys;
2532 
2533 			/* short-circuit if we already have L4 hash present */
2534 			if (skb->l4_hash)
2535 				return skb_get_hash_raw(skb) >> 1;
2536 
2537 			memset(&hash_keys, 0, sizeof(hash_keys));
2538 
2539 			if (!flkeys) {
2540 				skb_flow_dissect_flow_keys(skb, &keys, flag);
2541 				flkeys = &keys;
2542 			}
2543 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2544 			hash_keys.addrs.v6addrs.src = flkeys->addrs.v6addrs.src;
2545 			hash_keys.addrs.v6addrs.dst = flkeys->addrs.v6addrs.dst;
2546 			hash_keys.ports.src = flkeys->ports.src;
2547 			hash_keys.ports.dst = flkeys->ports.dst;
2548 			hash_keys.basic.ip_proto = flkeys->basic.ip_proto;
2549 		} else {
2550 			memset(&hash_keys, 0, sizeof(hash_keys));
2551 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2552 			hash_keys.addrs.v6addrs.src = fl6->saddr;
2553 			hash_keys.addrs.v6addrs.dst = fl6->daddr;
2554 			if (fl6->flowi6_flags & FLOWI_FLAG_ANY_SPORT)
2555 				hash_keys.ports.src = (__force __be16)get_random_u16();
2556 			else
2557 				hash_keys.ports.src = fl6->fl6_sport;
2558 			hash_keys.ports.dst = fl6->fl6_dport;
2559 			hash_keys.basic.ip_proto = fl6->flowi6_proto;
2560 		}
2561 		mhash = fib_multipath_hash_from_keys(net, &hash_keys);
2562 		break;
2563 	case 2:
2564 		memset(&hash_keys, 0, sizeof(hash_keys));
2565 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2566 		if (skb) {
2567 			struct flow_keys keys;
2568 
2569 			if (!flkeys) {
2570 				skb_flow_dissect_flow_keys(skb, &keys, 0);
2571 				flkeys = &keys;
2572 			}
2573 
2574 			/* Inner can be v4 or v6 */
2575 			if (flkeys->control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
2576 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2577 				hash_keys.addrs.v4addrs.src = flkeys->addrs.v4addrs.src;
2578 				hash_keys.addrs.v4addrs.dst = flkeys->addrs.v4addrs.dst;
2579 			} else if (flkeys->control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
2580 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2581 				hash_keys.addrs.v6addrs.src = flkeys->addrs.v6addrs.src;
2582 				hash_keys.addrs.v6addrs.dst = flkeys->addrs.v6addrs.dst;
2583 				hash_keys.tags.flow_label = flkeys->tags.flow_label;
2584 				hash_keys.basic.ip_proto = flkeys->basic.ip_proto;
2585 			} else {
2586 				/* Same as case 0 */
2587 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2588 				ip6_multipath_l3_keys(skb, &hash_keys, flkeys);
2589 			}
2590 		} else {
2591 			/* Same as case 0 */
2592 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2593 			hash_keys.addrs.v6addrs.src = fl6->saddr;
2594 			hash_keys.addrs.v6addrs.dst = fl6->daddr;
2595 			hash_keys.tags.flow_label = (__force u32)flowi6_get_flowlabel(fl6);
2596 			hash_keys.basic.ip_proto = fl6->flowi6_proto;
2597 		}
2598 		mhash = fib_multipath_hash_from_keys(net, &hash_keys);
2599 		break;
2600 	case 3:
2601 		if (skb)
2602 			mhash = rt6_multipath_custom_hash_skb(net, skb);
2603 		else
2604 			mhash = rt6_multipath_custom_hash_fl6(net, fl6);
2605 		break;
2606 	}
2607 
2608 	return mhash >> 1;
2609 }
2610 
2611 /* Called with rcu held */
2612 void ip6_route_input(struct sk_buff *skb)
2613 {
2614 	const struct ipv6hdr *iph = ipv6_hdr(skb);
2615 	struct net *net = dev_net(skb->dev);
2616 	int flags = RT6_LOOKUP_F_HAS_SADDR | RT6_LOOKUP_F_DST_NOREF;
2617 	struct ip_tunnel_info *tun_info;
2618 	struct flowi6 fl6 = {
2619 		.flowi6_iif = skb->dev->ifindex,
2620 		.daddr = iph->daddr,
2621 		.saddr = iph->saddr,
2622 		.flowlabel = ip6_flowinfo(iph),
2623 		.flowi6_mark = skb->mark,
2624 		.flowi6_proto = iph->nexthdr,
2625 	};
2626 	struct flow_keys *flkeys = NULL, _flkeys;
2627 
2628 	tun_info = skb_tunnel_info(skb);
2629 	if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX))
2630 		fl6.flowi6_tun_key.tun_id = tun_info->key.tun_id;
2631 
2632 	if (fib6_rules_early_flow_dissect(net, skb, &fl6, &_flkeys))
2633 		flkeys = &_flkeys;
2634 
2635 	if (unlikely(fl6.flowi6_proto == IPPROTO_ICMPV6))
2636 		fl6.mp_hash = rt6_multipath_hash(net, &fl6, skb, flkeys);
2637 	skb_dst_drop(skb);
2638 	skb_dst_set_noref(skb, ip6_route_input_lookup(net, skb->dev,
2639 						      &fl6, skb, flags));
2640 }
2641 
2642 INDIRECT_CALLABLE_SCOPE struct rt6_info *ip6_pol_route_output(struct net *net,
2643 					     struct fib6_table *table,
2644 					     struct flowi6 *fl6,
2645 					     const struct sk_buff *skb,
2646 					     int flags)
2647 {
2648 	return ip6_pol_route(net, table, fl6->flowi6_oif, fl6, skb, flags);
2649 }
2650 
2651 static struct dst_entry *ip6_route_output_flags_noref(struct net *net,
2652 						      const struct sock *sk,
2653 						      struct flowi6 *fl6,
2654 						      int flags)
2655 {
2656 	bool any_src;
2657 
2658 	if (ipv6_addr_type(&fl6->daddr) &
2659 	    (IPV6_ADDR_MULTICAST | IPV6_ADDR_LINKLOCAL)) {
2660 		struct dst_entry *dst;
2661 
2662 		/* This function does not take refcnt on the dst */
2663 		dst = l3mdev_link_scope_lookup(net, fl6);
2664 		if (dst)
2665 			return dst;
2666 	}
2667 
2668 	fl6->flowi6_iif = LOOPBACK_IFINDEX;
2669 
2670 	flags |= RT6_LOOKUP_F_DST_NOREF;
2671 	any_src = ipv6_addr_any(&fl6->saddr);
2672 	if ((sk && sk->sk_bound_dev_if) || rt6_need_strict(&fl6->daddr) ||
2673 	    (fl6->flowi6_oif && any_src))
2674 		flags |= RT6_LOOKUP_F_IFACE;
2675 
2676 	if (!any_src)
2677 		flags |= RT6_LOOKUP_F_HAS_SADDR;
2678 	else if (sk)
2679 		flags |= rt6_srcprefs2flags(READ_ONCE(inet6_sk(sk)->srcprefs));
2680 
2681 	return fib6_rule_lookup(net, fl6, NULL, flags, ip6_pol_route_output);
2682 }
2683 
2684 struct dst_entry *ip6_route_output_flags(struct net *net,
2685 					 const struct sock *sk,
2686 					 struct flowi6 *fl6,
2687 					 int flags)
2688 {
2689 	struct dst_entry *dst;
2690 	struct rt6_info *rt6;
2691 
2692 	rcu_read_lock();
2693 	dst = ip6_route_output_flags_noref(net, sk, fl6, flags);
2694 	rt6 = dst_rt6_info(dst);
2695 	/* For dst cached in uncached_list, refcnt is already taken. */
2696 	if (list_empty(&rt6->dst.rt_uncached) && !dst_hold_safe(dst)) {
2697 		dst = &net->ipv6.ip6_null_entry->dst;
2698 		dst_hold(dst);
2699 	}
2700 	rcu_read_unlock();
2701 
2702 	return dst;
2703 }
2704 EXPORT_SYMBOL_GPL(ip6_route_output_flags);
2705 
2706 struct dst_entry *ip6_blackhole_route(struct net *net, struct dst_entry *dst_orig)
2707 {
2708 	struct rt6_info *rt, *ort = dst_rt6_info(dst_orig);
2709 	struct net_device *loopback_dev = net->loopback_dev;
2710 	struct dst_entry *new = NULL;
2711 
2712 	rt = dst_alloc(&ip6_dst_blackhole_ops, loopback_dev,
2713 		       DST_OBSOLETE_DEAD, 0);
2714 	if (rt) {
2715 		rt6_info_init(rt);
2716 		atomic_inc(&net->ipv6.rt6_stats->fib_rt_alloc);
2717 
2718 		new = &rt->dst;
2719 		new->__use = 1;
2720 		new->input = dst_discard;
2721 		new->output = dst_discard_out;
2722 
2723 		dst_copy_metrics(new, &ort->dst);
2724 
2725 		rt->rt6i_idev = in6_dev_get(loopback_dev);
2726 		rt->rt6i_gateway = ort->rt6i_gateway;
2727 		rt->rt6i_flags = ort->rt6i_flags & ~RTF_PCPU;
2728 
2729 		memcpy(&rt->rt6i_dst, &ort->rt6i_dst, sizeof(struct rt6key));
2730 #ifdef CONFIG_IPV6_SUBTREES
2731 		memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
2732 #endif
2733 	}
2734 
2735 	dst_release(dst_orig);
2736 	return new ? new : ERR_PTR(-ENOMEM);
2737 }
2738 
2739 /*
2740  *	Destination cache support functions
2741  */
2742 
2743 static bool fib6_check(struct fib6_info *f6i, u32 cookie)
2744 {
2745 	u32 rt_cookie = 0;
2746 
2747 	if (!fib6_get_cookie_safe(f6i, &rt_cookie) || rt_cookie != cookie)
2748 		return false;
2749 
2750 	if (fib6_check_expired(f6i))
2751 		return false;
2752 
2753 	return true;
2754 }
2755 
2756 static struct dst_entry *rt6_check(struct rt6_info *rt,
2757 				   struct fib6_info *from,
2758 				   u32 cookie)
2759 {
2760 	u32 rt_cookie = 0;
2761 
2762 	if (!from || !fib6_get_cookie_safe(from, &rt_cookie) ||
2763 	    rt_cookie != cookie)
2764 		return NULL;
2765 
2766 	if (rt6_check_expired(rt))
2767 		return NULL;
2768 
2769 	return &rt->dst;
2770 }
2771 
2772 static struct dst_entry *rt6_dst_from_check(struct rt6_info *rt,
2773 					    struct fib6_info *from,
2774 					    u32 cookie)
2775 {
2776 	if (!__rt6_check_expired(rt) &&
2777 	    rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK &&
2778 	    fib6_check(from, cookie))
2779 		return &rt->dst;
2780 	else
2781 		return NULL;
2782 }
2783 
2784 INDIRECT_CALLABLE_SCOPE struct dst_entry *ip6_dst_check(struct dst_entry *dst,
2785 							u32 cookie)
2786 {
2787 	struct dst_entry *dst_ret;
2788 	struct fib6_info *from;
2789 	struct rt6_info *rt;
2790 
2791 	rt = dst_rt6_info(dst);
2792 
2793 	if (rt->sernum)
2794 		return rt6_is_valid(rt) ? dst : NULL;
2795 
2796 	rcu_read_lock();
2797 
2798 	/* All IPV6 dsts are created with ->obsolete set to the value
2799 	 * DST_OBSOLETE_FORCE_CHK which forces validation calls down
2800 	 * into this function always.
2801 	 */
2802 
2803 	from = rcu_dereference(rt->from);
2804 
2805 	if (from && (rt->rt6i_flags & RTF_PCPU ||
2806 	    unlikely(!list_empty(&rt->dst.rt_uncached))))
2807 		dst_ret = rt6_dst_from_check(rt, from, cookie);
2808 	else
2809 		dst_ret = rt6_check(rt, from, cookie);
2810 
2811 	rcu_read_unlock();
2812 
2813 	return dst_ret;
2814 }
2815 EXPORT_INDIRECT_CALLABLE(ip6_dst_check);
2816 
2817 static void ip6_negative_advice(struct sock *sk,
2818 				struct dst_entry *dst)
2819 {
2820 	struct rt6_info *rt = dst_rt6_info(dst);
2821 
2822 	if (rt->rt6i_flags & RTF_CACHE) {
2823 		rcu_read_lock();
2824 		if (rt6_check_expired(rt)) {
2825 			/* rt/dst can not be destroyed yet,
2826 			 * because of rcu_read_lock()
2827 			 */
2828 			sk_dst_reset(sk);
2829 			rt6_remove_exception_rt(rt);
2830 		}
2831 		rcu_read_unlock();
2832 		return;
2833 	}
2834 	sk_dst_reset(sk);
2835 }
2836 
2837 static void ip6_link_failure(struct sk_buff *skb)
2838 {
2839 	struct rt6_info *rt;
2840 
2841 	icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0);
2842 
2843 	rt = dst_rt6_info(skb_dst(skb));
2844 	if (rt) {
2845 		rcu_read_lock();
2846 		if (rt->rt6i_flags & RTF_CACHE) {
2847 			rt6_remove_exception_rt(rt);
2848 		} else {
2849 			struct fib6_info *from;
2850 			struct fib6_node *fn;
2851 
2852 			from = rcu_dereference(rt->from);
2853 			if (from) {
2854 				fn = rcu_dereference(from->fib6_node);
2855 				if (fn && (rt->rt6i_flags & RTF_DEFAULT))
2856 					WRITE_ONCE(fn->fn_sernum, -1);
2857 			}
2858 		}
2859 		rcu_read_unlock();
2860 	}
2861 }
2862 
2863 static void rt6_update_expires(struct rt6_info *rt0, int timeout)
2864 {
2865 	if (!(rt0->rt6i_flags & RTF_EXPIRES)) {
2866 		struct fib6_info *from;
2867 
2868 		rcu_read_lock();
2869 		from = rcu_dereference(rt0->from);
2870 		if (from)
2871 			rt0->dst.expires = from->expires;
2872 		rcu_read_unlock();
2873 	}
2874 
2875 	dst_set_expires(&rt0->dst, timeout);
2876 	rt0->rt6i_flags |= RTF_EXPIRES;
2877 }
2878 
2879 static void rt6_do_update_pmtu(struct rt6_info *rt, u32 mtu)
2880 {
2881 	struct net *net = dev_net(rt->dst.dev);
2882 
2883 	dst_metric_set(&rt->dst, RTAX_MTU, mtu);
2884 	rt->rt6i_flags |= RTF_MODIFIED;
2885 	rt6_update_expires(rt, net->ipv6.sysctl.ip6_rt_mtu_expires);
2886 }
2887 
2888 static bool rt6_cache_allowed_for_pmtu(const struct rt6_info *rt)
2889 {
2890 	return !(rt->rt6i_flags & RTF_CACHE) &&
2891 		(rt->rt6i_flags & RTF_PCPU || rcu_access_pointer(rt->from));
2892 }
2893 
2894 static void __ip6_rt_update_pmtu(struct dst_entry *dst, const struct sock *sk,
2895 				 const struct ipv6hdr *iph, u32 mtu,
2896 				 bool confirm_neigh)
2897 {
2898 	const struct in6_addr *daddr, *saddr;
2899 	struct rt6_info *rt6 = dst_rt6_info(dst);
2900 
2901 	/* Note: do *NOT* check dst_metric_locked(dst, RTAX_MTU)
2902 	 * IPv6 pmtu discovery isn't optional, so 'mtu lock' cannot disable it.
2903 	 * [see also comment in rt6_mtu_change_route()]
2904 	 */
2905 
2906 	if (iph) {
2907 		daddr = &iph->daddr;
2908 		saddr = &iph->saddr;
2909 	} else if (sk) {
2910 		daddr = &sk->sk_v6_daddr;
2911 		saddr = &inet6_sk(sk)->saddr;
2912 	} else {
2913 		daddr = NULL;
2914 		saddr = NULL;
2915 	}
2916 
2917 	if (confirm_neigh)
2918 		dst_confirm_neigh(dst, daddr);
2919 
2920 	if (mtu < IPV6_MIN_MTU)
2921 		return;
2922 	if (mtu >= dst_mtu(dst))
2923 		return;
2924 
2925 	if (!rt6_cache_allowed_for_pmtu(rt6)) {
2926 		rt6_do_update_pmtu(rt6, mtu);
2927 		/* update rt6_ex->stamp for cache */
2928 		if (rt6->rt6i_flags & RTF_CACHE)
2929 			rt6_update_exception_stamp_rt(rt6);
2930 	} else if (daddr) {
2931 		struct fib6_result res = {};
2932 		struct rt6_info *nrt6;
2933 
2934 		rcu_read_lock();
2935 		res.f6i = rcu_dereference(rt6->from);
2936 		if (!res.f6i)
2937 			goto out_unlock;
2938 
2939 		res.fib6_flags = res.f6i->fib6_flags;
2940 		res.fib6_type = res.f6i->fib6_type;
2941 
2942 		if (res.f6i->nh) {
2943 			struct fib6_nh_match_arg arg = {
2944 				.dev = dst->dev,
2945 				.gw = &rt6->rt6i_gateway,
2946 			};
2947 
2948 			nexthop_for_each_fib6_nh(res.f6i->nh,
2949 						 fib6_nh_find_match, &arg);
2950 
2951 			/* fib6_info uses a nexthop that does not have fib6_nh
2952 			 * using the dst->dev + gw. Should be impossible.
2953 			 */
2954 			if (!arg.match)
2955 				goto out_unlock;
2956 
2957 			res.nh = arg.match;
2958 		} else {
2959 			res.nh = res.f6i->fib6_nh;
2960 		}
2961 
2962 		nrt6 = ip6_rt_cache_alloc(&res, daddr, saddr);
2963 		if (nrt6) {
2964 			rt6_do_update_pmtu(nrt6, mtu);
2965 			if (rt6_insert_exception(nrt6, &res))
2966 				dst_release_immediate(&nrt6->dst);
2967 		}
2968 out_unlock:
2969 		rcu_read_unlock();
2970 	}
2971 }
2972 
2973 static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
2974 			       struct sk_buff *skb, u32 mtu,
2975 			       bool confirm_neigh)
2976 {
2977 	__ip6_rt_update_pmtu(dst, sk, skb ? ipv6_hdr(skb) : NULL, mtu,
2978 			     confirm_neigh);
2979 }
2980 
2981 void ip6_update_pmtu(struct sk_buff *skb, struct net *net, __be32 mtu,
2982 		     int oif, u32 mark, kuid_t uid)
2983 {
2984 	const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
2985 	struct dst_entry *dst;
2986 	struct flowi6 fl6 = {
2987 		.flowi6_oif = oif,
2988 		.flowi6_mark = mark ? mark : IP6_REPLY_MARK(net, skb->mark),
2989 		.daddr = iph->daddr,
2990 		.saddr = iph->saddr,
2991 		.flowlabel = ip6_flowinfo(iph),
2992 		.flowi6_uid = uid,
2993 	};
2994 
2995 	dst = ip6_route_output(net, NULL, &fl6);
2996 	if (!dst->error)
2997 		__ip6_rt_update_pmtu(dst, NULL, iph, ntohl(mtu), true);
2998 	dst_release(dst);
2999 }
3000 EXPORT_SYMBOL_GPL(ip6_update_pmtu);
3001 
3002 void ip6_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, __be32 mtu)
3003 {
3004 	int oif = sk->sk_bound_dev_if;
3005 	struct dst_entry *dst;
3006 
3007 	if (!oif && skb->dev)
3008 		oif = l3mdev_master_ifindex(skb->dev);
3009 
3010 	ip6_update_pmtu(skb, sock_net(sk), mtu, oif, READ_ONCE(sk->sk_mark),
3011 			sk->sk_uid);
3012 
3013 	dst = __sk_dst_get(sk);
3014 	if (!dst || !dst->obsolete ||
3015 	    dst->ops->check(dst, inet6_sk(sk)->dst_cookie))
3016 		return;
3017 
3018 	bh_lock_sock(sk);
3019 	if (!sock_owned_by_user(sk) && !ipv6_addr_v4mapped(&sk->sk_v6_daddr))
3020 		ip6_datagram_dst_update(sk, false);
3021 	bh_unlock_sock(sk);
3022 }
3023 EXPORT_SYMBOL_GPL(ip6_sk_update_pmtu);
3024 
3025 void ip6_sk_dst_store_flow(struct sock *sk, struct dst_entry *dst,
3026 			   const struct flowi6 *fl6)
3027 {
3028 #ifdef CONFIG_IPV6_SUBTREES
3029 	struct ipv6_pinfo *np = inet6_sk(sk);
3030 #endif
3031 
3032 	ip6_dst_store(sk, dst,
3033 		      ipv6_addr_equal(&fl6->daddr, &sk->sk_v6_daddr) ?
3034 		      &sk->sk_v6_daddr : NULL,
3035 #ifdef CONFIG_IPV6_SUBTREES
3036 		      ipv6_addr_equal(&fl6->saddr, &np->saddr) ?
3037 		      &np->saddr :
3038 #endif
3039 		      NULL);
3040 }
3041 
3042 static bool ip6_redirect_nh_match(const struct fib6_result *res,
3043 				  struct flowi6 *fl6,
3044 				  const struct in6_addr *gw,
3045 				  struct rt6_info **ret)
3046 {
3047 	const struct fib6_nh *nh = res->nh;
3048 
3049 	if (nh->fib_nh_flags & RTNH_F_DEAD || !nh->fib_nh_gw_family ||
3050 	    fl6->flowi6_oif != nh->fib_nh_dev->ifindex)
3051 		return false;
3052 
3053 	/* rt_cache's gateway might be different from its 'parent'
3054 	 * in the case of an ip redirect.
3055 	 * So we keep searching in the exception table if the gateway
3056 	 * is different.
3057 	 */
3058 	if (!ipv6_addr_equal(gw, &nh->fib_nh_gw6)) {
3059 		struct rt6_info *rt_cache;
3060 
3061 		rt_cache = rt6_find_cached_rt(res, &fl6->daddr, &fl6->saddr);
3062 		if (rt_cache &&
3063 		    ipv6_addr_equal(gw, &rt_cache->rt6i_gateway)) {
3064 			*ret = rt_cache;
3065 			return true;
3066 		}
3067 		return false;
3068 	}
3069 	return true;
3070 }
3071 
3072 struct fib6_nh_rd_arg {
3073 	struct fib6_result	*res;
3074 	struct flowi6		*fl6;
3075 	const struct in6_addr	*gw;
3076 	struct rt6_info		**ret;
3077 };
3078 
3079 static int fib6_nh_redirect_match(struct fib6_nh *nh, void *_arg)
3080 {
3081 	struct fib6_nh_rd_arg *arg = _arg;
3082 
3083 	arg->res->nh = nh;
3084 	return ip6_redirect_nh_match(arg->res, arg->fl6, arg->gw, arg->ret);
3085 }
3086 
3087 /* Handle redirects */
3088 struct ip6rd_flowi {
3089 	struct flowi6 fl6;
3090 	struct in6_addr gateway;
3091 };
3092 
3093 INDIRECT_CALLABLE_SCOPE struct rt6_info *__ip6_route_redirect(struct net *net,
3094 					     struct fib6_table *table,
3095 					     struct flowi6 *fl6,
3096 					     const struct sk_buff *skb,
3097 					     int flags)
3098 {
3099 	struct ip6rd_flowi *rdfl = (struct ip6rd_flowi *)fl6;
3100 	struct rt6_info *ret = NULL;
3101 	struct fib6_result res = {};
3102 	struct fib6_nh_rd_arg arg = {
3103 		.res = &res,
3104 		.fl6 = fl6,
3105 		.gw  = &rdfl->gateway,
3106 		.ret = &ret
3107 	};
3108 	struct fib6_info *rt;
3109 	struct fib6_node *fn;
3110 
3111 	/* Get the "current" route for this destination and
3112 	 * check if the redirect has come from appropriate router.
3113 	 *
3114 	 * RFC 4861 specifies that redirects should only be
3115 	 * accepted if they come from the nexthop to the target.
3116 	 * Due to the way the routes are chosen, this notion
3117 	 * is a bit fuzzy and one might need to check all possible
3118 	 * routes.
3119 	 */
3120 
3121 	rcu_read_lock();
3122 	fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
3123 restart:
3124 	for_each_fib6_node_rt_rcu(fn) {
3125 		res.f6i = rt;
3126 		if (fib6_check_expired(rt))
3127 			continue;
3128 		if (rt->fib6_flags & RTF_REJECT)
3129 			break;
3130 		if (unlikely(rt->nh)) {
3131 			if (nexthop_is_blackhole(rt->nh))
3132 				continue;
3133 			/* on match, res->nh is filled in and potentially ret */
3134 			if (nexthop_for_each_fib6_nh(rt->nh,
3135 						     fib6_nh_redirect_match,
3136 						     &arg))
3137 				goto out;
3138 		} else {
3139 			res.nh = rt->fib6_nh;
3140 			if (ip6_redirect_nh_match(&res, fl6, &rdfl->gateway,
3141 						  &ret))
3142 				goto out;
3143 		}
3144 	}
3145 
3146 	if (!rt)
3147 		rt = net->ipv6.fib6_null_entry;
3148 	else if (rt->fib6_flags & RTF_REJECT) {
3149 		ret = net->ipv6.ip6_null_entry;
3150 		goto out;
3151 	}
3152 
3153 	if (rt == net->ipv6.fib6_null_entry) {
3154 		fn = fib6_backtrack(fn, &fl6->saddr);
3155 		if (fn)
3156 			goto restart;
3157 	}
3158 
3159 	res.f6i = rt;
3160 	res.nh = rt->fib6_nh;
3161 out:
3162 	if (ret) {
3163 		ip6_hold_safe(net, &ret);
3164 	} else {
3165 		res.fib6_flags = res.f6i->fib6_flags;
3166 		res.fib6_type = res.f6i->fib6_type;
3167 		ret = ip6_create_rt_rcu(&res);
3168 	}
3169 
3170 	rcu_read_unlock();
3171 
3172 	trace_fib6_table_lookup(net, &res, table, fl6);
3173 	return ret;
3174 };
3175 
3176 static struct dst_entry *ip6_route_redirect(struct net *net,
3177 					    const struct flowi6 *fl6,
3178 					    const struct sk_buff *skb,
3179 					    const struct in6_addr *gateway)
3180 {
3181 	int flags = RT6_LOOKUP_F_HAS_SADDR;
3182 	struct ip6rd_flowi rdfl;
3183 
3184 	rdfl.fl6 = *fl6;
3185 	rdfl.gateway = *gateway;
3186 
3187 	return fib6_rule_lookup(net, &rdfl.fl6, skb,
3188 				flags, __ip6_route_redirect);
3189 }
3190 
3191 void ip6_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark,
3192 		  kuid_t uid)
3193 {
3194 	const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
3195 	struct dst_entry *dst;
3196 	struct flowi6 fl6 = {
3197 		.flowi6_iif = LOOPBACK_IFINDEX,
3198 		.flowi6_oif = oif,
3199 		.flowi6_mark = mark,
3200 		.daddr = iph->daddr,
3201 		.saddr = iph->saddr,
3202 		.flowlabel = ip6_flowinfo(iph),
3203 		.flowi6_uid = uid,
3204 	};
3205 
3206 	dst = ip6_route_redirect(net, &fl6, skb, &ipv6_hdr(skb)->saddr);
3207 	rt6_do_redirect(dst, NULL, skb);
3208 	dst_release(dst);
3209 }
3210 EXPORT_SYMBOL_GPL(ip6_redirect);
3211 
3212 void ip6_redirect_no_header(struct sk_buff *skb, struct net *net, int oif)
3213 {
3214 	const struct ipv6hdr *iph = ipv6_hdr(skb);
3215 	const struct rd_msg *msg = (struct rd_msg *)icmp6_hdr(skb);
3216 	struct dst_entry *dst;
3217 	struct flowi6 fl6 = {
3218 		.flowi6_iif = LOOPBACK_IFINDEX,
3219 		.flowi6_oif = oif,
3220 		.daddr = msg->dest,
3221 		.saddr = iph->daddr,
3222 		.flowi6_uid = sock_net_uid(net, NULL),
3223 	};
3224 
3225 	dst = ip6_route_redirect(net, &fl6, skb, &iph->saddr);
3226 	rt6_do_redirect(dst, NULL, skb);
3227 	dst_release(dst);
3228 }
3229 
3230 void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk)
3231 {
3232 	ip6_redirect(skb, sock_net(sk), sk->sk_bound_dev_if,
3233 		     READ_ONCE(sk->sk_mark), sk->sk_uid);
3234 }
3235 EXPORT_SYMBOL_GPL(ip6_sk_redirect);
3236 
3237 static unsigned int ip6_default_advmss(const struct dst_entry *dst)
3238 {
3239 	struct net_device *dev = dst->dev;
3240 	unsigned int mtu = dst_mtu(dst);
3241 	struct net *net;
3242 
3243 	mtu -= sizeof(struct ipv6hdr) + sizeof(struct tcphdr);
3244 
3245 	rcu_read_lock();
3246 
3247 	net = dev_net_rcu(dev);
3248 	if (mtu < net->ipv6.sysctl.ip6_rt_min_advmss)
3249 		mtu = net->ipv6.sysctl.ip6_rt_min_advmss;
3250 
3251 	rcu_read_unlock();
3252 
3253 	/*
3254 	 * Maximal non-jumbo IPv6 payload is IPV6_MAXPLEN and
3255 	 * corresponding MSS is IPV6_MAXPLEN - tcp_header_size.
3256 	 * IPV6_MAXPLEN is also valid and means: "any MSS,
3257 	 * rely only on pmtu discovery"
3258 	 */
3259 	if (mtu > IPV6_MAXPLEN - sizeof(struct tcphdr))
3260 		mtu = IPV6_MAXPLEN;
3261 	return mtu;
3262 }
3263 
3264 INDIRECT_CALLABLE_SCOPE unsigned int ip6_mtu(const struct dst_entry *dst)
3265 {
3266 	return ip6_dst_mtu_maybe_forward(dst, false);
3267 }
3268 EXPORT_INDIRECT_CALLABLE(ip6_mtu);
3269 
3270 /* MTU selection:
3271  * 1. mtu on route is locked - use it
3272  * 2. mtu from nexthop exception
3273  * 3. mtu from egress device
3274  *
3275  * based on ip6_dst_mtu_forward and exception logic of
3276  * rt6_find_cached_rt; called with rcu_read_lock
3277  */
3278 u32 ip6_mtu_from_fib6(const struct fib6_result *res,
3279 		      const struct in6_addr *daddr,
3280 		      const struct in6_addr *saddr)
3281 {
3282 	const struct fib6_nh *nh = res->nh;
3283 	struct fib6_info *f6i = res->f6i;
3284 	struct inet6_dev *idev;
3285 	struct rt6_info *rt;
3286 	u32 mtu = 0;
3287 
3288 	if (unlikely(fib6_metric_locked(f6i, RTAX_MTU))) {
3289 		mtu = f6i->fib6_pmtu;
3290 		if (mtu)
3291 			goto out;
3292 	}
3293 
3294 	rt = rt6_find_cached_rt(res, daddr, saddr);
3295 	if (unlikely(rt)) {
3296 		mtu = dst_metric_raw(&rt->dst, RTAX_MTU);
3297 	} else {
3298 		struct net_device *dev = nh->fib_nh_dev;
3299 
3300 		mtu = IPV6_MIN_MTU;
3301 		idev = __in6_dev_get(dev);
3302 		if (idev)
3303 			mtu = max_t(u32, mtu, READ_ONCE(idev->cnf.mtu6));
3304 	}
3305 
3306 	mtu = min_t(unsigned int, mtu, IP6_MAX_MTU);
3307 out:
3308 	return mtu - lwtunnel_headroom(nh->fib_nh_lws, mtu);
3309 }
3310 
3311 struct dst_entry *icmp6_dst_alloc(struct net_device *dev,
3312 				  struct flowi6 *fl6)
3313 {
3314 	struct dst_entry *dst;
3315 	struct rt6_info *rt;
3316 	struct inet6_dev *idev = in6_dev_get(dev);
3317 	struct net *net = dev_net(dev);
3318 
3319 	if (unlikely(!idev))
3320 		return ERR_PTR(-ENODEV);
3321 
3322 	rt = ip6_dst_alloc(net, dev, 0);
3323 	if (unlikely(!rt)) {
3324 		in6_dev_put(idev);
3325 		dst = ERR_PTR(-ENOMEM);
3326 		goto out;
3327 	}
3328 
3329 	rt->dst.input = ip6_input;
3330 	rt->dst.output  = ip6_output;
3331 	rt->rt6i_gateway  = fl6->daddr;
3332 	rt->rt6i_dst.addr = fl6->daddr;
3333 	rt->rt6i_dst.plen = 128;
3334 	rt->rt6i_idev     = idev;
3335 	dst_metric_set(&rt->dst, RTAX_HOPLIMIT, 0);
3336 
3337 	/* Add this dst into uncached_list so that rt6_disable_ip() can
3338 	 * do proper release of the net_device
3339 	 */
3340 	rt6_uncached_list_add(rt);
3341 
3342 	dst = xfrm_lookup(net, &rt->dst, flowi6_to_flowi(fl6), NULL, 0);
3343 
3344 out:
3345 	return dst;
3346 }
3347 
3348 static void ip6_dst_gc(struct dst_ops *ops)
3349 {
3350 	struct net *net = container_of(ops, struct net, ipv6.ip6_dst_ops);
3351 	int rt_min_interval = net->ipv6.sysctl.ip6_rt_gc_min_interval;
3352 	int rt_elasticity = net->ipv6.sysctl.ip6_rt_gc_elasticity;
3353 	int rt_gc_timeout = net->ipv6.sysctl.ip6_rt_gc_timeout;
3354 	unsigned long rt_last_gc = net->ipv6.ip6_rt_last_gc;
3355 	unsigned int val;
3356 	int entries;
3357 
3358 	if (time_after(rt_last_gc + rt_min_interval, jiffies))
3359 		goto out;
3360 
3361 	fib6_run_gc(atomic_inc_return(&net->ipv6.ip6_rt_gc_expire), net, true);
3362 	entries = dst_entries_get_slow(ops);
3363 	if (entries < ops->gc_thresh)
3364 		atomic_set(&net->ipv6.ip6_rt_gc_expire, rt_gc_timeout >> 1);
3365 out:
3366 	val = atomic_read(&net->ipv6.ip6_rt_gc_expire);
3367 	atomic_set(&net->ipv6.ip6_rt_gc_expire, val - (val >> rt_elasticity));
3368 }
3369 
3370 static int ip6_nh_lookup_table(struct net *net, struct fib6_config *cfg,
3371 			       const struct in6_addr *gw_addr, u32 tbid,
3372 			       int flags, struct fib6_result *res)
3373 {
3374 	struct flowi6 fl6 = {
3375 		.flowi6_oif = cfg->fc_ifindex,
3376 		.daddr = *gw_addr,
3377 		.saddr = cfg->fc_prefsrc,
3378 	};
3379 	struct fib6_table *table;
3380 	int err;
3381 
3382 	table = fib6_get_table(net, tbid);
3383 	if (!table)
3384 		return -EINVAL;
3385 
3386 	if (!ipv6_addr_any(&cfg->fc_prefsrc))
3387 		flags |= RT6_LOOKUP_F_HAS_SADDR;
3388 
3389 	flags |= RT6_LOOKUP_F_IGNORE_LINKSTATE;
3390 
3391 	err = fib6_table_lookup(net, table, cfg->fc_ifindex, &fl6, res, flags);
3392 	if (!err && res->f6i != net->ipv6.fib6_null_entry)
3393 		fib6_select_path(net, res, &fl6, cfg->fc_ifindex,
3394 				 cfg->fc_ifindex != 0, NULL, flags);
3395 
3396 	return err;
3397 }
3398 
3399 static int ip6_route_check_nh_onlink(struct net *net,
3400 				     struct fib6_config *cfg,
3401 				     const struct net_device *dev,
3402 				     struct netlink_ext_ack *extack)
3403 {
3404 	u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
3405 	const struct in6_addr *gw_addr = &cfg->fc_gateway;
3406 	struct fib6_result res = {};
3407 	int err;
3408 
3409 	err = ip6_nh_lookup_table(net, cfg, gw_addr, tbid, 0, &res);
3410 	if (!err && !(res.fib6_flags & RTF_REJECT) &&
3411 	    /* ignore match if it is the default route */
3412 	    !ipv6_addr_any(&res.f6i->fib6_dst.addr) &&
3413 	    (res.fib6_type != RTN_UNICAST || dev != res.nh->fib_nh_dev)) {
3414 		NL_SET_ERR_MSG(extack,
3415 			       "Nexthop has invalid gateway or device mismatch");
3416 		err = -EINVAL;
3417 	}
3418 
3419 	return err;
3420 }
3421 
3422 static int ip6_route_check_nh(struct net *net,
3423 			      struct fib6_config *cfg,
3424 			      struct net_device **_dev,
3425 			      netdevice_tracker *dev_tracker,
3426 			      struct inet6_dev **idev)
3427 {
3428 	const struct in6_addr *gw_addr = &cfg->fc_gateway;
3429 	struct net_device *dev = _dev ? *_dev : NULL;
3430 	int flags = RT6_LOOKUP_F_IFACE;
3431 	struct fib6_result res = {};
3432 	int err = -EHOSTUNREACH;
3433 
3434 	if (cfg->fc_table) {
3435 		err = ip6_nh_lookup_table(net, cfg, gw_addr,
3436 					  cfg->fc_table, flags, &res);
3437 		/* gw_addr can not require a gateway or resolve to a reject
3438 		 * route. If a device is given, it must match the result.
3439 		 */
3440 		if (err || res.fib6_flags & RTF_REJECT ||
3441 		    res.nh->fib_nh_gw_family ||
3442 		    (dev && dev != res.nh->fib_nh_dev))
3443 			err = -EHOSTUNREACH;
3444 	}
3445 
3446 	if (err < 0) {
3447 		struct flowi6 fl6 = {
3448 			.flowi6_oif = cfg->fc_ifindex,
3449 			.daddr = *gw_addr,
3450 		};
3451 
3452 		err = fib6_lookup(net, cfg->fc_ifindex, &fl6, &res, flags);
3453 		if (err || res.fib6_flags & RTF_REJECT ||
3454 		    res.nh->fib_nh_gw_family)
3455 			err = -EHOSTUNREACH;
3456 
3457 		if (err)
3458 			return err;
3459 
3460 		fib6_select_path(net, &res, &fl6, cfg->fc_ifindex,
3461 				 cfg->fc_ifindex != 0, NULL, flags);
3462 	}
3463 
3464 	err = 0;
3465 	if (dev) {
3466 		if (dev != res.nh->fib_nh_dev)
3467 			err = -EHOSTUNREACH;
3468 	} else {
3469 		*_dev = dev = res.nh->fib_nh_dev;
3470 		netdev_hold(dev, dev_tracker, GFP_ATOMIC);
3471 		*idev = in6_dev_get(dev);
3472 	}
3473 
3474 	return err;
3475 }
3476 
3477 static int ip6_validate_gw(struct net *net, struct fib6_config *cfg,
3478 			   struct net_device **_dev,
3479 			   netdevice_tracker *dev_tracker,
3480 			   struct inet6_dev **idev,
3481 			   struct netlink_ext_ack *extack)
3482 {
3483 	const struct in6_addr *gw_addr = &cfg->fc_gateway;
3484 	int gwa_type = ipv6_addr_type(gw_addr);
3485 	bool skip_dev = gwa_type & IPV6_ADDR_LINKLOCAL ? false : true;
3486 	const struct net_device *dev = *_dev;
3487 	bool need_addr_check = !dev;
3488 	int err = -EINVAL;
3489 
3490 	/* if gw_addr is local we will fail to detect this in case
3491 	 * address is still TENTATIVE (DAD in progress). rt6_lookup()
3492 	 * will return already-added prefix route via interface that
3493 	 * prefix route was assigned to, which might be non-loopback.
3494 	 */
3495 	if (dev &&
3496 	    ipv6_chk_addr_and_flags(net, gw_addr, dev, skip_dev, 0, 0)) {
3497 		NL_SET_ERR_MSG(extack, "Gateway can not be a local address");
3498 		goto out;
3499 	}
3500 
3501 	if (gwa_type != (IPV6_ADDR_LINKLOCAL | IPV6_ADDR_UNICAST)) {
3502 		/* IPv6 strictly inhibits using not link-local
3503 		 * addresses as nexthop address.
3504 		 * Otherwise, router will not able to send redirects.
3505 		 * It is very good, but in some (rare!) circumstances
3506 		 * (SIT, PtP, NBMA NOARP links) it is handy to allow
3507 		 * some exceptions. --ANK
3508 		 * We allow IPv4-mapped nexthops to support RFC4798-type
3509 		 * addressing
3510 		 */
3511 		if (!(gwa_type & (IPV6_ADDR_UNICAST | IPV6_ADDR_MAPPED))) {
3512 			NL_SET_ERR_MSG(extack, "Invalid gateway address");
3513 			goto out;
3514 		}
3515 
3516 		rcu_read_lock();
3517 
3518 		if (cfg->fc_flags & RTNH_F_ONLINK)
3519 			err = ip6_route_check_nh_onlink(net, cfg, dev, extack);
3520 		else
3521 			err = ip6_route_check_nh(net, cfg, _dev, dev_tracker,
3522 						 idev);
3523 
3524 		rcu_read_unlock();
3525 
3526 		if (err)
3527 			goto out;
3528 	}
3529 
3530 	/* reload in case device was changed */
3531 	dev = *_dev;
3532 
3533 	err = -EINVAL;
3534 	if (!dev) {
3535 		NL_SET_ERR_MSG(extack, "Egress device not specified");
3536 		goto out;
3537 	} else if (dev->flags & IFF_LOOPBACK) {
3538 		NL_SET_ERR_MSG(extack,
3539 			       "Egress device can not be loopback device for this route");
3540 		goto out;
3541 	}
3542 
3543 	/* if we did not check gw_addr above, do so now that the
3544 	 * egress device has been resolved.
3545 	 */
3546 	if (need_addr_check &&
3547 	    ipv6_chk_addr_and_flags(net, gw_addr, dev, skip_dev, 0, 0)) {
3548 		NL_SET_ERR_MSG(extack, "Gateway can not be a local address");
3549 		goto out;
3550 	}
3551 
3552 	err = 0;
3553 out:
3554 	return err;
3555 }
3556 
3557 static bool fib6_is_reject(u32 flags, struct net_device *dev, int addr_type)
3558 {
3559 	if ((flags & RTF_REJECT) ||
3560 	    (dev && (dev->flags & IFF_LOOPBACK) &&
3561 	     !(addr_type & IPV6_ADDR_LOOPBACK) &&
3562 	     !(flags & (RTF_ANYCAST | RTF_LOCAL))))
3563 		return true;
3564 
3565 	return false;
3566 }
3567 
3568 int fib6_nh_init(struct net *net, struct fib6_nh *fib6_nh,
3569 		 struct fib6_config *cfg, gfp_t gfp_flags,
3570 		 struct netlink_ext_ack *extack)
3571 {
3572 	netdevice_tracker *dev_tracker = &fib6_nh->fib_nh_dev_tracker;
3573 	struct net_device *dev = NULL;
3574 	struct inet6_dev *idev = NULL;
3575 	int addr_type;
3576 	int err;
3577 
3578 	fib6_nh->fib_nh_family = AF_INET6;
3579 #ifdef CONFIG_IPV6_ROUTER_PREF
3580 	fib6_nh->last_probe = jiffies;
3581 #endif
3582 	if (cfg->fc_is_fdb) {
3583 		fib6_nh->fib_nh_gw6 = cfg->fc_gateway;
3584 		fib6_nh->fib_nh_gw_family = AF_INET6;
3585 		return 0;
3586 	}
3587 
3588 	err = -ENODEV;
3589 	if (cfg->fc_ifindex) {
3590 		dev = netdev_get_by_index(net, cfg->fc_ifindex,
3591 					  dev_tracker, gfp_flags);
3592 		if (!dev)
3593 			goto out;
3594 		idev = in6_dev_get(dev);
3595 		if (!idev)
3596 			goto out;
3597 	}
3598 
3599 	if (cfg->fc_flags & RTNH_F_ONLINK) {
3600 		if (!dev) {
3601 			NL_SET_ERR_MSG(extack,
3602 				       "Nexthop device required for onlink");
3603 			goto out;
3604 		}
3605 
3606 		if (!(dev->flags & IFF_UP)) {
3607 			NL_SET_ERR_MSG(extack, "Nexthop device is not up");
3608 			err = -ENETDOWN;
3609 			goto out;
3610 		}
3611 
3612 		fib6_nh->fib_nh_flags |= RTNH_F_ONLINK;
3613 	}
3614 
3615 	fib6_nh->fib_nh_weight = 1;
3616 
3617 	/* We cannot add true routes via loopback here,
3618 	 * they would result in kernel looping; promote them to reject routes
3619 	 */
3620 	addr_type = ipv6_addr_type(&cfg->fc_dst);
3621 	if (fib6_is_reject(cfg->fc_flags, dev, addr_type)) {
3622 		/* hold loopback dev/idev if we haven't done so. */
3623 		if (dev != net->loopback_dev) {
3624 			if (dev) {
3625 				netdev_put(dev, dev_tracker);
3626 				in6_dev_put(idev);
3627 			}
3628 			dev = net->loopback_dev;
3629 			netdev_hold(dev, dev_tracker, gfp_flags);
3630 			idev = in6_dev_get(dev);
3631 			if (!idev) {
3632 				err = -ENODEV;
3633 				goto out;
3634 			}
3635 		}
3636 		goto pcpu_alloc;
3637 	}
3638 
3639 	if (cfg->fc_flags & RTF_GATEWAY) {
3640 		err = ip6_validate_gw(net, cfg, &dev, dev_tracker,
3641 				      &idev, extack);
3642 		if (err)
3643 			goto out;
3644 
3645 		fib6_nh->fib_nh_gw6 = cfg->fc_gateway;
3646 		fib6_nh->fib_nh_gw_family = AF_INET6;
3647 	}
3648 
3649 	err = -ENODEV;
3650 	if (!dev)
3651 		goto out;
3652 
3653 	if (!idev || idev->cnf.disable_ipv6) {
3654 		NL_SET_ERR_MSG(extack, "IPv6 is disabled on nexthop device");
3655 		err = -EACCES;
3656 		goto out;
3657 	}
3658 
3659 	if (!(dev->flags & IFF_UP) && !cfg->fc_ignore_dev_down) {
3660 		NL_SET_ERR_MSG(extack, "Nexthop device is not up");
3661 		err = -ENETDOWN;
3662 		goto out;
3663 	}
3664 
3665 	if (!(cfg->fc_flags & (RTF_LOCAL | RTF_ANYCAST)) &&
3666 	    !netif_carrier_ok(dev))
3667 		fib6_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
3668 
3669 	err = fib_nh_common_init(net, &fib6_nh->nh_common, cfg->fc_encap,
3670 				 cfg->fc_encap_type, cfg, gfp_flags, extack);
3671 	if (err)
3672 		goto out;
3673 
3674 pcpu_alloc:
3675 	if (!fib6_nh->rt6i_pcpu) {
3676 		fib6_nh->rt6i_pcpu = alloc_percpu_gfp(struct rt6_info *, gfp_flags);
3677 		if (!fib6_nh->rt6i_pcpu) {
3678 			err = -ENOMEM;
3679 			goto out;
3680 		}
3681 	}
3682 
3683 	fib6_nh->fib_nh_dev = dev;
3684 	fib6_nh->fib_nh_oif = dev->ifindex;
3685 	err = 0;
3686 out:
3687 	if (idev)
3688 		in6_dev_put(idev);
3689 
3690 	if (err) {
3691 		fib_nh_common_release(&fib6_nh->nh_common);
3692 		fib6_nh->nh_common.nhc_pcpu_rth_output = NULL;
3693 		fib6_nh->fib_nh_lws = NULL;
3694 		netdev_put(dev, dev_tracker);
3695 	}
3696 
3697 	return err;
3698 }
3699 
3700 void fib6_nh_release(struct fib6_nh *fib6_nh)
3701 {
3702 	struct rt6_exception_bucket *bucket;
3703 
3704 	rcu_read_lock();
3705 
3706 	fib6_nh_flush_exceptions(fib6_nh, NULL);
3707 	bucket = fib6_nh_get_excptn_bucket(fib6_nh, NULL);
3708 	if (bucket) {
3709 		rcu_assign_pointer(fib6_nh->rt6i_exception_bucket, NULL);
3710 		kfree(bucket);
3711 	}
3712 
3713 	rcu_read_unlock();
3714 
3715 	fib6_nh_release_dsts(fib6_nh);
3716 	free_percpu(fib6_nh->rt6i_pcpu);
3717 
3718 	fib_nh_common_release(&fib6_nh->nh_common);
3719 }
3720 
3721 void fib6_nh_release_dsts(struct fib6_nh *fib6_nh)
3722 {
3723 	int cpu;
3724 
3725 	if (!fib6_nh->rt6i_pcpu)
3726 		return;
3727 
3728 	for_each_possible_cpu(cpu) {
3729 		struct rt6_info *pcpu_rt, **ppcpu_rt;
3730 
3731 		ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
3732 		pcpu_rt = xchg(ppcpu_rt, NULL);
3733 		if (pcpu_rt) {
3734 			dst_dev_put(&pcpu_rt->dst);
3735 			dst_release(&pcpu_rt->dst);
3736 		}
3737 	}
3738 }
3739 
3740 static int fib6_nh_prealloc_percpu(struct fib6_nh *fib6_nh, gfp_t gfp_flags)
3741 {
3742 	struct fib_nh_common *nhc = &fib6_nh->nh_common;
3743 
3744 	fib6_nh->rt6i_pcpu = alloc_percpu_gfp(struct rt6_info *, gfp_flags);
3745 	if (!fib6_nh->rt6i_pcpu)
3746 		return -ENOMEM;
3747 
3748 	nhc->nhc_pcpu_rth_output = alloc_percpu_gfp(struct rtable __rcu *,
3749 						    gfp_flags);
3750 	if (!nhc->nhc_pcpu_rth_output) {
3751 		free_percpu(fib6_nh->rt6i_pcpu);
3752 		return -ENOMEM;
3753 	}
3754 
3755 	return 0;
3756 }
3757 
3758 static struct fib6_info *ip6_route_info_create(struct fib6_config *cfg,
3759 					       gfp_t gfp_flags,
3760 					       struct netlink_ext_ack *extack)
3761 {
3762 	struct net *net = cfg->fc_nlinfo.nl_net;
3763 	struct fib6_table *table;
3764 	struct fib6_info *rt;
3765 	int err;
3766 
3767 	if (cfg->fc_nlinfo.nlh &&
3768 	    !(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
3769 		table = fib6_get_table(net, cfg->fc_table);
3770 		if (!table) {
3771 			pr_warn("NLM_F_CREATE should be specified when creating new route\n");
3772 			table = fib6_new_table(net, cfg->fc_table);
3773 		}
3774 	} else {
3775 		table = fib6_new_table(net, cfg->fc_table);
3776 	}
3777 	if (!table) {
3778 		err = -ENOBUFS;
3779 		goto err;
3780 	}
3781 
3782 	rt = fib6_info_alloc(gfp_flags, !cfg->fc_nh_id);
3783 	if (!rt) {
3784 		err = -ENOMEM;
3785 		goto err;
3786 	}
3787 
3788 	rt->fib6_metrics = ip_fib_metrics_init(cfg->fc_mx, cfg->fc_mx_len,
3789 					       extack);
3790 	if (IS_ERR(rt->fib6_metrics)) {
3791 		err = PTR_ERR(rt->fib6_metrics);
3792 		goto free;
3793 	}
3794 
3795 	if (!cfg->fc_nh_id) {
3796 		err = fib6_nh_prealloc_percpu(&rt->fib6_nh[0], gfp_flags);
3797 		if (err)
3798 			goto free_metrics;
3799 	}
3800 
3801 	if (cfg->fc_flags & RTF_ADDRCONF)
3802 		rt->dst_nocount = true;
3803 
3804 	if (cfg->fc_flags & RTF_EXPIRES)
3805 		fib6_set_expires(rt, jiffies +
3806 				 clock_t_to_jiffies(cfg->fc_expires));
3807 
3808 	if (cfg->fc_protocol == RTPROT_UNSPEC)
3809 		cfg->fc_protocol = RTPROT_BOOT;
3810 
3811 	rt->fib6_protocol = cfg->fc_protocol;
3812 	rt->fib6_table = table;
3813 	rt->fib6_metric = cfg->fc_metric;
3814 	rt->fib6_type = cfg->fc_type ? : RTN_UNICAST;
3815 	rt->fib6_flags = cfg->fc_flags & ~RTF_GATEWAY;
3816 
3817 	ipv6_addr_prefix(&rt->fib6_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
3818 	rt->fib6_dst.plen = cfg->fc_dst_len;
3819 
3820 #ifdef CONFIG_IPV6_SUBTREES
3821 	ipv6_addr_prefix(&rt->fib6_src.addr, &cfg->fc_src, cfg->fc_src_len);
3822 	rt->fib6_src.plen = cfg->fc_src_len;
3823 #endif
3824 	return rt;
3825 free_metrics:
3826 	ip_fib_metrics_put(rt->fib6_metrics);
3827 free:
3828 	kfree(rt);
3829 err:
3830 	return ERR_PTR(err);
3831 }
3832 
3833 static int ip6_route_info_create_nh(struct fib6_info *rt,
3834 				    struct fib6_config *cfg,
3835 				    struct netlink_ext_ack *extack)
3836 {
3837 	struct net *net = cfg->fc_nlinfo.nl_net;
3838 	struct fib6_nh *fib6_nh;
3839 	int err;
3840 
3841 	if (cfg->fc_nh_id) {
3842 		struct nexthop *nh;
3843 
3844 		nh = nexthop_find_by_id(net, cfg->fc_nh_id);
3845 		if (!nh) {
3846 			err = -EINVAL;
3847 			NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
3848 			goto out_free;
3849 		}
3850 
3851 		err = fib6_check_nexthop(nh, cfg, extack);
3852 		if (err)
3853 			goto out_free;
3854 
3855 		if (!nexthop_get(nh)) {
3856 			NL_SET_ERR_MSG(extack, "Nexthop has been deleted");
3857 			err = -ENOENT;
3858 			goto out_free;
3859 		}
3860 
3861 		rt->nh = nh;
3862 		fib6_nh = nexthop_fib6_nh(rt->nh);
3863 	} else {
3864 		int addr_type;
3865 
3866 		err = fib6_nh_init(net, rt->fib6_nh, cfg, GFP_ATOMIC, extack);
3867 		if (err)
3868 			goto out_release;
3869 
3870 		fib6_nh = rt->fib6_nh;
3871 
3872 		/* We cannot add true routes via loopback here, they would
3873 		 * result in kernel looping; promote them to reject routes
3874 		 */
3875 		addr_type = ipv6_addr_type(&cfg->fc_dst);
3876 		if (fib6_is_reject(cfg->fc_flags, rt->fib6_nh->fib_nh_dev,
3877 				   addr_type))
3878 			rt->fib6_flags = RTF_REJECT | RTF_NONEXTHOP;
3879 	}
3880 
3881 	if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
3882 		struct net_device *dev = fib6_nh->fib_nh_dev;
3883 
3884 		if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
3885 			NL_SET_ERR_MSG(extack, "Invalid source address");
3886 			err = -EINVAL;
3887 			goto out_release;
3888 		}
3889 		rt->fib6_prefsrc.addr = cfg->fc_prefsrc;
3890 		rt->fib6_prefsrc.plen = 128;
3891 	}
3892 
3893 	return 0;
3894 out_release:
3895 	fib6_info_release(rt);
3896 	return err;
3897 out_free:
3898 	ip_fib_metrics_put(rt->fib6_metrics);
3899 	kfree(rt);
3900 	return err;
3901 }
3902 
3903 int ip6_route_add(struct fib6_config *cfg, gfp_t gfp_flags,
3904 		  struct netlink_ext_ack *extack)
3905 {
3906 	struct fib6_info *rt;
3907 	int err;
3908 
3909 	rt = ip6_route_info_create(cfg, gfp_flags, extack);
3910 	if (IS_ERR(rt))
3911 		return PTR_ERR(rt);
3912 
3913 	rcu_read_lock();
3914 
3915 	err = ip6_route_info_create_nh(rt, cfg, extack);
3916 	if (err)
3917 		goto unlock;
3918 
3919 	err = __ip6_ins_rt(rt, &cfg->fc_nlinfo, extack);
3920 	fib6_info_release(rt);
3921 unlock:
3922 	rcu_read_unlock();
3923 
3924 	return err;
3925 }
3926 
3927 static int __ip6_del_rt(struct fib6_info *rt, struct nl_info *info)
3928 {
3929 	struct net *net = info->nl_net;
3930 	struct fib6_table *table;
3931 	int err;
3932 
3933 	if (rt == net->ipv6.fib6_null_entry) {
3934 		err = -ENOENT;
3935 		goto out;
3936 	}
3937 
3938 	table = rt->fib6_table;
3939 	spin_lock_bh(&table->tb6_lock);
3940 	err = fib6_del(rt, info);
3941 	spin_unlock_bh(&table->tb6_lock);
3942 
3943 out:
3944 	fib6_info_release(rt);
3945 	return err;
3946 }
3947 
3948 int ip6_del_rt(struct net *net, struct fib6_info *rt, bool skip_notify)
3949 {
3950 	struct nl_info info = {
3951 		.nl_net = net,
3952 		.skip_notify = skip_notify
3953 	};
3954 
3955 	return __ip6_del_rt(rt, &info);
3956 }
3957 
3958 static int __ip6_del_rt_siblings(struct fib6_info *rt, struct fib6_config *cfg)
3959 {
3960 	struct nl_info *info = &cfg->fc_nlinfo;
3961 	struct net *net = info->nl_net;
3962 	struct sk_buff *skb = NULL;
3963 	struct fib6_table *table;
3964 	int err = -ENOENT;
3965 
3966 	if (rt == net->ipv6.fib6_null_entry)
3967 		goto out_put;
3968 	table = rt->fib6_table;
3969 	spin_lock_bh(&table->tb6_lock);
3970 
3971 	if (rt->fib6_nsiblings && cfg->fc_delete_all_nh) {
3972 		struct fib6_info *sibling, *next_sibling;
3973 		struct fib6_node *fn;
3974 
3975 		/* prefer to send a single notification with all hops */
3976 		skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
3977 		if (skb) {
3978 			u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
3979 
3980 			if (rt6_fill_node(net, skb, rt, NULL,
3981 					  NULL, NULL, 0, RTM_DELROUTE,
3982 					  info->portid, seq, 0) < 0) {
3983 				kfree_skb(skb);
3984 				skb = NULL;
3985 			} else
3986 				info->skip_notify = 1;
3987 		}
3988 
3989 		/* 'rt' points to the first sibling route. If it is not the
3990 		 * leaf, then we do not need to send a notification. Otherwise,
3991 		 * we need to check if the last sibling has a next route or not
3992 		 * and emit a replace or delete notification, respectively.
3993 		 */
3994 		info->skip_notify_kernel = 1;
3995 		fn = rcu_dereference_protected(rt->fib6_node,
3996 					    lockdep_is_held(&table->tb6_lock));
3997 		if (rcu_access_pointer(fn->leaf) == rt) {
3998 			struct fib6_info *last_sibling, *replace_rt;
3999 
4000 			last_sibling = list_last_entry(&rt->fib6_siblings,
4001 						       struct fib6_info,
4002 						       fib6_siblings);
4003 			replace_rt = rcu_dereference_protected(
4004 					    last_sibling->fib6_next,
4005 					    lockdep_is_held(&table->tb6_lock));
4006 			if (replace_rt)
4007 				call_fib6_entry_notifiers_replace(net,
4008 								  replace_rt);
4009 			else
4010 				call_fib6_multipath_entry_notifiers(net,
4011 						       FIB_EVENT_ENTRY_DEL,
4012 						       rt, rt->fib6_nsiblings,
4013 						       NULL);
4014 		}
4015 		list_for_each_entry_safe(sibling, next_sibling,
4016 					 &rt->fib6_siblings,
4017 					 fib6_siblings) {
4018 			err = fib6_del(sibling, info);
4019 			if (err)
4020 				goto out_unlock;
4021 		}
4022 	}
4023 
4024 	err = fib6_del(rt, info);
4025 out_unlock:
4026 	spin_unlock_bh(&table->tb6_lock);
4027 out_put:
4028 	fib6_info_release(rt);
4029 
4030 	if (skb) {
4031 		rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
4032 			    info->nlh, gfp_any());
4033 	}
4034 	return err;
4035 }
4036 
4037 static int __ip6_del_cached_rt(struct rt6_info *rt, struct fib6_config *cfg)
4038 {
4039 	int rc = -ESRCH;
4040 
4041 	if (cfg->fc_ifindex && rt->dst.dev->ifindex != cfg->fc_ifindex)
4042 		goto out;
4043 
4044 	if (cfg->fc_flags & RTF_GATEWAY &&
4045 	    !ipv6_addr_equal(&cfg->fc_gateway, &rt->rt6i_gateway))
4046 		goto out;
4047 
4048 	rc = rt6_remove_exception_rt(rt);
4049 out:
4050 	return rc;
4051 }
4052 
4053 static int ip6_del_cached_rt(struct fib6_config *cfg, struct fib6_info *rt,
4054 			     struct fib6_nh *nh)
4055 {
4056 	struct fib6_result res = {
4057 		.f6i = rt,
4058 		.nh = nh,
4059 	};
4060 	struct rt6_info *rt_cache;
4061 
4062 	rt_cache = rt6_find_cached_rt(&res, &cfg->fc_dst, &cfg->fc_src);
4063 	if (rt_cache)
4064 		return __ip6_del_cached_rt(rt_cache, cfg);
4065 
4066 	return 0;
4067 }
4068 
4069 struct fib6_nh_del_cached_rt_arg {
4070 	struct fib6_config *cfg;
4071 	struct fib6_info *f6i;
4072 };
4073 
4074 static int fib6_nh_del_cached_rt(struct fib6_nh *nh, void *_arg)
4075 {
4076 	struct fib6_nh_del_cached_rt_arg *arg = _arg;
4077 	int rc;
4078 
4079 	rc = ip6_del_cached_rt(arg->cfg, arg->f6i, nh);
4080 	return rc != -ESRCH ? rc : 0;
4081 }
4082 
4083 static int ip6_del_cached_rt_nh(struct fib6_config *cfg, struct fib6_info *f6i)
4084 {
4085 	struct fib6_nh_del_cached_rt_arg arg = {
4086 		.cfg = cfg,
4087 		.f6i = f6i
4088 	};
4089 
4090 	return nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_del_cached_rt, &arg);
4091 }
4092 
4093 static int ip6_route_del(struct fib6_config *cfg,
4094 			 struct netlink_ext_ack *extack)
4095 {
4096 	struct fib6_table *table;
4097 	struct fib6_info *rt;
4098 	struct fib6_node *fn;
4099 	int err = -ESRCH;
4100 
4101 	table = fib6_get_table(cfg->fc_nlinfo.nl_net, cfg->fc_table);
4102 	if (!table) {
4103 		NL_SET_ERR_MSG(extack, "FIB table does not exist");
4104 		return err;
4105 	}
4106 
4107 	rcu_read_lock();
4108 
4109 	fn = fib6_locate(&table->tb6_root,
4110 			 &cfg->fc_dst, cfg->fc_dst_len,
4111 			 &cfg->fc_src, cfg->fc_src_len,
4112 			 !(cfg->fc_flags & RTF_CACHE));
4113 
4114 	if (fn) {
4115 		for_each_fib6_node_rt_rcu(fn) {
4116 			struct fib6_nh *nh;
4117 
4118 			if (rt->nh && cfg->fc_nh_id &&
4119 			    rt->nh->id != cfg->fc_nh_id)
4120 				continue;
4121 
4122 			if (cfg->fc_flags & RTF_CACHE) {
4123 				int rc = 0;
4124 
4125 				if (rt->nh) {
4126 					rc = ip6_del_cached_rt_nh(cfg, rt);
4127 				} else if (cfg->fc_nh_id) {
4128 					continue;
4129 				} else {
4130 					nh = rt->fib6_nh;
4131 					rc = ip6_del_cached_rt(cfg, rt, nh);
4132 				}
4133 				if (rc != -ESRCH) {
4134 					rcu_read_unlock();
4135 					return rc;
4136 				}
4137 				continue;
4138 			}
4139 
4140 			if (cfg->fc_metric && cfg->fc_metric != rt->fib6_metric)
4141 				continue;
4142 			if (cfg->fc_protocol &&
4143 			    cfg->fc_protocol != rt->fib6_protocol)
4144 				continue;
4145 
4146 			if (rt->nh) {
4147 				if (!fib6_info_hold_safe(rt))
4148 					continue;
4149 
4150 				err =  __ip6_del_rt(rt, &cfg->fc_nlinfo);
4151 				break;
4152 			}
4153 			if (cfg->fc_nh_id)
4154 				continue;
4155 
4156 			nh = rt->fib6_nh;
4157 			if (cfg->fc_ifindex &&
4158 			    (!nh->fib_nh_dev ||
4159 			     nh->fib_nh_dev->ifindex != cfg->fc_ifindex))
4160 				continue;
4161 			if (cfg->fc_flags & RTF_GATEWAY &&
4162 			    !ipv6_addr_equal(&cfg->fc_gateway, &nh->fib_nh_gw6))
4163 				continue;
4164 			if (!fib6_info_hold_safe(rt))
4165 				continue;
4166 
4167 			/* if gateway was specified only delete the one hop */
4168 			if (cfg->fc_flags & RTF_GATEWAY)
4169 				err = __ip6_del_rt(rt, &cfg->fc_nlinfo);
4170 			else
4171 				err = __ip6_del_rt_siblings(rt, cfg);
4172 			break;
4173 		}
4174 	}
4175 	rcu_read_unlock();
4176 
4177 	return err;
4178 }
4179 
4180 static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
4181 {
4182 	struct netevent_redirect netevent;
4183 	struct rt6_info *rt, *nrt = NULL;
4184 	struct fib6_result res = {};
4185 	struct ndisc_options ndopts;
4186 	struct inet6_dev *in6_dev;
4187 	struct neighbour *neigh;
4188 	struct rd_msg *msg;
4189 	int optlen, on_link;
4190 	u8 *lladdr;
4191 
4192 	optlen = skb_tail_pointer(skb) - skb_transport_header(skb);
4193 	optlen -= sizeof(*msg);
4194 
4195 	if (optlen < 0) {
4196 		net_dbg_ratelimited("rt6_do_redirect: packet too short\n");
4197 		return;
4198 	}
4199 
4200 	msg = (struct rd_msg *)icmp6_hdr(skb);
4201 
4202 	if (ipv6_addr_is_multicast(&msg->dest)) {
4203 		net_dbg_ratelimited("rt6_do_redirect: destination address is multicast\n");
4204 		return;
4205 	}
4206 
4207 	on_link = 0;
4208 	if (ipv6_addr_equal(&msg->dest, &msg->target)) {
4209 		on_link = 1;
4210 	} else if (ipv6_addr_type(&msg->target) !=
4211 		   (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) {
4212 		net_dbg_ratelimited("rt6_do_redirect: target address is not link-local unicast\n");
4213 		return;
4214 	}
4215 
4216 	in6_dev = __in6_dev_get(skb->dev);
4217 	if (!in6_dev)
4218 		return;
4219 	if (READ_ONCE(in6_dev->cnf.forwarding) ||
4220 	    !READ_ONCE(in6_dev->cnf.accept_redirects))
4221 		return;
4222 
4223 	/* RFC2461 8.1:
4224 	 *	The IP source address of the Redirect MUST be the same as the current
4225 	 *	first-hop router for the specified ICMP Destination Address.
4226 	 */
4227 
4228 	if (!ndisc_parse_options(skb->dev, msg->opt, optlen, &ndopts)) {
4229 		net_dbg_ratelimited("rt6_redirect: invalid ND options\n");
4230 		return;
4231 	}
4232 
4233 	lladdr = NULL;
4234 	if (ndopts.nd_opts_tgt_lladdr) {
4235 		lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr,
4236 					     skb->dev);
4237 		if (!lladdr) {
4238 			net_dbg_ratelimited("rt6_redirect: invalid link-layer address length\n");
4239 			return;
4240 		}
4241 	}
4242 
4243 	rt = dst_rt6_info(dst);
4244 	if (rt->rt6i_flags & RTF_REJECT) {
4245 		net_dbg_ratelimited("rt6_redirect: source isn't a valid nexthop for redirect target\n");
4246 		return;
4247 	}
4248 
4249 	/* Redirect received -> path was valid.
4250 	 * Look, redirects are sent only in response to data packets,
4251 	 * so that this nexthop apparently is reachable. --ANK
4252 	 */
4253 	dst_confirm_neigh(&rt->dst, &ipv6_hdr(skb)->saddr);
4254 
4255 	neigh = __neigh_lookup(&nd_tbl, &msg->target, skb->dev, 1);
4256 	if (!neigh)
4257 		return;
4258 
4259 	/*
4260 	 *	We have finally decided to accept it.
4261 	 */
4262 
4263 	ndisc_update(skb->dev, neigh, lladdr, NUD_STALE,
4264 		     NEIGH_UPDATE_F_WEAK_OVERRIDE|
4265 		     NEIGH_UPDATE_F_OVERRIDE|
4266 		     (on_link ? 0 : (NEIGH_UPDATE_F_OVERRIDE_ISROUTER|
4267 				     NEIGH_UPDATE_F_ISROUTER)),
4268 		     NDISC_REDIRECT, &ndopts);
4269 
4270 	rcu_read_lock();
4271 	res.f6i = rcu_dereference(rt->from);
4272 	if (!res.f6i)
4273 		goto out;
4274 
4275 	if (res.f6i->nh) {
4276 		struct fib6_nh_match_arg arg = {
4277 			.dev = dst->dev,
4278 			.gw = &rt->rt6i_gateway,
4279 		};
4280 
4281 		nexthop_for_each_fib6_nh(res.f6i->nh,
4282 					 fib6_nh_find_match, &arg);
4283 
4284 		/* fib6_info uses a nexthop that does not have fib6_nh
4285 		 * using the dst->dev. Should be impossible
4286 		 */
4287 		if (!arg.match)
4288 			goto out;
4289 		res.nh = arg.match;
4290 	} else {
4291 		res.nh = res.f6i->fib6_nh;
4292 	}
4293 
4294 	res.fib6_flags = res.f6i->fib6_flags;
4295 	res.fib6_type = res.f6i->fib6_type;
4296 	nrt = ip6_rt_cache_alloc(&res, &msg->dest, NULL);
4297 	if (!nrt)
4298 		goto out;
4299 
4300 	nrt->rt6i_flags = RTF_GATEWAY|RTF_UP|RTF_DYNAMIC|RTF_CACHE;
4301 	if (on_link)
4302 		nrt->rt6i_flags &= ~RTF_GATEWAY;
4303 
4304 	nrt->rt6i_gateway = *(struct in6_addr *)neigh->primary_key;
4305 
4306 	/* rt6_insert_exception() will take care of duplicated exceptions */
4307 	if (rt6_insert_exception(nrt, &res)) {
4308 		dst_release_immediate(&nrt->dst);
4309 		goto out;
4310 	}
4311 
4312 	netevent.old = &rt->dst;
4313 	netevent.new = &nrt->dst;
4314 	netevent.daddr = &msg->dest;
4315 	netevent.neigh = neigh;
4316 	call_netevent_notifiers(NETEVENT_REDIRECT, &netevent);
4317 
4318 out:
4319 	rcu_read_unlock();
4320 	neigh_release(neigh);
4321 }
4322 
4323 #ifdef CONFIG_IPV6_ROUTE_INFO
4324 static struct fib6_info *rt6_get_route_info(struct net *net,
4325 					   const struct in6_addr *prefix, int prefixlen,
4326 					   const struct in6_addr *gwaddr,
4327 					   struct net_device *dev)
4328 {
4329 	u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_INFO;
4330 	int ifindex = dev->ifindex;
4331 	struct fib6_node *fn;
4332 	struct fib6_info *rt = NULL;
4333 	struct fib6_table *table;
4334 
4335 	table = fib6_get_table(net, tb_id);
4336 	if (!table)
4337 		return NULL;
4338 
4339 	rcu_read_lock();
4340 	fn = fib6_locate(&table->tb6_root, prefix, prefixlen, NULL, 0, true);
4341 	if (!fn)
4342 		goto out;
4343 
4344 	for_each_fib6_node_rt_rcu(fn) {
4345 		/* these routes do not use nexthops */
4346 		if (rt->nh)
4347 			continue;
4348 		if (rt->fib6_nh->fib_nh_dev->ifindex != ifindex)
4349 			continue;
4350 		if (!(rt->fib6_flags & RTF_ROUTEINFO) ||
4351 		    !rt->fib6_nh->fib_nh_gw_family)
4352 			continue;
4353 		if (!ipv6_addr_equal(&rt->fib6_nh->fib_nh_gw6, gwaddr))
4354 			continue;
4355 		if (!fib6_info_hold_safe(rt))
4356 			continue;
4357 		break;
4358 	}
4359 out:
4360 	rcu_read_unlock();
4361 	return rt;
4362 }
4363 
4364 static struct fib6_info *rt6_add_route_info(struct net *net,
4365 					   const struct in6_addr *prefix, int prefixlen,
4366 					   const struct in6_addr *gwaddr,
4367 					   struct net_device *dev,
4368 					   unsigned int pref)
4369 {
4370 	struct fib6_config cfg = {
4371 		.fc_metric	= IP6_RT_PRIO_USER,
4372 		.fc_ifindex	= dev->ifindex,
4373 		.fc_dst_len	= prefixlen,
4374 		.fc_flags	= RTF_GATEWAY | RTF_ADDRCONF | RTF_ROUTEINFO |
4375 				  RTF_UP | RTF_PREF(pref),
4376 		.fc_protocol = RTPROT_RA,
4377 		.fc_type = RTN_UNICAST,
4378 		.fc_nlinfo.portid = 0,
4379 		.fc_nlinfo.nlh = NULL,
4380 		.fc_nlinfo.nl_net = net,
4381 	};
4382 
4383 	cfg.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_INFO;
4384 	cfg.fc_dst = *prefix;
4385 	cfg.fc_gateway = *gwaddr;
4386 
4387 	/* We should treat it as a default route if prefix length is 0. */
4388 	if (!prefixlen)
4389 		cfg.fc_flags |= RTF_DEFAULT;
4390 
4391 	ip6_route_add(&cfg, GFP_ATOMIC, NULL);
4392 
4393 	return rt6_get_route_info(net, prefix, prefixlen, gwaddr, dev);
4394 }
4395 #endif
4396 
4397 struct fib6_info *rt6_get_dflt_router(struct net *net,
4398 				     const struct in6_addr *addr,
4399 				     struct net_device *dev)
4400 {
4401 	u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_DFLT;
4402 	struct fib6_info *rt;
4403 	struct fib6_table *table;
4404 
4405 	table = fib6_get_table(net, tb_id);
4406 	if (!table)
4407 		return NULL;
4408 
4409 	rcu_read_lock();
4410 	for_each_fib6_node_rt_rcu(&table->tb6_root) {
4411 		struct fib6_nh *nh;
4412 
4413 		/* RA routes do not use nexthops */
4414 		if (rt->nh)
4415 			continue;
4416 
4417 		nh = rt->fib6_nh;
4418 		if (dev == nh->fib_nh_dev &&
4419 		    ((rt->fib6_flags & (RTF_ADDRCONF | RTF_DEFAULT)) == (RTF_ADDRCONF | RTF_DEFAULT)) &&
4420 		    ipv6_addr_equal(&nh->fib_nh_gw6, addr))
4421 			break;
4422 	}
4423 	if (rt && !fib6_info_hold_safe(rt))
4424 		rt = NULL;
4425 	rcu_read_unlock();
4426 	return rt;
4427 }
4428 
4429 struct fib6_info *rt6_add_dflt_router(struct net *net,
4430 				     const struct in6_addr *gwaddr,
4431 				     struct net_device *dev,
4432 				     unsigned int pref,
4433 				     u32 defrtr_usr_metric,
4434 				     int lifetime)
4435 {
4436 	struct fib6_config cfg = {
4437 		.fc_table	= l3mdev_fib_table(dev) ? : RT6_TABLE_DFLT,
4438 		.fc_metric	= defrtr_usr_metric,
4439 		.fc_ifindex	= dev->ifindex,
4440 		.fc_flags	= RTF_GATEWAY | RTF_ADDRCONF | RTF_DEFAULT |
4441 				  RTF_UP | RTF_EXPIRES | RTF_PREF(pref),
4442 		.fc_protocol = RTPROT_RA,
4443 		.fc_type = RTN_UNICAST,
4444 		.fc_nlinfo.portid = 0,
4445 		.fc_nlinfo.nlh = NULL,
4446 		.fc_nlinfo.nl_net = net,
4447 		.fc_expires = jiffies_to_clock_t(lifetime * HZ),
4448 	};
4449 
4450 	cfg.fc_gateway = *gwaddr;
4451 
4452 	if (!ip6_route_add(&cfg, GFP_ATOMIC, NULL)) {
4453 		struct fib6_table *table;
4454 
4455 		table = fib6_get_table(dev_net(dev), cfg.fc_table);
4456 		if (table)
4457 			table->flags |= RT6_TABLE_HAS_DFLT_ROUTER;
4458 	}
4459 
4460 	return rt6_get_dflt_router(net, gwaddr, dev);
4461 }
4462 
4463 static void __rt6_purge_dflt_routers(struct net *net,
4464 				     struct fib6_table *table)
4465 {
4466 	struct fib6_info *rt;
4467 
4468 restart:
4469 	rcu_read_lock();
4470 	for_each_fib6_node_rt_rcu(&table->tb6_root) {
4471 		struct net_device *dev = fib6_info_nh_dev(rt);
4472 		struct inet6_dev *idev = dev ? __in6_dev_get(dev) : NULL;
4473 
4474 		if (rt->fib6_flags & (RTF_DEFAULT | RTF_ADDRCONF) &&
4475 		    (!idev || idev->cnf.accept_ra != 2) &&
4476 		    fib6_info_hold_safe(rt)) {
4477 			rcu_read_unlock();
4478 			ip6_del_rt(net, rt, false);
4479 			goto restart;
4480 		}
4481 	}
4482 	rcu_read_unlock();
4483 
4484 	table->flags &= ~RT6_TABLE_HAS_DFLT_ROUTER;
4485 }
4486 
4487 void rt6_purge_dflt_routers(struct net *net)
4488 {
4489 	struct fib6_table *table;
4490 	struct hlist_head *head;
4491 	unsigned int h;
4492 
4493 	rcu_read_lock();
4494 
4495 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
4496 		head = &net->ipv6.fib_table_hash[h];
4497 		hlist_for_each_entry_rcu(table, head, tb6_hlist) {
4498 			if (table->flags & RT6_TABLE_HAS_DFLT_ROUTER)
4499 				__rt6_purge_dflt_routers(net, table);
4500 		}
4501 	}
4502 
4503 	rcu_read_unlock();
4504 }
4505 
4506 static int fib6_config_validate(struct fib6_config *cfg,
4507 				struct netlink_ext_ack *extack)
4508 {
4509 	/* RTF_PCPU is an internal flag; can not be set by userspace */
4510 	if (cfg->fc_flags & RTF_PCPU) {
4511 		NL_SET_ERR_MSG(extack, "Userspace can not set RTF_PCPU");
4512 		goto errout;
4513 	}
4514 
4515 	/* RTF_CACHE is an internal flag; can not be set by userspace */
4516 	if (cfg->fc_flags & RTF_CACHE) {
4517 		NL_SET_ERR_MSG(extack, "Userspace can not set RTF_CACHE");
4518 		goto errout;
4519 	}
4520 
4521 	if (cfg->fc_type > RTN_MAX) {
4522 		NL_SET_ERR_MSG(extack, "Invalid route type");
4523 		goto errout;
4524 	}
4525 
4526 	if (cfg->fc_dst_len > 128) {
4527 		NL_SET_ERR_MSG(extack, "Invalid prefix length");
4528 		goto errout;
4529 	}
4530 
4531 #ifdef CONFIG_IPV6_SUBTREES
4532 	if (cfg->fc_src_len > 128) {
4533 		NL_SET_ERR_MSG(extack, "Invalid source address length");
4534 		goto errout;
4535 	}
4536 
4537 	if (cfg->fc_nh_id && cfg->fc_src_len) {
4538 		NL_SET_ERR_MSG(extack, "Nexthops can not be used with source routing");
4539 		goto errout;
4540 	}
4541 #else
4542 	if (cfg->fc_src_len) {
4543 		NL_SET_ERR_MSG(extack,
4544 			       "Specifying source address requires IPV6_SUBTREES to be enabled");
4545 		goto errout;
4546 	}
4547 #endif
4548 	return 0;
4549 errout:
4550 	return -EINVAL;
4551 }
4552 
4553 static void rtmsg_to_fib6_config(struct net *net,
4554 				 struct in6_rtmsg *rtmsg,
4555 				 struct fib6_config *cfg)
4556 {
4557 	*cfg = (struct fib6_config){
4558 		.fc_table = l3mdev_fib_table_by_index(net, rtmsg->rtmsg_ifindex) ?
4559 			 : RT6_TABLE_MAIN,
4560 		.fc_ifindex = rtmsg->rtmsg_ifindex,
4561 		.fc_metric = rtmsg->rtmsg_metric,
4562 		.fc_expires = rtmsg->rtmsg_info,
4563 		.fc_dst_len = rtmsg->rtmsg_dst_len,
4564 		.fc_src_len = rtmsg->rtmsg_src_len,
4565 		.fc_flags = rtmsg->rtmsg_flags,
4566 		.fc_type = rtmsg->rtmsg_type,
4567 
4568 		.fc_nlinfo.nl_net = net,
4569 
4570 		.fc_dst = rtmsg->rtmsg_dst,
4571 		.fc_src = rtmsg->rtmsg_src,
4572 		.fc_gateway = rtmsg->rtmsg_gateway,
4573 	};
4574 }
4575 
4576 int ipv6_route_ioctl(struct net *net, unsigned int cmd, struct in6_rtmsg *rtmsg)
4577 {
4578 	struct fib6_config cfg;
4579 	int err;
4580 
4581 	if (cmd != SIOCADDRT && cmd != SIOCDELRT)
4582 		return -EINVAL;
4583 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
4584 		return -EPERM;
4585 
4586 	rtmsg_to_fib6_config(net, rtmsg, &cfg);
4587 
4588 	switch (cmd) {
4589 	case SIOCADDRT:
4590 		err = fib6_config_validate(&cfg, NULL);
4591 		if (err)
4592 			break;
4593 
4594 		/* Only do the default setting of fc_metric in route adding */
4595 		if (cfg.fc_metric == 0)
4596 			cfg.fc_metric = IP6_RT_PRIO_USER;
4597 		err = ip6_route_add(&cfg, GFP_KERNEL, NULL);
4598 		break;
4599 	case SIOCDELRT:
4600 		err = ip6_route_del(&cfg, NULL);
4601 		break;
4602 	}
4603 
4604 	return err;
4605 }
4606 
4607 /*
4608  *	Drop the packet on the floor
4609  */
4610 
4611 static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
4612 {
4613 	struct dst_entry *dst = skb_dst(skb);
4614 	struct net *net = dev_net(dst->dev);
4615 	struct inet6_dev *idev;
4616 	SKB_DR(reason);
4617 	int type;
4618 
4619 	if (netif_is_l3_master(skb->dev) ||
4620 	    dst->dev == net->loopback_dev)
4621 		idev = __in6_dev_get_safely(dev_get_by_index_rcu(net, IP6CB(skb)->iif));
4622 	else
4623 		idev = ip6_dst_idev(dst);
4624 
4625 	switch (ipstats_mib_noroutes) {
4626 	case IPSTATS_MIB_INNOROUTES:
4627 		type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
4628 		if (type == IPV6_ADDR_ANY) {
4629 			SKB_DR_SET(reason, IP_INADDRERRORS);
4630 			IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
4631 			break;
4632 		}
4633 		SKB_DR_SET(reason, IP_INNOROUTES);
4634 		fallthrough;
4635 	case IPSTATS_MIB_OUTNOROUTES:
4636 		SKB_DR_OR(reason, IP_OUTNOROUTES);
4637 		IP6_INC_STATS(net, idev, ipstats_mib_noroutes);
4638 		break;
4639 	}
4640 
4641 	/* Start over by dropping the dst for l3mdev case */
4642 	if (netif_is_l3_master(skb->dev))
4643 		skb_dst_drop(skb);
4644 
4645 	icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
4646 	kfree_skb_reason(skb, reason);
4647 	return 0;
4648 }
4649 
4650 static int ip6_pkt_discard(struct sk_buff *skb)
4651 {
4652 	return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
4653 }
4654 
4655 static int ip6_pkt_discard_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4656 {
4657 	skb->dev = skb_dst(skb)->dev;
4658 	return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
4659 }
4660 
4661 static int ip6_pkt_prohibit(struct sk_buff *skb)
4662 {
4663 	return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
4664 }
4665 
4666 static int ip6_pkt_prohibit_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4667 {
4668 	skb->dev = skb_dst(skb)->dev;
4669 	return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
4670 }
4671 
4672 /*
4673  *	Allocate a dst for local (unicast / anycast) address.
4674  */
4675 
4676 struct fib6_info *addrconf_f6i_alloc(struct net *net,
4677 				     struct inet6_dev *idev,
4678 				     const struct in6_addr *addr,
4679 				     bool anycast, gfp_t gfp_flags,
4680 				     struct netlink_ext_ack *extack)
4681 {
4682 	struct fib6_config cfg = {
4683 		.fc_table = l3mdev_fib_table(idev->dev) ? : RT6_TABLE_LOCAL,
4684 		.fc_ifindex = idev->dev->ifindex,
4685 		.fc_flags = RTF_UP | RTF_NONEXTHOP,
4686 		.fc_dst = *addr,
4687 		.fc_dst_len = 128,
4688 		.fc_protocol = RTPROT_KERNEL,
4689 		.fc_nlinfo.nl_net = net,
4690 		.fc_ignore_dev_down = true,
4691 	};
4692 	struct fib6_info *f6i;
4693 	int err;
4694 
4695 	if (anycast) {
4696 		cfg.fc_type = RTN_ANYCAST;
4697 		cfg.fc_flags |= RTF_ANYCAST;
4698 	} else {
4699 		cfg.fc_type = RTN_LOCAL;
4700 		cfg.fc_flags |= RTF_LOCAL;
4701 	}
4702 
4703 	f6i = ip6_route_info_create(&cfg, gfp_flags, extack);
4704 	if (IS_ERR(f6i))
4705 		return f6i;
4706 
4707 	err = ip6_route_info_create_nh(f6i, &cfg, extack);
4708 	if (err)
4709 		return ERR_PTR(err);
4710 
4711 	f6i->dst_nocount = true;
4712 
4713 	if (!anycast &&
4714 	    (READ_ONCE(net->ipv6.devconf_all->disable_policy) ||
4715 	     READ_ONCE(idev->cnf.disable_policy)))
4716 		f6i->dst_nopolicy = true;
4717 
4718 	return f6i;
4719 }
4720 
4721 /* remove deleted ip from prefsrc entries */
4722 struct arg_dev_net_ip {
4723 	struct net *net;
4724 	struct in6_addr *addr;
4725 };
4726 
4727 static int fib6_remove_prefsrc(struct fib6_info *rt, void *arg)
4728 {
4729 	struct net *net = ((struct arg_dev_net_ip *)arg)->net;
4730 	struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
4731 
4732 	if (!rt->nh &&
4733 	    rt != net->ipv6.fib6_null_entry &&
4734 	    ipv6_addr_equal(addr, &rt->fib6_prefsrc.addr) &&
4735 	    !ipv6_chk_addr(net, addr, rt->fib6_nh->fib_nh_dev, 0)) {
4736 		spin_lock_bh(&rt6_exception_lock);
4737 		/* remove prefsrc entry */
4738 		rt->fib6_prefsrc.plen = 0;
4739 		spin_unlock_bh(&rt6_exception_lock);
4740 	}
4741 	return 0;
4742 }
4743 
4744 void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
4745 {
4746 	struct net *net = dev_net(ifp->idev->dev);
4747 	struct arg_dev_net_ip adni = {
4748 		.net = net,
4749 		.addr = &ifp->addr,
4750 	};
4751 	fib6_clean_all(net, fib6_remove_prefsrc, &adni);
4752 }
4753 
4754 #define RTF_RA_ROUTER		(RTF_ADDRCONF | RTF_DEFAULT)
4755 
4756 /* Remove routers and update dst entries when gateway turn into host. */
4757 static int fib6_clean_tohost(struct fib6_info *rt, void *arg)
4758 {
4759 	struct in6_addr *gateway = (struct in6_addr *)arg;
4760 	struct fib6_nh *nh;
4761 
4762 	/* RA routes do not use nexthops */
4763 	if (rt->nh)
4764 		return 0;
4765 
4766 	nh = rt->fib6_nh;
4767 	if (((rt->fib6_flags & RTF_RA_ROUTER) == RTF_RA_ROUTER) &&
4768 	    nh->fib_nh_gw_family && ipv6_addr_equal(gateway, &nh->fib_nh_gw6))
4769 		return -1;
4770 
4771 	/* Further clean up cached routes in exception table.
4772 	 * This is needed because cached route may have a different
4773 	 * gateway than its 'parent' in the case of an ip redirect.
4774 	 */
4775 	fib6_nh_exceptions_clean_tohost(nh, gateway);
4776 
4777 	return 0;
4778 }
4779 
4780 void rt6_clean_tohost(struct net *net, struct in6_addr *gateway)
4781 {
4782 	fib6_clean_all(net, fib6_clean_tohost, gateway);
4783 }
4784 
4785 struct arg_netdev_event {
4786 	const struct net_device *dev;
4787 	union {
4788 		unsigned char nh_flags;
4789 		unsigned long event;
4790 	};
4791 };
4792 
4793 static struct fib6_info *rt6_multipath_first_sibling(const struct fib6_info *rt)
4794 {
4795 	struct fib6_info *iter;
4796 	struct fib6_node *fn;
4797 
4798 	fn = rcu_dereference_protected(rt->fib6_node,
4799 			lockdep_is_held(&rt->fib6_table->tb6_lock));
4800 	iter = rcu_dereference_protected(fn->leaf,
4801 			lockdep_is_held(&rt->fib6_table->tb6_lock));
4802 	while (iter) {
4803 		if (iter->fib6_metric == rt->fib6_metric &&
4804 		    rt6_qualify_for_ecmp(iter))
4805 			return iter;
4806 		iter = rcu_dereference_protected(iter->fib6_next,
4807 				lockdep_is_held(&rt->fib6_table->tb6_lock));
4808 	}
4809 
4810 	return NULL;
4811 }
4812 
4813 /* only called for fib entries with builtin fib6_nh */
4814 static bool rt6_is_dead(const struct fib6_info *rt)
4815 {
4816 	if (rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD ||
4817 	    (rt->fib6_nh->fib_nh_flags & RTNH_F_LINKDOWN &&
4818 	     ip6_ignore_linkdown(rt->fib6_nh->fib_nh_dev)))
4819 		return true;
4820 
4821 	return false;
4822 }
4823 
4824 static int rt6_multipath_total_weight(const struct fib6_info *rt)
4825 {
4826 	struct fib6_info *iter;
4827 	int total = 0;
4828 
4829 	if (!rt6_is_dead(rt))
4830 		total += rt->fib6_nh->fib_nh_weight;
4831 
4832 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings) {
4833 		if (!rt6_is_dead(iter))
4834 			total += iter->fib6_nh->fib_nh_weight;
4835 	}
4836 
4837 	return total;
4838 }
4839 
4840 static void rt6_upper_bound_set(struct fib6_info *rt, int *weight, int total)
4841 {
4842 	int upper_bound = -1;
4843 
4844 	if (!rt6_is_dead(rt)) {
4845 		*weight += rt->fib6_nh->fib_nh_weight;
4846 		upper_bound = DIV_ROUND_CLOSEST_ULL((u64) (*weight) << 31,
4847 						    total) - 1;
4848 	}
4849 	atomic_set(&rt->fib6_nh->fib_nh_upper_bound, upper_bound);
4850 }
4851 
4852 static void rt6_multipath_upper_bound_set(struct fib6_info *rt, int total)
4853 {
4854 	struct fib6_info *iter;
4855 	int weight = 0;
4856 
4857 	rt6_upper_bound_set(rt, &weight, total);
4858 
4859 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4860 		rt6_upper_bound_set(iter, &weight, total);
4861 }
4862 
4863 void rt6_multipath_rebalance(struct fib6_info *rt)
4864 {
4865 	struct fib6_info *first;
4866 	int total;
4867 
4868 	/* In case the entire multipath route was marked for flushing,
4869 	 * then there is no need to rebalance upon the removal of every
4870 	 * sibling route.
4871 	 */
4872 	if (!rt->fib6_nsiblings || rt->should_flush)
4873 		return;
4874 
4875 	/* During lookup routes are evaluated in order, so we need to
4876 	 * make sure upper bounds are assigned from the first sibling
4877 	 * onwards.
4878 	 */
4879 	first = rt6_multipath_first_sibling(rt);
4880 	if (WARN_ON_ONCE(!first))
4881 		return;
4882 
4883 	total = rt6_multipath_total_weight(first);
4884 	rt6_multipath_upper_bound_set(first, total);
4885 }
4886 
4887 static int fib6_ifup(struct fib6_info *rt, void *p_arg)
4888 {
4889 	const struct arg_netdev_event *arg = p_arg;
4890 	struct net *net = dev_net(arg->dev);
4891 
4892 	if (rt != net->ipv6.fib6_null_entry && !rt->nh &&
4893 	    rt->fib6_nh->fib_nh_dev == arg->dev) {
4894 		rt->fib6_nh->fib_nh_flags &= ~arg->nh_flags;
4895 		fib6_update_sernum_upto_root(net, rt);
4896 		rt6_multipath_rebalance(rt);
4897 	}
4898 
4899 	return 0;
4900 }
4901 
4902 void rt6_sync_up(struct net_device *dev, unsigned char nh_flags)
4903 {
4904 	struct arg_netdev_event arg = {
4905 		.dev = dev,
4906 		{
4907 			.nh_flags = nh_flags,
4908 		},
4909 	};
4910 
4911 	if (nh_flags & RTNH_F_DEAD && netif_carrier_ok(dev))
4912 		arg.nh_flags |= RTNH_F_LINKDOWN;
4913 
4914 	fib6_clean_all(dev_net(dev), fib6_ifup, &arg);
4915 }
4916 
4917 /* only called for fib entries with inline fib6_nh */
4918 static bool rt6_multipath_uses_dev(const struct fib6_info *rt,
4919 				   const struct net_device *dev)
4920 {
4921 	struct fib6_info *iter;
4922 
4923 	if (rt->fib6_nh->fib_nh_dev == dev)
4924 		return true;
4925 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4926 		if (iter->fib6_nh->fib_nh_dev == dev)
4927 			return true;
4928 
4929 	return false;
4930 }
4931 
4932 static void rt6_multipath_flush(struct fib6_info *rt)
4933 {
4934 	struct fib6_info *iter;
4935 
4936 	rt->should_flush = 1;
4937 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4938 		iter->should_flush = 1;
4939 }
4940 
4941 static unsigned int rt6_multipath_dead_count(const struct fib6_info *rt,
4942 					     const struct net_device *down_dev)
4943 {
4944 	struct fib6_info *iter;
4945 	unsigned int dead = 0;
4946 
4947 	if (rt->fib6_nh->fib_nh_dev == down_dev ||
4948 	    rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4949 		dead++;
4950 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4951 		if (iter->fib6_nh->fib_nh_dev == down_dev ||
4952 		    iter->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4953 			dead++;
4954 
4955 	return dead;
4956 }
4957 
4958 static void rt6_multipath_nh_flags_set(struct fib6_info *rt,
4959 				       const struct net_device *dev,
4960 				       unsigned char nh_flags)
4961 {
4962 	struct fib6_info *iter;
4963 
4964 	if (rt->fib6_nh->fib_nh_dev == dev)
4965 		rt->fib6_nh->fib_nh_flags |= nh_flags;
4966 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4967 		if (iter->fib6_nh->fib_nh_dev == dev)
4968 			iter->fib6_nh->fib_nh_flags |= nh_flags;
4969 }
4970 
4971 /* called with write lock held for table with rt */
4972 static int fib6_ifdown(struct fib6_info *rt, void *p_arg)
4973 {
4974 	const struct arg_netdev_event *arg = p_arg;
4975 	const struct net_device *dev = arg->dev;
4976 	struct net *net = dev_net(dev);
4977 
4978 	if (rt == net->ipv6.fib6_null_entry || rt->nh)
4979 		return 0;
4980 
4981 	switch (arg->event) {
4982 	case NETDEV_UNREGISTER:
4983 		return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4984 	case NETDEV_DOWN:
4985 		if (rt->should_flush)
4986 			return -1;
4987 		if (!rt->fib6_nsiblings)
4988 			return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4989 		if (rt6_multipath_uses_dev(rt, dev)) {
4990 			unsigned int count;
4991 
4992 			count = rt6_multipath_dead_count(rt, dev);
4993 			if (rt->fib6_nsiblings + 1 == count) {
4994 				rt6_multipath_flush(rt);
4995 				return -1;
4996 			}
4997 			rt6_multipath_nh_flags_set(rt, dev, RTNH_F_DEAD |
4998 						   RTNH_F_LINKDOWN);
4999 			fib6_update_sernum(net, rt);
5000 			rt6_multipath_rebalance(rt);
5001 		}
5002 		return -2;
5003 	case NETDEV_CHANGE:
5004 		if (rt->fib6_nh->fib_nh_dev != dev ||
5005 		    rt->fib6_flags & (RTF_LOCAL | RTF_ANYCAST))
5006 			break;
5007 		rt->fib6_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
5008 		rt6_multipath_rebalance(rt);
5009 		break;
5010 	}
5011 
5012 	return 0;
5013 }
5014 
5015 void rt6_sync_down_dev(struct net_device *dev, unsigned long event)
5016 {
5017 	struct arg_netdev_event arg = {
5018 		.dev = dev,
5019 		{
5020 			.event = event,
5021 		},
5022 	};
5023 	struct net *net = dev_net(dev);
5024 
5025 	if (net->ipv6.sysctl.skip_notify_on_dev_down)
5026 		fib6_clean_all_skip_notify(net, fib6_ifdown, &arg);
5027 	else
5028 		fib6_clean_all(net, fib6_ifdown, &arg);
5029 }
5030 
5031 void rt6_disable_ip(struct net_device *dev, unsigned long event)
5032 {
5033 	rt6_sync_down_dev(dev, event);
5034 	rt6_uncached_list_flush_dev(dev);
5035 	neigh_ifdown(&nd_tbl, dev);
5036 }
5037 
5038 struct rt6_mtu_change_arg {
5039 	struct net_device *dev;
5040 	unsigned int mtu;
5041 	struct fib6_info *f6i;
5042 };
5043 
5044 static int fib6_nh_mtu_change(struct fib6_nh *nh, void *_arg)
5045 {
5046 	struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *)_arg;
5047 	struct fib6_info *f6i = arg->f6i;
5048 
5049 	/* For administrative MTU increase, there is no way to discover
5050 	 * IPv6 PMTU increase, so PMTU increase should be updated here.
5051 	 * Since RFC 1981 doesn't include administrative MTU increase
5052 	 * update PMTU increase is a MUST. (i.e. jumbo frame)
5053 	 */
5054 	if (nh->fib_nh_dev == arg->dev) {
5055 		struct inet6_dev *idev = __in6_dev_get(arg->dev);
5056 		u32 mtu = f6i->fib6_pmtu;
5057 
5058 		if (mtu >= arg->mtu ||
5059 		    (mtu < arg->mtu && mtu == idev->cnf.mtu6))
5060 			fib6_metric_set(f6i, RTAX_MTU, arg->mtu);
5061 
5062 		spin_lock_bh(&rt6_exception_lock);
5063 		rt6_exceptions_update_pmtu(idev, nh, arg->mtu);
5064 		spin_unlock_bh(&rt6_exception_lock);
5065 	}
5066 
5067 	return 0;
5068 }
5069 
5070 static int rt6_mtu_change_route(struct fib6_info *f6i, void *p_arg)
5071 {
5072 	struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
5073 	struct inet6_dev *idev;
5074 
5075 	/* In IPv6 pmtu discovery is not optional,
5076 	   so that RTAX_MTU lock cannot disable it.
5077 	   We still use this lock to block changes
5078 	   caused by addrconf/ndisc.
5079 	*/
5080 
5081 	idev = __in6_dev_get(arg->dev);
5082 	if (!idev)
5083 		return 0;
5084 
5085 	if (fib6_metric_locked(f6i, RTAX_MTU))
5086 		return 0;
5087 
5088 	arg->f6i = f6i;
5089 	if (f6i->nh) {
5090 		/* fib6_nh_mtu_change only returns 0, so this is safe */
5091 		return nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_mtu_change,
5092 						arg);
5093 	}
5094 
5095 	return fib6_nh_mtu_change(f6i->fib6_nh, arg);
5096 }
5097 
5098 void rt6_mtu_change(struct net_device *dev, unsigned int mtu)
5099 {
5100 	struct rt6_mtu_change_arg arg = {
5101 		.dev = dev,
5102 		.mtu = mtu,
5103 	};
5104 
5105 	fib6_clean_all(dev_net(dev), rt6_mtu_change_route, &arg);
5106 }
5107 
5108 static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
5109 	[RTA_UNSPEC]		= { .strict_start_type = RTA_DPORT + 1 },
5110 	[RTA_GATEWAY]           = { .len = sizeof(struct in6_addr) },
5111 	[RTA_PREFSRC]		= { .len = sizeof(struct in6_addr) },
5112 	[RTA_OIF]               = { .type = NLA_U32 },
5113 	[RTA_IIF]		= { .type = NLA_U32 },
5114 	[RTA_PRIORITY]          = { .type = NLA_U32 },
5115 	[RTA_METRICS]           = { .type = NLA_NESTED },
5116 	[RTA_MULTIPATH]		= { .len = sizeof(struct rtnexthop) },
5117 	[RTA_PREF]              = { .type = NLA_U8 },
5118 	[RTA_ENCAP_TYPE]	= { .type = NLA_U16 },
5119 	[RTA_ENCAP]		= { .type = NLA_NESTED },
5120 	[RTA_EXPIRES]		= { .type = NLA_U32 },
5121 	[RTA_UID]		= { .type = NLA_U32 },
5122 	[RTA_MARK]		= { .type = NLA_U32 },
5123 	[RTA_TABLE]		= { .type = NLA_U32 },
5124 	[RTA_IP_PROTO]		= { .type = NLA_U8 },
5125 	[RTA_SPORT]		= { .type = NLA_U16 },
5126 	[RTA_DPORT]		= { .type = NLA_U16 },
5127 	[RTA_NH_ID]		= { .type = NLA_U32 },
5128 	[RTA_FLOWLABEL]		= { .type = NLA_BE32 },
5129 };
5130 
5131 static int rtm_to_fib6_multipath_config(struct fib6_config *cfg,
5132 					struct netlink_ext_ack *extack,
5133 					bool newroute)
5134 {
5135 	struct rtnexthop *rtnh;
5136 	int remaining;
5137 
5138 	remaining = cfg->fc_mp_len;
5139 	rtnh = (struct rtnexthop *)cfg->fc_mp;
5140 
5141 	if (!rtnh_ok(rtnh, remaining)) {
5142 		NL_SET_ERR_MSG(extack, "Invalid nexthop configuration - no valid nexthops");
5143 		return -EINVAL;
5144 	}
5145 
5146 	do {
5147 		bool has_gateway = cfg->fc_flags & RTF_GATEWAY;
5148 		int attrlen = rtnh_attrlen(rtnh);
5149 
5150 		if (attrlen > 0) {
5151 			struct nlattr *nla, *attrs;
5152 
5153 			attrs = rtnh_attrs(rtnh);
5154 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
5155 			if (nla) {
5156 				if (nla_len(nla) < sizeof(cfg->fc_gateway)) {
5157 					NL_SET_ERR_MSG(extack,
5158 						       "Invalid IPv6 address in RTA_GATEWAY");
5159 					return -EINVAL;
5160 				}
5161 
5162 				has_gateway = true;
5163 			}
5164 		}
5165 
5166 		if (newroute && (cfg->fc_nh_id || !has_gateway)) {
5167 			NL_SET_ERR_MSG(extack,
5168 				       "Device only routes can not be added for IPv6 using the multipath API.");
5169 			return -EINVAL;
5170 		}
5171 
5172 		rtnh = rtnh_next(rtnh, &remaining);
5173 	} while (rtnh_ok(rtnh, remaining));
5174 
5175 	return lwtunnel_valid_encap_type_attr(cfg->fc_mp, cfg->fc_mp_len,
5176 					      extack, false);
5177 }
5178 
5179 static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
5180 			      struct fib6_config *cfg,
5181 			      struct netlink_ext_ack *extack)
5182 {
5183 	bool newroute = nlh->nlmsg_type == RTM_NEWROUTE;
5184 	struct nlattr *tb[RTA_MAX+1];
5185 	struct rtmsg *rtm;
5186 	unsigned int pref;
5187 	int err;
5188 
5189 	err = nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
5190 				     rtm_ipv6_policy, extack);
5191 	if (err < 0)
5192 		goto errout;
5193 
5194 	err = -EINVAL;
5195 	rtm = nlmsg_data(nlh);
5196 
5197 	if (rtm->rtm_tos) {
5198 		NL_SET_ERR_MSG(extack,
5199 			       "Invalid dsfield (tos): option not available for IPv6");
5200 		goto errout;
5201 	}
5202 
5203 	if (tb[RTA_FLOWLABEL]) {
5204 		NL_SET_ERR_MSG_ATTR(extack, tb[RTA_FLOWLABEL],
5205 				    "Flow label cannot be specified for this operation");
5206 		goto errout;
5207 	}
5208 
5209 	*cfg = (struct fib6_config){
5210 		.fc_table = rtm->rtm_table,
5211 		.fc_dst_len = rtm->rtm_dst_len,
5212 		.fc_src_len = rtm->rtm_src_len,
5213 		.fc_flags = RTF_UP,
5214 		.fc_protocol = rtm->rtm_protocol,
5215 		.fc_type = rtm->rtm_type,
5216 
5217 		.fc_nlinfo.portid = NETLINK_CB(skb).portid,
5218 		.fc_nlinfo.nlh = nlh,
5219 		.fc_nlinfo.nl_net = sock_net(skb->sk),
5220 	};
5221 
5222 	if (rtm->rtm_type == RTN_UNREACHABLE ||
5223 	    rtm->rtm_type == RTN_BLACKHOLE ||
5224 	    rtm->rtm_type == RTN_PROHIBIT ||
5225 	    rtm->rtm_type == RTN_THROW)
5226 		cfg->fc_flags |= RTF_REJECT;
5227 
5228 	if (rtm->rtm_type == RTN_LOCAL)
5229 		cfg->fc_flags |= RTF_LOCAL;
5230 
5231 	if (rtm->rtm_flags & RTM_F_CLONED)
5232 		cfg->fc_flags |= RTF_CACHE;
5233 
5234 	cfg->fc_flags |= (rtm->rtm_flags & RTNH_F_ONLINK);
5235 
5236 	if (tb[RTA_NH_ID]) {
5237 		if (tb[RTA_GATEWAY]   || tb[RTA_OIF] ||
5238 		    tb[RTA_MULTIPATH] || tb[RTA_ENCAP]) {
5239 			NL_SET_ERR_MSG(extack,
5240 				       "Nexthop specification and nexthop id are mutually exclusive");
5241 			goto errout;
5242 		}
5243 		cfg->fc_nh_id = nla_get_u32(tb[RTA_NH_ID]);
5244 	}
5245 
5246 	if (tb[RTA_GATEWAY]) {
5247 		cfg->fc_gateway = nla_get_in6_addr(tb[RTA_GATEWAY]);
5248 		cfg->fc_flags |= RTF_GATEWAY;
5249 	}
5250 	if (tb[RTA_VIA]) {
5251 		NL_SET_ERR_MSG(extack, "IPv6 does not support RTA_VIA attribute");
5252 		goto errout;
5253 	}
5254 
5255 	if (tb[RTA_DST]) {
5256 		int plen = (rtm->rtm_dst_len + 7) >> 3;
5257 
5258 		if (nla_len(tb[RTA_DST]) < plen)
5259 			goto errout;
5260 
5261 		nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
5262 	}
5263 
5264 	if (tb[RTA_SRC]) {
5265 		int plen = (rtm->rtm_src_len + 7) >> 3;
5266 
5267 		if (nla_len(tb[RTA_SRC]) < plen)
5268 			goto errout;
5269 
5270 		nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
5271 	}
5272 
5273 	if (tb[RTA_PREFSRC])
5274 		cfg->fc_prefsrc = nla_get_in6_addr(tb[RTA_PREFSRC]);
5275 
5276 	if (tb[RTA_OIF])
5277 		cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
5278 
5279 	if (tb[RTA_PRIORITY])
5280 		cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
5281 
5282 	if (tb[RTA_METRICS]) {
5283 		cfg->fc_mx = nla_data(tb[RTA_METRICS]);
5284 		cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
5285 	}
5286 
5287 	if (tb[RTA_TABLE])
5288 		cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
5289 
5290 	if (tb[RTA_MULTIPATH]) {
5291 		cfg->fc_mp = nla_data(tb[RTA_MULTIPATH]);
5292 		cfg->fc_mp_len = nla_len(tb[RTA_MULTIPATH]);
5293 
5294 		err = rtm_to_fib6_multipath_config(cfg, extack, newroute);
5295 		if (err < 0)
5296 			goto errout;
5297 	}
5298 
5299 	if (tb[RTA_PREF]) {
5300 		pref = nla_get_u8(tb[RTA_PREF]);
5301 		if (pref != ICMPV6_ROUTER_PREF_LOW &&
5302 		    pref != ICMPV6_ROUTER_PREF_HIGH)
5303 			pref = ICMPV6_ROUTER_PREF_MEDIUM;
5304 		cfg->fc_flags |= RTF_PREF(pref);
5305 	}
5306 
5307 	if (tb[RTA_ENCAP])
5308 		cfg->fc_encap = tb[RTA_ENCAP];
5309 
5310 	if (tb[RTA_ENCAP_TYPE]) {
5311 		cfg->fc_encap_type = nla_get_u16(tb[RTA_ENCAP_TYPE]);
5312 
5313 		err = lwtunnel_valid_encap_type(cfg->fc_encap_type,
5314 						extack, false);
5315 		if (err < 0)
5316 			goto errout;
5317 	}
5318 
5319 	if (tb[RTA_EXPIRES]) {
5320 		unsigned long timeout = addrconf_timeout_fixup(nla_get_u32(tb[RTA_EXPIRES]), HZ);
5321 
5322 		if (addrconf_finite_timeout(timeout)) {
5323 			cfg->fc_expires = jiffies_to_clock_t(timeout * HZ);
5324 			cfg->fc_flags |= RTF_EXPIRES;
5325 		}
5326 	}
5327 
5328 	err = 0;
5329 errout:
5330 	return err;
5331 }
5332 
5333 struct rt6_nh {
5334 	struct fib6_info *fib6_info;
5335 	struct fib6_config r_cfg;
5336 	struct list_head list;
5337 	int weight;
5338 };
5339 
5340 static void ip6_route_mpath_info_cleanup(struct list_head *rt6_nh_list)
5341 {
5342 	struct rt6_nh *nh, *nh_next;
5343 
5344 	list_for_each_entry_safe(nh, nh_next, rt6_nh_list, list) {
5345 		struct fib6_info *rt = nh->fib6_info;
5346 
5347 		if (rt) {
5348 			free_percpu(rt->fib6_nh->nh_common.nhc_pcpu_rth_output);
5349 			free_percpu(rt->fib6_nh->rt6i_pcpu);
5350 			ip_fib_metrics_put(rt->fib6_metrics);
5351 			kfree(rt);
5352 		}
5353 
5354 		list_del(&nh->list);
5355 		kfree(nh);
5356 	}
5357 }
5358 
5359 static int ip6_route_mpath_info_create(struct list_head *rt6_nh_list,
5360 				       struct fib6_config *cfg,
5361 				       struct netlink_ext_ack *extack)
5362 {
5363 	struct rtnexthop *rtnh;
5364 	int remaining;
5365 	int err;
5366 
5367 	remaining = cfg->fc_mp_len;
5368 	rtnh = (struct rtnexthop *)cfg->fc_mp;
5369 
5370 	/* Parse a Multipath Entry and build a list (rt6_nh_list) of
5371 	 * fib6_info structs per nexthop
5372 	 */
5373 	while (rtnh_ok(rtnh, remaining)) {
5374 		struct fib6_config r_cfg;
5375 		struct fib6_info *rt;
5376 		struct rt6_nh *nh;
5377 		int attrlen;
5378 
5379 		nh = kzalloc(sizeof(*nh), GFP_KERNEL);
5380 		if (!nh) {
5381 			err = -ENOMEM;
5382 			goto err;
5383 		}
5384 
5385 		list_add_tail(&nh->list, rt6_nh_list);
5386 
5387 		memcpy(&r_cfg, cfg, sizeof(*cfg));
5388 		if (rtnh->rtnh_ifindex)
5389 			r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
5390 
5391 		attrlen = rtnh_attrlen(rtnh);
5392 		if (attrlen > 0) {
5393 			struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
5394 
5395 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
5396 			if (nla) {
5397 				r_cfg.fc_gateway = nla_get_in6_addr(nla);
5398 				r_cfg.fc_flags |= RTF_GATEWAY;
5399 			}
5400 
5401 			r_cfg.fc_encap = nla_find(attrs, attrlen, RTA_ENCAP);
5402 			nla = nla_find(attrs, attrlen, RTA_ENCAP_TYPE);
5403 			if (nla)
5404 				r_cfg.fc_encap_type = nla_get_u16(nla);
5405 		}
5406 
5407 		r_cfg.fc_flags |= (rtnh->rtnh_flags & RTNH_F_ONLINK);
5408 
5409 		rt = ip6_route_info_create(&r_cfg, GFP_KERNEL, extack);
5410 		if (IS_ERR(rt)) {
5411 			err = PTR_ERR(rt);
5412 			goto err;
5413 		}
5414 
5415 		nh->fib6_info = rt;
5416 		nh->weight = rtnh->rtnh_hops + 1;
5417 		memcpy(&nh->r_cfg, &r_cfg, sizeof(r_cfg));
5418 
5419 		rtnh = rtnh_next(rtnh, &remaining);
5420 	}
5421 
5422 	return 0;
5423 err:
5424 	ip6_route_mpath_info_cleanup(rt6_nh_list);
5425 	return err;
5426 }
5427 
5428 static int ip6_route_mpath_info_create_nh(struct list_head *rt6_nh_list,
5429 					  struct netlink_ext_ack *extack)
5430 {
5431 	struct rt6_nh *nh, *nh_next, *nh_tmp;
5432 	LIST_HEAD(tmp);
5433 	int err;
5434 
5435 	list_for_each_entry_safe(nh, nh_next, rt6_nh_list, list) {
5436 		struct fib6_info *rt = nh->fib6_info;
5437 
5438 		err = ip6_route_info_create_nh(rt, &nh->r_cfg, extack);
5439 		if (err) {
5440 			nh->fib6_info = NULL;
5441 			goto err;
5442 		}
5443 
5444 		rt->fib6_nh->fib_nh_weight = nh->weight;
5445 
5446 		list_move_tail(&nh->list, &tmp);
5447 
5448 		list_for_each_entry(nh_tmp, rt6_nh_list, list) {
5449 			/* check if fib6_info already exists */
5450 			if (rt6_duplicate_nexthop(nh_tmp->fib6_info, rt)) {
5451 				err = -EEXIST;
5452 				goto err;
5453 			}
5454 		}
5455 	}
5456 out:
5457 	list_splice(&tmp, rt6_nh_list);
5458 	return err;
5459 err:
5460 	ip6_route_mpath_info_cleanup(rt6_nh_list);
5461 	goto out;
5462 }
5463 
5464 static void ip6_route_mpath_notify(struct fib6_info *rt,
5465 				   struct fib6_info *rt_last,
5466 				   struct nl_info *info,
5467 				   __u16 nlflags)
5468 {
5469 	/* if this is an APPEND route, then rt points to the first route
5470 	 * inserted and rt_last points to last route inserted. Userspace
5471 	 * wants a consistent dump of the route which starts at the first
5472 	 * nexthop. Since sibling routes are always added at the end of
5473 	 * the list, find the first sibling of the last route appended
5474 	 */
5475 	rcu_read_lock();
5476 
5477 	if ((nlflags & NLM_F_APPEND) && rt_last && rt_last->fib6_nsiblings) {
5478 		rt = list_first_or_null_rcu(&rt_last->fib6_siblings,
5479 					    struct fib6_info,
5480 					    fib6_siblings);
5481 	}
5482 
5483 	if (rt)
5484 		inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
5485 
5486 	rcu_read_unlock();
5487 }
5488 
5489 static bool ip6_route_mpath_should_notify(const struct fib6_info *rt)
5490 {
5491 	bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
5492 	bool should_notify = false;
5493 	struct fib6_info *leaf;
5494 	struct fib6_node *fn;
5495 
5496 	rcu_read_lock();
5497 	fn = rcu_dereference(rt->fib6_node);
5498 	if (!fn)
5499 		goto out;
5500 
5501 	leaf = rcu_dereference(fn->leaf);
5502 	if (!leaf)
5503 		goto out;
5504 
5505 	if (rt == leaf ||
5506 	    (rt_can_ecmp && rt->fib6_metric == leaf->fib6_metric &&
5507 	     rt6_qualify_for_ecmp(leaf)))
5508 		should_notify = true;
5509 out:
5510 	rcu_read_unlock();
5511 
5512 	return should_notify;
5513 }
5514 
5515 static int ip6_route_multipath_add(struct fib6_config *cfg,
5516 				   struct netlink_ext_ack *extack)
5517 {
5518 	struct fib6_info *rt_notif = NULL, *rt_last = NULL;
5519 	struct nl_info *info = &cfg->fc_nlinfo;
5520 	struct rt6_nh *nh, *nh_safe;
5521 	LIST_HEAD(rt6_nh_list);
5522 	struct rt6_nh *err_nh;
5523 	__u16 nlflags;
5524 	int nhn = 0;
5525 	int replace;
5526 	int err;
5527 
5528 	replace = (cfg->fc_nlinfo.nlh &&
5529 		   (cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_REPLACE));
5530 
5531 	nlflags = replace ? NLM_F_REPLACE : NLM_F_CREATE;
5532 	if (info->nlh && info->nlh->nlmsg_flags & NLM_F_APPEND)
5533 		nlflags |= NLM_F_APPEND;
5534 
5535 	err = ip6_route_mpath_info_create(&rt6_nh_list, cfg, extack);
5536 	if (err)
5537 		return err;
5538 
5539 	rcu_read_lock();
5540 
5541 	err = ip6_route_mpath_info_create_nh(&rt6_nh_list, extack);
5542 	if (err)
5543 		goto cleanup;
5544 
5545 	/* for add and replace send one notification with all nexthops.
5546 	 * Skip the notification in fib6_add_rt2node and send one with
5547 	 * the full route when done
5548 	 */
5549 	info->skip_notify = 1;
5550 
5551 	/* For add and replace, send one notification with all nexthops. For
5552 	 * append, send one notification with all appended nexthops.
5553 	 */
5554 	info->skip_notify_kernel = 1;
5555 
5556 	err_nh = NULL;
5557 	list_for_each_entry(nh, &rt6_nh_list, list) {
5558 		err = __ip6_ins_rt(nh->fib6_info, info, extack);
5559 
5560 		if (err) {
5561 			if (replace && nhn)
5562 				NL_SET_ERR_MSG_MOD(extack,
5563 						   "multipath route replace failed (check consistency of installed routes)");
5564 			err_nh = nh;
5565 			goto add_errout;
5566 		}
5567 		/* save reference to last route successfully inserted */
5568 		rt_last = nh->fib6_info;
5569 
5570 		/* save reference to first route for notification */
5571 		if (!rt_notif)
5572 			rt_notif = nh->fib6_info;
5573 
5574 		/* Because each route is added like a single route we remove
5575 		 * these flags after the first nexthop: if there is a collision,
5576 		 * we have already failed to add the first nexthop:
5577 		 * fib6_add_rt2node() has rejected it; when replacing, old
5578 		 * nexthops have been replaced by first new, the rest should
5579 		 * be added to it.
5580 		 */
5581 		if (cfg->fc_nlinfo.nlh) {
5582 			cfg->fc_nlinfo.nlh->nlmsg_flags &= ~(NLM_F_EXCL |
5583 							     NLM_F_REPLACE);
5584 			cfg->fc_nlinfo.nlh->nlmsg_flags |= NLM_F_CREATE;
5585 		}
5586 		nhn++;
5587 	}
5588 
5589 	/* An in-kernel notification should only be sent in case the new
5590 	 * multipath route is added as the first route in the node, or if
5591 	 * it was appended to it. We pass 'rt_notif' since it is the first
5592 	 * sibling and might allow us to skip some checks in the replace case.
5593 	 */
5594 	if (ip6_route_mpath_should_notify(rt_notif)) {
5595 		enum fib_event_type fib_event;
5596 
5597 		if (rt_notif->fib6_nsiblings != nhn - 1)
5598 			fib_event = FIB_EVENT_ENTRY_APPEND;
5599 		else
5600 			fib_event = FIB_EVENT_ENTRY_REPLACE;
5601 
5602 		err = call_fib6_multipath_entry_notifiers(info->nl_net,
5603 							  fib_event, rt_notif,
5604 							  nhn - 1, extack);
5605 		if (err) {
5606 			/* Delete all the siblings that were just added */
5607 			err_nh = NULL;
5608 			goto add_errout;
5609 		}
5610 	}
5611 
5612 	/* success ... tell user about new route */
5613 	ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
5614 	goto cleanup;
5615 
5616 add_errout:
5617 	/* send notification for routes that were added so that
5618 	 * the delete notifications sent by ip6_route_del are
5619 	 * coherent
5620 	 */
5621 	if (rt_notif)
5622 		ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
5623 
5624 	/* Delete routes that were already added */
5625 	list_for_each_entry(nh, &rt6_nh_list, list) {
5626 		if (err_nh == nh)
5627 			break;
5628 		ip6_route_del(&nh->r_cfg, extack);
5629 	}
5630 
5631 cleanup:
5632 	rcu_read_unlock();
5633 
5634 	list_for_each_entry_safe(nh, nh_safe, &rt6_nh_list, list) {
5635 		fib6_info_release(nh->fib6_info);
5636 		list_del(&nh->list);
5637 		kfree(nh);
5638 	}
5639 
5640 	return err;
5641 }
5642 
5643 static int ip6_route_multipath_del(struct fib6_config *cfg,
5644 				   struct netlink_ext_ack *extack)
5645 {
5646 	struct fib6_config r_cfg;
5647 	struct rtnexthop *rtnh;
5648 	int last_err = 0;
5649 	int remaining;
5650 	int attrlen;
5651 	int err;
5652 
5653 	remaining = cfg->fc_mp_len;
5654 	rtnh = (struct rtnexthop *)cfg->fc_mp;
5655 
5656 	/* Parse a Multipath Entry */
5657 	while (rtnh_ok(rtnh, remaining)) {
5658 		memcpy(&r_cfg, cfg, sizeof(*cfg));
5659 		if (rtnh->rtnh_ifindex)
5660 			r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
5661 
5662 		attrlen = rtnh_attrlen(rtnh);
5663 		if (attrlen > 0) {
5664 			struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
5665 
5666 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
5667 			if (nla) {
5668 				r_cfg.fc_gateway = nla_get_in6_addr(nla);
5669 				r_cfg.fc_flags |= RTF_GATEWAY;
5670 			}
5671 		}
5672 
5673 		err = ip6_route_del(&r_cfg, extack);
5674 		if (err)
5675 			last_err = err;
5676 
5677 		rtnh = rtnh_next(rtnh, &remaining);
5678 	}
5679 
5680 	return last_err;
5681 }
5682 
5683 static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
5684 			      struct netlink_ext_ack *extack)
5685 {
5686 	struct fib6_config cfg;
5687 	int err;
5688 
5689 	err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
5690 	if (err < 0)
5691 		return err;
5692 
5693 	if (cfg.fc_nh_id) {
5694 		rcu_read_lock();
5695 		err = !nexthop_find_by_id(sock_net(skb->sk), cfg.fc_nh_id);
5696 		rcu_read_unlock();
5697 
5698 		if (err) {
5699 			NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
5700 			return -EINVAL;
5701 		}
5702 	}
5703 
5704 	if (cfg.fc_mp) {
5705 		return ip6_route_multipath_del(&cfg, extack);
5706 	} else {
5707 		cfg.fc_delete_all_nh = 1;
5708 		return ip6_route_del(&cfg, extack);
5709 	}
5710 }
5711 
5712 static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
5713 			      struct netlink_ext_ack *extack)
5714 {
5715 	struct fib6_config cfg;
5716 	int err;
5717 
5718 	err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
5719 	if (err < 0)
5720 		return err;
5721 
5722 	err = fib6_config_validate(&cfg, extack);
5723 	if (err)
5724 		return err;
5725 
5726 	if (cfg.fc_metric == 0)
5727 		cfg.fc_metric = IP6_RT_PRIO_USER;
5728 
5729 	if (cfg.fc_mp)
5730 		return ip6_route_multipath_add(&cfg, extack);
5731 	else
5732 		return ip6_route_add(&cfg, GFP_KERNEL, extack);
5733 }
5734 
5735 /* add the overhead of this fib6_nh to nexthop_len */
5736 static int rt6_nh_nlmsg_size(struct fib6_nh *nh, void *arg)
5737 {
5738 	int *nexthop_len = arg;
5739 
5740 	*nexthop_len += nla_total_size(0)	 /* RTA_MULTIPATH */
5741 		     + NLA_ALIGN(sizeof(struct rtnexthop))
5742 		     + nla_total_size(16); /* RTA_GATEWAY */
5743 
5744 	if (nh->fib_nh_lws) {
5745 		/* RTA_ENCAP_TYPE */
5746 		*nexthop_len += lwtunnel_get_encap_size(nh->fib_nh_lws);
5747 		/* RTA_ENCAP */
5748 		*nexthop_len += nla_total_size(2);
5749 	}
5750 
5751 	return 0;
5752 }
5753 
5754 static size_t rt6_nlmsg_size(struct fib6_info *f6i)
5755 {
5756 	int nexthop_len;
5757 
5758 	if (f6i->nh) {
5759 		nexthop_len = nla_total_size(4); /* RTA_NH_ID */
5760 		nexthop_for_each_fib6_nh(f6i->nh, rt6_nh_nlmsg_size,
5761 					 &nexthop_len);
5762 	} else {
5763 		struct fib6_nh *nh = f6i->fib6_nh;
5764 		struct fib6_info *sibling;
5765 
5766 		nexthop_len = 0;
5767 		if (f6i->fib6_nsiblings) {
5768 			rt6_nh_nlmsg_size(nh, &nexthop_len);
5769 
5770 			rcu_read_lock();
5771 
5772 			list_for_each_entry_rcu(sibling, &f6i->fib6_siblings,
5773 						fib6_siblings) {
5774 				rt6_nh_nlmsg_size(sibling->fib6_nh, &nexthop_len);
5775 			}
5776 
5777 			rcu_read_unlock();
5778 		}
5779 		nexthop_len += lwtunnel_get_encap_size(nh->fib_nh_lws);
5780 	}
5781 
5782 	return NLMSG_ALIGN(sizeof(struct rtmsg))
5783 	       + nla_total_size(16) /* RTA_SRC */
5784 	       + nla_total_size(16) /* RTA_DST */
5785 	       + nla_total_size(16) /* RTA_GATEWAY */
5786 	       + nla_total_size(16) /* RTA_PREFSRC */
5787 	       + nla_total_size(4) /* RTA_TABLE */
5788 	       + nla_total_size(4) /* RTA_IIF */
5789 	       + nla_total_size(4) /* RTA_OIF */
5790 	       + nla_total_size(4) /* RTA_PRIORITY */
5791 	       + RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
5792 	       + nla_total_size(sizeof(struct rta_cacheinfo))
5793 	       + nla_total_size(TCP_CA_NAME_MAX) /* RTAX_CC_ALGO */
5794 	       + nla_total_size(1) /* RTA_PREF */
5795 	       + nexthop_len;
5796 }
5797 
5798 static int rt6_fill_node_nexthop(struct sk_buff *skb, struct nexthop *nh,
5799 				 unsigned char *flags)
5800 {
5801 	if (nexthop_is_multipath(nh)) {
5802 		struct nlattr *mp;
5803 
5804 		mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
5805 		if (!mp)
5806 			goto nla_put_failure;
5807 
5808 		if (nexthop_mpath_fill_node(skb, nh, AF_INET6))
5809 			goto nla_put_failure;
5810 
5811 		nla_nest_end(skb, mp);
5812 	} else {
5813 		struct fib6_nh *fib6_nh;
5814 
5815 		fib6_nh = nexthop_fib6_nh(nh);
5816 		if (fib_nexthop_info(skb, &fib6_nh->nh_common, AF_INET6,
5817 				     flags, false) < 0)
5818 			goto nla_put_failure;
5819 	}
5820 
5821 	return 0;
5822 
5823 nla_put_failure:
5824 	return -EMSGSIZE;
5825 }
5826 
5827 static int rt6_fill_node(struct net *net, struct sk_buff *skb,
5828 			 struct fib6_info *rt, struct dst_entry *dst,
5829 			 struct in6_addr *dest, struct in6_addr *src,
5830 			 int iif, int type, u32 portid, u32 seq,
5831 			 unsigned int flags)
5832 {
5833 	struct rt6_info *rt6 = dst_rt6_info(dst);
5834 	struct rt6key *rt6_dst, *rt6_src;
5835 	u32 *pmetrics, table, rt6_flags;
5836 	unsigned char nh_flags = 0;
5837 	struct nlmsghdr *nlh;
5838 	struct rtmsg *rtm;
5839 	long expires = 0;
5840 
5841 	nlh = nlmsg_put(skb, portid, seq, type, sizeof(*rtm), flags);
5842 	if (!nlh)
5843 		return -EMSGSIZE;
5844 
5845 	if (rt6) {
5846 		rt6_dst = &rt6->rt6i_dst;
5847 		rt6_src = &rt6->rt6i_src;
5848 		rt6_flags = rt6->rt6i_flags;
5849 	} else {
5850 		rt6_dst = &rt->fib6_dst;
5851 		rt6_src = &rt->fib6_src;
5852 		rt6_flags = rt->fib6_flags;
5853 	}
5854 
5855 	rtm = nlmsg_data(nlh);
5856 	rtm->rtm_family = AF_INET6;
5857 	rtm->rtm_dst_len = rt6_dst->plen;
5858 	rtm->rtm_src_len = rt6_src->plen;
5859 	rtm->rtm_tos = 0;
5860 	if (rt->fib6_table)
5861 		table = rt->fib6_table->tb6_id;
5862 	else
5863 		table = RT6_TABLE_UNSPEC;
5864 	rtm->rtm_table = table < 256 ? table : RT_TABLE_COMPAT;
5865 	if (nla_put_u32(skb, RTA_TABLE, table))
5866 		goto nla_put_failure;
5867 
5868 	rtm->rtm_type = rt->fib6_type;
5869 	rtm->rtm_flags = 0;
5870 	rtm->rtm_scope = RT_SCOPE_UNIVERSE;
5871 	rtm->rtm_protocol = rt->fib6_protocol;
5872 
5873 	if (rt6_flags & RTF_CACHE)
5874 		rtm->rtm_flags |= RTM_F_CLONED;
5875 
5876 	if (dest) {
5877 		if (nla_put_in6_addr(skb, RTA_DST, dest))
5878 			goto nla_put_failure;
5879 		rtm->rtm_dst_len = 128;
5880 	} else if (rtm->rtm_dst_len)
5881 		if (nla_put_in6_addr(skb, RTA_DST, &rt6_dst->addr))
5882 			goto nla_put_failure;
5883 #ifdef CONFIG_IPV6_SUBTREES
5884 	if (src) {
5885 		if (nla_put_in6_addr(skb, RTA_SRC, src))
5886 			goto nla_put_failure;
5887 		rtm->rtm_src_len = 128;
5888 	} else if (rtm->rtm_src_len &&
5889 		   nla_put_in6_addr(skb, RTA_SRC, &rt6_src->addr))
5890 		goto nla_put_failure;
5891 #endif
5892 	if (iif) {
5893 #ifdef CONFIG_IPV6_MROUTE
5894 		if (ipv6_addr_is_multicast(&rt6_dst->addr)) {
5895 			int err = ip6mr_get_route(net, skb, rtm, portid);
5896 
5897 			if (err == 0)
5898 				return 0;
5899 			if (err < 0)
5900 				goto nla_put_failure;
5901 		} else
5902 #endif
5903 			if (nla_put_u32(skb, RTA_IIF, iif))
5904 				goto nla_put_failure;
5905 	} else if (dest) {
5906 		struct in6_addr saddr_buf;
5907 		if (ip6_route_get_saddr(net, rt, dest, 0, 0, &saddr_buf) == 0 &&
5908 		    nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5909 			goto nla_put_failure;
5910 	}
5911 
5912 	if (rt->fib6_prefsrc.plen) {
5913 		struct in6_addr saddr_buf;
5914 		saddr_buf = rt->fib6_prefsrc.addr;
5915 		if (nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5916 			goto nla_put_failure;
5917 	}
5918 
5919 	pmetrics = dst ? dst_metrics_ptr(dst) : rt->fib6_metrics->metrics;
5920 	if (rtnetlink_put_metrics(skb, pmetrics) < 0)
5921 		goto nla_put_failure;
5922 
5923 	if (nla_put_u32(skb, RTA_PRIORITY, rt->fib6_metric))
5924 		goto nla_put_failure;
5925 
5926 	/* For multipath routes, walk the siblings list and add
5927 	 * each as a nexthop within RTA_MULTIPATH.
5928 	 */
5929 	if (rt6) {
5930 		if (rt6_flags & RTF_GATEWAY &&
5931 		    nla_put_in6_addr(skb, RTA_GATEWAY, &rt6->rt6i_gateway))
5932 			goto nla_put_failure;
5933 
5934 		if (dst->dev && nla_put_u32(skb, RTA_OIF, dst->dev->ifindex))
5935 			goto nla_put_failure;
5936 
5937 		if (dst->lwtstate &&
5938 		    lwtunnel_fill_encap(skb, dst->lwtstate, RTA_ENCAP, RTA_ENCAP_TYPE) < 0)
5939 			goto nla_put_failure;
5940 	} else if (rt->fib6_nsiblings) {
5941 		struct fib6_info *sibling;
5942 		struct nlattr *mp;
5943 
5944 		mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
5945 		if (!mp)
5946 			goto nla_put_failure;
5947 
5948 		if (fib_add_nexthop(skb, &rt->fib6_nh->nh_common,
5949 				    rt->fib6_nh->fib_nh_weight, AF_INET6,
5950 				    0) < 0)
5951 			goto nla_put_failure;
5952 
5953 		rcu_read_lock();
5954 
5955 		list_for_each_entry_rcu(sibling, &rt->fib6_siblings,
5956 					fib6_siblings) {
5957 			if (fib_add_nexthop(skb, &sibling->fib6_nh->nh_common,
5958 					    sibling->fib6_nh->fib_nh_weight,
5959 					    AF_INET6, 0) < 0) {
5960 				rcu_read_unlock();
5961 
5962 				goto nla_put_failure;
5963 			}
5964 		}
5965 
5966 		rcu_read_unlock();
5967 
5968 		nla_nest_end(skb, mp);
5969 	} else if (rt->nh) {
5970 		if (nla_put_u32(skb, RTA_NH_ID, rt->nh->id))
5971 			goto nla_put_failure;
5972 
5973 		if (nexthop_is_blackhole(rt->nh))
5974 			rtm->rtm_type = RTN_BLACKHOLE;
5975 
5976 		if (READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode) &&
5977 		    rt6_fill_node_nexthop(skb, rt->nh, &nh_flags) < 0)
5978 			goto nla_put_failure;
5979 
5980 		rtm->rtm_flags |= nh_flags;
5981 	} else {
5982 		if (fib_nexthop_info(skb, &rt->fib6_nh->nh_common, AF_INET6,
5983 				     &nh_flags, false) < 0)
5984 			goto nla_put_failure;
5985 
5986 		rtm->rtm_flags |= nh_flags;
5987 	}
5988 
5989 	if (rt6_flags & RTF_EXPIRES) {
5990 		expires = dst ? dst->expires : rt->expires;
5991 		expires -= jiffies;
5992 	}
5993 
5994 	if (!dst) {
5995 		if (READ_ONCE(rt->offload))
5996 			rtm->rtm_flags |= RTM_F_OFFLOAD;
5997 		if (READ_ONCE(rt->trap))
5998 			rtm->rtm_flags |= RTM_F_TRAP;
5999 		if (READ_ONCE(rt->offload_failed))
6000 			rtm->rtm_flags |= RTM_F_OFFLOAD_FAILED;
6001 	}
6002 
6003 	if (rtnl_put_cacheinfo(skb, dst, 0, expires, dst ? dst->error : 0) < 0)
6004 		goto nla_put_failure;
6005 
6006 	if (nla_put_u8(skb, RTA_PREF, IPV6_EXTRACT_PREF(rt6_flags)))
6007 		goto nla_put_failure;
6008 
6009 
6010 	nlmsg_end(skb, nlh);
6011 	return 0;
6012 
6013 nla_put_failure:
6014 	nlmsg_cancel(skb, nlh);
6015 	return -EMSGSIZE;
6016 }
6017 
6018 static int fib6_info_nh_uses_dev(struct fib6_nh *nh, void *arg)
6019 {
6020 	const struct net_device *dev = arg;
6021 
6022 	if (nh->fib_nh_dev == dev)
6023 		return 1;
6024 
6025 	return 0;
6026 }
6027 
6028 static bool fib6_info_uses_dev(const struct fib6_info *f6i,
6029 			       const struct net_device *dev)
6030 {
6031 	if (f6i->nh) {
6032 		struct net_device *_dev = (struct net_device *)dev;
6033 
6034 		return !!nexthop_for_each_fib6_nh(f6i->nh,
6035 						  fib6_info_nh_uses_dev,
6036 						  _dev);
6037 	}
6038 
6039 	if (f6i->fib6_nh->fib_nh_dev == dev)
6040 		return true;
6041 
6042 	if (f6i->fib6_nsiblings) {
6043 		struct fib6_info *sibling, *next_sibling;
6044 
6045 		list_for_each_entry_safe(sibling, next_sibling,
6046 					 &f6i->fib6_siblings, fib6_siblings) {
6047 			if (sibling->fib6_nh->fib_nh_dev == dev)
6048 				return true;
6049 		}
6050 	}
6051 
6052 	return false;
6053 }
6054 
6055 struct fib6_nh_exception_dump_walker {
6056 	struct rt6_rtnl_dump_arg *dump;
6057 	struct fib6_info *rt;
6058 	unsigned int flags;
6059 	unsigned int skip;
6060 	unsigned int count;
6061 };
6062 
6063 static int rt6_nh_dump_exceptions(struct fib6_nh *nh, void *arg)
6064 {
6065 	struct fib6_nh_exception_dump_walker *w = arg;
6066 	struct rt6_rtnl_dump_arg *dump = w->dump;
6067 	struct rt6_exception_bucket *bucket;
6068 	struct rt6_exception *rt6_ex;
6069 	int i, err;
6070 
6071 	bucket = fib6_nh_get_excptn_bucket(nh, NULL);
6072 	if (!bucket)
6073 		return 0;
6074 
6075 	for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
6076 		hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
6077 			if (w->skip) {
6078 				w->skip--;
6079 				continue;
6080 			}
6081 
6082 			/* Expiration of entries doesn't bump sernum, insertion
6083 			 * does. Removal is triggered by insertion, so we can
6084 			 * rely on the fact that if entries change between two
6085 			 * partial dumps, this node is scanned again completely,
6086 			 * see rt6_insert_exception() and fib6_dump_table().
6087 			 *
6088 			 * Count expired entries we go through as handled
6089 			 * entries that we'll skip next time, in case of partial
6090 			 * node dump. Otherwise, if entries expire meanwhile,
6091 			 * we'll skip the wrong amount.
6092 			 */
6093 			if (rt6_check_expired(rt6_ex->rt6i)) {
6094 				w->count++;
6095 				continue;
6096 			}
6097 
6098 			err = rt6_fill_node(dump->net, dump->skb, w->rt,
6099 					    &rt6_ex->rt6i->dst, NULL, NULL, 0,
6100 					    RTM_NEWROUTE,
6101 					    NETLINK_CB(dump->cb->skb).portid,
6102 					    dump->cb->nlh->nlmsg_seq, w->flags);
6103 			if (err)
6104 				return err;
6105 
6106 			w->count++;
6107 		}
6108 		bucket++;
6109 	}
6110 
6111 	return 0;
6112 }
6113 
6114 /* Return -1 if done with node, number of handled routes on partial dump */
6115 int rt6_dump_route(struct fib6_info *rt, void *p_arg, unsigned int skip)
6116 {
6117 	struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
6118 	struct fib_dump_filter *filter = &arg->filter;
6119 	unsigned int flags = NLM_F_MULTI;
6120 	struct net *net = arg->net;
6121 	int count = 0;
6122 
6123 	if (rt == net->ipv6.fib6_null_entry)
6124 		return -1;
6125 
6126 	if ((filter->flags & RTM_F_PREFIX) &&
6127 	    !(rt->fib6_flags & RTF_PREFIX_RT)) {
6128 		/* success since this is not a prefix route */
6129 		return -1;
6130 	}
6131 	if (filter->filter_set &&
6132 	    ((filter->rt_type  && rt->fib6_type != filter->rt_type) ||
6133 	     (filter->dev      && !fib6_info_uses_dev(rt, filter->dev)) ||
6134 	     (filter->protocol && rt->fib6_protocol != filter->protocol))) {
6135 		return -1;
6136 	}
6137 
6138 	if (filter->filter_set ||
6139 	    !filter->dump_routes || !filter->dump_exceptions) {
6140 		flags |= NLM_F_DUMP_FILTERED;
6141 	}
6142 
6143 	if (filter->dump_routes) {
6144 		if (skip) {
6145 			skip--;
6146 		} else {
6147 			if (rt6_fill_node(net, arg->skb, rt, NULL, NULL, NULL,
6148 					  0, RTM_NEWROUTE,
6149 					  NETLINK_CB(arg->cb->skb).portid,
6150 					  arg->cb->nlh->nlmsg_seq, flags)) {
6151 				return 0;
6152 			}
6153 			count++;
6154 		}
6155 	}
6156 
6157 	if (filter->dump_exceptions) {
6158 		struct fib6_nh_exception_dump_walker w = { .dump = arg,
6159 							   .rt = rt,
6160 							   .flags = flags,
6161 							   .skip = skip,
6162 							   .count = 0 };
6163 		int err;
6164 
6165 		rcu_read_lock();
6166 		if (rt->nh) {
6167 			err = nexthop_for_each_fib6_nh(rt->nh,
6168 						       rt6_nh_dump_exceptions,
6169 						       &w);
6170 		} else {
6171 			err = rt6_nh_dump_exceptions(rt->fib6_nh, &w);
6172 		}
6173 		rcu_read_unlock();
6174 
6175 		if (err)
6176 			return count + w.count;
6177 	}
6178 
6179 	return -1;
6180 }
6181 
6182 static int inet6_rtm_valid_getroute_req(struct sk_buff *skb,
6183 					const struct nlmsghdr *nlh,
6184 					struct nlattr **tb,
6185 					struct netlink_ext_ack *extack)
6186 {
6187 	struct rtmsg *rtm;
6188 	int i, err;
6189 
6190 	rtm = nlmsg_payload(nlh, sizeof(*rtm));
6191 	if (!rtm) {
6192 		NL_SET_ERR_MSG_MOD(extack,
6193 				   "Invalid header for get route request");
6194 		return -EINVAL;
6195 	}
6196 
6197 	if (!netlink_strict_get_check(skb))
6198 		return nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
6199 					      rtm_ipv6_policy, extack);
6200 
6201 	if ((rtm->rtm_src_len && rtm->rtm_src_len != 128) ||
6202 	    (rtm->rtm_dst_len && rtm->rtm_dst_len != 128) ||
6203 	    rtm->rtm_table || rtm->rtm_protocol || rtm->rtm_scope ||
6204 	    rtm->rtm_type) {
6205 		NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for get route request");
6206 		return -EINVAL;
6207 	}
6208 	if (rtm->rtm_flags & ~RTM_F_FIB_MATCH) {
6209 		NL_SET_ERR_MSG_MOD(extack,
6210 				   "Invalid flags for get route request");
6211 		return -EINVAL;
6212 	}
6213 
6214 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
6215 					    rtm_ipv6_policy, extack);
6216 	if (err)
6217 		return err;
6218 
6219 	if ((tb[RTA_SRC] && !rtm->rtm_src_len) ||
6220 	    (tb[RTA_DST] && !rtm->rtm_dst_len)) {
6221 		NL_SET_ERR_MSG_MOD(extack, "rtm_src_len and rtm_dst_len must be 128 for IPv6");
6222 		return -EINVAL;
6223 	}
6224 
6225 	if (tb[RTA_FLOWLABEL] &&
6226 	    (nla_get_be32(tb[RTA_FLOWLABEL]) & ~IPV6_FLOWLABEL_MASK)) {
6227 		NL_SET_ERR_MSG_ATTR(extack, tb[RTA_FLOWLABEL],
6228 				    "Invalid flow label");
6229 		return -EINVAL;
6230 	}
6231 
6232 	for (i = 0; i <= RTA_MAX; i++) {
6233 		if (!tb[i])
6234 			continue;
6235 
6236 		switch (i) {
6237 		case RTA_SRC:
6238 		case RTA_DST:
6239 		case RTA_IIF:
6240 		case RTA_OIF:
6241 		case RTA_MARK:
6242 		case RTA_UID:
6243 		case RTA_SPORT:
6244 		case RTA_DPORT:
6245 		case RTA_IP_PROTO:
6246 		case RTA_FLOWLABEL:
6247 			break;
6248 		default:
6249 			NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in get route request");
6250 			return -EINVAL;
6251 		}
6252 	}
6253 
6254 	return 0;
6255 }
6256 
6257 static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
6258 			      struct netlink_ext_ack *extack)
6259 {
6260 	struct net *net = sock_net(in_skb->sk);
6261 	struct nlattr *tb[RTA_MAX+1];
6262 	int err, iif = 0, oif = 0;
6263 	struct fib6_info *from;
6264 	struct dst_entry *dst;
6265 	struct rt6_info *rt;
6266 	struct sk_buff *skb;
6267 	struct rtmsg *rtm;
6268 	struct flowi6 fl6 = {};
6269 	__be32 flowlabel;
6270 	bool fibmatch;
6271 
6272 	err = inet6_rtm_valid_getroute_req(in_skb, nlh, tb, extack);
6273 	if (err < 0)
6274 		goto errout;
6275 
6276 	err = -EINVAL;
6277 	rtm = nlmsg_data(nlh);
6278 	fibmatch = !!(rtm->rtm_flags & RTM_F_FIB_MATCH);
6279 
6280 	if (tb[RTA_SRC]) {
6281 		if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
6282 			goto errout;
6283 
6284 		fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
6285 	}
6286 
6287 	if (tb[RTA_DST]) {
6288 		if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
6289 			goto errout;
6290 
6291 		fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
6292 	}
6293 
6294 	if (tb[RTA_IIF])
6295 		iif = nla_get_u32(tb[RTA_IIF]);
6296 
6297 	if (tb[RTA_OIF])
6298 		oif = nla_get_u32(tb[RTA_OIF]);
6299 
6300 	if (tb[RTA_MARK])
6301 		fl6.flowi6_mark = nla_get_u32(tb[RTA_MARK]);
6302 
6303 	if (tb[RTA_UID])
6304 		fl6.flowi6_uid = make_kuid(current_user_ns(),
6305 					   nla_get_u32(tb[RTA_UID]));
6306 	else
6307 		fl6.flowi6_uid = iif ? INVALID_UID : current_uid();
6308 
6309 	if (tb[RTA_SPORT])
6310 		fl6.fl6_sport = nla_get_be16(tb[RTA_SPORT]);
6311 
6312 	if (tb[RTA_DPORT])
6313 		fl6.fl6_dport = nla_get_be16(tb[RTA_DPORT]);
6314 
6315 	if (tb[RTA_IP_PROTO]) {
6316 		err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO],
6317 						  &fl6.flowi6_proto, AF_INET6,
6318 						  extack);
6319 		if (err)
6320 			goto errout;
6321 	}
6322 
6323 	flowlabel = nla_get_be32_default(tb[RTA_FLOWLABEL], 0);
6324 	fl6.flowlabel = ip6_make_flowinfo(rtm->rtm_tos, flowlabel);
6325 
6326 	if (iif) {
6327 		struct net_device *dev;
6328 		int flags = 0;
6329 
6330 		rcu_read_lock();
6331 
6332 		dev = dev_get_by_index_rcu(net, iif);
6333 		if (!dev) {
6334 			rcu_read_unlock();
6335 			err = -ENODEV;
6336 			goto errout;
6337 		}
6338 
6339 		fl6.flowi6_iif = iif;
6340 
6341 		if (!ipv6_addr_any(&fl6.saddr))
6342 			flags |= RT6_LOOKUP_F_HAS_SADDR;
6343 
6344 		dst = ip6_route_input_lookup(net, dev, &fl6, NULL, flags);
6345 
6346 		rcu_read_unlock();
6347 	} else {
6348 		fl6.flowi6_oif = oif;
6349 
6350 		dst = ip6_route_output(net, NULL, &fl6);
6351 	}
6352 
6353 
6354 	rt = dst_rt6_info(dst);
6355 	if (rt->dst.error) {
6356 		err = rt->dst.error;
6357 		ip6_rt_put(rt);
6358 		goto errout;
6359 	}
6360 
6361 	if (rt == net->ipv6.ip6_null_entry) {
6362 		err = rt->dst.error;
6363 		ip6_rt_put(rt);
6364 		goto errout;
6365 	}
6366 
6367 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
6368 	if (!skb) {
6369 		ip6_rt_put(rt);
6370 		err = -ENOBUFS;
6371 		goto errout;
6372 	}
6373 
6374 	skb_dst_set(skb, &rt->dst);
6375 
6376 	rcu_read_lock();
6377 	from = rcu_dereference(rt->from);
6378 	if (from) {
6379 		if (fibmatch)
6380 			err = rt6_fill_node(net, skb, from, NULL, NULL, NULL,
6381 					    iif, RTM_NEWROUTE,
6382 					    NETLINK_CB(in_skb).portid,
6383 					    nlh->nlmsg_seq, 0);
6384 		else
6385 			err = rt6_fill_node(net, skb, from, dst, &fl6.daddr,
6386 					    &fl6.saddr, iif, RTM_NEWROUTE,
6387 					    NETLINK_CB(in_skb).portid,
6388 					    nlh->nlmsg_seq, 0);
6389 	} else {
6390 		err = -ENETUNREACH;
6391 	}
6392 	rcu_read_unlock();
6393 
6394 	if (err < 0) {
6395 		kfree_skb(skb);
6396 		goto errout;
6397 	}
6398 
6399 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
6400 errout:
6401 	return err;
6402 }
6403 
6404 void inet6_rt_notify(int event, struct fib6_info *rt, struct nl_info *info,
6405 		     unsigned int nlm_flags)
6406 {
6407 	struct sk_buff *skb;
6408 	struct net *net = info->nl_net;
6409 	u32 seq;
6410 	int err;
6411 
6412 	err = -ENOBUFS;
6413 	seq = info->nlh ? info->nlh->nlmsg_seq : 0;
6414 
6415 	skb = nlmsg_new(rt6_nlmsg_size(rt), GFP_ATOMIC);
6416 	if (!skb)
6417 		goto errout;
6418 
6419 	err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
6420 			    event, info->portid, seq, nlm_flags);
6421 	if (err < 0) {
6422 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6423 		WARN_ON(err == -EMSGSIZE);
6424 		kfree_skb(skb);
6425 		goto errout;
6426 	}
6427 	rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
6428 		    info->nlh, GFP_ATOMIC);
6429 	return;
6430 errout:
6431 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6432 }
6433 
6434 void fib6_rt_update(struct net *net, struct fib6_info *rt,
6435 		    struct nl_info *info)
6436 {
6437 	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
6438 	struct sk_buff *skb;
6439 	int err = -ENOBUFS;
6440 
6441 	skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
6442 	if (!skb)
6443 		goto errout;
6444 
6445 	err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
6446 			    RTM_NEWROUTE, info->portid, seq, NLM_F_REPLACE);
6447 	if (err < 0) {
6448 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6449 		WARN_ON(err == -EMSGSIZE);
6450 		kfree_skb(skb);
6451 		goto errout;
6452 	}
6453 	rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
6454 		    info->nlh, gfp_any());
6455 	return;
6456 errout:
6457 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6458 }
6459 
6460 void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i,
6461 			    bool offload, bool trap, bool offload_failed)
6462 {
6463 	struct sk_buff *skb;
6464 	int err;
6465 
6466 	if (READ_ONCE(f6i->offload) == offload &&
6467 	    READ_ONCE(f6i->trap) == trap &&
6468 	    READ_ONCE(f6i->offload_failed) == offload_failed)
6469 		return;
6470 
6471 	WRITE_ONCE(f6i->offload, offload);
6472 	WRITE_ONCE(f6i->trap, trap);
6473 
6474 	/* 2 means send notifications only if offload_failed was changed. */
6475 	if (net->ipv6.sysctl.fib_notify_on_flag_change == 2 &&
6476 	    READ_ONCE(f6i->offload_failed) == offload_failed)
6477 		return;
6478 
6479 	WRITE_ONCE(f6i->offload_failed, offload_failed);
6480 
6481 	if (!rcu_access_pointer(f6i->fib6_node))
6482 		/* The route was removed from the tree, do not send
6483 		 * notification.
6484 		 */
6485 		return;
6486 
6487 	if (!net->ipv6.sysctl.fib_notify_on_flag_change)
6488 		return;
6489 
6490 	skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_KERNEL);
6491 	if (!skb) {
6492 		err = -ENOBUFS;
6493 		goto errout;
6494 	}
6495 
6496 	err = rt6_fill_node(net, skb, f6i, NULL, NULL, NULL, 0, RTM_NEWROUTE, 0,
6497 			    0, 0);
6498 	if (err < 0) {
6499 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6500 		WARN_ON(err == -EMSGSIZE);
6501 		kfree_skb(skb);
6502 		goto errout;
6503 	}
6504 
6505 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_ROUTE, NULL, GFP_KERNEL);
6506 	return;
6507 
6508 errout:
6509 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6510 }
6511 EXPORT_SYMBOL(fib6_info_hw_flags_set);
6512 
6513 static int ip6_route_dev_notify(struct notifier_block *this,
6514 				unsigned long event, void *ptr)
6515 {
6516 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
6517 	struct net *net = dev_net(dev);
6518 
6519 	if (!(dev->flags & IFF_LOOPBACK))
6520 		return NOTIFY_OK;
6521 
6522 	if (event == NETDEV_REGISTER) {
6523 		net->ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = dev;
6524 		net->ipv6.ip6_null_entry->dst.dev = dev;
6525 		net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
6526 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6527 		net->ipv6.ip6_prohibit_entry->dst.dev = dev;
6528 		net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
6529 		net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
6530 		net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
6531 #endif
6532 	 } else if (event == NETDEV_UNREGISTER &&
6533 		    dev->reg_state != NETREG_UNREGISTERED) {
6534 		/* NETDEV_UNREGISTER could be fired for multiple times by
6535 		 * netdev_wait_allrefs(). Make sure we only call this once.
6536 		 */
6537 		in6_dev_put_clear(&net->ipv6.ip6_null_entry->rt6i_idev);
6538 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6539 		in6_dev_put_clear(&net->ipv6.ip6_prohibit_entry->rt6i_idev);
6540 		in6_dev_put_clear(&net->ipv6.ip6_blk_hole_entry->rt6i_idev);
6541 #endif
6542 	}
6543 
6544 	return NOTIFY_OK;
6545 }
6546 
6547 /*
6548  *	/proc
6549  */
6550 
6551 #ifdef CONFIG_PROC_FS
6552 static int rt6_stats_seq_show(struct seq_file *seq, void *v)
6553 {
6554 	struct net *net = (struct net *)seq->private;
6555 	seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
6556 		   net->ipv6.rt6_stats->fib_nodes,
6557 		   net->ipv6.rt6_stats->fib_route_nodes,
6558 		   atomic_read(&net->ipv6.rt6_stats->fib_rt_alloc),
6559 		   net->ipv6.rt6_stats->fib_rt_entries,
6560 		   net->ipv6.rt6_stats->fib_rt_cache,
6561 		   dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
6562 		   net->ipv6.rt6_stats->fib_discarded_routes);
6563 
6564 	return 0;
6565 }
6566 #endif	/* CONFIG_PROC_FS */
6567 
6568 #ifdef CONFIG_SYSCTL
6569 
6570 static int ipv6_sysctl_rtcache_flush(const struct ctl_table *ctl, int write,
6571 			      void *buffer, size_t *lenp, loff_t *ppos)
6572 {
6573 	struct net *net;
6574 	int delay;
6575 	int ret;
6576 	if (!write)
6577 		return -EINVAL;
6578 
6579 	ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
6580 	if (ret)
6581 		return ret;
6582 
6583 	net = (struct net *)ctl->extra1;
6584 	delay = net->ipv6.sysctl.flush_delay;
6585 	fib6_run_gc(delay <= 0 ? 0 : (unsigned long)delay, net, delay > 0);
6586 	return 0;
6587 }
6588 
6589 static struct ctl_table ipv6_route_table_template[] = {
6590 	{
6591 		.procname	=	"max_size",
6592 		.data		=	&init_net.ipv6.sysctl.ip6_rt_max_size,
6593 		.maxlen		=	sizeof(int),
6594 		.mode		=	0644,
6595 		.proc_handler	=	proc_dointvec,
6596 	},
6597 	{
6598 		.procname	=	"gc_thresh",
6599 		.data		=	&ip6_dst_ops_template.gc_thresh,
6600 		.maxlen		=	sizeof(int),
6601 		.mode		=	0644,
6602 		.proc_handler	=	proc_dointvec,
6603 	},
6604 	{
6605 		.procname	=	"flush",
6606 		.data		=	&init_net.ipv6.sysctl.flush_delay,
6607 		.maxlen		=	sizeof(int),
6608 		.mode		=	0200,
6609 		.proc_handler	=	ipv6_sysctl_rtcache_flush
6610 	},
6611 	{
6612 		.procname	=	"gc_min_interval",
6613 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
6614 		.maxlen		=	sizeof(int),
6615 		.mode		=	0644,
6616 		.proc_handler	=	proc_dointvec_jiffies,
6617 	},
6618 	{
6619 		.procname	=	"gc_timeout",
6620 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_timeout,
6621 		.maxlen		=	sizeof(int),
6622 		.mode		=	0644,
6623 		.proc_handler	=	proc_dointvec_jiffies,
6624 	},
6625 	{
6626 		.procname	=	"gc_interval",
6627 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_interval,
6628 		.maxlen		=	sizeof(int),
6629 		.mode		=	0644,
6630 		.proc_handler	=	proc_dointvec_jiffies,
6631 	},
6632 	{
6633 		.procname	=	"gc_elasticity",
6634 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
6635 		.maxlen		=	sizeof(int),
6636 		.mode		=	0644,
6637 		.proc_handler	=	proc_dointvec,
6638 	},
6639 	{
6640 		.procname	=	"mtu_expires",
6641 		.data		=	&init_net.ipv6.sysctl.ip6_rt_mtu_expires,
6642 		.maxlen		=	sizeof(int),
6643 		.mode		=	0644,
6644 		.proc_handler	=	proc_dointvec_jiffies,
6645 	},
6646 	{
6647 		.procname	=	"min_adv_mss",
6648 		.data		=	&init_net.ipv6.sysctl.ip6_rt_min_advmss,
6649 		.maxlen		=	sizeof(int),
6650 		.mode		=	0644,
6651 		.proc_handler	=	proc_dointvec,
6652 	},
6653 	{
6654 		.procname	=	"gc_min_interval_ms",
6655 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
6656 		.maxlen		=	sizeof(int),
6657 		.mode		=	0644,
6658 		.proc_handler	=	proc_dointvec_ms_jiffies,
6659 	},
6660 	{
6661 		.procname	=	"skip_notify_on_dev_down",
6662 		.data		=	&init_net.ipv6.sysctl.skip_notify_on_dev_down,
6663 		.maxlen		=	sizeof(u8),
6664 		.mode		=	0644,
6665 		.proc_handler	=	proc_dou8vec_minmax,
6666 		.extra1		=	SYSCTL_ZERO,
6667 		.extra2		=	SYSCTL_ONE,
6668 	},
6669 };
6670 
6671 struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
6672 {
6673 	struct ctl_table *table;
6674 
6675 	table = kmemdup(ipv6_route_table_template,
6676 			sizeof(ipv6_route_table_template),
6677 			GFP_KERNEL);
6678 
6679 	if (table) {
6680 		table[0].data = &net->ipv6.sysctl.ip6_rt_max_size;
6681 		table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
6682 		table[2].data = &net->ipv6.sysctl.flush_delay;
6683 		table[2].extra1 = net;
6684 		table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
6685 		table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
6686 		table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
6687 		table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
6688 		table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
6689 		table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
6690 		table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
6691 		table[10].data = &net->ipv6.sysctl.skip_notify_on_dev_down;
6692 	}
6693 
6694 	return table;
6695 }
6696 
6697 size_t ipv6_route_sysctl_table_size(struct net *net)
6698 {
6699 	/* Don't export sysctls to unprivileged users */
6700 	if (net->user_ns != &init_user_ns)
6701 		return 1;
6702 
6703 	return ARRAY_SIZE(ipv6_route_table_template);
6704 }
6705 #endif
6706 
6707 static int __net_init ip6_route_net_init(struct net *net)
6708 {
6709 	int ret = -ENOMEM;
6710 
6711 	memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
6712 	       sizeof(net->ipv6.ip6_dst_ops));
6713 
6714 	if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
6715 		goto out_ip6_dst_ops;
6716 
6717 	net->ipv6.fib6_null_entry = fib6_info_alloc(GFP_KERNEL, true);
6718 	if (!net->ipv6.fib6_null_entry)
6719 		goto out_ip6_dst_entries;
6720 	memcpy(net->ipv6.fib6_null_entry, &fib6_null_entry_template,
6721 	       sizeof(*net->ipv6.fib6_null_entry));
6722 
6723 	net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
6724 					   sizeof(*net->ipv6.ip6_null_entry),
6725 					   GFP_KERNEL);
6726 	if (!net->ipv6.ip6_null_entry)
6727 		goto out_fib6_null_entry;
6728 	net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6729 	dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
6730 			 ip6_template_metrics, true);
6731 	INIT_LIST_HEAD(&net->ipv6.ip6_null_entry->dst.rt_uncached);
6732 
6733 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6734 	net->ipv6.fib6_has_custom_rules = false;
6735 	net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
6736 					       sizeof(*net->ipv6.ip6_prohibit_entry),
6737 					       GFP_KERNEL);
6738 	if (!net->ipv6.ip6_prohibit_entry)
6739 		goto out_ip6_null_entry;
6740 	net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6741 	dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
6742 			 ip6_template_metrics, true);
6743 	INIT_LIST_HEAD(&net->ipv6.ip6_prohibit_entry->dst.rt_uncached);
6744 
6745 	net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
6746 					       sizeof(*net->ipv6.ip6_blk_hole_entry),
6747 					       GFP_KERNEL);
6748 	if (!net->ipv6.ip6_blk_hole_entry)
6749 		goto out_ip6_prohibit_entry;
6750 	net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6751 	dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
6752 			 ip6_template_metrics, true);
6753 	INIT_LIST_HEAD(&net->ipv6.ip6_blk_hole_entry->dst.rt_uncached);
6754 #ifdef CONFIG_IPV6_SUBTREES
6755 	net->ipv6.fib6_routes_require_src = 0;
6756 #endif
6757 #endif
6758 
6759 	net->ipv6.sysctl.flush_delay = 0;
6760 	net->ipv6.sysctl.ip6_rt_max_size = INT_MAX;
6761 	net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
6762 	net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
6763 	net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
6764 	net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
6765 	net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
6766 	net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
6767 	net->ipv6.sysctl.skip_notify_on_dev_down = 0;
6768 
6769 	atomic_set(&net->ipv6.ip6_rt_gc_expire, 30*HZ);
6770 
6771 	ret = 0;
6772 out:
6773 	return ret;
6774 
6775 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6776 out_ip6_prohibit_entry:
6777 	kfree(net->ipv6.ip6_prohibit_entry);
6778 out_ip6_null_entry:
6779 	kfree(net->ipv6.ip6_null_entry);
6780 #endif
6781 out_fib6_null_entry:
6782 	kfree(net->ipv6.fib6_null_entry);
6783 out_ip6_dst_entries:
6784 	dst_entries_destroy(&net->ipv6.ip6_dst_ops);
6785 out_ip6_dst_ops:
6786 	goto out;
6787 }
6788 
6789 static void __net_exit ip6_route_net_exit(struct net *net)
6790 {
6791 	kfree(net->ipv6.fib6_null_entry);
6792 	kfree(net->ipv6.ip6_null_entry);
6793 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6794 	kfree(net->ipv6.ip6_prohibit_entry);
6795 	kfree(net->ipv6.ip6_blk_hole_entry);
6796 #endif
6797 	dst_entries_destroy(&net->ipv6.ip6_dst_ops);
6798 }
6799 
6800 static int __net_init ip6_route_net_init_late(struct net *net)
6801 {
6802 #ifdef CONFIG_PROC_FS
6803 	if (!proc_create_net("ipv6_route", 0, net->proc_net,
6804 			     &ipv6_route_seq_ops,
6805 			     sizeof(struct ipv6_route_iter)))
6806 		return -ENOMEM;
6807 
6808 	if (!proc_create_net_single("rt6_stats", 0444, net->proc_net,
6809 				    rt6_stats_seq_show, NULL)) {
6810 		remove_proc_entry("ipv6_route", net->proc_net);
6811 		return -ENOMEM;
6812 	}
6813 #endif
6814 	return 0;
6815 }
6816 
6817 static void __net_exit ip6_route_net_exit_late(struct net *net)
6818 {
6819 #ifdef CONFIG_PROC_FS
6820 	remove_proc_entry("ipv6_route", net->proc_net);
6821 	remove_proc_entry("rt6_stats", net->proc_net);
6822 #endif
6823 }
6824 
6825 static struct pernet_operations ip6_route_net_ops = {
6826 	.init = ip6_route_net_init,
6827 	.exit = ip6_route_net_exit,
6828 };
6829 
6830 static int __net_init ipv6_inetpeer_init(struct net *net)
6831 {
6832 	struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
6833 
6834 	if (!bp)
6835 		return -ENOMEM;
6836 	inet_peer_base_init(bp);
6837 	net->ipv6.peers = bp;
6838 	return 0;
6839 }
6840 
6841 static void __net_exit ipv6_inetpeer_exit(struct net *net)
6842 {
6843 	struct inet_peer_base *bp = net->ipv6.peers;
6844 
6845 	net->ipv6.peers = NULL;
6846 	inetpeer_invalidate_tree(bp);
6847 	kfree(bp);
6848 }
6849 
6850 static struct pernet_operations ipv6_inetpeer_ops = {
6851 	.init	=	ipv6_inetpeer_init,
6852 	.exit	=	ipv6_inetpeer_exit,
6853 };
6854 
6855 static struct pernet_operations ip6_route_net_late_ops = {
6856 	.init = ip6_route_net_init_late,
6857 	.exit = ip6_route_net_exit_late,
6858 };
6859 
6860 static struct notifier_block ip6_route_dev_notifier = {
6861 	.notifier_call = ip6_route_dev_notify,
6862 	.priority = ADDRCONF_NOTIFY_PRIORITY - 10,
6863 };
6864 
6865 void __init ip6_route_init_special_entries(void)
6866 {
6867 	/* Registering of the loopback is done before this portion of code,
6868 	 * the loopback reference in rt6_info will not be taken, do it
6869 	 * manually for init_net */
6870 	init_net.ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = init_net.loopback_dev;
6871 	init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
6872 	init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6873   #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6874 	init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
6875 	init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6876 	init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
6877 	init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6878   #endif
6879 }
6880 
6881 #if IS_BUILTIN(CONFIG_IPV6)
6882 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
6883 DEFINE_BPF_ITER_FUNC(ipv6_route, struct bpf_iter_meta *meta, struct fib6_info *rt)
6884 
6885 BTF_ID_LIST(btf_fib6_info_id)
6886 BTF_ID(struct, fib6_info)
6887 
6888 static const struct bpf_iter_seq_info ipv6_route_seq_info = {
6889 	.seq_ops		= &ipv6_route_seq_ops,
6890 	.init_seq_private	= bpf_iter_init_seq_net,
6891 	.fini_seq_private	= bpf_iter_fini_seq_net,
6892 	.seq_priv_size		= sizeof(struct ipv6_route_iter),
6893 };
6894 
6895 static struct bpf_iter_reg ipv6_route_reg_info = {
6896 	.target			= "ipv6_route",
6897 	.ctx_arg_info_size	= 1,
6898 	.ctx_arg_info		= {
6899 		{ offsetof(struct bpf_iter__ipv6_route, rt),
6900 		  PTR_TO_BTF_ID_OR_NULL },
6901 	},
6902 	.seq_info		= &ipv6_route_seq_info,
6903 };
6904 
6905 static int __init bpf_iter_register(void)
6906 {
6907 	ipv6_route_reg_info.ctx_arg_info[0].btf_id = *btf_fib6_info_id;
6908 	return bpf_iter_reg_target(&ipv6_route_reg_info);
6909 }
6910 
6911 static void bpf_iter_unregister(void)
6912 {
6913 	bpf_iter_unreg_target(&ipv6_route_reg_info);
6914 }
6915 #endif
6916 #endif
6917 
6918 static const struct rtnl_msg_handler ip6_route_rtnl_msg_handlers[] __initconst_or_module = {
6919 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_NEWROUTE,
6920 	 .doit = inet6_rtm_newroute, .flags = RTNL_FLAG_DOIT_UNLOCKED},
6921 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_DELROUTE,
6922 	 .doit = inet6_rtm_delroute, .flags = RTNL_FLAG_DOIT_UNLOCKED},
6923 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETROUTE,
6924 	 .doit = inet6_rtm_getroute, .flags = RTNL_FLAG_DOIT_UNLOCKED},
6925 };
6926 
6927 int __init ip6_route_init(void)
6928 {
6929 	int ret;
6930 	int cpu;
6931 
6932 	ret = -ENOMEM;
6933 	ip6_dst_ops_template.kmem_cachep =
6934 		kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
6935 				  SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT, NULL);
6936 	if (!ip6_dst_ops_template.kmem_cachep)
6937 		goto out;
6938 
6939 	ret = dst_entries_init(&ip6_dst_blackhole_ops);
6940 	if (ret)
6941 		goto out_kmem_cache;
6942 
6943 	ret = register_pernet_subsys(&ipv6_inetpeer_ops);
6944 	if (ret)
6945 		goto out_dst_entries;
6946 
6947 	ret = register_pernet_subsys(&ip6_route_net_ops);
6948 	if (ret)
6949 		goto out_register_inetpeer;
6950 
6951 	ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
6952 
6953 	ret = fib6_init();
6954 	if (ret)
6955 		goto out_register_subsys;
6956 
6957 	ret = xfrm6_init();
6958 	if (ret)
6959 		goto out_fib6_init;
6960 
6961 	ret = fib6_rules_init();
6962 	if (ret)
6963 		goto xfrm6_init;
6964 
6965 	ret = register_pernet_subsys(&ip6_route_net_late_ops);
6966 	if (ret)
6967 		goto fib6_rules_init;
6968 
6969 	ret = rtnl_register_many(ip6_route_rtnl_msg_handlers);
6970 	if (ret < 0)
6971 		goto out_register_late_subsys;
6972 
6973 	ret = register_netdevice_notifier(&ip6_route_dev_notifier);
6974 	if (ret)
6975 		goto out_register_late_subsys;
6976 
6977 #if IS_BUILTIN(CONFIG_IPV6)
6978 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
6979 	ret = bpf_iter_register();
6980 	if (ret)
6981 		goto out_register_late_subsys;
6982 #endif
6983 #endif
6984 
6985 	for_each_possible_cpu(cpu) {
6986 		struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu);
6987 
6988 		INIT_LIST_HEAD(&ul->head);
6989 		spin_lock_init(&ul->lock);
6990 	}
6991 
6992 out:
6993 	return ret;
6994 
6995 out_register_late_subsys:
6996 	rtnl_unregister_all(PF_INET6);
6997 	unregister_pernet_subsys(&ip6_route_net_late_ops);
6998 fib6_rules_init:
6999 	fib6_rules_cleanup();
7000 xfrm6_init:
7001 	xfrm6_fini();
7002 out_fib6_init:
7003 	fib6_gc_cleanup();
7004 out_register_subsys:
7005 	unregister_pernet_subsys(&ip6_route_net_ops);
7006 out_register_inetpeer:
7007 	unregister_pernet_subsys(&ipv6_inetpeer_ops);
7008 out_dst_entries:
7009 	dst_entries_destroy(&ip6_dst_blackhole_ops);
7010 out_kmem_cache:
7011 	kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
7012 	goto out;
7013 }
7014 
7015 void ip6_route_cleanup(void)
7016 {
7017 #if IS_BUILTIN(CONFIG_IPV6)
7018 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
7019 	bpf_iter_unregister();
7020 #endif
7021 #endif
7022 	unregister_netdevice_notifier(&ip6_route_dev_notifier);
7023 	unregister_pernet_subsys(&ip6_route_net_late_ops);
7024 	fib6_rules_cleanup();
7025 	xfrm6_fini();
7026 	fib6_gc_cleanup();
7027 	unregister_pernet_subsys(&ipv6_inetpeer_ops);
7028 	unregister_pernet_subsys(&ip6_route_net_ops);
7029 	dst_entries_destroy(&ip6_dst_blackhole_ops);
7030 	kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
7031 }
7032