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