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