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