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