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