1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	Linux INET6 implementation
4  *	FIB front-end.
5  *
6  *	Authors:
7  *	Pedro Roque		<[email protected]>
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) ? : 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) ? : 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) ? : 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) ? : 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_purge_dflt_routers(struct net * net,struct fib6_table * table)4442 static void __rt6_purge_dflt_routers(struct net *net,
4443 				     struct fib6_table *table)
4444 {
4445 	struct fib6_info *rt;
4446 
4447 restart:
4448 	rcu_read_lock();
4449 	for_each_fib6_node_rt_rcu(&table->tb6_root) {
4450 		struct net_device *dev = fib6_info_nh_dev(rt);
4451 		struct inet6_dev *idev = dev ? __in6_dev_get(dev) : NULL;
4452 
4453 		if (rt->fib6_flags & (RTF_DEFAULT | RTF_ADDRCONF) &&
4454 		    (!idev || idev->cnf.accept_ra != 2) &&
4455 		    fib6_info_hold_safe(rt)) {
4456 			rcu_read_unlock();
4457 			ip6_del_rt(net, rt, false);
4458 			goto restart;
4459 		}
4460 	}
4461 	rcu_read_unlock();
4462 
4463 	table->flags &= ~RT6_TABLE_HAS_DFLT_ROUTER;
4464 }
4465 
rt6_purge_dflt_routers(struct net * net)4466 void rt6_purge_dflt_routers(struct net *net)
4467 {
4468 	struct fib6_table *table;
4469 	struct hlist_head *head;
4470 	unsigned int h;
4471 
4472 	rcu_read_lock();
4473 
4474 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
4475 		head = &net->ipv6.fib_table_hash[h];
4476 		hlist_for_each_entry_rcu(table, head, tb6_hlist) {
4477 			if (table->flags & RT6_TABLE_HAS_DFLT_ROUTER)
4478 				__rt6_purge_dflt_routers(net, table);
4479 		}
4480 	}
4481 
4482 	rcu_read_unlock();
4483 }
4484 
rtmsg_to_fib6_config(struct net * net,struct in6_rtmsg * rtmsg,struct fib6_config * cfg)4485 static void rtmsg_to_fib6_config(struct net *net,
4486 				 struct in6_rtmsg *rtmsg,
4487 				 struct fib6_config *cfg)
4488 {
4489 	*cfg = (struct fib6_config){
4490 		.fc_table = l3mdev_fib_table_by_index(net, rtmsg->rtmsg_ifindex) ?
4491 			 : RT6_TABLE_MAIN,
4492 		.fc_ifindex = rtmsg->rtmsg_ifindex,
4493 		.fc_metric = rtmsg->rtmsg_metric,
4494 		.fc_expires = rtmsg->rtmsg_info,
4495 		.fc_dst_len = rtmsg->rtmsg_dst_len,
4496 		.fc_src_len = rtmsg->rtmsg_src_len,
4497 		.fc_flags = rtmsg->rtmsg_flags,
4498 		.fc_type = rtmsg->rtmsg_type,
4499 
4500 		.fc_nlinfo.nl_net = net,
4501 
4502 		.fc_dst = rtmsg->rtmsg_dst,
4503 		.fc_src = rtmsg->rtmsg_src,
4504 		.fc_gateway = rtmsg->rtmsg_gateway,
4505 	};
4506 }
4507 
ipv6_route_ioctl(struct net * net,unsigned int cmd,struct in6_rtmsg * rtmsg)4508 int ipv6_route_ioctl(struct net *net, unsigned int cmd, struct in6_rtmsg *rtmsg)
4509 {
4510 	struct fib6_config cfg;
4511 	int err;
4512 
4513 	if (cmd != SIOCADDRT && cmd != SIOCDELRT)
4514 		return -EINVAL;
4515 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
4516 		return -EPERM;
4517 
4518 	rtmsg_to_fib6_config(net, rtmsg, &cfg);
4519 
4520 	rtnl_lock();
4521 	switch (cmd) {
4522 	case SIOCADDRT:
4523 		/* Only do the default setting of fc_metric in route adding */
4524 		if (cfg.fc_metric == 0)
4525 			cfg.fc_metric = IP6_RT_PRIO_USER;
4526 		err = ip6_route_add(&cfg, GFP_KERNEL, NULL);
4527 		break;
4528 	case SIOCDELRT:
4529 		err = ip6_route_del(&cfg, NULL);
4530 		break;
4531 	}
4532 	rtnl_unlock();
4533 	return err;
4534 }
4535 
4536 /*
4537  *	Drop the packet on the floor
4538  */
4539 
ip6_pkt_drop(struct sk_buff * skb,u8 code,int ipstats_mib_noroutes)4540 static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
4541 {
4542 	struct dst_entry *dst = skb_dst(skb);
4543 	struct net *net = dev_net(dst->dev);
4544 	struct inet6_dev *idev;
4545 	SKB_DR(reason);
4546 	int type;
4547 
4548 	if (netif_is_l3_master(skb->dev) ||
4549 	    dst->dev == net->loopback_dev)
4550 		idev = __in6_dev_get_safely(dev_get_by_index_rcu(net, IP6CB(skb)->iif));
4551 	else
4552 		idev = ip6_dst_idev(dst);
4553 
4554 	switch (ipstats_mib_noroutes) {
4555 	case IPSTATS_MIB_INNOROUTES:
4556 		type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
4557 		if (type == IPV6_ADDR_ANY) {
4558 			SKB_DR_SET(reason, IP_INADDRERRORS);
4559 			IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
4560 			break;
4561 		}
4562 		SKB_DR_SET(reason, IP_INNOROUTES);
4563 		fallthrough;
4564 	case IPSTATS_MIB_OUTNOROUTES:
4565 		SKB_DR_OR(reason, IP_OUTNOROUTES);
4566 		IP6_INC_STATS(net, idev, ipstats_mib_noroutes);
4567 		break;
4568 	}
4569 
4570 	/* Start over by dropping the dst for l3mdev case */
4571 	if (netif_is_l3_master(skb->dev))
4572 		skb_dst_drop(skb);
4573 
4574 	icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
4575 	kfree_skb_reason(skb, reason);
4576 	return 0;
4577 }
4578 
ip6_pkt_discard(struct sk_buff * skb)4579 static int ip6_pkt_discard(struct sk_buff *skb)
4580 {
4581 	return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
4582 }
4583 
ip6_pkt_discard_out(struct net * net,struct sock * sk,struct sk_buff * skb)4584 static int ip6_pkt_discard_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4585 {
4586 	skb->dev = skb_dst(skb)->dev;
4587 	return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
4588 }
4589 
ip6_pkt_prohibit(struct sk_buff * skb)4590 static int ip6_pkt_prohibit(struct sk_buff *skb)
4591 {
4592 	return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
4593 }
4594 
ip6_pkt_prohibit_out(struct net * net,struct sock * sk,struct sk_buff * skb)4595 static int ip6_pkt_prohibit_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4596 {
4597 	skb->dev = skb_dst(skb)->dev;
4598 	return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
4599 }
4600 
4601 /*
4602  *	Allocate a dst for local (unicast / anycast) address.
4603  */
4604 
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)4605 struct fib6_info *addrconf_f6i_alloc(struct net *net,
4606 				     struct inet6_dev *idev,
4607 				     const struct in6_addr *addr,
4608 				     bool anycast, gfp_t gfp_flags,
4609 				     struct netlink_ext_ack *extack)
4610 {
4611 	struct fib6_config cfg = {
4612 		.fc_table = l3mdev_fib_table(idev->dev) ? : RT6_TABLE_LOCAL,
4613 		.fc_ifindex = idev->dev->ifindex,
4614 		.fc_flags = RTF_UP | RTF_NONEXTHOP,
4615 		.fc_dst = *addr,
4616 		.fc_dst_len = 128,
4617 		.fc_protocol = RTPROT_KERNEL,
4618 		.fc_nlinfo.nl_net = net,
4619 		.fc_ignore_dev_down = true,
4620 	};
4621 	struct fib6_info *f6i;
4622 
4623 	if (anycast) {
4624 		cfg.fc_type = RTN_ANYCAST;
4625 		cfg.fc_flags |= RTF_ANYCAST;
4626 	} else {
4627 		cfg.fc_type = RTN_LOCAL;
4628 		cfg.fc_flags |= RTF_LOCAL;
4629 	}
4630 
4631 	f6i = ip6_route_info_create(&cfg, gfp_flags, extack);
4632 	if (!IS_ERR(f6i)) {
4633 		f6i->dst_nocount = true;
4634 
4635 		if (!anycast &&
4636 		    (READ_ONCE(net->ipv6.devconf_all->disable_policy) ||
4637 		     READ_ONCE(idev->cnf.disable_policy)))
4638 			f6i->dst_nopolicy = true;
4639 	}
4640 
4641 	return f6i;
4642 }
4643 
4644 /* remove deleted ip from prefsrc entries */
4645 struct arg_dev_net_ip {
4646 	struct net *net;
4647 	struct in6_addr *addr;
4648 };
4649 
fib6_remove_prefsrc(struct fib6_info * rt,void * arg)4650 static int fib6_remove_prefsrc(struct fib6_info *rt, void *arg)
4651 {
4652 	struct net *net = ((struct arg_dev_net_ip *)arg)->net;
4653 	struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
4654 
4655 	if (!rt->nh &&
4656 	    rt != net->ipv6.fib6_null_entry &&
4657 	    ipv6_addr_equal(addr, &rt->fib6_prefsrc.addr) &&
4658 	    !ipv6_chk_addr(net, addr, rt->fib6_nh->fib_nh_dev, 0)) {
4659 		spin_lock_bh(&rt6_exception_lock);
4660 		/* remove prefsrc entry */
4661 		rt->fib6_prefsrc.plen = 0;
4662 		spin_unlock_bh(&rt6_exception_lock);
4663 	}
4664 	return 0;
4665 }
4666 
rt6_remove_prefsrc(struct inet6_ifaddr * ifp)4667 void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
4668 {
4669 	struct net *net = dev_net(ifp->idev->dev);
4670 	struct arg_dev_net_ip adni = {
4671 		.net = net,
4672 		.addr = &ifp->addr,
4673 	};
4674 	fib6_clean_all(net, fib6_remove_prefsrc, &adni);
4675 }
4676 
4677 #define RTF_RA_ROUTER		(RTF_ADDRCONF | RTF_DEFAULT)
4678 
4679 /* Remove routers and update dst entries when gateway turn into host. */
fib6_clean_tohost(struct fib6_info * rt,void * arg)4680 static int fib6_clean_tohost(struct fib6_info *rt, void *arg)
4681 {
4682 	struct in6_addr *gateway = (struct in6_addr *)arg;
4683 	struct fib6_nh *nh;
4684 
4685 	/* RA routes do not use nexthops */
4686 	if (rt->nh)
4687 		return 0;
4688 
4689 	nh = rt->fib6_nh;
4690 	if (((rt->fib6_flags & RTF_RA_ROUTER) == RTF_RA_ROUTER) &&
4691 	    nh->fib_nh_gw_family && ipv6_addr_equal(gateway, &nh->fib_nh_gw6))
4692 		return -1;
4693 
4694 	/* Further clean up cached routes in exception table.
4695 	 * This is needed because cached route may have a different
4696 	 * gateway than its 'parent' in the case of an ip redirect.
4697 	 */
4698 	fib6_nh_exceptions_clean_tohost(nh, gateway);
4699 
4700 	return 0;
4701 }
4702 
rt6_clean_tohost(struct net * net,struct in6_addr * gateway)4703 void rt6_clean_tohost(struct net *net, struct in6_addr *gateway)
4704 {
4705 	fib6_clean_all(net, fib6_clean_tohost, gateway);
4706 }
4707 
4708 struct arg_netdev_event {
4709 	const struct net_device *dev;
4710 	union {
4711 		unsigned char nh_flags;
4712 		unsigned long event;
4713 	};
4714 };
4715 
rt6_multipath_first_sibling(const struct fib6_info * rt)4716 static struct fib6_info *rt6_multipath_first_sibling(const struct fib6_info *rt)
4717 {
4718 	struct fib6_info *iter;
4719 	struct fib6_node *fn;
4720 
4721 	fn = rcu_dereference_protected(rt->fib6_node,
4722 			lockdep_is_held(&rt->fib6_table->tb6_lock));
4723 	iter = rcu_dereference_protected(fn->leaf,
4724 			lockdep_is_held(&rt->fib6_table->tb6_lock));
4725 	while (iter) {
4726 		if (iter->fib6_metric == rt->fib6_metric &&
4727 		    rt6_qualify_for_ecmp(iter))
4728 			return iter;
4729 		iter = rcu_dereference_protected(iter->fib6_next,
4730 				lockdep_is_held(&rt->fib6_table->tb6_lock));
4731 	}
4732 
4733 	return NULL;
4734 }
4735 
4736 /* only called for fib entries with builtin fib6_nh */
rt6_is_dead(const struct fib6_info * rt)4737 static bool rt6_is_dead(const struct fib6_info *rt)
4738 {
4739 	if (rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD ||
4740 	    (rt->fib6_nh->fib_nh_flags & RTNH_F_LINKDOWN &&
4741 	     ip6_ignore_linkdown(rt->fib6_nh->fib_nh_dev)))
4742 		return true;
4743 
4744 	return false;
4745 }
4746 
rt6_multipath_total_weight(const struct fib6_info * rt)4747 static int rt6_multipath_total_weight(const struct fib6_info *rt)
4748 {
4749 	struct fib6_info *iter;
4750 	int total = 0;
4751 
4752 	if (!rt6_is_dead(rt))
4753 		total += rt->fib6_nh->fib_nh_weight;
4754 
4755 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings) {
4756 		if (!rt6_is_dead(iter))
4757 			total += iter->fib6_nh->fib_nh_weight;
4758 	}
4759 
4760 	return total;
4761 }
4762 
rt6_upper_bound_set(struct fib6_info * rt,int * weight,int total)4763 static void rt6_upper_bound_set(struct fib6_info *rt, int *weight, int total)
4764 {
4765 	int upper_bound = -1;
4766 
4767 	if (!rt6_is_dead(rt)) {
4768 		*weight += rt->fib6_nh->fib_nh_weight;
4769 		upper_bound = DIV_ROUND_CLOSEST_ULL((u64) (*weight) << 31,
4770 						    total) - 1;
4771 	}
4772 	atomic_set(&rt->fib6_nh->fib_nh_upper_bound, upper_bound);
4773 }
4774 
rt6_multipath_upper_bound_set(struct fib6_info * rt,int total)4775 static void rt6_multipath_upper_bound_set(struct fib6_info *rt, int total)
4776 {
4777 	struct fib6_info *iter;
4778 	int weight = 0;
4779 
4780 	rt6_upper_bound_set(rt, &weight, total);
4781 
4782 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4783 		rt6_upper_bound_set(iter, &weight, total);
4784 }
4785 
rt6_multipath_rebalance(struct fib6_info * rt)4786 void rt6_multipath_rebalance(struct fib6_info *rt)
4787 {
4788 	struct fib6_info *first;
4789 	int total;
4790 
4791 	/* In case the entire multipath route was marked for flushing,
4792 	 * then there is no need to rebalance upon the removal of every
4793 	 * sibling route.
4794 	 */
4795 	if (!rt->fib6_nsiblings || rt->should_flush)
4796 		return;
4797 
4798 	/* During lookup routes are evaluated in order, so we need to
4799 	 * make sure upper bounds are assigned from the first sibling
4800 	 * onwards.
4801 	 */
4802 	first = rt6_multipath_first_sibling(rt);
4803 	if (WARN_ON_ONCE(!first))
4804 		return;
4805 
4806 	total = rt6_multipath_total_weight(first);
4807 	rt6_multipath_upper_bound_set(first, total);
4808 }
4809 
fib6_ifup(struct fib6_info * rt,void * p_arg)4810 static int fib6_ifup(struct fib6_info *rt, void *p_arg)
4811 {
4812 	const struct arg_netdev_event *arg = p_arg;
4813 	struct net *net = dev_net(arg->dev);
4814 
4815 	if (rt != net->ipv6.fib6_null_entry && !rt->nh &&
4816 	    rt->fib6_nh->fib_nh_dev == arg->dev) {
4817 		rt->fib6_nh->fib_nh_flags &= ~arg->nh_flags;
4818 		fib6_update_sernum_upto_root(net, rt);
4819 		rt6_multipath_rebalance(rt);
4820 	}
4821 
4822 	return 0;
4823 }
4824 
rt6_sync_up(struct net_device * dev,unsigned char nh_flags)4825 void rt6_sync_up(struct net_device *dev, unsigned char nh_flags)
4826 {
4827 	struct arg_netdev_event arg = {
4828 		.dev = dev,
4829 		{
4830 			.nh_flags = nh_flags,
4831 		},
4832 	};
4833 
4834 	if (nh_flags & RTNH_F_DEAD && netif_carrier_ok(dev))
4835 		arg.nh_flags |= RTNH_F_LINKDOWN;
4836 
4837 	fib6_clean_all(dev_net(dev), fib6_ifup, &arg);
4838 }
4839 
4840 /* only called for fib entries with inline fib6_nh */
rt6_multipath_uses_dev(const struct fib6_info * rt,const struct net_device * dev)4841 static bool rt6_multipath_uses_dev(const struct fib6_info *rt,
4842 				   const struct net_device *dev)
4843 {
4844 	struct fib6_info *iter;
4845 
4846 	if (rt->fib6_nh->fib_nh_dev == dev)
4847 		return true;
4848 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4849 		if (iter->fib6_nh->fib_nh_dev == dev)
4850 			return true;
4851 
4852 	return false;
4853 }
4854 
rt6_multipath_flush(struct fib6_info * rt)4855 static void rt6_multipath_flush(struct fib6_info *rt)
4856 {
4857 	struct fib6_info *iter;
4858 
4859 	rt->should_flush = 1;
4860 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4861 		iter->should_flush = 1;
4862 }
4863 
rt6_multipath_dead_count(const struct fib6_info * rt,const struct net_device * down_dev)4864 static unsigned int rt6_multipath_dead_count(const struct fib6_info *rt,
4865 					     const struct net_device *down_dev)
4866 {
4867 	struct fib6_info *iter;
4868 	unsigned int dead = 0;
4869 
4870 	if (rt->fib6_nh->fib_nh_dev == down_dev ||
4871 	    rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4872 		dead++;
4873 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4874 		if (iter->fib6_nh->fib_nh_dev == down_dev ||
4875 		    iter->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4876 			dead++;
4877 
4878 	return dead;
4879 }
4880 
rt6_multipath_nh_flags_set(struct fib6_info * rt,const struct net_device * dev,unsigned char nh_flags)4881 static void rt6_multipath_nh_flags_set(struct fib6_info *rt,
4882 				       const struct net_device *dev,
4883 				       unsigned char nh_flags)
4884 {
4885 	struct fib6_info *iter;
4886 
4887 	if (rt->fib6_nh->fib_nh_dev == dev)
4888 		rt->fib6_nh->fib_nh_flags |= nh_flags;
4889 	list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4890 		if (iter->fib6_nh->fib_nh_dev == dev)
4891 			iter->fib6_nh->fib_nh_flags |= nh_flags;
4892 }
4893 
4894 /* called with write lock held for table with rt */
fib6_ifdown(struct fib6_info * rt,void * p_arg)4895 static int fib6_ifdown(struct fib6_info *rt, void *p_arg)
4896 {
4897 	const struct arg_netdev_event *arg = p_arg;
4898 	const struct net_device *dev = arg->dev;
4899 	struct net *net = dev_net(dev);
4900 
4901 	if (rt == net->ipv6.fib6_null_entry || rt->nh)
4902 		return 0;
4903 
4904 	switch (arg->event) {
4905 	case NETDEV_UNREGISTER:
4906 		return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4907 	case NETDEV_DOWN:
4908 		if (rt->should_flush)
4909 			return -1;
4910 		if (!rt->fib6_nsiblings)
4911 			return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4912 		if (rt6_multipath_uses_dev(rt, dev)) {
4913 			unsigned int count;
4914 
4915 			count = rt6_multipath_dead_count(rt, dev);
4916 			if (rt->fib6_nsiblings + 1 == count) {
4917 				rt6_multipath_flush(rt);
4918 				return -1;
4919 			}
4920 			rt6_multipath_nh_flags_set(rt, dev, RTNH_F_DEAD |
4921 						   RTNH_F_LINKDOWN);
4922 			fib6_update_sernum(net, rt);
4923 			rt6_multipath_rebalance(rt);
4924 		}
4925 		return -2;
4926 	case NETDEV_CHANGE:
4927 		if (rt->fib6_nh->fib_nh_dev != dev ||
4928 		    rt->fib6_flags & (RTF_LOCAL | RTF_ANYCAST))
4929 			break;
4930 		rt->fib6_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
4931 		rt6_multipath_rebalance(rt);
4932 		break;
4933 	}
4934 
4935 	return 0;
4936 }
4937 
rt6_sync_down_dev(struct net_device * dev,unsigned long event)4938 void rt6_sync_down_dev(struct net_device *dev, unsigned long event)
4939 {
4940 	struct arg_netdev_event arg = {
4941 		.dev = dev,
4942 		{
4943 			.event = event,
4944 		},
4945 	};
4946 	struct net *net = dev_net(dev);
4947 
4948 	if (net->ipv6.sysctl.skip_notify_on_dev_down)
4949 		fib6_clean_all_skip_notify(net, fib6_ifdown, &arg);
4950 	else
4951 		fib6_clean_all(net, fib6_ifdown, &arg);
4952 }
4953 
rt6_disable_ip(struct net_device * dev,unsigned long event)4954 void rt6_disable_ip(struct net_device *dev, unsigned long event)
4955 {
4956 	rt6_sync_down_dev(dev, event);
4957 	rt6_uncached_list_flush_dev(dev);
4958 	neigh_ifdown(&nd_tbl, dev);
4959 }
4960 
4961 struct rt6_mtu_change_arg {
4962 	struct net_device *dev;
4963 	unsigned int mtu;
4964 	struct fib6_info *f6i;
4965 };
4966 
fib6_nh_mtu_change(struct fib6_nh * nh,void * _arg)4967 static int fib6_nh_mtu_change(struct fib6_nh *nh, void *_arg)
4968 {
4969 	struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *)_arg;
4970 	struct fib6_info *f6i = arg->f6i;
4971 
4972 	/* For administrative MTU increase, there is no way to discover
4973 	 * IPv6 PMTU increase, so PMTU increase should be updated here.
4974 	 * Since RFC 1981 doesn't include administrative MTU increase
4975 	 * update PMTU increase is a MUST. (i.e. jumbo frame)
4976 	 */
4977 	if (nh->fib_nh_dev == arg->dev) {
4978 		struct inet6_dev *idev = __in6_dev_get(arg->dev);
4979 		u32 mtu = f6i->fib6_pmtu;
4980 
4981 		if (mtu >= arg->mtu ||
4982 		    (mtu < arg->mtu && mtu == idev->cnf.mtu6))
4983 			fib6_metric_set(f6i, RTAX_MTU, arg->mtu);
4984 
4985 		spin_lock_bh(&rt6_exception_lock);
4986 		rt6_exceptions_update_pmtu(idev, nh, arg->mtu);
4987 		spin_unlock_bh(&rt6_exception_lock);
4988 	}
4989 
4990 	return 0;
4991 }
4992 
rt6_mtu_change_route(struct fib6_info * f6i,void * p_arg)4993 static int rt6_mtu_change_route(struct fib6_info *f6i, void *p_arg)
4994 {
4995 	struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
4996 	struct inet6_dev *idev;
4997 
4998 	/* In IPv6 pmtu discovery is not optional,
4999 	   so that RTAX_MTU lock cannot disable it.
5000 	   We still use this lock to block changes
5001 	   caused by addrconf/ndisc.
5002 	*/
5003 
5004 	idev = __in6_dev_get(arg->dev);
5005 	if (!idev)
5006 		return 0;
5007 
5008 	if (fib6_metric_locked(f6i, RTAX_MTU))
5009 		return 0;
5010 
5011 	arg->f6i = f6i;
5012 	if (f6i->nh) {
5013 		/* fib6_nh_mtu_change only returns 0, so this is safe */
5014 		return nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_mtu_change,
5015 						arg);
5016 	}
5017 
5018 	return fib6_nh_mtu_change(f6i->fib6_nh, arg);
5019 }
5020 
rt6_mtu_change(struct net_device * dev,unsigned int mtu)5021 void rt6_mtu_change(struct net_device *dev, unsigned int mtu)
5022 {
5023 	struct rt6_mtu_change_arg arg = {
5024 		.dev = dev,
5025 		.mtu = mtu,
5026 	};
5027 
5028 	fib6_clean_all(dev_net(dev), rt6_mtu_change_route, &arg);
5029 }
5030 
5031 static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
5032 	[RTA_UNSPEC]		= { .strict_start_type = RTA_DPORT + 1 },
5033 	[RTA_GATEWAY]           = { .len = sizeof(struct in6_addr) },
5034 	[RTA_PREFSRC]		= { .len = sizeof(struct in6_addr) },
5035 	[RTA_OIF]               = { .type = NLA_U32 },
5036 	[RTA_IIF]		= { .type = NLA_U32 },
5037 	[RTA_PRIORITY]          = { .type = NLA_U32 },
5038 	[RTA_METRICS]           = { .type = NLA_NESTED },
5039 	[RTA_MULTIPATH]		= { .len = sizeof(struct rtnexthop) },
5040 	[RTA_PREF]              = { .type = NLA_U8 },
5041 	[RTA_ENCAP_TYPE]	= { .type = NLA_U16 },
5042 	[RTA_ENCAP]		= { .type = NLA_NESTED },
5043 	[RTA_EXPIRES]		= { .type = NLA_U32 },
5044 	[RTA_UID]		= { .type = NLA_U32 },
5045 	[RTA_MARK]		= { .type = NLA_U32 },
5046 	[RTA_TABLE]		= { .type = NLA_U32 },
5047 	[RTA_IP_PROTO]		= { .type = NLA_U8 },
5048 	[RTA_SPORT]		= { .type = NLA_U16 },
5049 	[RTA_DPORT]		= { .type = NLA_U16 },
5050 	[RTA_NH_ID]		= { .type = NLA_U32 },
5051 	[RTA_FLOWLABEL]		= { .type = NLA_BE32 },
5052 };
5053 
rtm_to_fib6_config(struct sk_buff * skb,struct nlmsghdr * nlh,struct fib6_config * cfg,struct netlink_ext_ack * extack)5054 static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
5055 			      struct fib6_config *cfg,
5056 			      struct netlink_ext_ack *extack)
5057 {
5058 	struct rtmsg *rtm;
5059 	struct nlattr *tb[RTA_MAX+1];
5060 	unsigned int pref;
5061 	int err;
5062 
5063 	err = nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
5064 				     rtm_ipv6_policy, extack);
5065 	if (err < 0)
5066 		goto errout;
5067 
5068 	err = -EINVAL;
5069 	rtm = nlmsg_data(nlh);
5070 
5071 	if (rtm->rtm_tos) {
5072 		NL_SET_ERR_MSG(extack,
5073 			       "Invalid dsfield (tos): option not available for IPv6");
5074 		goto errout;
5075 	}
5076 
5077 	if (tb[RTA_FLOWLABEL]) {
5078 		NL_SET_ERR_MSG_ATTR(extack, tb[RTA_FLOWLABEL],
5079 				    "Flow label cannot be specified for this operation");
5080 		goto errout;
5081 	}
5082 
5083 	*cfg = (struct fib6_config){
5084 		.fc_table = rtm->rtm_table,
5085 		.fc_dst_len = rtm->rtm_dst_len,
5086 		.fc_src_len = rtm->rtm_src_len,
5087 		.fc_flags = RTF_UP,
5088 		.fc_protocol = rtm->rtm_protocol,
5089 		.fc_type = rtm->rtm_type,
5090 
5091 		.fc_nlinfo.portid = NETLINK_CB(skb).portid,
5092 		.fc_nlinfo.nlh = nlh,
5093 		.fc_nlinfo.nl_net = sock_net(skb->sk),
5094 	};
5095 
5096 	if (rtm->rtm_type == RTN_UNREACHABLE ||
5097 	    rtm->rtm_type == RTN_BLACKHOLE ||
5098 	    rtm->rtm_type == RTN_PROHIBIT ||
5099 	    rtm->rtm_type == RTN_THROW)
5100 		cfg->fc_flags |= RTF_REJECT;
5101 
5102 	if (rtm->rtm_type == RTN_LOCAL)
5103 		cfg->fc_flags |= RTF_LOCAL;
5104 
5105 	if (rtm->rtm_flags & RTM_F_CLONED)
5106 		cfg->fc_flags |= RTF_CACHE;
5107 
5108 	cfg->fc_flags |= (rtm->rtm_flags & RTNH_F_ONLINK);
5109 
5110 	if (tb[RTA_NH_ID]) {
5111 		if (tb[RTA_GATEWAY]   || tb[RTA_OIF] ||
5112 		    tb[RTA_MULTIPATH] || tb[RTA_ENCAP]) {
5113 			NL_SET_ERR_MSG(extack,
5114 				       "Nexthop specification and nexthop id are mutually exclusive");
5115 			goto errout;
5116 		}
5117 		cfg->fc_nh_id = nla_get_u32(tb[RTA_NH_ID]);
5118 	}
5119 
5120 	if (tb[RTA_GATEWAY]) {
5121 		cfg->fc_gateway = nla_get_in6_addr(tb[RTA_GATEWAY]);
5122 		cfg->fc_flags |= RTF_GATEWAY;
5123 	}
5124 	if (tb[RTA_VIA]) {
5125 		NL_SET_ERR_MSG(extack, "IPv6 does not support RTA_VIA attribute");
5126 		goto errout;
5127 	}
5128 
5129 	if (tb[RTA_DST]) {
5130 		int plen = (rtm->rtm_dst_len + 7) >> 3;
5131 
5132 		if (nla_len(tb[RTA_DST]) < plen)
5133 			goto errout;
5134 
5135 		nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
5136 	}
5137 
5138 	if (tb[RTA_SRC]) {
5139 		int plen = (rtm->rtm_src_len + 7) >> 3;
5140 
5141 		if (nla_len(tb[RTA_SRC]) < plen)
5142 			goto errout;
5143 
5144 		nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
5145 	}
5146 
5147 	if (tb[RTA_PREFSRC])
5148 		cfg->fc_prefsrc = nla_get_in6_addr(tb[RTA_PREFSRC]);
5149 
5150 	if (tb[RTA_OIF])
5151 		cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
5152 
5153 	if (tb[RTA_PRIORITY])
5154 		cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
5155 
5156 	if (tb[RTA_METRICS]) {
5157 		cfg->fc_mx = nla_data(tb[RTA_METRICS]);
5158 		cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
5159 	}
5160 
5161 	if (tb[RTA_TABLE])
5162 		cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
5163 
5164 	if (tb[RTA_MULTIPATH]) {
5165 		cfg->fc_mp = nla_data(tb[RTA_MULTIPATH]);
5166 		cfg->fc_mp_len = nla_len(tb[RTA_MULTIPATH]);
5167 
5168 		err = lwtunnel_valid_encap_type_attr(cfg->fc_mp,
5169 						     cfg->fc_mp_len, extack);
5170 		if (err < 0)
5171 			goto errout;
5172 	}
5173 
5174 	if (tb[RTA_PREF]) {
5175 		pref = nla_get_u8(tb[RTA_PREF]);
5176 		if (pref != ICMPV6_ROUTER_PREF_LOW &&
5177 		    pref != ICMPV6_ROUTER_PREF_HIGH)
5178 			pref = ICMPV6_ROUTER_PREF_MEDIUM;
5179 		cfg->fc_flags |= RTF_PREF(pref);
5180 	}
5181 
5182 	if (tb[RTA_ENCAP])
5183 		cfg->fc_encap = tb[RTA_ENCAP];
5184 
5185 	if (tb[RTA_ENCAP_TYPE]) {
5186 		cfg->fc_encap_type = nla_get_u16(tb[RTA_ENCAP_TYPE]);
5187 
5188 		err = lwtunnel_valid_encap_type(cfg->fc_encap_type, extack);
5189 		if (err < 0)
5190 			goto errout;
5191 	}
5192 
5193 	if (tb[RTA_EXPIRES]) {
5194 		unsigned long timeout = addrconf_timeout_fixup(nla_get_u32(tb[RTA_EXPIRES]), HZ);
5195 
5196 		if (addrconf_finite_timeout(timeout)) {
5197 			cfg->fc_expires = jiffies_to_clock_t(timeout * HZ);
5198 			cfg->fc_flags |= RTF_EXPIRES;
5199 		}
5200 	}
5201 
5202 	err = 0;
5203 errout:
5204 	return err;
5205 }
5206 
5207 struct rt6_nh {
5208 	struct fib6_info *fib6_info;
5209 	struct fib6_config r_cfg;
5210 	struct list_head next;
5211 };
5212 
ip6_route_info_append(struct net * net,struct list_head * rt6_nh_list,struct fib6_info * rt,struct fib6_config * r_cfg)5213 static int ip6_route_info_append(struct net *net,
5214 				 struct list_head *rt6_nh_list,
5215 				 struct fib6_info *rt,
5216 				 struct fib6_config *r_cfg)
5217 {
5218 	struct rt6_nh *nh;
5219 	int err = -EEXIST;
5220 
5221 	list_for_each_entry(nh, rt6_nh_list, next) {
5222 		/* check if fib6_info already exists */
5223 		if (rt6_duplicate_nexthop(nh->fib6_info, rt))
5224 			return err;
5225 	}
5226 
5227 	nh = kzalloc(sizeof(*nh), GFP_KERNEL);
5228 	if (!nh)
5229 		return -ENOMEM;
5230 	nh->fib6_info = rt;
5231 	memcpy(&nh->r_cfg, r_cfg, sizeof(*r_cfg));
5232 	list_add_tail(&nh->next, rt6_nh_list);
5233 
5234 	return 0;
5235 }
5236 
ip6_route_mpath_notify(struct fib6_info * rt,struct fib6_info * rt_last,struct nl_info * info,__u16 nlflags)5237 static void ip6_route_mpath_notify(struct fib6_info *rt,
5238 				   struct fib6_info *rt_last,
5239 				   struct nl_info *info,
5240 				   __u16 nlflags)
5241 {
5242 	/* if this is an APPEND route, then rt points to the first route
5243 	 * inserted and rt_last points to last route inserted. Userspace
5244 	 * wants a consistent dump of the route which starts at the first
5245 	 * nexthop. Since sibling routes are always added at the end of
5246 	 * the list, find the first sibling of the last route appended
5247 	 */
5248 	rcu_read_lock();
5249 
5250 	if ((nlflags & NLM_F_APPEND) && rt_last && rt_last->fib6_nsiblings) {
5251 		rt = list_first_or_null_rcu(&rt_last->fib6_siblings,
5252 					    struct fib6_info,
5253 					    fib6_siblings);
5254 	}
5255 
5256 	if (rt)
5257 		inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
5258 
5259 	rcu_read_unlock();
5260 }
5261 
ip6_route_mpath_should_notify(const struct fib6_info * rt)5262 static bool ip6_route_mpath_should_notify(const struct fib6_info *rt)
5263 {
5264 	bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
5265 	bool should_notify = false;
5266 	struct fib6_info *leaf;
5267 	struct fib6_node *fn;
5268 
5269 	rcu_read_lock();
5270 	fn = rcu_dereference(rt->fib6_node);
5271 	if (!fn)
5272 		goto out;
5273 
5274 	leaf = rcu_dereference(fn->leaf);
5275 	if (!leaf)
5276 		goto out;
5277 
5278 	if (rt == leaf ||
5279 	    (rt_can_ecmp && rt->fib6_metric == leaf->fib6_metric &&
5280 	     rt6_qualify_for_ecmp(leaf)))
5281 		should_notify = true;
5282 out:
5283 	rcu_read_unlock();
5284 
5285 	return should_notify;
5286 }
5287 
fib6_gw_from_attr(struct in6_addr * gw,struct nlattr * nla,struct netlink_ext_ack * extack)5288 static int fib6_gw_from_attr(struct in6_addr *gw, struct nlattr *nla,
5289 			     struct netlink_ext_ack *extack)
5290 {
5291 	if (nla_len(nla) < sizeof(*gw)) {
5292 		NL_SET_ERR_MSG(extack, "Invalid IPv6 address in RTA_GATEWAY");
5293 		return -EINVAL;
5294 	}
5295 
5296 	*gw = nla_get_in6_addr(nla);
5297 
5298 	return 0;
5299 }
5300 
ip6_route_multipath_add(struct fib6_config * cfg,struct netlink_ext_ack * extack)5301 static int ip6_route_multipath_add(struct fib6_config *cfg,
5302 				   struct netlink_ext_ack *extack)
5303 {
5304 	struct fib6_info *rt_notif = NULL, *rt_last = NULL;
5305 	struct nl_info *info = &cfg->fc_nlinfo;
5306 	struct fib6_config r_cfg;
5307 	struct rtnexthop *rtnh;
5308 	struct fib6_info *rt;
5309 	struct rt6_nh *err_nh;
5310 	struct rt6_nh *nh, *nh_safe;
5311 	__u16 nlflags;
5312 	int remaining;
5313 	int attrlen;
5314 	int err = 1;
5315 	int nhn = 0;
5316 	int replace = (cfg->fc_nlinfo.nlh &&
5317 		       (cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_REPLACE));
5318 	LIST_HEAD(rt6_nh_list);
5319 
5320 	nlflags = replace ? NLM_F_REPLACE : NLM_F_CREATE;
5321 	if (info->nlh && info->nlh->nlmsg_flags & NLM_F_APPEND)
5322 		nlflags |= NLM_F_APPEND;
5323 
5324 	remaining = cfg->fc_mp_len;
5325 	rtnh = (struct rtnexthop *)cfg->fc_mp;
5326 
5327 	/* Parse a Multipath Entry and build a list (rt6_nh_list) of
5328 	 * fib6_info structs per nexthop
5329 	 */
5330 	while (rtnh_ok(rtnh, remaining)) {
5331 		memcpy(&r_cfg, cfg, sizeof(*cfg));
5332 		if (rtnh->rtnh_ifindex)
5333 			r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
5334 
5335 		attrlen = rtnh_attrlen(rtnh);
5336 		if (attrlen > 0) {
5337 			struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
5338 
5339 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
5340 			if (nla) {
5341 				err = fib6_gw_from_attr(&r_cfg.fc_gateway, nla,
5342 							extack);
5343 				if (err)
5344 					goto cleanup;
5345 
5346 				r_cfg.fc_flags |= RTF_GATEWAY;
5347 			}
5348 			r_cfg.fc_encap = nla_find(attrs, attrlen, RTA_ENCAP);
5349 
5350 			/* RTA_ENCAP_TYPE length checked in
5351 			 * lwtunnel_valid_encap_type_attr
5352 			 */
5353 			nla = nla_find(attrs, attrlen, RTA_ENCAP_TYPE);
5354 			if (nla)
5355 				r_cfg.fc_encap_type = nla_get_u16(nla);
5356 		}
5357 
5358 		r_cfg.fc_flags |= (rtnh->rtnh_flags & RTNH_F_ONLINK);
5359 		rt = ip6_route_info_create(&r_cfg, GFP_KERNEL, extack);
5360 		if (IS_ERR(rt)) {
5361 			err = PTR_ERR(rt);
5362 			rt = NULL;
5363 			goto cleanup;
5364 		}
5365 		if (!rt6_qualify_for_ecmp(rt)) {
5366 			err = -EINVAL;
5367 			NL_SET_ERR_MSG(extack,
5368 				       "Device only routes can not be added for IPv6 using the multipath API.");
5369 			fib6_info_release(rt);
5370 			goto cleanup;
5371 		}
5372 
5373 		rt->fib6_nh->fib_nh_weight = rtnh->rtnh_hops + 1;
5374 
5375 		err = ip6_route_info_append(info->nl_net, &rt6_nh_list,
5376 					    rt, &r_cfg);
5377 		if (err) {
5378 			fib6_info_release(rt);
5379 			goto cleanup;
5380 		}
5381 
5382 		rtnh = rtnh_next(rtnh, &remaining);
5383 	}
5384 
5385 	if (list_empty(&rt6_nh_list)) {
5386 		NL_SET_ERR_MSG(extack,
5387 			       "Invalid nexthop configuration - no valid nexthops");
5388 		return -EINVAL;
5389 	}
5390 
5391 	/* for add and replace send one notification with all nexthops.
5392 	 * Skip the notification in fib6_add_rt2node and send one with
5393 	 * the full route when done
5394 	 */
5395 	info->skip_notify = 1;
5396 
5397 	/* For add and replace, send one notification with all nexthops. For
5398 	 * append, send one notification with all appended nexthops.
5399 	 */
5400 	info->skip_notify_kernel = 1;
5401 
5402 	err_nh = NULL;
5403 	list_for_each_entry(nh, &rt6_nh_list, next) {
5404 		err = __ip6_ins_rt(nh->fib6_info, info, extack);
5405 
5406 		if (err) {
5407 			if (replace && nhn)
5408 				NL_SET_ERR_MSG_MOD(extack,
5409 						   "multipath route replace failed (check consistency of installed routes)");
5410 			err_nh = nh;
5411 			goto add_errout;
5412 		}
5413 		/* save reference to last route successfully inserted */
5414 		rt_last = nh->fib6_info;
5415 
5416 		/* save reference to first route for notification */
5417 		if (!rt_notif)
5418 			rt_notif = nh->fib6_info;
5419 
5420 		/* Because each route is added like a single route we remove
5421 		 * these flags after the first nexthop: if there is a collision,
5422 		 * we have already failed to add the first nexthop:
5423 		 * fib6_add_rt2node() has rejected it; when replacing, old
5424 		 * nexthops have been replaced by first new, the rest should
5425 		 * be added to it.
5426 		 */
5427 		if (cfg->fc_nlinfo.nlh) {
5428 			cfg->fc_nlinfo.nlh->nlmsg_flags &= ~(NLM_F_EXCL |
5429 							     NLM_F_REPLACE);
5430 			cfg->fc_nlinfo.nlh->nlmsg_flags |= NLM_F_CREATE;
5431 		}
5432 		nhn++;
5433 	}
5434 
5435 	/* An in-kernel notification should only be sent in case the new
5436 	 * multipath route is added as the first route in the node, or if
5437 	 * it was appended to it. We pass 'rt_notif' since it is the first
5438 	 * sibling and might allow us to skip some checks in the replace case.
5439 	 */
5440 	if (ip6_route_mpath_should_notify(rt_notif)) {
5441 		enum fib_event_type fib_event;
5442 
5443 		if (rt_notif->fib6_nsiblings != nhn - 1)
5444 			fib_event = FIB_EVENT_ENTRY_APPEND;
5445 		else
5446 			fib_event = FIB_EVENT_ENTRY_REPLACE;
5447 
5448 		err = call_fib6_multipath_entry_notifiers(info->nl_net,
5449 							  fib_event, rt_notif,
5450 							  nhn - 1, extack);
5451 		if (err) {
5452 			/* Delete all the siblings that were just added */
5453 			err_nh = NULL;
5454 			goto add_errout;
5455 		}
5456 	}
5457 
5458 	/* success ... tell user about new route */
5459 	ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
5460 	goto cleanup;
5461 
5462 add_errout:
5463 	/* send notification for routes that were added so that
5464 	 * the delete notifications sent by ip6_route_del are
5465 	 * coherent
5466 	 */
5467 	if (rt_notif)
5468 		ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
5469 
5470 	/* Delete routes that were already added */
5471 	list_for_each_entry(nh, &rt6_nh_list, next) {
5472 		if (err_nh == nh)
5473 			break;
5474 		ip6_route_del(&nh->r_cfg, extack);
5475 	}
5476 
5477 cleanup:
5478 	list_for_each_entry_safe(nh, nh_safe, &rt6_nh_list, next) {
5479 		fib6_info_release(nh->fib6_info);
5480 		list_del(&nh->next);
5481 		kfree(nh);
5482 	}
5483 
5484 	return err;
5485 }
5486 
ip6_route_multipath_del(struct fib6_config * cfg,struct netlink_ext_ack * extack)5487 static int ip6_route_multipath_del(struct fib6_config *cfg,
5488 				   struct netlink_ext_ack *extack)
5489 {
5490 	struct fib6_config r_cfg;
5491 	struct rtnexthop *rtnh;
5492 	int last_err = 0;
5493 	int remaining;
5494 	int attrlen;
5495 	int err;
5496 
5497 	remaining = cfg->fc_mp_len;
5498 	rtnh = (struct rtnexthop *)cfg->fc_mp;
5499 
5500 	/* Parse a Multipath Entry */
5501 	while (rtnh_ok(rtnh, remaining)) {
5502 		memcpy(&r_cfg, cfg, sizeof(*cfg));
5503 		if (rtnh->rtnh_ifindex)
5504 			r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
5505 
5506 		attrlen = rtnh_attrlen(rtnh);
5507 		if (attrlen > 0) {
5508 			struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
5509 
5510 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
5511 			if (nla) {
5512 				err = fib6_gw_from_attr(&r_cfg.fc_gateway, nla,
5513 							extack);
5514 				if (err) {
5515 					last_err = err;
5516 					goto next_rtnh;
5517 				}
5518 
5519 				r_cfg.fc_flags |= RTF_GATEWAY;
5520 			}
5521 		}
5522 		err = ip6_route_del(&r_cfg, extack);
5523 		if (err)
5524 			last_err = err;
5525 
5526 next_rtnh:
5527 		rtnh = rtnh_next(rtnh, &remaining);
5528 	}
5529 
5530 	return last_err;
5531 }
5532 
inet6_rtm_delroute(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)5533 static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
5534 			      struct netlink_ext_ack *extack)
5535 {
5536 	struct fib6_config cfg;
5537 	int err;
5538 
5539 	err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
5540 	if (err < 0)
5541 		return err;
5542 
5543 	if (cfg.fc_nh_id &&
5544 	    !nexthop_find_by_id(sock_net(skb->sk), cfg.fc_nh_id)) {
5545 		NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
5546 		return -EINVAL;
5547 	}
5548 
5549 	if (cfg.fc_mp)
5550 		return ip6_route_multipath_del(&cfg, extack);
5551 	else {
5552 		cfg.fc_delete_all_nh = 1;
5553 		return ip6_route_del(&cfg, extack);
5554 	}
5555 }
5556 
inet6_rtm_newroute(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)5557 static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
5558 			      struct netlink_ext_ack *extack)
5559 {
5560 	struct fib6_config cfg;
5561 	int err;
5562 
5563 	err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
5564 	if (err < 0)
5565 		return err;
5566 
5567 	if (cfg.fc_metric == 0)
5568 		cfg.fc_metric = IP6_RT_PRIO_USER;
5569 
5570 	if (cfg.fc_mp)
5571 		return ip6_route_multipath_add(&cfg, extack);
5572 	else
5573 		return ip6_route_add(&cfg, GFP_KERNEL, extack);
5574 }
5575 
5576 /* add the overhead of this fib6_nh to nexthop_len */
rt6_nh_nlmsg_size(struct fib6_nh * nh,void * arg)5577 static int rt6_nh_nlmsg_size(struct fib6_nh *nh, void *arg)
5578 {
5579 	int *nexthop_len = arg;
5580 
5581 	*nexthop_len += nla_total_size(0)	 /* RTA_MULTIPATH */
5582 		     + NLA_ALIGN(sizeof(struct rtnexthop))
5583 		     + nla_total_size(16); /* RTA_GATEWAY */
5584 
5585 	if (nh->fib_nh_lws) {
5586 		/* RTA_ENCAP_TYPE */
5587 		*nexthop_len += lwtunnel_get_encap_size(nh->fib_nh_lws);
5588 		/* RTA_ENCAP */
5589 		*nexthop_len += nla_total_size(2);
5590 	}
5591 
5592 	return 0;
5593 }
5594 
rt6_nlmsg_size(struct fib6_info * f6i)5595 static size_t rt6_nlmsg_size(struct fib6_info *f6i)
5596 {
5597 	int nexthop_len;
5598 
5599 	if (f6i->nh) {
5600 		nexthop_len = nla_total_size(4); /* RTA_NH_ID */
5601 		nexthop_for_each_fib6_nh(f6i->nh, rt6_nh_nlmsg_size,
5602 					 &nexthop_len);
5603 	} else {
5604 		struct fib6_nh *nh = f6i->fib6_nh;
5605 		struct fib6_info *sibling;
5606 
5607 		nexthop_len = 0;
5608 		if (f6i->fib6_nsiblings) {
5609 			rt6_nh_nlmsg_size(nh, &nexthop_len);
5610 
5611 			rcu_read_lock();
5612 
5613 			list_for_each_entry_rcu(sibling, &f6i->fib6_siblings,
5614 						fib6_siblings) {
5615 				rt6_nh_nlmsg_size(sibling->fib6_nh, &nexthop_len);
5616 			}
5617 
5618 			rcu_read_unlock();
5619 		}
5620 		nexthop_len += lwtunnel_get_encap_size(nh->fib_nh_lws);
5621 	}
5622 
5623 	return NLMSG_ALIGN(sizeof(struct rtmsg))
5624 	       + nla_total_size(16) /* RTA_SRC */
5625 	       + nla_total_size(16) /* RTA_DST */
5626 	       + nla_total_size(16) /* RTA_GATEWAY */
5627 	       + nla_total_size(16) /* RTA_PREFSRC */
5628 	       + nla_total_size(4) /* RTA_TABLE */
5629 	       + nla_total_size(4) /* RTA_IIF */
5630 	       + nla_total_size(4) /* RTA_OIF */
5631 	       + nla_total_size(4) /* RTA_PRIORITY */
5632 	       + RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
5633 	       + nla_total_size(sizeof(struct rta_cacheinfo))
5634 	       + nla_total_size(TCP_CA_NAME_MAX) /* RTAX_CC_ALGO */
5635 	       + nla_total_size(1) /* RTA_PREF */
5636 	       + nexthop_len;
5637 }
5638 
rt6_fill_node_nexthop(struct sk_buff * skb,struct nexthop * nh,unsigned char * flags)5639 static int rt6_fill_node_nexthop(struct sk_buff *skb, struct nexthop *nh,
5640 				 unsigned char *flags)
5641 {
5642 	if (nexthop_is_multipath(nh)) {
5643 		struct nlattr *mp;
5644 
5645 		mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
5646 		if (!mp)
5647 			goto nla_put_failure;
5648 
5649 		if (nexthop_mpath_fill_node(skb, nh, AF_INET6))
5650 			goto nla_put_failure;
5651 
5652 		nla_nest_end(skb, mp);
5653 	} else {
5654 		struct fib6_nh *fib6_nh;
5655 
5656 		fib6_nh = nexthop_fib6_nh(nh);
5657 		if (fib_nexthop_info(skb, &fib6_nh->nh_common, AF_INET6,
5658 				     flags, false) < 0)
5659 			goto nla_put_failure;
5660 	}
5661 
5662 	return 0;
5663 
5664 nla_put_failure:
5665 	return -EMSGSIZE;
5666 }
5667 
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)5668 static int rt6_fill_node(struct net *net, struct sk_buff *skb,
5669 			 struct fib6_info *rt, struct dst_entry *dst,
5670 			 struct in6_addr *dest, struct in6_addr *src,
5671 			 int iif, int type, u32 portid, u32 seq,
5672 			 unsigned int flags)
5673 {
5674 	struct rt6_info *rt6 = dst_rt6_info(dst);
5675 	struct rt6key *rt6_dst, *rt6_src;
5676 	u32 *pmetrics, table, rt6_flags;
5677 	unsigned char nh_flags = 0;
5678 	struct nlmsghdr *nlh;
5679 	struct rtmsg *rtm;
5680 	long expires = 0;
5681 
5682 	nlh = nlmsg_put(skb, portid, seq, type, sizeof(*rtm), flags);
5683 	if (!nlh)
5684 		return -EMSGSIZE;
5685 
5686 	if (rt6) {
5687 		rt6_dst = &rt6->rt6i_dst;
5688 		rt6_src = &rt6->rt6i_src;
5689 		rt6_flags = rt6->rt6i_flags;
5690 	} else {
5691 		rt6_dst = &rt->fib6_dst;
5692 		rt6_src = &rt->fib6_src;
5693 		rt6_flags = rt->fib6_flags;
5694 	}
5695 
5696 	rtm = nlmsg_data(nlh);
5697 	rtm->rtm_family = AF_INET6;
5698 	rtm->rtm_dst_len = rt6_dst->plen;
5699 	rtm->rtm_src_len = rt6_src->plen;
5700 	rtm->rtm_tos = 0;
5701 	if (rt->fib6_table)
5702 		table = rt->fib6_table->tb6_id;
5703 	else
5704 		table = RT6_TABLE_UNSPEC;
5705 	rtm->rtm_table = table < 256 ? table : RT_TABLE_COMPAT;
5706 	if (nla_put_u32(skb, RTA_TABLE, table))
5707 		goto nla_put_failure;
5708 
5709 	rtm->rtm_type = rt->fib6_type;
5710 	rtm->rtm_flags = 0;
5711 	rtm->rtm_scope = RT_SCOPE_UNIVERSE;
5712 	rtm->rtm_protocol = rt->fib6_protocol;
5713 
5714 	if (rt6_flags & RTF_CACHE)
5715 		rtm->rtm_flags |= RTM_F_CLONED;
5716 
5717 	if (dest) {
5718 		if (nla_put_in6_addr(skb, RTA_DST, dest))
5719 			goto nla_put_failure;
5720 		rtm->rtm_dst_len = 128;
5721 	} else if (rtm->rtm_dst_len)
5722 		if (nla_put_in6_addr(skb, RTA_DST, &rt6_dst->addr))
5723 			goto nla_put_failure;
5724 #ifdef CONFIG_IPV6_SUBTREES
5725 	if (src) {
5726 		if (nla_put_in6_addr(skb, RTA_SRC, src))
5727 			goto nla_put_failure;
5728 		rtm->rtm_src_len = 128;
5729 	} else if (rtm->rtm_src_len &&
5730 		   nla_put_in6_addr(skb, RTA_SRC, &rt6_src->addr))
5731 		goto nla_put_failure;
5732 #endif
5733 	if (iif) {
5734 #ifdef CONFIG_IPV6_MROUTE
5735 		if (ipv6_addr_is_multicast(&rt6_dst->addr)) {
5736 			int err = ip6mr_get_route(net, skb, rtm, portid);
5737 
5738 			if (err == 0)
5739 				return 0;
5740 			if (err < 0)
5741 				goto nla_put_failure;
5742 		} else
5743 #endif
5744 			if (nla_put_u32(skb, RTA_IIF, iif))
5745 				goto nla_put_failure;
5746 	} else if (dest) {
5747 		struct in6_addr saddr_buf;
5748 		if (ip6_route_get_saddr(net, rt, dest, 0, 0, &saddr_buf) == 0 &&
5749 		    nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5750 			goto nla_put_failure;
5751 	}
5752 
5753 	if (rt->fib6_prefsrc.plen) {
5754 		struct in6_addr saddr_buf;
5755 		saddr_buf = rt->fib6_prefsrc.addr;
5756 		if (nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5757 			goto nla_put_failure;
5758 	}
5759 
5760 	pmetrics = dst ? dst_metrics_ptr(dst) : rt->fib6_metrics->metrics;
5761 	if (rtnetlink_put_metrics(skb, pmetrics) < 0)
5762 		goto nla_put_failure;
5763 
5764 	if (nla_put_u32(skb, RTA_PRIORITY, rt->fib6_metric))
5765 		goto nla_put_failure;
5766 
5767 	/* For multipath routes, walk the siblings list and add
5768 	 * each as a nexthop within RTA_MULTIPATH.
5769 	 */
5770 	if (rt6) {
5771 		if (rt6_flags & RTF_GATEWAY &&
5772 		    nla_put_in6_addr(skb, RTA_GATEWAY, &rt6->rt6i_gateway))
5773 			goto nla_put_failure;
5774 
5775 		if (dst->dev && nla_put_u32(skb, RTA_OIF, dst->dev->ifindex))
5776 			goto nla_put_failure;
5777 
5778 		if (dst->lwtstate &&
5779 		    lwtunnel_fill_encap(skb, dst->lwtstate, RTA_ENCAP, RTA_ENCAP_TYPE) < 0)
5780 			goto nla_put_failure;
5781 	} else if (rt->fib6_nsiblings) {
5782 		struct fib6_info *sibling;
5783 		struct nlattr *mp;
5784 
5785 		mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
5786 		if (!mp)
5787 			goto nla_put_failure;
5788 
5789 		if (fib_add_nexthop(skb, &rt->fib6_nh->nh_common,
5790 				    rt->fib6_nh->fib_nh_weight, AF_INET6,
5791 				    0) < 0)
5792 			goto nla_put_failure;
5793 
5794 		rcu_read_lock();
5795 
5796 		list_for_each_entry_rcu(sibling, &rt->fib6_siblings,
5797 					fib6_siblings) {
5798 			if (fib_add_nexthop(skb, &sibling->fib6_nh->nh_common,
5799 					    sibling->fib6_nh->fib_nh_weight,
5800 					    AF_INET6, 0) < 0) {
5801 				rcu_read_unlock();
5802 
5803 				goto nla_put_failure;
5804 			}
5805 		}
5806 
5807 		rcu_read_unlock();
5808 
5809 		nla_nest_end(skb, mp);
5810 	} else if (rt->nh) {
5811 		if (nla_put_u32(skb, RTA_NH_ID, rt->nh->id))
5812 			goto nla_put_failure;
5813 
5814 		if (nexthop_is_blackhole(rt->nh))
5815 			rtm->rtm_type = RTN_BLACKHOLE;
5816 
5817 		if (READ_ONCE(net->ipv4.sysctl_nexthop_compat_mode) &&
5818 		    rt6_fill_node_nexthop(skb, rt->nh, &nh_flags) < 0)
5819 			goto nla_put_failure;
5820 
5821 		rtm->rtm_flags |= nh_flags;
5822 	} else {
5823 		if (fib_nexthop_info(skb, &rt->fib6_nh->nh_common, AF_INET6,
5824 				     &nh_flags, false) < 0)
5825 			goto nla_put_failure;
5826 
5827 		rtm->rtm_flags |= nh_flags;
5828 	}
5829 
5830 	if (rt6_flags & RTF_EXPIRES) {
5831 		expires = dst ? dst->expires : rt->expires;
5832 		expires -= jiffies;
5833 	}
5834 
5835 	if (!dst) {
5836 		if (READ_ONCE(rt->offload))
5837 			rtm->rtm_flags |= RTM_F_OFFLOAD;
5838 		if (READ_ONCE(rt->trap))
5839 			rtm->rtm_flags |= RTM_F_TRAP;
5840 		if (READ_ONCE(rt->offload_failed))
5841 			rtm->rtm_flags |= RTM_F_OFFLOAD_FAILED;
5842 	}
5843 
5844 	if (rtnl_put_cacheinfo(skb, dst, 0, expires, dst ? dst->error : 0) < 0)
5845 		goto nla_put_failure;
5846 
5847 	if (nla_put_u8(skb, RTA_PREF, IPV6_EXTRACT_PREF(rt6_flags)))
5848 		goto nla_put_failure;
5849 
5850 
5851 	nlmsg_end(skb, nlh);
5852 	return 0;
5853 
5854 nla_put_failure:
5855 	nlmsg_cancel(skb, nlh);
5856 	return -EMSGSIZE;
5857 }
5858 
fib6_info_nh_uses_dev(struct fib6_nh * nh,void * arg)5859 static int fib6_info_nh_uses_dev(struct fib6_nh *nh, void *arg)
5860 {
5861 	const struct net_device *dev = arg;
5862 
5863 	if (nh->fib_nh_dev == dev)
5864 		return 1;
5865 
5866 	return 0;
5867 }
5868 
fib6_info_uses_dev(const struct fib6_info * f6i,const struct net_device * dev)5869 static bool fib6_info_uses_dev(const struct fib6_info *f6i,
5870 			       const struct net_device *dev)
5871 {
5872 	if (f6i->nh) {
5873 		struct net_device *_dev = (struct net_device *)dev;
5874 
5875 		return !!nexthop_for_each_fib6_nh(f6i->nh,
5876 						  fib6_info_nh_uses_dev,
5877 						  _dev);
5878 	}
5879 
5880 	if (f6i->fib6_nh->fib_nh_dev == dev)
5881 		return true;
5882 
5883 	if (f6i->fib6_nsiblings) {
5884 		struct fib6_info *sibling, *next_sibling;
5885 
5886 		list_for_each_entry_safe(sibling, next_sibling,
5887 					 &f6i->fib6_siblings, fib6_siblings) {
5888 			if (sibling->fib6_nh->fib_nh_dev == dev)
5889 				return true;
5890 		}
5891 	}
5892 
5893 	return false;
5894 }
5895 
5896 struct fib6_nh_exception_dump_walker {
5897 	struct rt6_rtnl_dump_arg *dump;
5898 	struct fib6_info *rt;
5899 	unsigned int flags;
5900 	unsigned int skip;
5901 	unsigned int count;
5902 };
5903 
rt6_nh_dump_exceptions(struct fib6_nh * nh,void * arg)5904 static int rt6_nh_dump_exceptions(struct fib6_nh *nh, void *arg)
5905 {
5906 	struct fib6_nh_exception_dump_walker *w = arg;
5907 	struct rt6_rtnl_dump_arg *dump = w->dump;
5908 	struct rt6_exception_bucket *bucket;
5909 	struct rt6_exception *rt6_ex;
5910 	int i, err;
5911 
5912 	bucket = fib6_nh_get_excptn_bucket(nh, NULL);
5913 	if (!bucket)
5914 		return 0;
5915 
5916 	for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
5917 		hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
5918 			if (w->skip) {
5919 				w->skip--;
5920 				continue;
5921 			}
5922 
5923 			/* Expiration of entries doesn't bump sernum, insertion
5924 			 * does. Removal is triggered by insertion, so we can
5925 			 * rely on the fact that if entries change between two
5926 			 * partial dumps, this node is scanned again completely,
5927 			 * see rt6_insert_exception() and fib6_dump_table().
5928 			 *
5929 			 * Count expired entries we go through as handled
5930 			 * entries that we'll skip next time, in case of partial
5931 			 * node dump. Otherwise, if entries expire meanwhile,
5932 			 * we'll skip the wrong amount.
5933 			 */
5934 			if (rt6_check_expired(rt6_ex->rt6i)) {
5935 				w->count++;
5936 				continue;
5937 			}
5938 
5939 			err = rt6_fill_node(dump->net, dump->skb, w->rt,
5940 					    &rt6_ex->rt6i->dst, NULL, NULL, 0,
5941 					    RTM_NEWROUTE,
5942 					    NETLINK_CB(dump->cb->skb).portid,
5943 					    dump->cb->nlh->nlmsg_seq, w->flags);
5944 			if (err)
5945 				return err;
5946 
5947 			w->count++;
5948 		}
5949 		bucket++;
5950 	}
5951 
5952 	return 0;
5953 }
5954 
5955 /* 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)5956 int rt6_dump_route(struct fib6_info *rt, void *p_arg, unsigned int skip)
5957 {
5958 	struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
5959 	struct fib_dump_filter *filter = &arg->filter;
5960 	unsigned int flags = NLM_F_MULTI;
5961 	struct net *net = arg->net;
5962 	int count = 0;
5963 
5964 	if (rt == net->ipv6.fib6_null_entry)
5965 		return -1;
5966 
5967 	if ((filter->flags & RTM_F_PREFIX) &&
5968 	    !(rt->fib6_flags & RTF_PREFIX_RT)) {
5969 		/* success since this is not a prefix route */
5970 		return -1;
5971 	}
5972 	if (filter->filter_set &&
5973 	    ((filter->rt_type  && rt->fib6_type != filter->rt_type) ||
5974 	     (filter->dev      && !fib6_info_uses_dev(rt, filter->dev)) ||
5975 	     (filter->protocol && rt->fib6_protocol != filter->protocol))) {
5976 		return -1;
5977 	}
5978 
5979 	if (filter->filter_set ||
5980 	    !filter->dump_routes || !filter->dump_exceptions) {
5981 		flags |= NLM_F_DUMP_FILTERED;
5982 	}
5983 
5984 	if (filter->dump_routes) {
5985 		if (skip) {
5986 			skip--;
5987 		} else {
5988 			if (rt6_fill_node(net, arg->skb, rt, NULL, NULL, NULL,
5989 					  0, RTM_NEWROUTE,
5990 					  NETLINK_CB(arg->cb->skb).portid,
5991 					  arg->cb->nlh->nlmsg_seq, flags)) {
5992 				return 0;
5993 			}
5994 			count++;
5995 		}
5996 	}
5997 
5998 	if (filter->dump_exceptions) {
5999 		struct fib6_nh_exception_dump_walker w = { .dump = arg,
6000 							   .rt = rt,
6001 							   .flags = flags,
6002 							   .skip = skip,
6003 							   .count = 0 };
6004 		int err;
6005 
6006 		rcu_read_lock();
6007 		if (rt->nh) {
6008 			err = nexthop_for_each_fib6_nh(rt->nh,
6009 						       rt6_nh_dump_exceptions,
6010 						       &w);
6011 		} else {
6012 			err = rt6_nh_dump_exceptions(rt->fib6_nh, &w);
6013 		}
6014 		rcu_read_unlock();
6015 
6016 		if (err)
6017 			return count + w.count;
6018 	}
6019 
6020 	return -1;
6021 }
6022 
inet6_rtm_valid_getroute_req(struct sk_buff * skb,const struct nlmsghdr * nlh,struct nlattr ** tb,struct netlink_ext_ack * extack)6023 static int inet6_rtm_valid_getroute_req(struct sk_buff *skb,
6024 					const struct nlmsghdr *nlh,
6025 					struct nlattr **tb,
6026 					struct netlink_ext_ack *extack)
6027 {
6028 	struct rtmsg *rtm;
6029 	int i, err;
6030 
6031 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) {
6032 		NL_SET_ERR_MSG_MOD(extack,
6033 				   "Invalid header for get route request");
6034 		return -EINVAL;
6035 	}
6036 
6037 	if (!netlink_strict_get_check(skb))
6038 		return nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
6039 					      rtm_ipv6_policy, extack);
6040 
6041 	rtm = nlmsg_data(nlh);
6042 	if ((rtm->rtm_src_len && rtm->rtm_src_len != 128) ||
6043 	    (rtm->rtm_dst_len && rtm->rtm_dst_len != 128) ||
6044 	    rtm->rtm_table || rtm->rtm_protocol || rtm->rtm_scope ||
6045 	    rtm->rtm_type) {
6046 		NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for get route request");
6047 		return -EINVAL;
6048 	}
6049 	if (rtm->rtm_flags & ~RTM_F_FIB_MATCH) {
6050 		NL_SET_ERR_MSG_MOD(extack,
6051 				   "Invalid flags for get route request");
6052 		return -EINVAL;
6053 	}
6054 
6055 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
6056 					    rtm_ipv6_policy, extack);
6057 	if (err)
6058 		return err;
6059 
6060 	if ((tb[RTA_SRC] && !rtm->rtm_src_len) ||
6061 	    (tb[RTA_DST] && !rtm->rtm_dst_len)) {
6062 		NL_SET_ERR_MSG_MOD(extack, "rtm_src_len and rtm_dst_len must be 128 for IPv6");
6063 		return -EINVAL;
6064 	}
6065 
6066 	if (tb[RTA_FLOWLABEL] &&
6067 	    (nla_get_be32(tb[RTA_FLOWLABEL]) & ~IPV6_FLOWLABEL_MASK)) {
6068 		NL_SET_ERR_MSG_ATTR(extack, tb[RTA_FLOWLABEL],
6069 				    "Invalid flow label");
6070 		return -EINVAL;
6071 	}
6072 
6073 	for (i = 0; i <= RTA_MAX; i++) {
6074 		if (!tb[i])
6075 			continue;
6076 
6077 		switch (i) {
6078 		case RTA_SRC:
6079 		case RTA_DST:
6080 		case RTA_IIF:
6081 		case RTA_OIF:
6082 		case RTA_MARK:
6083 		case RTA_UID:
6084 		case RTA_SPORT:
6085 		case RTA_DPORT:
6086 		case RTA_IP_PROTO:
6087 		case RTA_FLOWLABEL:
6088 			break;
6089 		default:
6090 			NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in get route request");
6091 			return -EINVAL;
6092 		}
6093 	}
6094 
6095 	return 0;
6096 }
6097 
inet6_rtm_getroute(struct sk_buff * in_skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)6098 static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
6099 			      struct netlink_ext_ack *extack)
6100 {
6101 	struct net *net = sock_net(in_skb->sk);
6102 	struct nlattr *tb[RTA_MAX+1];
6103 	int err, iif = 0, oif = 0;
6104 	struct fib6_info *from;
6105 	struct dst_entry *dst;
6106 	struct rt6_info *rt;
6107 	struct sk_buff *skb;
6108 	struct rtmsg *rtm;
6109 	struct flowi6 fl6 = {};
6110 	__be32 flowlabel;
6111 	bool fibmatch;
6112 
6113 	err = inet6_rtm_valid_getroute_req(in_skb, nlh, tb, extack);
6114 	if (err < 0)
6115 		goto errout;
6116 
6117 	err = -EINVAL;
6118 	rtm = nlmsg_data(nlh);
6119 	fibmatch = !!(rtm->rtm_flags & RTM_F_FIB_MATCH);
6120 
6121 	if (tb[RTA_SRC]) {
6122 		if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
6123 			goto errout;
6124 
6125 		fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
6126 	}
6127 
6128 	if (tb[RTA_DST]) {
6129 		if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
6130 			goto errout;
6131 
6132 		fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
6133 	}
6134 
6135 	if (tb[RTA_IIF])
6136 		iif = nla_get_u32(tb[RTA_IIF]);
6137 
6138 	if (tb[RTA_OIF])
6139 		oif = nla_get_u32(tb[RTA_OIF]);
6140 
6141 	if (tb[RTA_MARK])
6142 		fl6.flowi6_mark = nla_get_u32(tb[RTA_MARK]);
6143 
6144 	if (tb[RTA_UID])
6145 		fl6.flowi6_uid = make_kuid(current_user_ns(),
6146 					   nla_get_u32(tb[RTA_UID]));
6147 	else
6148 		fl6.flowi6_uid = iif ? INVALID_UID : current_uid();
6149 
6150 	if (tb[RTA_SPORT])
6151 		fl6.fl6_sport = nla_get_be16(tb[RTA_SPORT]);
6152 
6153 	if (tb[RTA_DPORT])
6154 		fl6.fl6_dport = nla_get_be16(tb[RTA_DPORT]);
6155 
6156 	if (tb[RTA_IP_PROTO]) {
6157 		err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO],
6158 						  &fl6.flowi6_proto, AF_INET6,
6159 						  extack);
6160 		if (err)
6161 			goto errout;
6162 	}
6163 
6164 	flowlabel = nla_get_be32_default(tb[RTA_FLOWLABEL], 0);
6165 	fl6.flowlabel = ip6_make_flowinfo(rtm->rtm_tos, flowlabel);
6166 
6167 	if (iif) {
6168 		struct net_device *dev;
6169 		int flags = 0;
6170 
6171 		rcu_read_lock();
6172 
6173 		dev = dev_get_by_index_rcu(net, iif);
6174 		if (!dev) {
6175 			rcu_read_unlock();
6176 			err = -ENODEV;
6177 			goto errout;
6178 		}
6179 
6180 		fl6.flowi6_iif = iif;
6181 
6182 		if (!ipv6_addr_any(&fl6.saddr))
6183 			flags |= RT6_LOOKUP_F_HAS_SADDR;
6184 
6185 		dst = ip6_route_input_lookup(net, dev, &fl6, NULL, flags);
6186 
6187 		rcu_read_unlock();
6188 	} else {
6189 		fl6.flowi6_oif = oif;
6190 
6191 		dst = ip6_route_output(net, NULL, &fl6);
6192 	}
6193 
6194 
6195 	rt = dst_rt6_info(dst);
6196 	if (rt->dst.error) {
6197 		err = rt->dst.error;
6198 		ip6_rt_put(rt);
6199 		goto errout;
6200 	}
6201 
6202 	if (rt == net->ipv6.ip6_null_entry) {
6203 		err = rt->dst.error;
6204 		ip6_rt_put(rt);
6205 		goto errout;
6206 	}
6207 
6208 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
6209 	if (!skb) {
6210 		ip6_rt_put(rt);
6211 		err = -ENOBUFS;
6212 		goto errout;
6213 	}
6214 
6215 	skb_dst_set(skb, &rt->dst);
6216 
6217 	rcu_read_lock();
6218 	from = rcu_dereference(rt->from);
6219 	if (from) {
6220 		if (fibmatch)
6221 			err = rt6_fill_node(net, skb, from, NULL, NULL, NULL,
6222 					    iif, RTM_NEWROUTE,
6223 					    NETLINK_CB(in_skb).portid,
6224 					    nlh->nlmsg_seq, 0);
6225 		else
6226 			err = rt6_fill_node(net, skb, from, dst, &fl6.daddr,
6227 					    &fl6.saddr, iif, RTM_NEWROUTE,
6228 					    NETLINK_CB(in_skb).portid,
6229 					    nlh->nlmsg_seq, 0);
6230 	} else {
6231 		err = -ENETUNREACH;
6232 	}
6233 	rcu_read_unlock();
6234 
6235 	if (err < 0) {
6236 		kfree_skb(skb);
6237 		goto errout;
6238 	}
6239 
6240 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
6241 errout:
6242 	return err;
6243 }
6244 
inet6_rt_notify(int event,struct fib6_info * rt,struct nl_info * info,unsigned int nlm_flags)6245 void inet6_rt_notify(int event, struct fib6_info *rt, struct nl_info *info,
6246 		     unsigned int nlm_flags)
6247 {
6248 	struct sk_buff *skb;
6249 	struct net *net = info->nl_net;
6250 	u32 seq;
6251 	int err;
6252 
6253 	err = -ENOBUFS;
6254 	seq = info->nlh ? info->nlh->nlmsg_seq : 0;
6255 
6256 	skb = nlmsg_new(rt6_nlmsg_size(rt), GFP_ATOMIC);
6257 	if (!skb)
6258 		goto errout;
6259 
6260 	err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
6261 			    event, info->portid, seq, nlm_flags);
6262 	if (err < 0) {
6263 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6264 		WARN_ON(err == -EMSGSIZE);
6265 		kfree_skb(skb);
6266 		goto errout;
6267 	}
6268 	rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
6269 		    info->nlh, GFP_ATOMIC);
6270 	return;
6271 errout:
6272 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6273 }
6274 
fib6_rt_update(struct net * net,struct fib6_info * rt,struct nl_info * info)6275 void fib6_rt_update(struct net *net, struct fib6_info *rt,
6276 		    struct nl_info *info)
6277 {
6278 	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
6279 	struct sk_buff *skb;
6280 	int err = -ENOBUFS;
6281 
6282 	skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
6283 	if (!skb)
6284 		goto errout;
6285 
6286 	err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
6287 			    RTM_NEWROUTE, info->portid, seq, NLM_F_REPLACE);
6288 	if (err < 0) {
6289 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6290 		WARN_ON(err == -EMSGSIZE);
6291 		kfree_skb(skb);
6292 		goto errout;
6293 	}
6294 	rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
6295 		    info->nlh, gfp_any());
6296 	return;
6297 errout:
6298 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6299 }
6300 
fib6_info_hw_flags_set(struct net * net,struct fib6_info * f6i,bool offload,bool trap,bool offload_failed)6301 void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i,
6302 			    bool offload, bool trap, bool offload_failed)
6303 {
6304 	struct sk_buff *skb;
6305 	int err;
6306 
6307 	if (READ_ONCE(f6i->offload) == offload &&
6308 	    READ_ONCE(f6i->trap) == trap &&
6309 	    READ_ONCE(f6i->offload_failed) == offload_failed)
6310 		return;
6311 
6312 	WRITE_ONCE(f6i->offload, offload);
6313 	WRITE_ONCE(f6i->trap, trap);
6314 
6315 	/* 2 means send notifications only if offload_failed was changed. */
6316 	if (net->ipv6.sysctl.fib_notify_on_flag_change == 2 &&
6317 	    READ_ONCE(f6i->offload_failed) == offload_failed)
6318 		return;
6319 
6320 	WRITE_ONCE(f6i->offload_failed, offload_failed);
6321 
6322 	if (!rcu_access_pointer(f6i->fib6_node))
6323 		/* The route was removed from the tree, do not send
6324 		 * notification.
6325 		 */
6326 		return;
6327 
6328 	if (!net->ipv6.sysctl.fib_notify_on_flag_change)
6329 		return;
6330 
6331 	skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_KERNEL);
6332 	if (!skb) {
6333 		err = -ENOBUFS;
6334 		goto errout;
6335 	}
6336 
6337 	err = rt6_fill_node(net, skb, f6i, NULL, NULL, NULL, 0, RTM_NEWROUTE, 0,
6338 			    0, 0);
6339 	if (err < 0) {
6340 		/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6341 		WARN_ON(err == -EMSGSIZE);
6342 		kfree_skb(skb);
6343 		goto errout;
6344 	}
6345 
6346 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_ROUTE, NULL, GFP_KERNEL);
6347 	return;
6348 
6349 errout:
6350 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
6351 }
6352 EXPORT_SYMBOL(fib6_info_hw_flags_set);
6353 
ip6_route_dev_notify(struct notifier_block * this,unsigned long event,void * ptr)6354 static int ip6_route_dev_notify(struct notifier_block *this,
6355 				unsigned long event, void *ptr)
6356 {
6357 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
6358 	struct net *net = dev_net(dev);
6359 
6360 	if (!(dev->flags & IFF_LOOPBACK))
6361 		return NOTIFY_OK;
6362 
6363 	if (event == NETDEV_REGISTER) {
6364 		net->ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = dev;
6365 		net->ipv6.ip6_null_entry->dst.dev = dev;
6366 		net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
6367 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6368 		net->ipv6.ip6_prohibit_entry->dst.dev = dev;
6369 		net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
6370 		net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
6371 		net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
6372 #endif
6373 	 } else if (event == NETDEV_UNREGISTER &&
6374 		    dev->reg_state != NETREG_UNREGISTERED) {
6375 		/* NETDEV_UNREGISTER could be fired for multiple times by
6376 		 * netdev_wait_allrefs(). Make sure we only call this once.
6377 		 */
6378 		in6_dev_put_clear(&net->ipv6.ip6_null_entry->rt6i_idev);
6379 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6380 		in6_dev_put_clear(&net->ipv6.ip6_prohibit_entry->rt6i_idev);
6381 		in6_dev_put_clear(&net->ipv6.ip6_blk_hole_entry->rt6i_idev);
6382 #endif
6383 	}
6384 
6385 	return NOTIFY_OK;
6386 }
6387 
6388 /*
6389  *	/proc
6390  */
6391 
6392 #ifdef CONFIG_PROC_FS
rt6_stats_seq_show(struct seq_file * seq,void * v)6393 static int rt6_stats_seq_show(struct seq_file *seq, void *v)
6394 {
6395 	struct net *net = (struct net *)seq->private;
6396 	seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
6397 		   net->ipv6.rt6_stats->fib_nodes,
6398 		   net->ipv6.rt6_stats->fib_route_nodes,
6399 		   atomic_read(&net->ipv6.rt6_stats->fib_rt_alloc),
6400 		   net->ipv6.rt6_stats->fib_rt_entries,
6401 		   net->ipv6.rt6_stats->fib_rt_cache,
6402 		   dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
6403 		   net->ipv6.rt6_stats->fib_discarded_routes);
6404 
6405 	return 0;
6406 }
6407 #endif	/* CONFIG_PROC_FS */
6408 
6409 #ifdef CONFIG_SYSCTL
6410 
ipv6_sysctl_rtcache_flush(const struct ctl_table * ctl,int write,void * buffer,size_t * lenp,loff_t * ppos)6411 static int ipv6_sysctl_rtcache_flush(const struct ctl_table *ctl, int write,
6412 			      void *buffer, size_t *lenp, loff_t *ppos)
6413 {
6414 	struct net *net;
6415 	int delay;
6416 	int ret;
6417 	if (!write)
6418 		return -EINVAL;
6419 
6420 	ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
6421 	if (ret)
6422 		return ret;
6423 
6424 	net = (struct net *)ctl->extra1;
6425 	delay = net->ipv6.sysctl.flush_delay;
6426 	fib6_run_gc(delay <= 0 ? 0 : (unsigned long)delay, net, delay > 0);
6427 	return 0;
6428 }
6429 
6430 static struct ctl_table ipv6_route_table_template[] = {
6431 	{
6432 		.procname	=	"max_size",
6433 		.data		=	&init_net.ipv6.sysctl.ip6_rt_max_size,
6434 		.maxlen		=	sizeof(int),
6435 		.mode		=	0644,
6436 		.proc_handler	=	proc_dointvec,
6437 	},
6438 	{
6439 		.procname	=	"gc_thresh",
6440 		.data		=	&ip6_dst_ops_template.gc_thresh,
6441 		.maxlen		=	sizeof(int),
6442 		.mode		=	0644,
6443 		.proc_handler	=	proc_dointvec,
6444 	},
6445 	{
6446 		.procname	=	"flush",
6447 		.data		=	&init_net.ipv6.sysctl.flush_delay,
6448 		.maxlen		=	sizeof(int),
6449 		.mode		=	0200,
6450 		.proc_handler	=	ipv6_sysctl_rtcache_flush
6451 	},
6452 	{
6453 		.procname	=	"gc_min_interval",
6454 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
6455 		.maxlen		=	sizeof(int),
6456 		.mode		=	0644,
6457 		.proc_handler	=	proc_dointvec_jiffies,
6458 	},
6459 	{
6460 		.procname	=	"gc_timeout",
6461 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_timeout,
6462 		.maxlen		=	sizeof(int),
6463 		.mode		=	0644,
6464 		.proc_handler	=	proc_dointvec_jiffies,
6465 	},
6466 	{
6467 		.procname	=	"gc_interval",
6468 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_interval,
6469 		.maxlen		=	sizeof(int),
6470 		.mode		=	0644,
6471 		.proc_handler	=	proc_dointvec_jiffies,
6472 	},
6473 	{
6474 		.procname	=	"gc_elasticity",
6475 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
6476 		.maxlen		=	sizeof(int),
6477 		.mode		=	0644,
6478 		.proc_handler	=	proc_dointvec,
6479 	},
6480 	{
6481 		.procname	=	"mtu_expires",
6482 		.data		=	&init_net.ipv6.sysctl.ip6_rt_mtu_expires,
6483 		.maxlen		=	sizeof(int),
6484 		.mode		=	0644,
6485 		.proc_handler	=	proc_dointvec_jiffies,
6486 	},
6487 	{
6488 		.procname	=	"min_adv_mss",
6489 		.data		=	&init_net.ipv6.sysctl.ip6_rt_min_advmss,
6490 		.maxlen		=	sizeof(int),
6491 		.mode		=	0644,
6492 		.proc_handler	=	proc_dointvec,
6493 	},
6494 	{
6495 		.procname	=	"gc_min_interval_ms",
6496 		.data		=	&init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
6497 		.maxlen		=	sizeof(int),
6498 		.mode		=	0644,
6499 		.proc_handler	=	proc_dointvec_ms_jiffies,
6500 	},
6501 	{
6502 		.procname	=	"skip_notify_on_dev_down",
6503 		.data		=	&init_net.ipv6.sysctl.skip_notify_on_dev_down,
6504 		.maxlen		=	sizeof(u8),
6505 		.mode		=	0644,
6506 		.proc_handler	=	proc_dou8vec_minmax,
6507 		.extra1		=	SYSCTL_ZERO,
6508 		.extra2		=	SYSCTL_ONE,
6509 	},
6510 };
6511 
ipv6_route_sysctl_init(struct net * net)6512 struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
6513 {
6514 	struct ctl_table *table;
6515 
6516 	table = kmemdup(ipv6_route_table_template,
6517 			sizeof(ipv6_route_table_template),
6518 			GFP_KERNEL);
6519 
6520 	if (table) {
6521 		table[0].data = &net->ipv6.sysctl.ip6_rt_max_size;
6522 		table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
6523 		table[2].data = &net->ipv6.sysctl.flush_delay;
6524 		table[2].extra1 = net;
6525 		table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
6526 		table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
6527 		table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
6528 		table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
6529 		table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
6530 		table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
6531 		table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
6532 		table[10].data = &net->ipv6.sysctl.skip_notify_on_dev_down;
6533 	}
6534 
6535 	return table;
6536 }
6537 
ipv6_route_sysctl_table_size(struct net * net)6538 size_t ipv6_route_sysctl_table_size(struct net *net)
6539 {
6540 	/* Don't export sysctls to unprivileged users */
6541 	if (net->user_ns != &init_user_ns)
6542 		return 1;
6543 
6544 	return ARRAY_SIZE(ipv6_route_table_template);
6545 }
6546 #endif
6547 
ip6_route_net_init(struct net * net)6548 static int __net_init ip6_route_net_init(struct net *net)
6549 {
6550 	int ret = -ENOMEM;
6551 
6552 	memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
6553 	       sizeof(net->ipv6.ip6_dst_ops));
6554 
6555 	if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
6556 		goto out_ip6_dst_ops;
6557 
6558 	net->ipv6.fib6_null_entry = fib6_info_alloc(GFP_KERNEL, true);
6559 	if (!net->ipv6.fib6_null_entry)
6560 		goto out_ip6_dst_entries;
6561 	memcpy(net->ipv6.fib6_null_entry, &fib6_null_entry_template,
6562 	       sizeof(*net->ipv6.fib6_null_entry));
6563 
6564 	net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
6565 					   sizeof(*net->ipv6.ip6_null_entry),
6566 					   GFP_KERNEL);
6567 	if (!net->ipv6.ip6_null_entry)
6568 		goto out_fib6_null_entry;
6569 	net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6570 	dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
6571 			 ip6_template_metrics, true);
6572 	INIT_LIST_HEAD(&net->ipv6.ip6_null_entry->dst.rt_uncached);
6573 
6574 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6575 	net->ipv6.fib6_has_custom_rules = false;
6576 	net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
6577 					       sizeof(*net->ipv6.ip6_prohibit_entry),
6578 					       GFP_KERNEL);
6579 	if (!net->ipv6.ip6_prohibit_entry)
6580 		goto out_ip6_null_entry;
6581 	net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6582 	dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
6583 			 ip6_template_metrics, true);
6584 	INIT_LIST_HEAD(&net->ipv6.ip6_prohibit_entry->dst.rt_uncached);
6585 
6586 	net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
6587 					       sizeof(*net->ipv6.ip6_blk_hole_entry),
6588 					       GFP_KERNEL);
6589 	if (!net->ipv6.ip6_blk_hole_entry)
6590 		goto out_ip6_prohibit_entry;
6591 	net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
6592 	dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
6593 			 ip6_template_metrics, true);
6594 	INIT_LIST_HEAD(&net->ipv6.ip6_blk_hole_entry->dst.rt_uncached);
6595 #ifdef CONFIG_IPV6_SUBTREES
6596 	net->ipv6.fib6_routes_require_src = 0;
6597 #endif
6598 #endif
6599 
6600 	net->ipv6.sysctl.flush_delay = 0;
6601 	net->ipv6.sysctl.ip6_rt_max_size = INT_MAX;
6602 	net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
6603 	net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
6604 	net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
6605 	net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
6606 	net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
6607 	net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
6608 	net->ipv6.sysctl.skip_notify_on_dev_down = 0;
6609 
6610 	atomic_set(&net->ipv6.ip6_rt_gc_expire, 30*HZ);
6611 
6612 	ret = 0;
6613 out:
6614 	return ret;
6615 
6616 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6617 out_ip6_prohibit_entry:
6618 	kfree(net->ipv6.ip6_prohibit_entry);
6619 out_ip6_null_entry:
6620 	kfree(net->ipv6.ip6_null_entry);
6621 #endif
6622 out_fib6_null_entry:
6623 	kfree(net->ipv6.fib6_null_entry);
6624 out_ip6_dst_entries:
6625 	dst_entries_destroy(&net->ipv6.ip6_dst_ops);
6626 out_ip6_dst_ops:
6627 	goto out;
6628 }
6629 
ip6_route_net_exit(struct net * net)6630 static void __net_exit ip6_route_net_exit(struct net *net)
6631 {
6632 	kfree(net->ipv6.fib6_null_entry);
6633 	kfree(net->ipv6.ip6_null_entry);
6634 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6635 	kfree(net->ipv6.ip6_prohibit_entry);
6636 	kfree(net->ipv6.ip6_blk_hole_entry);
6637 #endif
6638 	dst_entries_destroy(&net->ipv6.ip6_dst_ops);
6639 }
6640 
ip6_route_net_init_late(struct net * net)6641 static int __net_init ip6_route_net_init_late(struct net *net)
6642 {
6643 #ifdef CONFIG_PROC_FS
6644 	if (!proc_create_net("ipv6_route", 0, net->proc_net,
6645 			     &ipv6_route_seq_ops,
6646 			     sizeof(struct ipv6_route_iter)))
6647 		return -ENOMEM;
6648 
6649 	if (!proc_create_net_single("rt6_stats", 0444, net->proc_net,
6650 				    rt6_stats_seq_show, NULL)) {
6651 		remove_proc_entry("ipv6_route", net->proc_net);
6652 		return -ENOMEM;
6653 	}
6654 #endif
6655 	return 0;
6656 }
6657 
ip6_route_net_exit_late(struct net * net)6658 static void __net_exit ip6_route_net_exit_late(struct net *net)
6659 {
6660 #ifdef CONFIG_PROC_FS
6661 	remove_proc_entry("ipv6_route", net->proc_net);
6662 	remove_proc_entry("rt6_stats", net->proc_net);
6663 #endif
6664 }
6665 
6666 static struct pernet_operations ip6_route_net_ops = {
6667 	.init = ip6_route_net_init,
6668 	.exit = ip6_route_net_exit,
6669 };
6670 
ipv6_inetpeer_init(struct net * net)6671 static int __net_init ipv6_inetpeer_init(struct net *net)
6672 {
6673 	struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
6674 
6675 	if (!bp)
6676 		return -ENOMEM;
6677 	inet_peer_base_init(bp);
6678 	net->ipv6.peers = bp;
6679 	return 0;
6680 }
6681 
ipv6_inetpeer_exit(struct net * net)6682 static void __net_exit ipv6_inetpeer_exit(struct net *net)
6683 {
6684 	struct inet_peer_base *bp = net->ipv6.peers;
6685 
6686 	net->ipv6.peers = NULL;
6687 	inetpeer_invalidate_tree(bp);
6688 	kfree(bp);
6689 }
6690 
6691 static struct pernet_operations ipv6_inetpeer_ops = {
6692 	.init	=	ipv6_inetpeer_init,
6693 	.exit	=	ipv6_inetpeer_exit,
6694 };
6695 
6696 static struct pernet_operations ip6_route_net_late_ops = {
6697 	.init = ip6_route_net_init_late,
6698 	.exit = ip6_route_net_exit_late,
6699 };
6700 
6701 static struct notifier_block ip6_route_dev_notifier = {
6702 	.notifier_call = ip6_route_dev_notify,
6703 	.priority = ADDRCONF_NOTIFY_PRIORITY - 10,
6704 };
6705 
ip6_route_init_special_entries(void)6706 void __init ip6_route_init_special_entries(void)
6707 {
6708 	/* Registering of the loopback is done before this portion of code,
6709 	 * the loopback reference in rt6_info will not be taken, do it
6710 	 * manually for init_net */
6711 	init_net.ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = init_net.loopback_dev;
6712 	init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
6713 	init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6714   #ifdef CONFIG_IPV6_MULTIPLE_TABLES
6715 	init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
6716 	init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6717 	init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
6718 	init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
6719   #endif
6720 }
6721 
6722 #if IS_BUILTIN(CONFIG_IPV6)
6723 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
6724 DEFINE_BPF_ITER_FUNC(ipv6_route, struct bpf_iter_meta *meta, struct fib6_info *rt)
6725 
6726 BTF_ID_LIST(btf_fib6_info_id)
6727 BTF_ID(struct, fib6_info)
6728 
6729 static const struct bpf_iter_seq_info ipv6_route_seq_info = {
6730 	.seq_ops		= &ipv6_route_seq_ops,
6731 	.init_seq_private	= bpf_iter_init_seq_net,
6732 	.fini_seq_private	= bpf_iter_fini_seq_net,
6733 	.seq_priv_size		= sizeof(struct ipv6_route_iter),
6734 };
6735 
6736 static struct bpf_iter_reg ipv6_route_reg_info = {
6737 	.target			= "ipv6_route",
6738 	.ctx_arg_info_size	= 1,
6739 	.ctx_arg_info		= {
6740 		{ offsetof(struct bpf_iter__ipv6_route, rt),
6741 		  PTR_TO_BTF_ID_OR_NULL },
6742 	},
6743 	.seq_info		= &ipv6_route_seq_info,
6744 };
6745 
bpf_iter_register(void)6746 static int __init bpf_iter_register(void)
6747 {
6748 	ipv6_route_reg_info.ctx_arg_info[0].btf_id = *btf_fib6_info_id;
6749 	return bpf_iter_reg_target(&ipv6_route_reg_info);
6750 }
6751 
bpf_iter_unregister(void)6752 static void bpf_iter_unregister(void)
6753 {
6754 	bpf_iter_unreg_target(&ipv6_route_reg_info);
6755 }
6756 #endif
6757 #endif
6758 
6759 static const struct rtnl_msg_handler ip6_route_rtnl_msg_handlers[] __initconst_or_module = {
6760 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_NEWROUTE,
6761 	 .doit = inet6_rtm_newroute},
6762 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_DELROUTE,
6763 	 .doit = inet6_rtm_delroute},
6764 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETROUTE,
6765 	 .doit = inet6_rtm_getroute, .flags = RTNL_FLAG_DOIT_UNLOCKED},
6766 };
6767 
ip6_route_init(void)6768 int __init ip6_route_init(void)
6769 {
6770 	int ret;
6771 	int cpu;
6772 
6773 	ret = -ENOMEM;
6774 	ip6_dst_ops_template.kmem_cachep =
6775 		kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
6776 				  SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT, NULL);
6777 	if (!ip6_dst_ops_template.kmem_cachep)
6778 		goto out;
6779 
6780 	ret = dst_entries_init(&ip6_dst_blackhole_ops);
6781 	if (ret)
6782 		goto out_kmem_cache;
6783 
6784 	ret = register_pernet_subsys(&ipv6_inetpeer_ops);
6785 	if (ret)
6786 		goto out_dst_entries;
6787 
6788 	ret = register_pernet_subsys(&ip6_route_net_ops);
6789 	if (ret)
6790 		goto out_register_inetpeer;
6791 
6792 	ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
6793 
6794 	ret = fib6_init();
6795 	if (ret)
6796 		goto out_register_subsys;
6797 
6798 	ret = xfrm6_init();
6799 	if (ret)
6800 		goto out_fib6_init;
6801 
6802 	ret = fib6_rules_init();
6803 	if (ret)
6804 		goto xfrm6_init;
6805 
6806 	ret = register_pernet_subsys(&ip6_route_net_late_ops);
6807 	if (ret)
6808 		goto fib6_rules_init;
6809 
6810 	ret = rtnl_register_many(ip6_route_rtnl_msg_handlers);
6811 	if (ret < 0)
6812 		goto out_register_late_subsys;
6813 
6814 	ret = register_netdevice_notifier(&ip6_route_dev_notifier);
6815 	if (ret)
6816 		goto out_register_late_subsys;
6817 
6818 #if IS_BUILTIN(CONFIG_IPV6)
6819 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
6820 	ret = bpf_iter_register();
6821 	if (ret)
6822 		goto out_register_late_subsys;
6823 #endif
6824 #endif
6825 
6826 	for_each_possible_cpu(cpu) {
6827 		struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu);
6828 
6829 		INIT_LIST_HEAD(&ul->head);
6830 		spin_lock_init(&ul->lock);
6831 	}
6832 
6833 out:
6834 	return ret;
6835 
6836 out_register_late_subsys:
6837 	rtnl_unregister_all(PF_INET6);
6838 	unregister_pernet_subsys(&ip6_route_net_late_ops);
6839 fib6_rules_init:
6840 	fib6_rules_cleanup();
6841 xfrm6_init:
6842 	xfrm6_fini();
6843 out_fib6_init:
6844 	fib6_gc_cleanup();
6845 out_register_subsys:
6846 	unregister_pernet_subsys(&ip6_route_net_ops);
6847 out_register_inetpeer:
6848 	unregister_pernet_subsys(&ipv6_inetpeer_ops);
6849 out_dst_entries:
6850 	dst_entries_destroy(&ip6_dst_blackhole_ops);
6851 out_kmem_cache:
6852 	kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
6853 	goto out;
6854 }
6855 
ip6_route_cleanup(void)6856 void ip6_route_cleanup(void)
6857 {
6858 #if IS_BUILTIN(CONFIG_IPV6)
6859 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
6860 	bpf_iter_unregister();
6861 #endif
6862 #endif
6863 	unregister_netdevice_notifier(&ip6_route_dev_notifier);
6864 	unregister_pernet_subsys(&ip6_route_net_late_ops);
6865 	fib6_rules_cleanup();
6866 	xfrm6_fini();
6867 	fib6_gc_cleanup();
6868 	unregister_pernet_subsys(&ipv6_inetpeer_ops);
6869 	unregister_pernet_subsys(&ip6_route_net_ops);
6870 	dst_entries_destroy(&ip6_dst_blackhole_ops);
6871 	kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
6872 }
6873