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