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