xref: /linux/net/ipv4/fib_semantics.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		IPv4 Forwarding Information Base: semantics.
8  *
9  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  */
11 
12 #include <linux/uaccess.h>
13 #include <linux/bitops.h>
14 #include <linux/types.h>
15 #include <linux/kernel.h>
16 #include <linux/jiffies.h>
17 #include <linux/mm.h>
18 #include <linux/string.h>
19 #include <linux/socket.h>
20 #include <linux/sockios.h>
21 #include <linux/errno.h>
22 #include <linux/in.h>
23 #include <linux/inet.h>
24 #include <linux/inetdevice.h>
25 #include <linux/netdevice.h>
26 #include <linux/if_arp.h>
27 #include <linux/proc_fs.h>
28 #include <linux/skbuff.h>
29 #include <linux/init.h>
30 #include <linux/slab.h>
31 #include <linux/netlink.h>
32 #include <linux/hash.h>
33 #include <linux/nospec.h>
34 
35 #include <net/arp.h>
36 #include <net/inet_dscp.h>
37 #include <net/ip.h>
38 #include <net/protocol.h>
39 #include <net/route.h>
40 #include <net/tcp.h>
41 #include <net/sock.h>
42 #include <net/ip_fib.h>
43 #include <net/ip6_fib.h>
44 #include <net/nexthop.h>
45 #include <net/netlink.h>
46 #include <net/rtnh.h>
47 #include <net/lwtunnel.h>
48 #include <net/fib_notifier.h>
49 #include <net/addrconf.h>
50 
51 #include "fib_lookup.h"
52 
53 /* for_nexthops and change_nexthops only used when nexthop object
54  * is not set in a fib_info. The logic within can reference fib_nh.
55  */
56 #ifdef CONFIG_IP_ROUTE_MULTIPATH
57 
58 #define for_nexthops(fi) {						\
59 	int nhsel; const struct fib_nh *nh;				\
60 	for (nhsel = 0, nh = (fi)->fib_nh;				\
61 	     nhsel < fib_info_num_path((fi));				\
62 	     nh++, nhsel++)
63 
64 #define change_nexthops(fi) {						\
65 	int nhsel; struct fib_nh *nexthop_nh;				\
66 	for (nhsel = 0,	nexthop_nh = (struct fib_nh *)((fi)->fib_nh);	\
67 	     nhsel < fib_info_num_path((fi));				\
68 	     nexthop_nh++, nhsel++)
69 
70 #else /* CONFIG_IP_ROUTE_MULTIPATH */
71 
72 /* Hope, that gcc will optimize it to get rid of dummy loop */
73 
74 #define for_nexthops(fi) {						\
75 	int nhsel; const struct fib_nh *nh = (fi)->fib_nh;		\
76 	for (nhsel = 0; nhsel < 1; nhsel++)
77 
78 #define change_nexthops(fi) {						\
79 	int nhsel;							\
80 	struct fib_nh *nexthop_nh = (struct fib_nh *)((fi)->fib_nh);	\
81 	for (nhsel = 0; nhsel < 1; nhsel++)
82 
83 #endif /* CONFIG_IP_ROUTE_MULTIPATH */
84 
85 #define endfor_nexthops(fi) }
86 
87 
88 const struct fib_prop fib_props[RTN_MAX + 1] = {
89 	[RTN_UNSPEC] = {
90 		.error	= 0,
91 		.scope	= RT_SCOPE_NOWHERE,
92 	},
93 	[RTN_UNICAST] = {
94 		.error	= 0,
95 		.scope	= RT_SCOPE_UNIVERSE,
96 	},
97 	[RTN_LOCAL] = {
98 		.error	= 0,
99 		.scope	= RT_SCOPE_HOST,
100 	},
101 	[RTN_BROADCAST] = {
102 		.error	= 0,
103 		.scope	= RT_SCOPE_LINK,
104 	},
105 	[RTN_ANYCAST] = {
106 		.error	= 0,
107 		.scope	= RT_SCOPE_LINK,
108 	},
109 	[RTN_MULTICAST] = {
110 		.error	= 0,
111 		.scope	= RT_SCOPE_UNIVERSE,
112 	},
113 	[RTN_BLACKHOLE] = {
114 		.error	= -EINVAL,
115 		.scope	= RT_SCOPE_UNIVERSE,
116 	},
117 	[RTN_UNREACHABLE] = {
118 		.error	= -EHOSTUNREACH,
119 		.scope	= RT_SCOPE_UNIVERSE,
120 	},
121 	[RTN_PROHIBIT] = {
122 		.error	= -EACCES,
123 		.scope	= RT_SCOPE_UNIVERSE,
124 	},
125 	[RTN_THROW] = {
126 		.error	= -EAGAIN,
127 		.scope	= RT_SCOPE_UNIVERSE,
128 	},
129 	[RTN_NAT] = {
130 		.error	= -EINVAL,
131 		.scope	= RT_SCOPE_NOWHERE,
132 	},
133 	[RTN_XRESOLVE] = {
134 		.error	= -EINVAL,
135 		.scope	= RT_SCOPE_NOWHERE,
136 	},
137 };
138 
rt_fibinfo_free(struct rtable __rcu ** rtp)139 static void rt_fibinfo_free(struct rtable __rcu **rtp)
140 {
141 	struct rtable *rt = rcu_dereference_protected(*rtp, 1);
142 
143 	if (!rt)
144 		return;
145 
146 	/* Not even needed : RCU_INIT_POINTER(*rtp, NULL);
147 	 * because we waited an RCU grace period before calling
148 	 * free_fib_info_rcu()
149 	 */
150 
151 	dst_dev_put(&rt->dst);
152 	dst_release_immediate(&rt->dst);
153 }
154 
free_nh_exceptions(struct fib_nh_common * nhc)155 static void free_nh_exceptions(struct fib_nh_common *nhc)
156 {
157 	struct fnhe_hash_bucket *hash;
158 	int i;
159 
160 	hash = rcu_dereference_protected(nhc->nhc_exceptions, 1);
161 	if (!hash)
162 		return;
163 	for (i = 0; i < FNHE_HASH_SIZE; i++) {
164 		struct fib_nh_exception *fnhe;
165 
166 		fnhe = rcu_dereference_protected(hash[i].chain, 1);
167 		while (fnhe) {
168 			struct fib_nh_exception *next;
169 
170 			next = rcu_dereference_protected(fnhe->fnhe_next, 1);
171 
172 			rt_fibinfo_free(&fnhe->fnhe_rth_input);
173 			rt_fibinfo_free(&fnhe->fnhe_rth_output);
174 
175 			kfree(fnhe);
176 
177 			fnhe = next;
178 		}
179 	}
180 	kfree(hash);
181 }
182 
rt_fibinfo_free_cpus(struct rtable __rcu * __percpu * rtp)183 static void rt_fibinfo_free_cpus(struct rtable __rcu * __percpu *rtp)
184 {
185 	int cpu;
186 
187 	if (!rtp)
188 		return;
189 
190 	for_each_possible_cpu(cpu) {
191 		struct rtable *rt;
192 
193 		rt = rcu_dereference_protected(*per_cpu_ptr(rtp, cpu), 1);
194 		if (rt) {
195 			dst_dev_put(&rt->dst);
196 			dst_release_immediate(&rt->dst);
197 		}
198 	}
199 	free_percpu(rtp);
200 }
201 
fib_nh_common_release(struct fib_nh_common * nhc)202 void fib_nh_common_release(struct fib_nh_common *nhc)
203 {
204 	netdev_put(nhc->nhc_dev, &nhc->nhc_dev_tracker);
205 	lwtstate_put(nhc->nhc_lwtstate);
206 	rt_fibinfo_free_cpus(nhc->nhc_pcpu_rth_output);
207 	rt_fibinfo_free(&nhc->nhc_rth_input);
208 	free_nh_exceptions(nhc);
209 }
210 
fib_nh_release(struct net * net,struct fib_nh * fib_nh)211 void fib_nh_release(struct net *net, struct fib_nh *fib_nh)
212 {
213 #ifdef CONFIG_IP_ROUTE_CLASSID
214 	if (fib_nh->nh_tclassid)
215 		atomic_dec(&net->ipv4.fib_num_tclassid_users);
216 #endif
217 	fib_nh_common_release(&fib_nh->nh_common);
218 }
219 
220 /* Release a nexthop info record */
free_fib_info_rcu(struct rcu_head * head)221 static void free_fib_info_rcu(struct rcu_head *head)
222 {
223 	struct fib_info *fi = container_of(head, struct fib_info, rcu);
224 
225 	if (fi->nh) {
226 		nexthop_put(fi->nh);
227 	} else {
228 		change_nexthops(fi) {
229 			fib_nh_release(fi->fib_net, nexthop_nh);
230 		} endfor_nexthops(fi);
231 	}
232 
233 	ip_fib_metrics_put(fi->fib_metrics);
234 
235 	kfree(fi);
236 }
237 
free_fib_info(struct fib_info * fi)238 void free_fib_info(struct fib_info *fi)
239 {
240 	if (fi->fib_dead == 0) {
241 		pr_warn("Freeing alive fib_info %p\n", fi);
242 		return;
243 	}
244 
245 	call_rcu_hurry(&fi->rcu, free_fib_info_rcu);
246 }
247 EXPORT_SYMBOL_GPL(free_fib_info);
248 
fib_release_info(struct fib_info * fi)249 void fib_release_info(struct fib_info *fi)
250 {
251 	ASSERT_RTNL();
252 	if (fi && refcount_dec_and_test(&fi->fib_treeref)) {
253 		hlist_del(&fi->fib_hash);
254 		fi->fib_net->ipv4.fib_info_cnt--;
255 
256 		if (fi->fib_prefsrc)
257 			hlist_del(&fi->fib_lhash);
258 		if (fi->nh) {
259 			list_del(&fi->nh_list);
260 		} else {
261 			change_nexthops(fi) {
262 				if (!nexthop_nh->fib_nh_dev)
263 					continue;
264 				hlist_del_rcu(&nexthop_nh->nh_hash);
265 			} endfor_nexthops(fi)
266 		}
267 		/* Paired with READ_ONCE() from fib_table_lookup() */
268 		WRITE_ONCE(fi->fib_dead, 1);
269 		fib_info_put(fi);
270 	}
271 }
272 
nh_comp(struct fib_info * fi,struct fib_info * ofi)273 static inline int nh_comp(struct fib_info *fi, struct fib_info *ofi)
274 {
275 	const struct fib_nh *onh;
276 
277 	if (fi->nh || ofi->nh)
278 		return nexthop_cmp(fi->nh, ofi->nh) ? 0 : -1;
279 
280 	if (ofi->fib_nhs == 0)
281 		return 0;
282 
283 	for_nexthops(fi) {
284 		onh = fib_info_nh(ofi, nhsel);
285 
286 		if (nh->fib_nh_oif != onh->fib_nh_oif ||
287 		    nh->fib_nh_gw_family != onh->fib_nh_gw_family ||
288 		    nh->fib_nh_scope != onh->fib_nh_scope ||
289 #ifdef CONFIG_IP_ROUTE_MULTIPATH
290 		    nh->fib_nh_weight != onh->fib_nh_weight ||
291 #endif
292 #ifdef CONFIG_IP_ROUTE_CLASSID
293 		    nh->nh_tclassid != onh->nh_tclassid ||
294 #endif
295 		    lwtunnel_cmp_encap(nh->fib_nh_lws, onh->fib_nh_lws) ||
296 		    ((nh->fib_nh_flags ^ onh->fib_nh_flags) & ~RTNH_COMPARE_MASK))
297 			return -1;
298 
299 		if (nh->fib_nh_gw_family == AF_INET &&
300 		    nh->fib_nh_gw4 != onh->fib_nh_gw4)
301 			return -1;
302 
303 		if (nh->fib_nh_gw_family == AF_INET6 &&
304 		    ipv6_addr_cmp(&nh->fib_nh_gw6, &onh->fib_nh_gw6))
305 			return -1;
306 	} endfor_nexthops(fi);
307 	return 0;
308 }
309 
fib_nh_head(struct net_device * dev)310 static struct hlist_head *fib_nh_head(struct net_device *dev)
311 {
312 	return &dev->fib_nh_head;
313 }
314 
fib_info_hashfn_1(int init_val,u8 protocol,u8 scope,u32 prefsrc,u32 priority)315 static unsigned int fib_info_hashfn_1(int init_val, u8 protocol, u8 scope,
316 				      u32 prefsrc, u32 priority)
317 {
318 	unsigned int val = init_val;
319 
320 	val ^= (protocol << 8) | scope;
321 	val ^= prefsrc;
322 	val ^= priority;
323 
324 	return val;
325 }
326 
fib_info_hashfn_result(const struct net * net,unsigned int val)327 static unsigned int fib_info_hashfn_result(const struct net *net,
328 					   unsigned int val)
329 {
330 	return hash_32(val ^ net_hash_mix(net), net->ipv4.fib_info_hash_bits);
331 }
332 
fib_info_hash_bucket(struct fib_info * fi)333 static struct hlist_head *fib_info_hash_bucket(struct fib_info *fi)
334 {
335 	struct net *net = fi->fib_net;
336 	unsigned int val;
337 
338 	val = fib_info_hashfn_1(fi->fib_nhs, fi->fib_protocol,
339 				fi->fib_scope, (__force u32)fi->fib_prefsrc,
340 				fi->fib_priority);
341 
342 	if (fi->nh) {
343 		val ^= fi->nh->id;
344 	} else {
345 		for_nexthops(fi) {
346 			val ^= nh->fib_nh_oif;
347 		} endfor_nexthops(fi)
348 	}
349 
350 	return &net->ipv4.fib_info_hash[fib_info_hashfn_result(net, val)];
351 }
352 
fib_info_laddrhash_bucket(const struct net * net,__be32 val)353 static struct hlist_head *fib_info_laddrhash_bucket(const struct net *net,
354 						    __be32 val)
355 {
356 	unsigned int hash_bits = net->ipv4.fib_info_hash_bits;
357 	u32 slot;
358 
359 	slot = hash_32(net_hash_mix(net) ^ (__force u32)val, hash_bits);
360 
361 	return &net->ipv4.fib_info_hash[(1 << hash_bits) + slot];
362 }
363 
fib_info_hash_alloc(unsigned int hash_bits)364 static struct hlist_head *fib_info_hash_alloc(unsigned int hash_bits)
365 {
366 	/* The second half is used for prefsrc */
367 	return kvzalloc_objs(struct hlist_head, (1 << hash_bits) * 2);
368 }
369 
fib_info_hash_free(struct hlist_head * head)370 static void fib_info_hash_free(struct hlist_head *head)
371 {
372 	kvfree(head);
373 }
374 
fib_info_hash_grow(struct net * net)375 static void fib_info_hash_grow(struct net *net)
376 {
377 	unsigned int old_size = 1 << net->ipv4.fib_info_hash_bits;
378 	struct hlist_head *new_info_hash, *old_info_hash;
379 	unsigned int i;
380 
381 	if (net->ipv4.fib_info_cnt < old_size)
382 		return;
383 
384 	new_info_hash = fib_info_hash_alloc(net->ipv4.fib_info_hash_bits + 1);
385 	if (!new_info_hash)
386 		return;
387 
388 	old_info_hash = net->ipv4.fib_info_hash;
389 	net->ipv4.fib_info_hash = new_info_hash;
390 	net->ipv4.fib_info_hash_bits += 1;
391 
392 	for (i = 0; i < old_size; i++) {
393 		struct hlist_head *head = &old_info_hash[i];
394 		struct hlist_node *n;
395 		struct fib_info *fi;
396 
397 		hlist_for_each_entry_safe(fi, n, head, fib_hash)
398 			hlist_add_head(&fi->fib_hash, fib_info_hash_bucket(fi));
399 	}
400 
401 	for (i = 0; i < old_size; i++) {
402 		struct hlist_head *lhead = &old_info_hash[old_size + i];
403 		struct hlist_node *n;
404 		struct fib_info *fi;
405 
406 		hlist_for_each_entry_safe(fi, n, lhead, fib_lhash)
407 			hlist_add_head(&fi->fib_lhash,
408 				       fib_info_laddrhash_bucket(fi->fib_net,
409 								 fi->fib_prefsrc));
410 	}
411 
412 	fib_info_hash_free(old_info_hash);
413 }
414 
415 /* no metrics, only nexthop id */
fib_find_info_nh(struct net * net,const struct fib_config * cfg)416 static struct fib_info *fib_find_info_nh(struct net *net,
417 					 const struct fib_config *cfg)
418 {
419 	struct hlist_head *head;
420 	struct fib_info *fi;
421 	unsigned int hash;
422 
423 	hash = fib_info_hashfn_1(cfg->fc_nh_id,
424 				 cfg->fc_protocol, cfg->fc_scope,
425 				 (__force u32)cfg->fc_prefsrc,
426 				 cfg->fc_priority);
427 	hash = fib_info_hashfn_result(net, hash);
428 	head = &net->ipv4.fib_info_hash[hash];
429 
430 	hlist_for_each_entry(fi, head, fib_hash) {
431 		if (!fi->nh || fi->nh->id != cfg->fc_nh_id)
432 			continue;
433 
434 		if (cfg->fc_protocol == fi->fib_protocol &&
435 		    cfg->fc_scope == fi->fib_scope &&
436 		    cfg->fc_prefsrc == fi->fib_prefsrc &&
437 		    cfg->fc_priority == fi->fib_priority &&
438 		    cfg->fc_type == fi->fib_type &&
439 		    cfg->fc_table == fi->fib_tb_id &&
440 		    !((cfg->fc_flags ^ fi->fib_flags) & ~RTNH_COMPARE_MASK))
441 			return fi;
442 	}
443 
444 	return NULL;
445 }
446 
fib_find_info(struct fib_info * nfi)447 static struct fib_info *fib_find_info(struct fib_info *nfi)
448 {
449 	struct hlist_head *head = fib_info_hash_bucket(nfi);
450 	struct fib_info *fi;
451 
452 	hlist_for_each_entry(fi, head, fib_hash) {
453 		if (fi->fib_nhs != nfi->fib_nhs)
454 			continue;
455 
456 		if (nfi->fib_protocol == fi->fib_protocol &&
457 		    nfi->fib_scope == fi->fib_scope &&
458 		    nfi->fib_prefsrc == fi->fib_prefsrc &&
459 		    nfi->fib_priority == fi->fib_priority &&
460 		    nfi->fib_type == fi->fib_type &&
461 		    nfi->fib_tb_id == fi->fib_tb_id &&
462 		    memcmp(nfi->fib_metrics, fi->fib_metrics,
463 			   sizeof(u32) * RTAX_MAX) == 0 &&
464 		    !((nfi->fib_flags ^ fi->fib_flags) & ~RTNH_COMPARE_MASK) &&
465 		    nh_comp(fi, nfi) == 0)
466 			return fi;
467 	}
468 
469 	return NULL;
470 }
471 
472 /* Check, that the gateway is already configured.
473  * Used only by redirect accept routine, under rcu_read_lock();
474  */
ip_fib_check_default(__be32 gw,struct net_device * dev)475 int ip_fib_check_default(__be32 gw, struct net_device *dev)
476 {
477 	struct hlist_head *head;
478 	struct fib_nh *nh;
479 
480 	head = fib_nh_head(dev);
481 
482 	hlist_for_each_entry_rcu(nh, head, nh_hash) {
483 		DEBUG_NET_WARN_ON_ONCE(nh->fib_nh_dev != dev);
484 		if (nh->fib_nh_gw4 == gw &&
485 		    !(nh->fib_nh_flags & RTNH_F_DEAD)) {
486 			return 0;
487 		}
488 	}
489 
490 	return -1;
491 }
492 
fib_nexthop_nlmsg_size(const struct fib_nh_common * nhc,bool skip_oif)493 static size_t fib_nexthop_nlmsg_size(const struct fib_nh_common *nhc,
494 				     bool skip_oif)
495 {
496 	size_t nhsize = 0;
497 
498 	switch (nhc->nhc_gw_family) {
499 	case AF_INET:
500 		nhsize += nla_total_size(4); /* RTA_GATEWAY */
501 		break;
502 	case AF_INET6:
503 		nhsize += nla_total_size(sizeof(struct rtvia) +
504 					 sizeof(struct in6_addr));
505 		break;
506 	}
507 
508 	if (!skip_oif && nhc->nhc_dev)
509 		nhsize += nla_total_size(4); /* RTA_OIF */
510 
511 	if (nhc->nhc_lwtstate) {
512 		/* RTA_ENCAP */
513 		nhsize += lwtunnel_get_encap_size(nhc->nhc_lwtstate);
514 		/* RTA_ENCAP_TYPE */
515 		nhsize += nla_total_size(2);
516 	}
517 
518 	return nhsize;
519 }
520 
fib_nlmsg_size(struct fib_info * fi)521 size_t fib_nlmsg_size(struct fib_info *fi)
522 {
523 	size_t payload = NLMSG_ALIGN(sizeof(struct rtmsg))
524 			 + nla_total_size(4) /* RTA_TABLE */
525 			 + nla_total_size(4) /* RTA_DST */
526 			 + nla_total_size(4) /* RTA_PRIORITY */
527 			 + nla_total_size(4) /* RTA_PREFSRC */
528 			 + nla_total_size(TCP_CA_NAME_MAX); /* RTAX_CC_ALGO */
529 	unsigned int nhs = fib_info_num_path(fi);
530 
531 	/* space for nested metrics */
532 	payload += nla_total_size((RTAX_MAX * nla_total_size(4)));
533 
534 	if (fi->nh)
535 		payload += nla_total_size(4); /* RTA_NH_ID */
536 
537 	if (nhs) {
538 		size_t mpsize = 0;
539 		unsigned int i;
540 
541 		for (i = 0; i < fib_info_num_path(fi); i++) {
542 			struct fib_nh_common *nhc = fib_info_nhc(fi, i);
543 			size_t nhsize;
544 
545 			nhsize = fib_nexthop_nlmsg_size(nhc, nhs != 1);
546 
547 			if (nhs != 1)
548 				nhsize += NLA_ALIGN(sizeof(struct rtnexthop));
549 
550 #ifdef CONFIG_IP_ROUTE_CLASSID
551 			if (nhc->nhc_family == AF_INET) {
552 				struct fib_nh *nh;
553 
554 				nh = container_of(nhc, struct fib_nh, nh_common);
555 				if (nh->nh_tclassid)
556 					nhsize += nla_total_size(4);
557 			}
558 #endif
559 			if (nhs == 1)
560 				payload += nhsize;
561 			else
562 				mpsize += nhsize;
563 		}
564 
565 		if (nhs != 1)
566 			payload += nla_total_size(mpsize);
567 	}
568 
569 	return payload;
570 }
571 
rtmsg_fib(int event,__be32 key,struct fib_alias * fa,int dst_len,u32 tb_id,const struct nl_info * info,unsigned int nlm_flags)572 void rtmsg_fib(int event, __be32 key, struct fib_alias *fa,
573 	       int dst_len, u32 tb_id, const struct nl_info *info,
574 	       unsigned int nlm_flags)
575 {
576 	struct fib_rt_info fri;
577 	struct sk_buff *skb;
578 	u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
579 	int err = -ENOBUFS;
580 
581 	skb = nlmsg_new(fib_nlmsg_size(fa->fa_info), GFP_KERNEL);
582 	if (!skb)
583 		goto errout;
584 
585 	fri.fi = fa->fa_info;
586 	fri.tb_id = tb_id;
587 	fri.dst = key;
588 	fri.dst_len = dst_len;
589 	fri.dscp = fa->fa_dscp;
590 	fri.type = fa->fa_type;
591 	fri.offload = READ_ONCE(fa->offload);
592 	fri.trap = READ_ONCE(fa->trap);
593 	fri.offload_failed = READ_ONCE(fa->offload_failed);
594 	err = fib_dump_info(skb, info->portid, seq, event, &fri, nlm_flags);
595 	if (err < 0) {
596 		/* -EMSGSIZE implies BUG in fib_nlmsg_size() */
597 		WARN_ON(err == -EMSGSIZE);
598 		kfree_skb(skb);
599 		goto errout;
600 	}
601 	rtnl_notify(skb, info->nl_net, info->portid, RTNLGRP_IPV4_ROUTE,
602 		    info->nlh, GFP_KERNEL);
603 	return;
604 errout:
605 	rtnl_set_sk_err(info->nl_net, RTNLGRP_IPV4_ROUTE, err);
606 }
607 
fib_detect_death(struct fib_info * fi,int order,struct fib_info ** last_resort,int * last_idx,int dflt)608 static int fib_detect_death(struct fib_info *fi, int order,
609 			    struct fib_info **last_resort, int *last_idx,
610 			    int dflt)
611 {
612 	const struct fib_nh_common *nhc = fib_info_nhc(fi, 0);
613 	struct neighbour *n;
614 	int state = NUD_NONE;
615 
616 	if (likely(nhc->nhc_gw_family == AF_INET))
617 		n = neigh_lookup(&arp_tbl, &nhc->nhc_gw.ipv4, nhc->nhc_dev);
618 	else if (IS_ENABLED(CONFIG_IPV6) && nhc->nhc_gw_family == AF_INET6)
619 		n = neigh_lookup(&nd_tbl, &nhc->nhc_gw.ipv6, nhc->nhc_dev);
620 	else
621 		n = NULL;
622 
623 	if (n) {
624 		state = READ_ONCE(n->nud_state);
625 		neigh_release(n);
626 	} else {
627 		return 0;
628 	}
629 	if (state == NUD_REACHABLE)
630 		return 0;
631 	if ((state & NUD_VALID) && order != dflt)
632 		return 0;
633 	if ((state & NUD_VALID) ||
634 	    (*last_idx < 0 && order > dflt && state != NUD_INCOMPLETE)) {
635 		*last_resort = fi;
636 		*last_idx = order;
637 	}
638 	return 1;
639 }
640 
fib_nh_common_init(struct net * net,struct fib_nh_common * nhc,struct nlattr * encap,u16 encap_type,void * cfg,gfp_t gfp_flags,struct netlink_ext_ack * extack)641 int fib_nh_common_init(struct net *net, struct fib_nh_common *nhc,
642 		       struct nlattr *encap, u16 encap_type,
643 		       void *cfg, gfp_t gfp_flags,
644 		       struct netlink_ext_ack *extack)
645 {
646 	int err;
647 
648 	nhc->nhc_pcpu_rth_output = alloc_percpu_gfp(struct rtable __rcu *,
649 						    gfp_flags);
650 	if (!nhc->nhc_pcpu_rth_output)
651 		return -ENOMEM;
652 
653 	if (encap) {
654 		struct lwtunnel_state *lwtstate;
655 
656 		err = lwtunnel_build_state(net, encap_type, encap,
657 					   nhc->nhc_family, cfg, &lwtstate,
658 					   extack);
659 		if (err)
660 			goto lwt_failure;
661 
662 		nhc->nhc_lwtstate = lwtstate_get(lwtstate);
663 	}
664 
665 	return 0;
666 
667 lwt_failure:
668 	rt_fibinfo_free_cpus(nhc->nhc_pcpu_rth_output);
669 	nhc->nhc_pcpu_rth_output = NULL;
670 	return err;
671 }
672 
fib_nh_init(struct net * net,struct fib_nh * nh,struct fib_config * cfg,int nh_weight,struct netlink_ext_ack * extack)673 int fib_nh_init(struct net *net, struct fib_nh *nh,
674 		struct fib_config *cfg, int nh_weight,
675 		struct netlink_ext_ack *extack)
676 {
677 	int err;
678 
679 	nh->fib_nh_family = AF_INET;
680 
681 	err = fib_nh_common_init(net, &nh->nh_common, cfg->fc_encap,
682 				 cfg->fc_encap_type, cfg, GFP_KERNEL, extack);
683 	if (err)
684 		return err;
685 
686 	nh->fib_nh_oif = cfg->fc_oif;
687 	nh->fib_nh_gw_family = cfg->fc_gw_family;
688 	if (cfg->fc_gw_family == AF_INET)
689 		nh->fib_nh_gw4 = cfg->fc_gw4;
690 	else if (cfg->fc_gw_family == AF_INET6)
691 		nh->fib_nh_gw6 = cfg->fc_gw6;
692 
693 	nh->fib_nh_flags = cfg->fc_flags;
694 
695 #ifdef CONFIG_IP_ROUTE_CLASSID
696 	nh->nh_tclassid = cfg->fc_flow;
697 	if (nh->nh_tclassid)
698 		atomic_inc(&net->ipv4.fib_num_tclassid_users);
699 #endif
700 #ifdef CONFIG_IP_ROUTE_MULTIPATH
701 	nh->fib_nh_weight = nh_weight;
702 #endif
703 	return 0;
704 }
705 
706 #ifdef CONFIG_IP_ROUTE_MULTIPATH
707 
fib_count_nexthops(struct rtnexthop * rtnh,int remaining,struct netlink_ext_ack * extack)708 static int fib_count_nexthops(struct rtnexthop *rtnh, int remaining,
709 			      struct netlink_ext_ack *extack)
710 {
711 	int nhs = 0;
712 
713 	while (rtnh_ok(rtnh, remaining)) {
714 		nhs++;
715 		rtnh = rtnh_next(rtnh, &remaining);
716 	}
717 
718 	/* leftover implies invalid nexthop configuration, discard it */
719 	if (remaining > 0) {
720 		NL_SET_ERR_MSG(extack,
721 			       "Invalid nexthop configuration - extra data after nexthops");
722 		nhs = 0;
723 	}
724 
725 	return nhs;
726 }
727 
fib_gw_from_attr(__be32 * gw,struct nlattr * nla,struct netlink_ext_ack * extack)728 static int fib_gw_from_attr(__be32 *gw, struct nlattr *nla,
729 			    struct netlink_ext_ack *extack)
730 {
731 	if (nla_len(nla) < sizeof(*gw)) {
732 		NL_SET_ERR_MSG(extack, "Invalid IPv4 address in RTA_GATEWAY");
733 		return -EINVAL;
734 	}
735 
736 	*gw = nla_get_in_addr(nla);
737 
738 	return 0;
739 }
740 
741 /* only called when fib_nh is integrated into fib_info */
fib_get_nhs(struct fib_info * fi,struct rtnexthop * rtnh,int remaining,struct fib_config * cfg,struct netlink_ext_ack * extack)742 static int fib_get_nhs(struct fib_info *fi, struct rtnexthop *rtnh,
743 		       int remaining, struct fib_config *cfg,
744 		       struct netlink_ext_ack *extack)
745 {
746 	struct net *net = fi->fib_net;
747 	struct fib_config fib_cfg;
748 	struct fib_nh *nh;
749 	int ret;
750 
751 	change_nexthops(fi) {
752 		int attrlen;
753 
754 		memset(&fib_cfg, 0, sizeof(fib_cfg));
755 
756 		if (!rtnh_ok(rtnh, remaining)) {
757 			NL_SET_ERR_MSG(extack,
758 				       "Invalid nexthop configuration - extra data after nexthop");
759 			return -EINVAL;
760 		}
761 
762 		if (rtnh->rtnh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN)) {
763 			NL_SET_ERR_MSG(extack,
764 				       "Invalid flags for nexthop - can not contain DEAD or LINKDOWN");
765 			return -EINVAL;
766 		}
767 
768 		fib_cfg.fc_flags = (cfg->fc_flags & ~0xFF) | rtnh->rtnh_flags;
769 		fib_cfg.fc_oif = rtnh->rtnh_ifindex;
770 
771 		attrlen = rtnh_attrlen(rtnh);
772 		if (attrlen > 0) {
773 			struct nlattr *nla, *nlav, *attrs = rtnh_attrs(rtnh);
774 
775 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
776 			nlav = nla_find(attrs, attrlen, RTA_VIA);
777 			if (nla && nlav) {
778 				NL_SET_ERR_MSG(extack,
779 					       "Nexthop configuration can not contain both GATEWAY and VIA");
780 				return -EINVAL;
781 			}
782 			if (nla) {
783 				ret = fib_gw_from_attr(&fib_cfg.fc_gw4, nla,
784 						       extack);
785 				if (ret)
786 					goto errout;
787 
788 				if (fib_cfg.fc_gw4)
789 					fib_cfg.fc_gw_family = AF_INET;
790 			} else if (nlav) {
791 				ret = fib_gw_from_via(&fib_cfg, nlav, extack);
792 				if (ret)
793 					goto errout;
794 			}
795 
796 			nla = nla_find(attrs, attrlen, RTA_FLOW);
797 			if (nla) {
798 				if (nla_len(nla) < sizeof(u32)) {
799 					NL_SET_ERR_MSG(extack, "Invalid RTA_FLOW");
800 					return -EINVAL;
801 				}
802 				fib_cfg.fc_flow = nla_get_u32(nla);
803 			}
804 
805 			fib_cfg.fc_encap = nla_find(attrs, attrlen, RTA_ENCAP);
806 			/* RTA_ENCAP_TYPE length checked in
807 			 * lwtunnel_valid_encap_type_attr
808 			 */
809 			nla = nla_find(attrs, attrlen, RTA_ENCAP_TYPE);
810 			if (nla)
811 				fib_cfg.fc_encap_type = nla_get_u16(nla);
812 		}
813 
814 		ret = fib_nh_init(net, nexthop_nh, &fib_cfg,
815 				  rtnh->rtnh_hops + 1, extack);
816 		if (ret)
817 			goto errout;
818 
819 		rtnh = rtnh_next(rtnh, &remaining);
820 	} endfor_nexthops(fi);
821 
822 	ret = -EINVAL;
823 	nh = fib_info_nh(fi, 0);
824 	if (cfg->fc_oif && nh->fib_nh_oif != cfg->fc_oif) {
825 		NL_SET_ERR_MSG(extack,
826 			       "Nexthop device index does not match RTA_OIF");
827 		goto errout;
828 	}
829 	if (cfg->fc_gw_family) {
830 		if (cfg->fc_gw_family != nh->fib_nh_gw_family ||
831 		    (cfg->fc_gw_family == AF_INET &&
832 		     nh->fib_nh_gw4 != cfg->fc_gw4) ||
833 		    (cfg->fc_gw_family == AF_INET6 &&
834 		     ipv6_addr_cmp(&nh->fib_nh_gw6, &cfg->fc_gw6))) {
835 			NL_SET_ERR_MSG(extack,
836 				       "Nexthop gateway does not match RTA_GATEWAY or RTA_VIA");
837 			goto errout;
838 		}
839 	}
840 #ifdef CONFIG_IP_ROUTE_CLASSID
841 	if (cfg->fc_flow && nh->nh_tclassid != cfg->fc_flow) {
842 		NL_SET_ERR_MSG(extack,
843 			       "Nexthop class id does not match RTA_FLOW");
844 		goto errout;
845 	}
846 #endif
847 	ret = 0;
848 errout:
849 	return ret;
850 }
851 
852 /* only called when fib_nh is integrated into fib_info */
fib_rebalance(struct fib_info * fi)853 static void fib_rebalance(struct fib_info *fi)
854 {
855 	int total;
856 	int w;
857 
858 	if (fib_info_num_path(fi) < 2)
859 		return;
860 
861 	total = 0;
862 	for_nexthops(fi) {
863 		if (nh->fib_nh_flags & RTNH_F_DEAD)
864 			continue;
865 
866 		if (ip_ignore_linkdown(nh->fib_nh_dev) &&
867 		    nh->fib_nh_flags & RTNH_F_LINKDOWN)
868 			continue;
869 
870 		total += nh->fib_nh_weight;
871 	} endfor_nexthops(fi);
872 
873 	w = 0;
874 	change_nexthops(fi) {
875 		int upper_bound;
876 
877 		if (nexthop_nh->fib_nh_flags & RTNH_F_DEAD) {
878 			upper_bound = -1;
879 		} else if (ip_ignore_linkdown(nexthop_nh->fib_nh_dev) &&
880 			   nexthop_nh->fib_nh_flags & RTNH_F_LINKDOWN) {
881 			upper_bound = -1;
882 		} else {
883 			w += nexthop_nh->fib_nh_weight;
884 			upper_bound = DIV_ROUND_CLOSEST_ULL((u64)w << 31,
885 							    total) - 1;
886 		}
887 
888 		atomic_set(&nexthop_nh->fib_nh_upper_bound, upper_bound);
889 	} endfor_nexthops(fi);
890 }
891 #else /* CONFIG_IP_ROUTE_MULTIPATH */
892 
fib_get_nhs(struct fib_info * fi,struct rtnexthop * rtnh,int remaining,struct fib_config * cfg,struct netlink_ext_ack * extack)893 static int fib_get_nhs(struct fib_info *fi, struct rtnexthop *rtnh,
894 		       int remaining, struct fib_config *cfg,
895 		       struct netlink_ext_ack *extack)
896 {
897 	NL_SET_ERR_MSG(extack, "Multipath support not enabled in kernel");
898 
899 	return -EINVAL;
900 }
901 
902 #define fib_rebalance(fi) do { } while (0)
903 
904 #endif /* CONFIG_IP_ROUTE_MULTIPATH */
905 
fib_encap_match(struct net * net,u16 encap_type,struct nlattr * encap,const struct fib_nh * nh,const struct fib_config * cfg,struct netlink_ext_ack * extack)906 static int fib_encap_match(struct net *net, u16 encap_type,
907 			   struct nlattr *encap,
908 			   const struct fib_nh *nh,
909 			   const struct fib_config *cfg,
910 			   struct netlink_ext_ack *extack)
911 {
912 	struct lwtunnel_state *lwtstate;
913 	int ret, result = 0;
914 
915 	if (encap_type == LWTUNNEL_ENCAP_NONE)
916 		return 0;
917 
918 	ret = lwtunnel_build_state(net, encap_type, encap, AF_INET,
919 				   cfg, &lwtstate, extack);
920 	if (!ret) {
921 		result = lwtunnel_cmp_encap(lwtstate, nh->fib_nh_lws);
922 		lwtstate_free(lwtstate);
923 	}
924 
925 	return result;
926 }
927 
fib_nh_match(struct net * net,struct fib_config * cfg,struct fib_info * fi,struct netlink_ext_ack * extack)928 int fib_nh_match(struct net *net, struct fib_config *cfg, struct fib_info *fi,
929 		 struct netlink_ext_ack *extack)
930 {
931 #ifdef CONFIG_IP_ROUTE_MULTIPATH
932 	struct rtnexthop *rtnh;
933 	int remaining;
934 #endif
935 
936 	if (cfg->fc_priority && cfg->fc_priority != fi->fib_priority)
937 		return 1;
938 
939 	if (cfg->fc_nh_id) {
940 		if (fi->nh && cfg->fc_nh_id == fi->nh->id)
941 			return 0;
942 		return 1;
943 	}
944 
945 	if (fi->nh) {
946 		if (cfg->fc_oif || cfg->fc_gw_family || cfg->fc_mp)
947 			return 1;
948 		return 0;
949 	}
950 
951 	if (cfg->fc_oif || cfg->fc_gw_family) {
952 		struct fib_nh *nh;
953 
954 		nh = fib_info_nh(fi, 0);
955 		if (cfg->fc_encap) {
956 			if (fib_encap_match(net, cfg->fc_encap_type,
957 					    cfg->fc_encap, nh, cfg, extack))
958 				return 1;
959 		}
960 #ifdef CONFIG_IP_ROUTE_CLASSID
961 		if (cfg->fc_flow &&
962 		    cfg->fc_flow != nh->nh_tclassid)
963 			return 1;
964 #endif
965 		if ((cfg->fc_oif && cfg->fc_oif != nh->fib_nh_oif) ||
966 		    (cfg->fc_gw_family &&
967 		     cfg->fc_gw_family != nh->fib_nh_gw_family))
968 			return 1;
969 
970 		if (cfg->fc_gw_family == AF_INET &&
971 		    cfg->fc_gw4 != nh->fib_nh_gw4)
972 			return 1;
973 
974 		if (cfg->fc_gw_family == AF_INET6 &&
975 		    ipv6_addr_cmp(&cfg->fc_gw6, &nh->fib_nh_gw6))
976 			return 1;
977 
978 		return 0;
979 	}
980 
981 #ifdef CONFIG_IP_ROUTE_MULTIPATH
982 	if (!cfg->fc_mp)
983 		return 0;
984 
985 	rtnh = cfg->fc_mp;
986 	remaining = cfg->fc_mp_len;
987 
988 	for_nexthops(fi) {
989 		int attrlen;
990 
991 		if (!rtnh_ok(rtnh, remaining))
992 			return -EINVAL;
993 
994 		if (rtnh->rtnh_ifindex && rtnh->rtnh_ifindex != nh->fib_nh_oif)
995 			return 1;
996 
997 		attrlen = rtnh_attrlen(rtnh);
998 		if (attrlen > 0) {
999 			struct nlattr *nla, *nlav, *attrs = rtnh_attrs(rtnh);
1000 			int err;
1001 
1002 			nla = nla_find(attrs, attrlen, RTA_GATEWAY);
1003 			nlav = nla_find(attrs, attrlen, RTA_VIA);
1004 			if (nla && nlav) {
1005 				NL_SET_ERR_MSG(extack,
1006 					       "Nexthop configuration can not contain both GATEWAY and VIA");
1007 				return -EINVAL;
1008 			}
1009 
1010 			if (nla) {
1011 				__be32 gw;
1012 
1013 				err = fib_gw_from_attr(&gw, nla, extack);
1014 				if (err)
1015 					return err;
1016 
1017 				if (nh->fib_nh_gw_family != AF_INET ||
1018 				    gw != nh->fib_nh_gw4)
1019 					return 1;
1020 			} else if (nlav) {
1021 				struct fib_config cfg2;
1022 
1023 				err = fib_gw_from_via(&cfg2, nlav, extack);
1024 				if (err)
1025 					return err;
1026 
1027 				switch (nh->fib_nh_gw_family) {
1028 				case AF_INET:
1029 					if (cfg2.fc_gw_family != AF_INET ||
1030 					    cfg2.fc_gw4 != nh->fib_nh_gw4)
1031 						return 1;
1032 					break;
1033 				case AF_INET6:
1034 					if (cfg2.fc_gw_family != AF_INET6 ||
1035 					    ipv6_addr_cmp(&cfg2.fc_gw6,
1036 							  &nh->fib_nh_gw6))
1037 						return 1;
1038 					break;
1039 				}
1040 			}
1041 
1042 #ifdef CONFIG_IP_ROUTE_CLASSID
1043 			nla = nla_find(attrs, attrlen, RTA_FLOW);
1044 			if (nla) {
1045 				if (nla_len(nla) < sizeof(u32)) {
1046 					NL_SET_ERR_MSG(extack, "Invalid RTA_FLOW");
1047 					return -EINVAL;
1048 				}
1049 				if (nla_get_u32(nla) != nh->nh_tclassid)
1050 					return 1;
1051 			}
1052 #endif
1053 		}
1054 
1055 		rtnh = rtnh_next(rtnh, &remaining);
1056 	} endfor_nexthops(fi);
1057 #endif
1058 	return 0;
1059 }
1060 
fib_metrics_match(struct fib_config * cfg,struct fib_info * fi)1061 bool fib_metrics_match(struct fib_config *cfg, struct fib_info *fi)
1062 {
1063 	struct nlattr *nla;
1064 	int remaining;
1065 
1066 	if (!cfg->fc_mx)
1067 		return true;
1068 
1069 	nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
1070 		int type = nla_type(nla);
1071 		u32 fi_val, val;
1072 
1073 		if (!type)
1074 			continue;
1075 		if (type > RTAX_MAX)
1076 			return false;
1077 
1078 		type = array_index_nospec(type, RTAX_MAX + 1);
1079 		if (type == RTAX_CC_ALGO) {
1080 			char tmp[TCP_CA_NAME_MAX];
1081 			bool ecn_ca = false;
1082 
1083 			nla_strscpy(tmp, nla, sizeof(tmp));
1084 			val = tcp_ca_get_key_by_name(tmp, &ecn_ca);
1085 		} else {
1086 			if (nla_len(nla) != sizeof(u32))
1087 				return false;
1088 			val = nla_get_u32(nla);
1089 		}
1090 
1091 		fi_val = fi->fib_metrics->metrics[type - 1];
1092 		if (type == RTAX_FEATURES)
1093 			fi_val &= ~DST_FEATURE_ECN_CA;
1094 
1095 		if (fi_val != val)
1096 			return false;
1097 	}
1098 
1099 	return true;
1100 }
1101 
fib_check_nh_v6_gw(struct net * net,struct fib_nh * nh,u32 table,struct netlink_ext_ack * extack)1102 static int fib_check_nh_v6_gw(struct net *net, struct fib_nh *nh,
1103 			      u32 table, struct netlink_ext_ack *extack)
1104 {
1105 	struct fib6_config cfg = {
1106 		.fc_table = table,
1107 		.fc_flags = nh->fib_nh_flags | RTF_GATEWAY,
1108 		.fc_ifindex = nh->fib_nh_oif,
1109 		.fc_gateway = nh->fib_nh_gw6,
1110 	};
1111 	struct fib6_nh fib6_nh = {};
1112 	int err;
1113 
1114 	err = fib6_nh_init(net, &fib6_nh, &cfg, GFP_KERNEL, extack);
1115 	if (!err) {
1116 		nh->fib_nh_dev = fib6_nh.fib_nh_dev;
1117 		netdev_hold(nh->fib_nh_dev, &nh->fib_nh_dev_tracker,
1118 			    GFP_KERNEL);
1119 		nh->fib_nh_oif = nh->fib_nh_dev->ifindex;
1120 		nh->fib_nh_scope = RT_SCOPE_LINK;
1121 
1122 		fib6_nh_release(&fib6_nh);
1123 	}
1124 
1125 	return err;
1126 }
1127 
1128 /*
1129  * Picture
1130  * -------
1131  *
1132  * Semantics of nexthop is very messy by historical reasons.
1133  * We have to take into account, that:
1134  * a) gateway can be actually local interface address,
1135  *    so that gatewayed route is direct.
1136  * b) gateway must be on-link address, possibly
1137  *    described not by an ifaddr, but also by a direct route.
1138  * c) If both gateway and interface are specified, they should not
1139  *    contradict.
1140  * d) If we use tunnel routes, gateway could be not on-link.
1141  *
1142  * Attempt to reconcile all of these (alas, self-contradictory) conditions
1143  * results in pretty ugly and hairy code with obscure logic.
1144  *
1145  * I chose to generalized it instead, so that the size
1146  * of code does not increase practically, but it becomes
1147  * much more general.
1148  * Every prefix is assigned a "scope" value: "host" is local address,
1149  * "link" is direct route,
1150  * [ ... "site" ... "interior" ... ]
1151  * and "universe" is true gateway route with global meaning.
1152  *
1153  * Every prefix refers to a set of "nexthop"s (gw, oif),
1154  * where gw must have narrower scope. This recursion stops
1155  * when gw has LOCAL scope or if "nexthop" is declared ONLINK,
1156  * which means that gw is forced to be on link.
1157  *
1158  * Code is still hairy, but now it is apparently logically
1159  * consistent and very flexible. F.e. as by-product it allows
1160  * to co-exists in peace independent exterior and interior
1161  * routing processes.
1162  *
1163  * Normally it looks as following.
1164  *
1165  * {universe prefix}  -> (gw, oif) [scope link]
1166  *		  |
1167  *		  |-> {link prefix} -> (gw, oif) [scope local]
1168  *					|
1169  *					|-> {local prefix} (terminal node)
1170  */
fib_check_nh_v4_gw(struct net * net,struct fib_nh * nh,u32 table,u8 scope,struct netlink_ext_ack * extack)1171 static int fib_check_nh_v4_gw(struct net *net, struct fib_nh *nh, u32 table,
1172 			      u8 scope, struct netlink_ext_ack *extack)
1173 {
1174 	struct net_device *dev;
1175 	struct fib_result res;
1176 	int err = 0;
1177 
1178 	if (nh->fib_nh_flags & RTNH_F_ONLINK) {
1179 		unsigned int addr_type;
1180 
1181 		if (scope >= RT_SCOPE_LINK) {
1182 			NL_SET_ERR_MSG(extack, "Nexthop has invalid scope");
1183 			return -EINVAL;
1184 		}
1185 		dev = __dev_get_by_index(net, nh->fib_nh_oif);
1186 		if (!dev) {
1187 			NL_SET_ERR_MSG(extack, "Nexthop device required for onlink");
1188 			return -ENODEV;
1189 		}
1190 		if (!(dev->flags & IFF_UP)) {
1191 			NL_SET_ERR_MSG(extack, "Nexthop device is not up");
1192 			return -ENETDOWN;
1193 		}
1194 		addr_type = inet_addr_type_dev_table(net, dev, nh->fib_nh_gw4);
1195 		if (addr_type != RTN_UNICAST) {
1196 			NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1197 			return -EINVAL;
1198 		}
1199 		if (!netif_carrier_ok(dev))
1200 			nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1201 		nh->fib_nh_dev = dev;
1202 		netdev_hold(dev, &nh->fib_nh_dev_tracker, GFP_ATOMIC);
1203 		nh->fib_nh_scope = RT_SCOPE_LINK;
1204 		return 0;
1205 	}
1206 	rcu_read_lock();
1207 	{
1208 		struct fib_table *tbl = NULL;
1209 		struct flowi4 fl4 = {
1210 			.daddr = nh->fib_nh_gw4,
1211 			.flowi4_scope = scope + 1,
1212 			.flowi4_oif = nh->fib_nh_oif,
1213 			.flowi4_iif = LOOPBACK_IFINDEX,
1214 		};
1215 
1216 		/* It is not necessary, but requires a bit of thinking */
1217 		if (fl4.flowi4_scope < RT_SCOPE_LINK)
1218 			fl4.flowi4_scope = RT_SCOPE_LINK;
1219 
1220 		if (table && table != RT_TABLE_MAIN)
1221 			tbl = fib_get_table(net, table);
1222 
1223 		if (tbl)
1224 			err = fib_table_lookup(tbl, &fl4, &res,
1225 					       FIB_LOOKUP_IGNORE_LINKSTATE |
1226 					       FIB_LOOKUP_NOREF);
1227 
1228 		/* on error or if no table given do full lookup. This
1229 		 * is needed for example when nexthops are in the local
1230 		 * table rather than the given table
1231 		 */
1232 		if (!tbl || err) {
1233 			err = fib_lookup(net, &fl4, &res,
1234 					 FIB_LOOKUP_IGNORE_LINKSTATE);
1235 		}
1236 
1237 		if (err) {
1238 			NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1239 			goto out;
1240 		}
1241 	}
1242 
1243 	err = -EINVAL;
1244 	if (res.type != RTN_UNICAST && res.type != RTN_LOCAL) {
1245 		NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1246 		goto out;
1247 	}
1248 	nh->fib_nh_scope = res.scope;
1249 	nh->fib_nh_oif = FIB_RES_OIF(res);
1250 	nh->fib_nh_dev = dev = FIB_RES_DEV(res);
1251 	if (!dev) {
1252 		NL_SET_ERR_MSG(extack,
1253 			       "No egress device for nexthop gateway");
1254 		goto out;
1255 	}
1256 	netdev_hold(dev, &nh->fib_nh_dev_tracker, GFP_ATOMIC);
1257 	if (!netif_carrier_ok(dev))
1258 		nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1259 	err = (dev->flags & IFF_UP) ? 0 : -ENETDOWN;
1260 out:
1261 	rcu_read_unlock();
1262 	return err;
1263 }
1264 
fib_check_nh_nongw(struct net * net,struct fib_nh * nh,struct netlink_ext_ack * extack)1265 static int fib_check_nh_nongw(struct net *net, struct fib_nh *nh,
1266 			      struct netlink_ext_ack *extack)
1267 {
1268 	struct in_device *in_dev;
1269 	int err;
1270 
1271 	if (nh->fib_nh_flags & (RTNH_F_PERVASIVE | RTNH_F_ONLINK)) {
1272 		NL_SET_ERR_MSG(extack,
1273 			       "Invalid flags for nexthop - PERVASIVE and ONLINK can not be set");
1274 		return -EINVAL;
1275 	}
1276 
1277 	rcu_read_lock();
1278 
1279 	err = -ENODEV;
1280 	in_dev = inetdev_by_index(net, nh->fib_nh_oif);
1281 	if (!in_dev)
1282 		goto out;
1283 	err = -ENETDOWN;
1284 	if (!(in_dev->dev->flags & IFF_UP)) {
1285 		NL_SET_ERR_MSG(extack, "Device for nexthop is not up");
1286 		goto out;
1287 	}
1288 
1289 	nh->fib_nh_dev = in_dev->dev;
1290 	netdev_hold(nh->fib_nh_dev, &nh->fib_nh_dev_tracker, GFP_ATOMIC);
1291 	nh->fib_nh_scope = RT_SCOPE_HOST;
1292 	if (!netif_carrier_ok(nh->fib_nh_dev))
1293 		nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1294 	err = 0;
1295 out:
1296 	rcu_read_unlock();
1297 	return err;
1298 }
1299 
fib_check_nh(struct net * net,struct fib_nh * nh,u32 table,u8 scope,struct netlink_ext_ack * extack)1300 int fib_check_nh(struct net *net, struct fib_nh *nh, u32 table, u8 scope,
1301 		 struct netlink_ext_ack *extack)
1302 {
1303 	int err;
1304 
1305 	if (nh->fib_nh_gw_family == AF_INET)
1306 		err = fib_check_nh_v4_gw(net, nh, table, scope, extack);
1307 	else if (nh->fib_nh_gw_family == AF_INET6)
1308 		err = fib_check_nh_v6_gw(net, nh, table, extack);
1309 	else
1310 		err = fib_check_nh_nongw(net, nh, extack);
1311 
1312 	return err;
1313 }
1314 
fib_info_update_nhc_saddr(struct net * net,struct fib_nh_common * nhc,unsigned char scope)1315 __be32 fib_info_update_nhc_saddr(struct net *net, struct fib_nh_common *nhc,
1316 				 unsigned char scope)
1317 {
1318 	struct fib_nh *nh;
1319 	__be32 saddr;
1320 
1321 	if (nhc->nhc_family != AF_INET)
1322 		return inet_select_addr(nhc->nhc_dev, 0, scope);
1323 
1324 	nh = container_of(nhc, struct fib_nh, nh_common);
1325 	saddr = inet_select_addr(nh->fib_nh_dev, nh->fib_nh_gw4, scope);
1326 
1327 	WRITE_ONCE(nh->nh_saddr, saddr);
1328 	WRITE_ONCE(nh->nh_saddr_genid, atomic_read(&net->ipv4.dev_addr_genid));
1329 
1330 	return saddr;
1331 }
1332 
fib_result_prefsrc(struct net * net,struct fib_result * res)1333 __be32 fib_result_prefsrc(struct net *net, struct fib_result *res)
1334 {
1335 	struct fib_nh_common *nhc = res->nhc;
1336 
1337 	if (res->fi->fib_prefsrc)
1338 		return res->fi->fib_prefsrc;
1339 
1340 	if (nhc->nhc_family == AF_INET) {
1341 		struct fib_nh *nh;
1342 
1343 		nh = container_of(nhc, struct fib_nh, nh_common);
1344 		if (READ_ONCE(nh->nh_saddr_genid) ==
1345 		    atomic_read(&net->ipv4.dev_addr_genid))
1346 			return READ_ONCE(nh->nh_saddr);
1347 	}
1348 
1349 	return fib_info_update_nhc_saddr(net, nhc, res->fi->fib_scope);
1350 }
1351 
fib_valid_prefsrc(struct fib_config * cfg,__be32 fib_prefsrc)1352 static bool fib_valid_prefsrc(struct fib_config *cfg, __be32 fib_prefsrc)
1353 {
1354 	if (cfg->fc_type != RTN_LOCAL || !cfg->fc_dst ||
1355 	    fib_prefsrc != cfg->fc_dst) {
1356 		u32 tb_id = cfg->fc_table;
1357 		int rc;
1358 
1359 		if (tb_id == RT_TABLE_MAIN)
1360 			tb_id = RT_TABLE_LOCAL;
1361 
1362 		rc = inet_addr_type_table(cfg->fc_nlinfo.nl_net,
1363 					  fib_prefsrc, tb_id);
1364 
1365 		if (rc != RTN_LOCAL && tb_id != RT_TABLE_LOCAL) {
1366 			rc = inet_addr_type_table(cfg->fc_nlinfo.nl_net,
1367 						  fib_prefsrc, RT_TABLE_LOCAL);
1368 		}
1369 
1370 		if (rc != RTN_LOCAL)
1371 			return false;
1372 	}
1373 	return true;
1374 }
1375 
fib_create_info(struct fib_config * cfg,struct netlink_ext_ack * extack)1376 struct fib_info *fib_create_info(struct fib_config *cfg,
1377 				 struct netlink_ext_ack *extack)
1378 {
1379 	int err;
1380 	struct fib_info *fi = NULL;
1381 	struct nexthop *nh = NULL;
1382 	struct fib_info *ofi;
1383 	int nhs = 1;
1384 	struct net *net = cfg->fc_nlinfo.nl_net;
1385 
1386 	ASSERT_RTNL();
1387 	if (cfg->fc_type > RTN_MAX)
1388 		goto err_inval;
1389 
1390 	/* Fast check to catch the most weird cases */
1391 	if (fib_props[cfg->fc_type].scope > cfg->fc_scope) {
1392 		NL_SET_ERR_MSG(extack, "Invalid scope");
1393 		goto err_inval;
1394 	}
1395 
1396 	if (cfg->fc_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN)) {
1397 		NL_SET_ERR_MSG(extack,
1398 			       "Invalid rtm_flags - can not contain DEAD or LINKDOWN");
1399 		goto err_inval;
1400 	}
1401 
1402 	if (cfg->fc_nh_id) {
1403 		if (!cfg->fc_mx) {
1404 			fi = fib_find_info_nh(net, cfg);
1405 			if (fi) {
1406 				refcount_inc(&fi->fib_treeref);
1407 				return fi;
1408 			}
1409 		}
1410 
1411 		nh = nexthop_find_by_id(net, cfg->fc_nh_id);
1412 		if (!nh) {
1413 			NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
1414 			goto err_inval;
1415 		}
1416 		nhs = 0;
1417 	}
1418 
1419 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1420 	if (cfg->fc_mp) {
1421 		nhs = fib_count_nexthops(cfg->fc_mp, cfg->fc_mp_len, extack);
1422 		if (nhs == 0)
1423 			goto err_inval;
1424 	}
1425 #endif
1426 
1427 	fib_info_hash_grow(net);
1428 
1429 	fi = kzalloc_flex(*fi, fib_nh, nhs);
1430 	if (!fi) {
1431 		err = -ENOBUFS;
1432 		goto failure;
1433 	}
1434 
1435 	fi->fib_metrics = ip_fib_metrics_init(cfg->fc_mx, cfg->fc_mx_len, extack);
1436 	if (IS_ERR(fi->fib_metrics)) {
1437 		err = PTR_ERR(fi->fib_metrics);
1438 		kfree(fi);
1439 		return ERR_PTR(err);
1440 	}
1441 
1442 	fi->fib_net = net;
1443 	fi->fib_protocol = cfg->fc_protocol;
1444 	fi->fib_scope = cfg->fc_scope;
1445 	fi->fib_flags = cfg->fc_flags;
1446 	fi->fib_priority = cfg->fc_priority;
1447 	fi->fib_prefsrc = cfg->fc_prefsrc;
1448 	fi->fib_type = cfg->fc_type;
1449 	fi->fib_tb_id = cfg->fc_table;
1450 
1451 	fi->fib_nhs = nhs;
1452 	if (nh) {
1453 		if (!nexthop_get(nh)) {
1454 			NL_SET_ERR_MSG(extack, "Nexthop has been deleted");
1455 			err = -EINVAL;
1456 		} else {
1457 			err = 0;
1458 			fi->nh = nh;
1459 		}
1460 	} else {
1461 		change_nexthops(fi) {
1462 			nexthop_nh->nh_parent = fi;
1463 		} endfor_nexthops(fi)
1464 
1465 		if (cfg->fc_mp)
1466 			err = fib_get_nhs(fi, cfg->fc_mp, cfg->fc_mp_len, cfg,
1467 					  extack);
1468 		else
1469 			err = fib_nh_init(net, fi->fib_nh, cfg, 1, extack);
1470 	}
1471 
1472 	if (err != 0)
1473 		goto failure;
1474 
1475 	if (fib_props[cfg->fc_type].error) {
1476 		if (cfg->fc_gw_family || cfg->fc_oif || cfg->fc_mp) {
1477 			NL_SET_ERR_MSG(extack,
1478 				       "Gateway, device and multipath can not be specified for this route type");
1479 			goto err_inval;
1480 		}
1481 		goto link_it;
1482 	} else {
1483 		switch (cfg->fc_type) {
1484 		case RTN_UNICAST:
1485 		case RTN_LOCAL:
1486 		case RTN_BROADCAST:
1487 		case RTN_ANYCAST:
1488 		case RTN_MULTICAST:
1489 			break;
1490 		default:
1491 			NL_SET_ERR_MSG(extack, "Invalid route type");
1492 			goto err_inval;
1493 		}
1494 	}
1495 
1496 	if (cfg->fc_scope > RT_SCOPE_HOST) {
1497 		NL_SET_ERR_MSG(extack, "Invalid scope");
1498 		goto err_inval;
1499 	}
1500 
1501 	if (fi->nh) {
1502 		err = fib_check_nexthop(fi->nh, cfg->fc_scope, extack);
1503 		if (err)
1504 			goto failure;
1505 	} else if (cfg->fc_scope == RT_SCOPE_HOST) {
1506 		struct fib_nh *nh = fi->fib_nh;
1507 
1508 		/* Local address is added. */
1509 		if (nhs != 1) {
1510 			NL_SET_ERR_MSG(extack,
1511 				       "Route with host scope can not have multiple nexthops");
1512 			goto err_inval;
1513 		}
1514 		if (nh->fib_nh_gw_family) {
1515 			NL_SET_ERR_MSG(extack,
1516 				       "Route with host scope can not have a gateway");
1517 			goto err_inval;
1518 		}
1519 		nh->fib_nh_scope = RT_SCOPE_NOWHERE;
1520 		nh->fib_nh_dev = dev_get_by_index(net, nh->fib_nh_oif);
1521 		err = -ENODEV;
1522 		if (!nh->fib_nh_dev)
1523 			goto failure;
1524 		netdev_tracker_alloc(nh->fib_nh_dev, &nh->fib_nh_dev_tracker,
1525 				     GFP_KERNEL);
1526 	} else {
1527 		int linkdown = 0;
1528 
1529 		change_nexthops(fi) {
1530 			err = fib_check_nh(cfg->fc_nlinfo.nl_net, nexthop_nh,
1531 					   cfg->fc_table, cfg->fc_scope,
1532 					   extack);
1533 			if (err != 0)
1534 				goto failure;
1535 			if (nexthop_nh->fib_nh_flags & RTNH_F_LINKDOWN)
1536 				linkdown++;
1537 		} endfor_nexthops(fi)
1538 		if (linkdown == fi->fib_nhs)
1539 			fi->fib_flags |= RTNH_F_LINKDOWN;
1540 	}
1541 
1542 	if (fi->fib_prefsrc && !fib_valid_prefsrc(cfg, fi->fib_prefsrc)) {
1543 		NL_SET_ERR_MSG(extack, "Invalid prefsrc address");
1544 		goto err_inval;
1545 	}
1546 
1547 	if (!fi->nh) {
1548 		change_nexthops(fi) {
1549 			fib_info_update_nhc_saddr(net, &nexthop_nh->nh_common,
1550 						  fi->fib_scope);
1551 			if (nexthop_nh->fib_nh_gw_family == AF_INET6)
1552 				fi->fib_nh_is_v6 = true;
1553 		} endfor_nexthops(fi)
1554 
1555 		fib_rebalance(fi);
1556 	}
1557 
1558 link_it:
1559 	ofi = fib_find_info(fi);
1560 	if (ofi) {
1561 		/* fib_table_lookup() should not see @fi yet. */
1562 		fi->fib_dead = 1;
1563 		free_fib_info(fi);
1564 		refcount_inc(&ofi->fib_treeref);
1565 		return ofi;
1566 	}
1567 
1568 	refcount_set(&fi->fib_treeref, 1);
1569 	refcount_set(&fi->fib_clntref, 1);
1570 
1571 	net->ipv4.fib_info_cnt++;
1572 	hlist_add_head(&fi->fib_hash, fib_info_hash_bucket(fi));
1573 
1574 	if (fi->fib_prefsrc) {
1575 		struct hlist_head *head;
1576 
1577 		head = fib_info_laddrhash_bucket(net, fi->fib_prefsrc);
1578 		hlist_add_head(&fi->fib_lhash, head);
1579 	}
1580 	if (fi->nh) {
1581 		list_add(&fi->nh_list, &nh->fi_list);
1582 	} else {
1583 		change_nexthops(fi) {
1584 			struct hlist_head *head;
1585 
1586 			if (!nexthop_nh->fib_nh_dev)
1587 				continue;
1588 			head = fib_nh_head(nexthop_nh->fib_nh_dev);
1589 			hlist_add_head_rcu(&nexthop_nh->nh_hash, head);
1590 		} endfor_nexthops(fi)
1591 	}
1592 	return fi;
1593 
1594 err_inval:
1595 	err = -EINVAL;
1596 
1597 failure:
1598 	if (fi) {
1599 		/* fib_table_lookup() should not see @fi yet. */
1600 		fi->fib_dead = 1;
1601 		free_fib_info(fi);
1602 	}
1603 
1604 	return ERR_PTR(err);
1605 }
1606 
fib_nexthop_info(struct sk_buff * skb,const struct fib_nh_common * nhc,u8 rt_family,unsigned char * flags,bool skip_oif)1607 int fib_nexthop_info(struct sk_buff *skb, const struct fib_nh_common *nhc,
1608 		     u8 rt_family, unsigned char *flags, bool skip_oif)
1609 {
1610 	if (nhc->nhc_flags & RTNH_F_DEAD)
1611 		*flags |= RTNH_F_DEAD;
1612 
1613 	if (nhc->nhc_flags & RTNH_F_LINKDOWN) {
1614 		*flags |= RTNH_F_LINKDOWN;
1615 
1616 		rcu_read_lock();
1617 		switch (nhc->nhc_family) {
1618 		case AF_INET:
1619 			if (ip_ignore_linkdown(nhc->nhc_dev))
1620 				*flags |= RTNH_F_DEAD;
1621 			break;
1622 		case AF_INET6:
1623 			if (ip6_ignore_linkdown(nhc->nhc_dev))
1624 				*flags |= RTNH_F_DEAD;
1625 			break;
1626 		}
1627 		rcu_read_unlock();
1628 	}
1629 
1630 	switch (nhc->nhc_gw_family) {
1631 	case AF_INET:
1632 		if (nla_put_in_addr(skb, RTA_GATEWAY, nhc->nhc_gw.ipv4))
1633 			goto nla_put_failure;
1634 		break;
1635 	case AF_INET6:
1636 		/* if gateway family does not match nexthop family
1637 		 * gateway is encoded as RTA_VIA
1638 		 */
1639 		if (rt_family != nhc->nhc_gw_family) {
1640 			int alen = sizeof(struct in6_addr);
1641 			struct nlattr *nla;
1642 			struct rtvia *via;
1643 
1644 			nla = nla_reserve(skb, RTA_VIA, alen + 2);
1645 			if (!nla)
1646 				goto nla_put_failure;
1647 
1648 			via = nla_data(nla);
1649 			via->rtvia_family = AF_INET6;
1650 			memcpy(via->rtvia_addr, &nhc->nhc_gw.ipv6, alen);
1651 		} else if (nla_put_in6_addr(skb, RTA_GATEWAY,
1652 					    &nhc->nhc_gw.ipv6) < 0) {
1653 			goto nla_put_failure;
1654 		}
1655 		break;
1656 	}
1657 
1658 	*flags |= (nhc->nhc_flags &
1659 		   (RTNH_F_ONLINK | RTNH_F_OFFLOAD | RTNH_F_TRAP));
1660 
1661 	if (!skip_oif && nhc->nhc_dev &&
1662 	    nla_put_u32(skb, RTA_OIF, nhc->nhc_dev->ifindex))
1663 		goto nla_put_failure;
1664 
1665 	if (lwtunnel_fill_encap(skb, nhc->nhc_lwtstate,
1666 				RTA_ENCAP, RTA_ENCAP_TYPE) < 0)
1667 		goto nla_put_failure;
1668 
1669 	return 0;
1670 
1671 nla_put_failure:
1672 	return -EMSGSIZE;
1673 }
1674 
1675 #if IS_ENABLED(CONFIG_IP_ROUTE_MULTIPATH) || IS_ENABLED(CONFIG_IPV6)
fib_add_nexthop(struct sk_buff * skb,const struct fib_nh_common * nhc,int nh_weight,u8 rt_family,u32 nh_tclassid)1676 int fib_add_nexthop(struct sk_buff *skb, const struct fib_nh_common *nhc,
1677 		    int nh_weight, u8 rt_family, u32 nh_tclassid)
1678 {
1679 	const struct net_device *dev = nhc->nhc_dev;
1680 	struct rtnexthop *rtnh;
1681 	unsigned char flags = 0;
1682 
1683 	rtnh = nla_reserve_nohdr(skb, sizeof(*rtnh));
1684 	if (!rtnh)
1685 		goto nla_put_failure;
1686 
1687 	rtnh->rtnh_hops = nh_weight - 1;
1688 	rtnh->rtnh_ifindex = dev ? dev->ifindex : 0;
1689 
1690 	if (fib_nexthop_info(skb, nhc, rt_family, &flags, true) < 0)
1691 		goto nla_put_failure;
1692 
1693 	rtnh->rtnh_flags = flags;
1694 
1695 	if (nh_tclassid && nla_put_u32(skb, RTA_FLOW, nh_tclassid))
1696 		goto nla_put_failure;
1697 
1698 	/* length of rtnetlink header + attributes */
1699 	rtnh->rtnh_len = nlmsg_get_pos(skb) - (void *)rtnh;
1700 
1701 	return 0;
1702 
1703 nla_put_failure:
1704 	return -EMSGSIZE;
1705 }
1706 #endif
1707 
1708 #ifdef CONFIG_IP_ROUTE_MULTIPATH
fib_add_multipath(struct sk_buff * skb,struct fib_info * fi)1709 static int fib_add_multipath(struct sk_buff *skb, struct fib_info *fi)
1710 {
1711 	struct nlattr *mp;
1712 
1713 	mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
1714 	if (!mp)
1715 		goto nla_put_failure;
1716 
1717 	if (unlikely(fi->nh)) {
1718 		if (nexthop_mpath_fill_node(skb, fi->nh, AF_INET) < 0)
1719 			goto nla_put_failure;
1720 		goto mp_end;
1721 	}
1722 
1723 	for_nexthops(fi) {
1724 		u32 nh_tclassid = 0;
1725 #ifdef CONFIG_IP_ROUTE_CLASSID
1726 		nh_tclassid = nh->nh_tclassid;
1727 #endif
1728 		if (fib_add_nexthop(skb, &nh->nh_common, nh->fib_nh_weight,
1729 				    AF_INET, nh_tclassid) < 0)
1730 			goto nla_put_failure;
1731 	} endfor_nexthops(fi);
1732 
1733 mp_end:
1734 	nla_nest_end(skb, mp);
1735 
1736 	return 0;
1737 
1738 nla_put_failure:
1739 	return -EMSGSIZE;
1740 }
1741 #else
fib_add_multipath(struct sk_buff * skb,struct fib_info * fi)1742 static int fib_add_multipath(struct sk_buff *skb, struct fib_info *fi)
1743 {
1744 	return 0;
1745 }
1746 #endif
1747 
fib_dump_info(struct sk_buff * skb,u32 portid,u32 seq,int event,const struct fib_rt_info * fri,unsigned int flags)1748 int fib_dump_info(struct sk_buff *skb, u32 portid, u32 seq, int event,
1749 		  const struct fib_rt_info *fri, unsigned int flags)
1750 {
1751 	unsigned int nhs = fib_info_num_path(fri->fi);
1752 	struct fib_info *fi = fri->fi;
1753 	u32 tb_id = fri->tb_id;
1754 	struct nlmsghdr *nlh;
1755 	struct rtmsg *rtm;
1756 
1757 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*rtm), flags);
1758 	if (!nlh)
1759 		return -EMSGSIZE;
1760 
1761 	rtm = nlmsg_data(nlh);
1762 	rtm->rtm_family = AF_INET;
1763 	rtm->rtm_dst_len = fri->dst_len;
1764 	rtm->rtm_src_len = 0;
1765 	rtm->rtm_tos = inet_dscp_to_dsfield(fri->dscp);
1766 	if (tb_id < 256)
1767 		rtm->rtm_table = tb_id;
1768 	else
1769 		rtm->rtm_table = RT_TABLE_COMPAT;
1770 	if (nla_put_u32(skb, RTA_TABLE, tb_id))
1771 		goto nla_put_failure;
1772 	rtm->rtm_type = fri->type;
1773 	rtm->rtm_flags = fi->fib_flags;
1774 	rtm->rtm_scope = fi->fib_scope;
1775 	rtm->rtm_protocol = fi->fib_protocol;
1776 
1777 	if (rtm->rtm_dst_len &&
1778 	    nla_put_in_addr(skb, RTA_DST, fri->dst))
1779 		goto nla_put_failure;
1780 	if (fi->fib_priority &&
1781 	    nla_put_u32(skb, RTA_PRIORITY, fi->fib_priority))
1782 		goto nla_put_failure;
1783 	if (rtnetlink_put_metrics(skb, fi->fib_metrics->metrics) < 0)
1784 		goto nla_put_failure;
1785 
1786 	if (fi->fib_prefsrc &&
1787 	    nla_put_in_addr(skb, RTA_PREFSRC, fi->fib_prefsrc))
1788 		goto nla_put_failure;
1789 
1790 	if (fi->nh) {
1791 		if (nla_put_u32(skb, RTA_NH_ID, fi->nh->id))
1792 			goto nla_put_failure;
1793 		if (nexthop_is_blackhole(fi->nh))
1794 			rtm->rtm_type = RTN_BLACKHOLE;
1795 		if (!READ_ONCE(fi->fib_net->ipv4.sysctl_nexthop_compat_mode))
1796 			goto offload;
1797 	}
1798 
1799 	if (nhs == 1) {
1800 		const struct fib_nh_common *nhc = fib_info_nhc(fi, 0);
1801 		unsigned char flags = 0;
1802 
1803 		if (fib_nexthop_info(skb, nhc, AF_INET, &flags, false) < 0)
1804 			goto nla_put_failure;
1805 
1806 		rtm->rtm_flags = flags;
1807 #ifdef CONFIG_IP_ROUTE_CLASSID
1808 		if (nhc->nhc_family == AF_INET) {
1809 			struct fib_nh *nh;
1810 
1811 			nh = container_of(nhc, struct fib_nh, nh_common);
1812 			if (nh->nh_tclassid &&
1813 			    nla_put_u32(skb, RTA_FLOW, nh->nh_tclassid))
1814 				goto nla_put_failure;
1815 		}
1816 #endif
1817 	} else {
1818 		if (fib_add_multipath(skb, fi) < 0)
1819 			goto nla_put_failure;
1820 	}
1821 
1822 offload:
1823 	if (fri->offload)
1824 		rtm->rtm_flags |= RTM_F_OFFLOAD;
1825 	if (fri->trap)
1826 		rtm->rtm_flags |= RTM_F_TRAP;
1827 	if (fri->offload_failed)
1828 		rtm->rtm_flags |= RTM_F_OFFLOAD_FAILED;
1829 
1830 	nlmsg_end(skb, nlh);
1831 	return 0;
1832 
1833 nla_put_failure:
1834 	nlmsg_cancel(skb, nlh);
1835 	return -EMSGSIZE;
1836 }
1837 
1838 /*
1839  * Update FIB if:
1840  * - local address disappeared -> we must delete all the entries
1841  *   referring to it.
1842  * - device went down -> we must shutdown all nexthops going via it.
1843  */
fib_sync_down_addr(struct net_device * dev,__be32 local)1844 int fib_sync_down_addr(struct net_device *dev, __be32 local)
1845 {
1846 	int tb_id = l3mdev_fib_table(dev) ? : RT_TABLE_MAIN;
1847 	struct net *net = dev_net(dev);
1848 	struct hlist_head *head;
1849 	struct fib_info *fi;
1850 	int ret = 0;
1851 
1852 	if (!local)
1853 		return 0;
1854 
1855 	head = fib_info_laddrhash_bucket(net, local);
1856 	hlist_for_each_entry(fi, head, fib_lhash) {
1857 		if (!net_eq(fi->fib_net, net) ||
1858 		    fi->fib_tb_id != tb_id)
1859 			continue;
1860 		if (fi->fib_prefsrc == local) {
1861 			fi->fib_flags |= RTNH_F_DEAD;
1862 			fi->pfsrc_removed = true;
1863 			ret++;
1864 		}
1865 	}
1866 	return ret;
1867 }
1868 
call_fib_nh_notifiers(struct fib_nh * nh,enum fib_event_type event_type)1869 static int call_fib_nh_notifiers(struct fib_nh *nh,
1870 				 enum fib_event_type event_type)
1871 {
1872 	bool ignore_link_down = ip_ignore_linkdown(nh->fib_nh_dev);
1873 	struct fib_nh_notifier_info info = {
1874 		.fib_nh = nh,
1875 	};
1876 
1877 	switch (event_type) {
1878 	case FIB_EVENT_NH_ADD:
1879 		if (nh->fib_nh_flags & RTNH_F_DEAD)
1880 			break;
1881 		if (ignore_link_down && nh->fib_nh_flags & RTNH_F_LINKDOWN)
1882 			break;
1883 		return call_fib4_notifiers(dev_net(nh->fib_nh_dev), event_type,
1884 					   &info.info);
1885 	case FIB_EVENT_NH_DEL:
1886 		if ((ignore_link_down && nh->fib_nh_flags & RTNH_F_LINKDOWN) ||
1887 		    (nh->fib_nh_flags & RTNH_F_DEAD))
1888 			return call_fib4_notifiers(dev_net(nh->fib_nh_dev),
1889 						   event_type, &info.info);
1890 		break;
1891 	default:
1892 		break;
1893 	}
1894 
1895 	return NOTIFY_DONE;
1896 }
1897 
1898 /* Walk the exceptions of a nexthop after its first hop MTU changed. The
1899  * chain is RCU protected here, while fnhe_update_pmtu() takes fnhe_lock
1900  * for the update of each entry.
1901  */
fib_nhc_update_mtu(struct fib_nh_common * nhc,u32 new,u32 orig)1902 void fib_nhc_update_mtu(struct fib_nh_common *nhc, u32 new, u32 orig)
1903 {
1904 	struct fnhe_hash_bucket *bucket;
1905 	int i;
1906 
1907 	rcu_read_lock();
1908 	bucket = rcu_dereference(nhc->nhc_exceptions);
1909 	if (!bucket)
1910 		goto out;
1911 
1912 	for (i = 0; i < FNHE_HASH_SIZE; i++) {
1913 		struct fib_nh_exception *fnhe;
1914 
1915 		for (fnhe = rcu_dereference(bucket[i].chain);
1916 		     fnhe;
1917 		     fnhe = rcu_dereference(fnhe->fnhe_next))
1918 			fnhe_update_pmtu(fnhe, new, orig);
1919 	}
1920 out:
1921 	rcu_read_unlock();
1922 }
1923 
fib_sync_mtu(struct net_device * dev,u32 orig_mtu)1924 void fib_sync_mtu(struct net_device *dev, u32 orig_mtu)
1925 {
1926 	struct hlist_head *head = fib_nh_head(dev);
1927 	struct fib_nh *nh;
1928 
1929 	hlist_for_each_entry(nh, head, nh_hash) {
1930 		DEBUG_NET_WARN_ON_ONCE(nh->fib_nh_dev != dev);
1931 		fib_nhc_update_mtu(&nh->nh_common, dev->mtu, orig_mtu);
1932 	}
1933 }
1934 
1935 /* Event              force Flags           Description
1936  * NETDEV_CHANGE      0     LINKDOWN        Carrier OFF, not for scope host
1937  * NETDEV_DOWN        0     LINKDOWN|DEAD   Link down, not for scope host
1938  * NETDEV_DOWN        1     LINKDOWN|DEAD   Last address removed
1939  * NETDEV_UNREGISTER  1     LINKDOWN|DEAD   Device removed
1940  *
1941  * only used when fib_nh is built into fib_info
1942  */
fib_sync_down_dev(struct net_device * dev,unsigned long event,bool force)1943 int fib_sync_down_dev(struct net_device *dev, unsigned long event, bool force)
1944 {
1945 	struct hlist_head *head = fib_nh_head(dev);
1946 	struct fib_info *prev_fi = NULL;
1947 	int scope = RT_SCOPE_NOWHERE;
1948 	struct fib_nh *nh;
1949 	int ret = 0;
1950 
1951 	if (force)
1952 		scope = -1;
1953 
1954 	hlist_for_each_entry(nh, head, nh_hash) {
1955 		struct fib_info *fi = nh->nh_parent;
1956 		int dead;
1957 
1958 		BUG_ON(!fi->fib_nhs);
1959 		DEBUG_NET_WARN_ON_ONCE(nh->fib_nh_dev != dev);
1960 		if (fi == prev_fi)
1961 			continue;
1962 		prev_fi = fi;
1963 		dead = 0;
1964 		change_nexthops(fi) {
1965 			if (nexthop_nh->fib_nh_flags & RTNH_F_DEAD)
1966 				dead++;
1967 			else if (nexthop_nh->fib_nh_dev == dev &&
1968 				 nexthop_nh->fib_nh_scope != scope) {
1969 				switch (event) {
1970 				case NETDEV_DOWN:
1971 				case NETDEV_UNREGISTER:
1972 					nexthop_nh->fib_nh_flags |= RTNH_F_DEAD;
1973 					fallthrough;
1974 				case NETDEV_CHANGE:
1975 					nexthop_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1976 					break;
1977 				}
1978 				call_fib_nh_notifiers(nexthop_nh,
1979 						      FIB_EVENT_NH_DEL);
1980 				dead++;
1981 			}
1982 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1983 			if (event == NETDEV_UNREGISTER &&
1984 			    nexthop_nh->fib_nh_dev == dev) {
1985 				dead = fi->fib_nhs;
1986 				break;
1987 			}
1988 #endif
1989 		} endfor_nexthops(fi)
1990 		if (dead == fi->fib_nhs) {
1991 			switch (event) {
1992 			case NETDEV_DOWN:
1993 			case NETDEV_UNREGISTER:
1994 				fi->fib_flags |= RTNH_F_DEAD;
1995 				fallthrough;
1996 			case NETDEV_CHANGE:
1997 				fi->fib_flags |= RTNH_F_LINKDOWN;
1998 				break;
1999 			}
2000 			ret++;
2001 		}
2002 
2003 		fib_rebalance(fi);
2004 	}
2005 
2006 	return ret;
2007 }
2008 
2009 /* Must be invoked inside of an RCU protected region.  */
fib_select_default(const struct flowi4 * flp,struct fib_result * res)2010 static void fib_select_default(const struct flowi4 *flp, struct fib_result *res)
2011 {
2012 	struct fib_info *fi = NULL, *last_resort = NULL;
2013 	struct hlist_head *fa_head = res->fa_head;
2014 	struct fib_table *tb = res->table;
2015 	u8 slen = 32 - res->prefixlen;
2016 	int order = -1, last_idx = -1;
2017 	struct fib_alias *fa, *fa1 = NULL;
2018 	u32 last_prio = res->fi->fib_priority;
2019 	dscp_t last_dscp = 0;
2020 
2021 	hlist_for_each_entry_rcu(fa, fa_head, fa_list) {
2022 		struct fib_info *next_fi = fa->fa_info;
2023 		struct fib_nh_common *nhc;
2024 
2025 		if (fa->fa_slen != slen)
2026 			continue;
2027 		if (fa->fa_dscp && !fib_dscp_masked_match(fa->fa_dscp, flp))
2028 			continue;
2029 		if (fa->tb_id != tb->tb_id)
2030 			continue;
2031 		if (next_fi->fib_priority > last_prio &&
2032 		    fa->fa_dscp == last_dscp) {
2033 			if (last_dscp)
2034 				continue;
2035 			break;
2036 		}
2037 		if (next_fi->fib_flags & RTNH_F_DEAD)
2038 			continue;
2039 		last_dscp = fa->fa_dscp;
2040 		last_prio = next_fi->fib_priority;
2041 
2042 		if (next_fi->fib_scope != res->scope ||
2043 		    fa->fa_type != RTN_UNICAST)
2044 			continue;
2045 
2046 		nhc = fib_info_nhc(next_fi, 0);
2047 		if (!nhc->nhc_gw_family || nhc->nhc_scope != RT_SCOPE_LINK)
2048 			continue;
2049 
2050 		fib_alias_accessed(fa);
2051 
2052 		if (!fi) {
2053 			if (next_fi != res->fi)
2054 				break;
2055 			fa1 = fa;
2056 		} else if (!fib_detect_death(fi, order, &last_resort,
2057 					     &last_idx, fa1->fa_default)) {
2058 			fib_result_assign(res, fi);
2059 			fa1->fa_default = order;
2060 			goto out;
2061 		}
2062 		fi = next_fi;
2063 		order++;
2064 	}
2065 
2066 	if (order <= 0 || !fi) {
2067 		if (fa1)
2068 			fa1->fa_default = -1;
2069 		goto out;
2070 	}
2071 
2072 	if (!fib_detect_death(fi, order, &last_resort, &last_idx,
2073 			      fa1->fa_default)) {
2074 		fib_result_assign(res, fi);
2075 		fa1->fa_default = order;
2076 		goto out;
2077 	}
2078 
2079 	if (last_idx >= 0)
2080 		fib_result_assign(res, last_resort);
2081 	fa1->fa_default = last_idx;
2082 out:
2083 	return;
2084 }
2085 
2086 /*
2087  * Dead device goes up. We wake up dead nexthops.
2088  * It takes sense only on multipath routes.
2089  *
2090  * only used when fib_nh is built into fib_info
2091  */
fib_sync_up(struct net_device * dev,unsigned char nh_flags)2092 int fib_sync_up(struct net_device *dev, unsigned char nh_flags)
2093 {
2094 	struct fib_info *prev_fi;
2095 	struct hlist_head *head;
2096 	struct fib_nh *nh;
2097 	int ret;
2098 
2099 	if (!(dev->flags & IFF_UP))
2100 		return 0;
2101 
2102 	if (nh_flags & RTNH_F_DEAD) {
2103 		unsigned int flags = netif_get_flags(dev);
2104 
2105 		if (flags & (IFF_RUNNING | IFF_LOWER_UP))
2106 			nh_flags |= RTNH_F_LINKDOWN;
2107 	}
2108 
2109 	prev_fi = NULL;
2110 	head = fib_nh_head(dev);
2111 	ret = 0;
2112 
2113 	hlist_for_each_entry(nh, head, nh_hash) {
2114 		struct fib_info *fi = nh->nh_parent;
2115 		int alive;
2116 
2117 		BUG_ON(!fi->fib_nhs);
2118 		DEBUG_NET_WARN_ON_ONCE(nh->fib_nh_dev != dev);
2119 		if (fi == prev_fi)
2120 			continue;
2121 
2122 		prev_fi = fi;
2123 		alive = 0;
2124 		change_nexthops(fi) {
2125 			if (!(nexthop_nh->fib_nh_flags & nh_flags)) {
2126 				alive++;
2127 				continue;
2128 			}
2129 			if (!nexthop_nh->fib_nh_dev ||
2130 			    !(nexthop_nh->fib_nh_dev->flags & IFF_UP))
2131 				continue;
2132 			if (nexthop_nh->fib_nh_dev != dev ||
2133 			    !__in_dev_get_rtnl(dev))
2134 				continue;
2135 			alive++;
2136 			nexthop_nh->fib_nh_flags &= ~nh_flags;
2137 			call_fib_nh_notifiers(nexthop_nh, FIB_EVENT_NH_ADD);
2138 		} endfor_nexthops(fi)
2139 
2140 		if (alive > 0) {
2141 			fi->fib_flags &= ~nh_flags;
2142 			ret++;
2143 		}
2144 
2145 		fib_rebalance(fi);
2146 	}
2147 
2148 	return ret;
2149 }
2150 
2151 #ifdef CONFIG_IP_ROUTE_MULTIPATH
fib_good_nh(const struct fib_nh * nh)2152 static bool fib_good_nh(const struct fib_nh *nh)
2153 {
2154 	int state = NUD_REACHABLE;
2155 
2156 	if (nh->fib_nh_scope == RT_SCOPE_LINK) {
2157 		struct neighbour *n;
2158 
2159 		rcu_read_lock();
2160 
2161 		if (likely(nh->fib_nh_gw_family == AF_INET))
2162 			n = __ipv4_neigh_lookup_noref(nh->fib_nh_dev,
2163 						   (__force u32)nh->fib_nh_gw4);
2164 		else if (IS_ENABLED(CONFIG_IPV6) &&
2165 			 nh->fib_nh_gw_family == AF_INET6)
2166 			n = __ipv6_neigh_lookup_noref(nh->fib_nh_dev,
2167 						      &nh->fib_nh_gw6);
2168 		else
2169 			n = NULL;
2170 		if (n)
2171 			state = READ_ONCE(n->nud_state);
2172 
2173 		rcu_read_unlock();
2174 	}
2175 
2176 	return !!(state & NUD_VALID);
2177 }
2178 
fib_select_multipath(struct fib_result * res,int hash,const struct flowi4 * fl4)2179 void fib_select_multipath(struct fib_result *res, int hash,
2180 			  const struct flowi4 *fl4)
2181 {
2182 	struct fib_info *fi = res->fi;
2183 	struct net *net = fi->fib_net;
2184 	bool use_neigh;
2185 	int score = -1;
2186 	__be32 saddr;
2187 
2188 	if (unlikely(res->fi->nh)) {
2189 		nexthop_path_fib_result(res, hash);
2190 		return;
2191 	}
2192 
2193 	use_neigh = READ_ONCE(net->ipv4.sysctl_fib_multipath_use_neigh);
2194 	saddr = fl4 ? fl4->saddr : 0;
2195 
2196 	change_nexthops(fi) {
2197 		int nh_upper_bound, nh_score = 0;
2198 
2199 		/* Nexthops without a carrier are assigned an upper bound of
2200 		 * minus one when "ignore_routes_with_linkdown" is set.
2201 		 */
2202 		nh_upper_bound = atomic_read(&nexthop_nh->fib_nh_upper_bound);
2203 		if (nh_upper_bound == -1 ||
2204 		    (use_neigh && !fib_good_nh(nexthop_nh)))
2205 			continue;
2206 
2207 		if (saddr && nexthop_nh->nh_saddr == saddr)
2208 			nh_score += 2;
2209 		if (hash <= nh_upper_bound)
2210 			nh_score++;
2211 		if (score < nh_score) {
2212 			res->nh_sel = nhsel;
2213 			res->nhc = &nexthop_nh->nh_common;
2214 			if (nh_score == 3 || (!saddr && nh_score == 1))
2215 				return;
2216 			score = nh_score;
2217 		}
2218 
2219 	} endfor_nexthops(fi);
2220 }
2221 #endif
2222 
fib_select_path(struct net * net,struct fib_result * res,struct flowi4 * fl4,const struct sk_buff * skb)2223 void fib_select_path(struct net *net, struct fib_result *res,
2224 		     struct flowi4 *fl4, const struct sk_buff *skb)
2225 {
2226 	if (fl4->flowi4_oif)
2227 		goto check_saddr;
2228 
2229 #ifdef CONFIG_IP_ROUTE_MULTIPATH
2230 	if (fib_info_num_path(res->fi) > 1) {
2231 		int h = fib_multipath_hash(net, fl4, skb, NULL);
2232 
2233 		fib_select_multipath(res, h, fl4);
2234 	}
2235 	else
2236 #endif
2237 	if (!res->prefixlen &&
2238 	    res->table->tb_num_default > 1 &&
2239 	    res->type == RTN_UNICAST)
2240 		fib_select_default(fl4, res);
2241 
2242 check_saddr:
2243 	if (!fl4->saddr) {
2244 		struct net_device *l3mdev;
2245 
2246 		l3mdev = dev_get_by_index_rcu(net, fl4->flowi4_l3mdev);
2247 
2248 		if (!l3mdev ||
2249 		    l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) == l3mdev)
2250 			fl4->saddr = fib_result_prefsrc(net, res);
2251 		else
2252 			fl4->saddr = inet_select_addr(l3mdev, 0, RT_SCOPE_LINK);
2253 	}
2254 }
2255 
fib4_semantics_init(struct net * net)2256 int __net_init fib4_semantics_init(struct net *net)
2257 {
2258 	unsigned int hash_bits = 4;
2259 
2260 	net->ipv4.fib_info_hash = fib_info_hash_alloc(hash_bits);
2261 	if (!net->ipv4.fib_info_hash)
2262 		return -ENOMEM;
2263 
2264 	net->ipv4.fib_info_hash_bits = hash_bits;
2265 	net->ipv4.fib_info_cnt = 0;
2266 
2267 	return 0;
2268 }
2269 
fib4_semantics_exit(struct net * net)2270 void __net_exit fib4_semantics_exit(struct net *net)
2271 {
2272 	fib_info_hash_free(net->ipv4.fib_info_hash);
2273 }
2274